user3419789
user3419789

Reputation: 27

Can't detect collision properly

i am writing a game using Libgdx and i need to detect when the user touches a sprite. I tried to do so with this following code:

this code set the rect's position

    for(int i = 0;i<circlesArray.length;i++)
    {
        rect[i] = new Rectangle(circles.getPosition(i).x,circles.getPosition(i).y,height/8,height/8);
    } 

and this code set the click as rectangle and checks if it overlaps the sprite

  if(Gdx.input.isTouched())
        {
            click = new Rectangle(Gdx.input.getX(),Gdx.input.getY(),Gdx.input.getX(),Gdx.input.getY());

            if(Intersector.overlaps(click,rect[1]));
            {
                System.out.println("clicked");
                x[1] = 0;
            }

        }

From some reason that i cant understand the program detects a collision even when it is not happened, when i tap anywhere on the screen it says that i pressed the sprite.

What should i do to fix it?

Upvotes: 0

Views: 73

Answers (1)

John Cipponeri
John Cipponeri

Reputation: 892

This is your issue:

click = new Rectangle(Gdx.input.getX(), Gdx.input.getY(), Gdx.input.getX(), Gdx.input.getY());

Should be:

click = new Rectangle(Gdx.input.getX(), Gdx.input.getY(), 1, 1);

The last two parameters of a Rectangle are width and height. Here we give the rectangle a width and a height of 1 pixel but you can set it to whatever you like. You were setting those parameters as the inputs x and y which are different every time giving you varying results.

Edit: To translate the input coordinates to your game world's coordinates based on the camera you have to do this:

Vector3 clickPos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(clickPos);

click = new Rectangle(clickPos.x, clickPos.y, 1, 1);

When you use camera.unproject(Vector) it translates your inputs coordinates to work based off of where your camera is positioned in the game world. So now we're using a vector clickPos.

The reason we use a Vector3 is because this is what is required by the unproject function. We supply this vector with the inputs x and y but give it a 0 for the third parameter z since this is a 2d world.

Upvotes: 1

Related Questions