0
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ Questions that are essentially "debug my code for me" are not a good fit for this site. Since they typically only benefit the original poster. Glad you found your problem. \$\endgroup\$
    – House
    Oct 19 '13 at 14:58
2
\$\begingroup\$

Found the problem:

Replace

batch.draw(ballTex, ball.x, ball.y);

with

batch.draw(ballTex, ball.x-ball.radius, ball.y-ball.radius);

That's because batch.draw draws with the lower left corner at x/y.

\$\endgroup\$
1
  • \$\begingroup\$ Please mark this as an answer. \$\endgroup\$ Oct 20 '13 at 2:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .