如何检测Java libGDX中是否触摸了精灵?

mig*_*aud 5 java android libgdx

在过去的几天里,我一直将我的游戏(Apopalypse)移植到Android移动平台.我已经在Google上快速搜索了精灵触摸检测,但没有找到任何有用的信息.一旦触摸,每个气球都会弹出,我只需要检测它是否被触摸过.这是我的气球产卵代码:

渲染(x,y,宽度和高度随机化):

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

在主要游戏类中产卵:

addBalloon(new Balloon());

public static void addBalloon(Balloon b) {
    balloons.add(b);
}
Run Code Online (Sandbox Code Playgroud)

Kum*_*abh 5

在您的类中使用render方法可以执行以下代码

Vector3 touchPoint=new Vector3();

void update()
{
  if(Gdx.input.justTouched())
   {
    camera.unproject(touchpoint.set(Gdx.input.getX(),Gdx.input.getY(),0);
    if(balloon.getBoundingRectangles().contains(touchPoint.x,touchPoint.y))
     {
      // will be here when balloon will be touched
     }
    }
   }
Run Code Online (Sandbox Code Playgroud)


Epi*_*rce 3

我就是这样做的,但是根据您正在使用的场景和可以触摸的元素,可以有稍微更优化的方法来执行此操作:

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) ; 
    }
}
Run Code Online (Sandbox Code Playgroud)