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

时间:2014-07-01 01:32:03

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

主要游戏类产生:

addBalloon(new Balloon());

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

7 个答案:

答案 0 :(得分: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
     }
    }
   }

答案 1 :(得分: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) ; 
    }
}

答案 2 :(得分:2)

我制作了一个小课程,我用我的游戏来检测Sprite是否被触及

from operator import itemgetter

# ... your other code goes here

def averagescore():
    names_sql = "SELECT name FROM {0} GROUP BY name;".format(group)
    # lists names in database
    itr = cursor.execute(names_sql)
    allnames = sorted(list({x[0] for x in itr}))

    records = [{'name': name} for name in allnames]

    scores_sql = """
        SELECT total
          FROM {0}
         WHERE ("{1}") = NAME
      ORDER BY DATE DESC
         LIMIT 3;
    """

    for record in records:
        name = record['name']
        # 3 most recent scores
        itr = cursor.execute(scores_sql.format(group, name))
        scores = [i[0] for i in itr]
        avg = sum(scores) / len(scores)
        record.update({'avg': avg, 'scores': scores})

    tally.sort(key=itemgetter('avg'), reverse=True)

    for record in records:
        print(
            record['name'],
            "'s average is: ",
            record['avg'],
            ". From (up to) 3 most recent scores which were: ",
            record['scores']
        )

这里我是如何使用它的

public class SpriteTouchable extends Sprite {

    public SpriteTouchable(Texture texture) {
        super(texture);
    }

    public SpriteTouchable(Sprite sprite) {
        set(sprite);
    }

    public static float xTrans(float x)
    {
        return x*Gdx.graphics.getWidth()/480;
    }

    public static float yTrans(float y)
    {
        return y*Gdx.graphics.getHeight()/320;
    }

    private boolean isTouched;

    /**
     * Type: Input Listener function
     * listen if this sprite button was pressed (touched)
     * @param marge : the extra touchable space out of sprite
     * @param x     : x position touched by user
     * @param y     : y position touched by user
     * 
     * return true  : Sprite touched
     * return false : Sprite not touched
     */
    public boolean isPressing(int marge,int x, int y) {
        if((x>getX() -xTrans(marge))&& x<getX() +getWidth()+xTrans(marge)) {
            if((y>getY() -yTrans(marge))&& y<getY()+getHeight()+yTrans(marge)) {
                return true;
            }
        }
        return false;
    }
}

 public boolean isTouched() {
    return isTouched;
 }

使用相同的逻辑可以检测精灵释放,也可以在触摸精灵时自定义效果大小等等...

希望这有用!

答案 3 :(得分:0)

您有Gdx.input.getX()Gdx.input.getY()。最后一次触摸的X和Y坐标。 只需将它们与气球框架进行比较即可。

答案 4 :(得分:0)

您可以在鼠标上添加一个小的1x1像素矩形,并检查它是否相交或包含其他框。您需要使用方框来为您想要以这种方式点击的所有对象。

答案 5 :(得分:0)

我有一个简单的解决方案 这就像是一个像素一个像素地创建一个小矩形

Rectangle rect;

rect = new Rectangle(0, 0, 1, 1);

然后创建一个名为

的方法

touching_checking();

在这种方法中我们将做三件事

首先检查是否触摸了屏幕

第二个将矩形放在触摸屏幕的位置

然后最后检查你的矩形是否与精灵矩形重叠。 像那样

private void touching_checking() { if (Gdx.input.isTouched()) { rect.setPosition(Gdx.input.getX(), Gdx.input.getY()); if (rect.overlaps(back.getBoundingRectangle())) { //do what you want here } } } 我有一系列精灵叫做水平我检查哪一个我按下了

private void touching_checking() {
    if (Gdx.input.isTouched()) {
        rect.setPosition(Gdx.input.getX(), Gdx.graphics.getWidth() - Gdx.input.getY());
        for (int i = 0; i < levels.size; i++) {
            if (rect.overlaps(levels.get(i).getBoundingRectangle())) {
                //do what you want here
            }
        }
    }
}

答案 6 :(得分:0)

这是我在sprite类中使用的内容。我给它了一个向量,我点击了camera.unproject(new Vector3().set(x,y,0));。如果在精灵区域中单击,则返回true。

    /***
     * 
     * @param v3 Vector with MouseClickPosition
     * @return true if click was inside rectangle x --> x + width, y --> y + 
     * height
     */

    public boolean clicked(Vector3 v3){
    Rectangle rec = getBoundingRectangle();

    if(v3.x >= rec.x && v3.x < rec.x + getWidth()){
        if(v3.y >= rec.y && v3.y < rec.y + getHeight()){
            System.out.println("click_on\t" + v3.x + ", " + v3.y);
            return true;
        }
        else{
            return false;
        }
    }
    else{
        return false;
    }
}
相关问题