Search code examples
androidandenginegame-physicstouch-event

Using onAreaTouched with physics - AndEngine


I'm new to AndEngine and this really first attempt at using a touch event with game physics. I created this block of code following the mybringback AndEngine tutorial series. I created a sprite that simply bounces up and down on the ground. What I want to do is integrate a touch event so that the user may pick up the sprite (place it anywhere) then have it fall to the ground.

I have a sprite that bounces up and down, so that's good but my on touch event doesn't work. I did a little research for onAreaTouched but I think I'm still not understanding some of the concepts. If someone could tell me what I'm doing wrong that would be much appreciated.

Here is my onPopulateScene:

@Override
public void onPopulateScene(Scene pScene,

OnPopulateSceneCallback pOnPopulateSceneCallback) throws Exception {


    final Sprite sPlayer = new Sprite(CAMERA_WIDTH / 2,CAMERA_HEIGHT / 2,
            playerTexureRegion, this.mEngine.getVertexBufferObjectManager()){
        @Override
        public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float X, float Y) 
        {
            //Not sure if I'm doing this right
            if (pSceneTouchEvent.isActionUp())
            {
                this.setPosition(X, Y);


            }else if(pSceneTouchEvent.isActionDown())
            {
                this.setPosition(X, Y);
            }else if(pSceneTouchEvent.isActionMove())
            {
                this.setPosition(X, Y);
            }
            return true;
        };
    };


    sPlayer.setRotation(45.0f);


    final FixtureDef PLAYER_FIX = PhysicsFactory.createFixtureDef(10.0f,
            1.0f, 0.0f);
    Body body = PhysicsFactory.createCircleBody(physicsWorld, sPlayer,
            BodyType.DynamicBody, PLAYER_FIX);

    //Set touch Area here
    this.scene.registerTouchArea(sPlayer);

    this.scene.attachChild(sPlayer);
    physicsWorld.registerPhysicsConnector(new PhysicsConnector(sPlayer,
            body, true, false));
    pOnPopulateSceneCallback.onPopulateSceneFinished();

}

Solution

  • on a first look, your touch event looks right - for a game without physics extension.

    in physics, you don't want to touch/move the sprite itself, instead you want to move the underlying (invisible) physics body - the one that is handled by your physicsengine, that reacts on collisions and is responsible to move your sprite depending on the physics.

    so, you are trying to make it the wrong way around with moving your sprite instead of your body. to move your body have a look at mouse joints: