简体   繁体   English

Android检测触摸事件

[英]Android detect touch event

I'm using AndEngine and Box2d in android application.我在 android 应用程序中使用 AndEngine 和 Box2d。
How can I have just one event, attached to the "Game Scene", from where I can find out what is pressed, instead of putting an event on every button in "GameHud" and how to detect the hold of the buttons?我怎么能只有一个事件,附加到“游戏场景”,从那里我可以找出按下了什么,而不是在“GameHud”中的每个按钮上放置一个事件以及如何检测按钮的保持?

public class GameScene extends Scene{
  public GameScene(){
    GameHud hud = new GameHud(this,activity);
    camera.setHUD(hud);
  }
  //catch the touch event here 
}

public class GameHud extends HUD{
  public GameHud(Scene scene, GameActivity activity){
    Sprite leftArrow = new   Sprite(75,75,leftArrowRegion,activity.getVertexBufferObjectManager())
    {
      @Override
      public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
          float pTouchAreaLocalX, float pTouchAreaLocalY) {
          //...
          return true;
        }
    };
    scene.registerTouchArea(this.leftArrow);

    Sprite rightArrow = new Sprite(200, 75, rightArrowRegion, activity.getVertexBufferObjectManager())
    {
      @Override
      public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
        float pTouchAreaLocalX, float pTouchAreaLocalY) {
        //...
        return true;
      }
    };
    scene.registerTouchArea(this.rightArrow);
  }
}

本文“ Android检测触摸”是针对没有andengine的android项目?

You can listen for touch events in the Scene with this: 您可以使用以下方法在场景中监听触摸事件:

setOnSceneTouchListener(new IOnSceneTouchListener() {

        @Override
        public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
            // do something with the touch event
            return true; // or false if not handled
        }

    });

However, doing it this way will require you to calculate which, if any, button was clicked based on the (x, y) coordinates of the touch event. 但是,以这种方式进行操作将需要您根据触摸事件的(x,y)坐标计算单击了哪个按钮(如果有)。 If you feel that this is a better approach rather than registering events on each button you are more than welcome to do that, but you will be redoing a lot of the logic that is already embedded in the engine. 如果您认为这是比在每个按钮上注册事件更好的方法,那么欢迎您这样做,但是您将重做许多引擎中已经嵌入的逻辑。

If it is the logic of the touch events that you want to share between buttons, you can have each registered event call the same method with an id or something to differentiate the buttons. 如果要在按钮之间共享触摸事件的逻辑,则可以让每个注册的事件使用ID或类似的东西调用相同的方法来区分按钮。 That will allow you to centralize the action logic and not have to repeat it for each button being pressed. 这样一来,您就可以集中操作逻辑,而不必为每个按下的按钮重复操作。

If neither of these approaches are what you are looking for, feel free to leave a comment on what is missing and I'll do my best to help you achieve it. 如果您找不到这两种方法,请随时对缺失的内容发表评论,我会尽力帮助您实现这一目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM