Search code examples
javaandroidlibgdxcollision

Strange Collision in LibGDX


Im trying to create a simple ball reflection on a block. I'm using libgdx framework.

I have problems with Block Collision:

public class World {

public Ball ball;
public Bar bar;
public Block block;
public BoundingBox boundsBlock,boundsBall;

public World(){
    initialize();
}

public void initialize(){
    ball = new Ball(10 / 2, 6);
    bar = new Bar(4,1);
    block = new Block(4,7);
    boundsBlock = new BoundingBox(new Vector3(block.position.x,block.position.y,0),new Vector3(block.position.x+2,block.position.y+1,0));
    boundsBall = new BoundingBox(new Vector3(ball.position.x,ball.position.y,0),new Vector3(ball.position.x+1,ball.position.y+1,0));
}

public void update(float delta){
    ball.position.add(ball.direction.x*delta,ball.direction.y * delta,0);

    //Right Collision
    if(ball.position.x + 0.25f >9.65f){
        ball.position.x = 9.65f - 0.25f;
        ball.direction.x = -ball.VELOCITY;
    }


    //Top Collision
    if (ball.position.y + 0.25f > 14.65f){
        ball.position.y = 14.65f - 0.25f;
        ball.direction.y = -ball.VELOCITY;
    }

    //Left Collision
    if(ball.position.x - 0.25f < 0.35f){
        ball.position.x = 0.35f + 0.25f;
        ball.direction.x = ball.VELOCITY;
    }

    //Bar collision
    if(ball.position.y < 1+0.1f){
        if(ball.position.x > bar.position.x && ball.position.x < bar.position.x + 2){
            ball.position.y = 1+ 0.25f;
            ball.direction.y = ball.VELOCITY;
        }

    }

    //Block Collision
    if(boundsBlock.contains(boundsBall)){

        ball.direction.x = -ball.VELOCITY;
        ball.direction.y = -ball.VELOCITY;


    }

The problem begin with block collision. It seems like it were constantly "inside" the collision area and it changes my ball direction to negative all the time instead executing it only when the ball bounds "steps in" the block bounds.

All suggestions are welcomed!

Thank you so much for your help!


Solution

  • The problem is that you don't ever update boundsBall after initializing it, so it always thinks it's embedded in boundsBlock.