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

时间:2023-04-17
本文介绍了如何检测 Java libGDX 中是否触摸了精灵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在过去的几天里,我一直在将我的游戏 (Apopalypse) 移植到 Android 移动平台.我在谷歌上快速搜索了精灵触摸检测,但没有发现任何有用的东西.每个气球一旦被触摸就会弹出,我只需要检测它是否被触摸.这是我的气球生成代码:

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:

渲染(x、y、宽度和高度是随机的):

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();
}

在主游戏类中生成:

addBalloon(new Balloon());

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

推荐答案

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

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) ; 
    }
}

这篇关于如何检测 Java libGDX 中是否触摸了精灵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:使用 Libgdx 的圆和多边形碰撞 下一篇:Libgdx Box2D 像素到米的转换?

相关文章

最新文章