【问题标题】:How do I detect if the user touched my Sprites/screen?如何检测用户是否触摸了我的 Sprites/屏幕?
【发布时间】:2015-05-23 13:49:16
【问题描述】:

基本上,精灵每(1,2 或 3 秒)随机生成一次,并且无限次生成。我希望精灵在屏幕上触摸后消失。 (安卓触摸事件)

public void newEnemy(){
        Sprite newEnemy=Pools.obtain(Sprite.class);
        newEnemy.set(enemy);
        newEnemy.setPosition(200, 700);
        enemies.add(newEnemy);
    }

public void update(){
        deltaTime=Gdx.graphics.getDeltaTime();
        timer+=1*deltaTime;
        timer2+=1*deltaTime;
        timer3+=1*deltaTime;

        if(timer>=random){
            newEnemy();  //spawn a new enemy
            timer-=random;
            random=rTime.nextInt(3)*1f+1;//create random time if timer>= initial random time;
        }

【问题讨论】:

  • 你是在检查一个精灵是否接触了另一个精灵或其他类似鼠标的东西?
  • 我正在制作一个安卓游戏,我不想检测用户是否触摸了精灵/屏幕。

标签: java android libgdx touch spawning


【解决方案1】:

您需要设置一个触摸监听器。相关信息here

然后您需要检查触摸位置是否在您的精灵边界内。 一种常见的方法是创建一个矩形并检查触摸位置是否在矩形内部,像这样

 Rectangle2D bounds = new Rectangle2D.Float(x, y, width, height);

`if(bounds.contains(`the touch x value`,` the touch y value`){`

         //your code to remove the sprite
    }

或者,您可以在 sprite 中编写自己的方法,如果您只需要 contains 方法,这将是一个更好的决定。这样,您不必导入另一个库。 (请注意,这并没有太大区别,但这是一种很好的做法)

public boolean contains(int x, int y) {
     return (x > this.x && y > this.y && x < this.x + this.width && y < this.y + this.height);
}

【讨论】:

  • 我可以只使用普通矩形吗,因为我正在使用它们进行碰撞检测。顺便说一句,我正在使用 libgdx
  • 是的,你也可以让你的精灵包含四个变量xywidthheight并编写你自己的方法。
猜你喜欢
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-14
  • 1970-01-01
相关资源
最近更新 更多