libgdx intersection problem between rectangle and circle

Posted by Chris on Game Development See other posts from Game Development or by Chris
Published on 2013-10-19T10:52:59Z Indexed on 2013/10/19 16:10 UTC
Read the original article Hit count: 370

Filed under:

My collision detection in libgdx is somehow buggy. player.png is 20*80px and ball.png 25*25px.

Code:

@Override
public void create() {      
    // ...
    batch = new SpriteBatch();
    playerTex = new Texture(Gdx.files.internal("data/player.png"));
    ballTex = new Texture(Gdx.files.internal("data/ball.png"));

    player = new Rectangle();
    player.width = 20;
    player.height = 80;
    player.x =  Gdx.graphics.getWidth() - player.width - 10;
    player.y = 300;


    ball = new Circle();
    ball.x = Gdx.graphics.getWidth() / 2;
    ball.y = Gdx.graphics.getHeight() / 2;
    ball.radius = ballTex.getWidth() / 2;
}

@Override
public void render() {      
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    camera.update();

    // draw player, ball
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(ballTex, ball.x, ball.y);
    batch.draw(playerTex, player.x, player.y);

    batch.end();

    // update player position
    if(Gdx.input.isKeyPressed(Keys.DOWN)) player.y -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.UP)) player.y += 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.LEFT)) player.x -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.RIGHT)) player.x += 250 * Gdx.graphics.getDeltaTime();

     // don't let the player leave the field
     if(player.y < 0) player.y = 0;
     if(player.y > 600 - 80) player.y = 600 - 80;

     // check collision
     if (Intersector.overlaps(ball, player))
         Gdx.app.log("overlaps", "yes");
}

enter image description here

© Game Development or respective owner

Related posts about libgdx