Alex
Alex

Reputation: 859

Collision detection (LibGDX)

My programs detects collision between the image and the edge of the screen, but I cannot drag the image after collision. What do I change so I could still be able to drag the image around and didn't let the image go outside of the screen edges?

Gif example I made: https://s31.postimg.org/f60hh3z2z/Animation.gif

inside render

batch.begin();
batch.draw(texture, spritePosition.x, spritePosition.y);
batch.end();

if (Gdx.input.isTouched() && isNotColliding()) {

        camera.unproject(spritePosition.set(Gdx.input.getX() - texture.getWidth() / 2, Gdx.input.getY() + texture.getHeight() / 2, 0));

}


textureBounds.set(spritePosition.x, spritePosition.y, texture.getWidth(), texture.getHeight());

.

private boolean isNotColliding(){
    return screenBounds.contains(textureBounds);
}

Upvotes: 0

Views: 208

Answers (1)

Jim
Jim

Reputation: 1005

The position of the sprite is the lower left corner. This position is what you use to check if the sprite is colliding with the edge.

Because you can move the sprite more than 1 pixel in a frame you can have the sprite x position to be negative. If spritePosition.x == -1 you will be able to see the sprite just fine, but the first line of pixels will be outside the screen.

The reason you are not able to move the sprite anymore is becouse of your if

(Gdx.input.isTouched() && isNotColliding()) {

When spritePosition.x is < 0 isNotColliding() will be true.

Insead of not alowing the sprite to be moved, make it stay inside the screen.

if(spritePosition.x < 0){
    spritePosition.x = 0;
}

Upvotes: 1

Related Questions