如何在libgdx中检测纹理是否被触摸,不使用scene2d

5

我想知道是否有一种方法可以在不使用scene2d的情况下检测到特定纹理的触摸。 Gdx.input.isTouched()检测整个屏幕的触摸,是否有一种方式可以使用某些东西来检测纹理的触摸,而不需要使用scene2d?

1个回答

14

当然有,我也从未使用过Screne2d。

在你的更新方法中。

  if(Gdx.input.isTouched())
{
  Vector3 tmp=new Vector3(Gdx.input.getX(),Gdx.input.getY();
  camera.unproject(tmp);
  Rectangle textureBounds=new Rectangle(textureX,textureY,textureWidth,textureHeight);
  // texture x is the x position of the texture
  // texture y is the y position of the texture
  // texturewidth is the width of the texture (you can get it with texture.getWidth() or textureRegion.getRegionWidth() if you have a texture region
   // textureheight is the height of the texture (you can get it with texture.getHeight() or textureRegion.getRegionhHeight() if you have a texture region
  if(textureBounds.contains(tmp.x,tmp.y))
     {
     // you are touching your texture
     }
}

啊,谢谢你,但我不得不进行一些小修正,我将Vector3更改为Vector2(我有一个3D游戏),并删除了Camera.Unproject行,除此之外,非常好的方法,谢谢! - ilikeyoyo
这对我行得通,但我只想让你知道 if(textureBounds.contains(tmp.x,tmp.y) 后面缺少一个括号。 - twiz
1
即使您有一个2D游戏,仍需要使用Vector3 tmp = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);并将第三个参数设置为0,以及camera.unproject(tmp);。否则,在使用具有不同应用程序窗口大小的桌面版本时,解决方案将无法正常工作。 - MikaAll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接