1

I started using libGDX soon, and I was making a game that has water droplets falling from the top of the screen and the user should tap them before they do touch the bottom of the screen. I have a problem in knowing if the user did tap the droplet to do something.

This is my Render method:

Gdx.gl.glClearColor(0/255.0f, 0/255.0f, 100/255.0f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

cam.update();

if (TimeUtils.millis() - lastDrop > 333) 
    spawnRainDrop();

Iterator<Rectangle> iter = raindrops.iterator();
while (iter.hasNext()) {
    Rectangle raindrop = iter.next();
    raindrop.y -= 300 * Gdx.graphics.getDeltaTime();
    if (raindrop.y + 64 < 0) {
        iter.remove();
    }
    if (Gdx.input.isTouched()) {
        Vector3 touchPos = new Vector3();
        cam.unproject(touchPos);
        if (Gdx.input.getX() == raindrop.x + 64 / 2 &&  Gdx.input.getY() == raindrop.y + 64 / 2) {
            System.out.println("Tapped");
        }
    }   
}

The tapping code doesn't seem to work.

I would really appreciate if someone did explain their answer. Thanks

stealthjong
  • 10,858
  • 13
  • 45
  • 84

2 Answers2

0

You are testing for touch at a single point and not in a bounding box around your object. Use the following to test for touch inside a bounding box:

if(Gdx.input.isTouched()) {
   Vector3 touchPos = new Vector3();
   cam.unproject(touchPos);
   float halfWidth = 64 / 2.0f;  
   float halfHeight = 64 / 2.0f; 
   if( Gdx.input.getX() >= raindrop.x - halfWidth &&
       Gdx.input.getX() <= raindrop.x + halfWidth &&
       Gdx.input.getY() <= raindrop.y + halfHeight && 
       Gdx.input.getY() >= raindrop.y - halfHeight ) {
      System.out.println("Tapped");
   }
}

I'm assuming a bottom/left origin so just change the signs accordingly if you use a different one.

free3dom
  • 18,729
  • 7
  • 52
  • 51
  • I am trying to test for a touch around a bounding rectangle but the problem that my rectangle is an array, and I don't know how to tell him to print tapped when he presses on the specific rectangle(the drop). – Abdel-Rahman Amr Jul 30 '14 at 10:00
0

In two dimensions, I used the following approach to detect where the player clicked: https://stackoverflow.com/a/24511980/2413303

But in your case, I think the problem is just that you used Gdx.input.getX() and Gdx.input.getY() instead of the coordinates you've obtained from cam.unproject(touchPos), according to this other answer on the same question: https://stackoverflow.com/a/24503526/2413303 .

Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428