0

I'm using AndEngine and Box2d in android application.
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?

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);
  }
}
user3008254
  • 105
  • 4
  • 10
  • possible duplicate of [android detect touching](http://stackoverflow.com/questions/13374654/android-detect-touching) – jww Apr 05 '14 at 14:29

1 Answers1

0

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. 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. 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.

Dan Harms
  • 4,725
  • 2
  • 18
  • 28