Search code examples
javaandroidlibgdx

How do I detect if a sprite was touched in Java libGDX?


In the past few days I've been porting my game (Apopalypse) to the Android Mobile platform. I've did a quick search on Google of sprite touch detection but didn't find anything helpful. Each balloon will pop once touched and I just need to detect if it's touched. Here's my balloon spawning code:

Rendering (x, y, width, and height are randomized):

public void render() {
    y += 2;
    balloon.setX(x);
    balloon.setY(y);
    balloon.setSize(width, height);
    batch.begin();
    balloon.draw(batch);
    batch.end();
}

Spawning in main game class:

addBalloon(new Balloon());

public static void addBalloon(Balloon b) {
    balloons.add(b);
}

Solution

  • This is how I did it, but depending on the scene you are using and the elements that can be touched, there can be slightly more optimized ways of doing this:

    public GameScreen implements Screen, InputProcessor
    {
    
      @Override
      public void show()
      {
          Gdx.input.setInputProcessor(this);
      }
    
      @Override
      public boolean touchDown(int screenX, int screenY, int pointer, int button)
      {
          float pointerX = InputTransform.getCursorToModelX(windowWidth, screenX);
          float pointerY = InputTransform.getCursorToModelY(windowHeight, screenY);
          for(int i = 0; i < balloons.size(); i++)
          {
              if(balloons.get(i).contains(pointerX, pointerY))
              {
                  balloons.get(i).setSelected(true);
              }
          }
          return true;
       }
    
       @Override
       public boolean touchUp(int screenX, int screenY, int pointer, int button)
       {
           float pointerX = InputTransform.getCursorToModelX(windowWidth, screenX);
           float pointerY = InputTransform.getCursorToModelY(windowHeight, screenY);
           for(int i = 0; i < balloons.size(); i++)
           {
               if(balloons.get(i).contains(pointerX, pointerY) && balloons.get(i).getSelected())
               {
                   balloons.get(i).execute();
               }
               balloons.get(i).setSelected(false);
           }
           return true;
        }
    
    public class InputTransform
    {
        private static int appWidth = 480;
        private static int appHeight = 320;
    
        public static float getCursorToModelX(int screenX, int cursorX) 
        {
            return (((float)cursorX) * appWidth) / ((float)screenX); 
        }
    
        public static float getCursorToModelY(int screenY, int cursorY) 
        {
            return ((float)(screenY - cursorY)) * appHeight / ((float)screenY) ; 
        }
    }