Search code examples
andengine

Is it possible to have an Kinematic Body that moves along x axis, but still responds to user input to move it in y direction


Using andengine I'm trying to create a ball that will move across the screen at a set velocity, but I want to be able to move the ball when the user swipes up or down. This is what I have to move in x direction

FixtureDef BoxBodyFixtureDef =
            PhysicsFactory.createFixtureDef(20f, 0f, 0.5f);
    kinematicBody = PhysicsFactory.createBoxBody(mPhysicsWorld,
            mMarbleSprite, BodyType.KinematicBody, BoxBodyFixtureDef);
            mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
            mMarbleSprite, kinematicBody));

            kinematicBody.setLinearVelocity(1f, 0f);
            kinematicBody.setAngularVelocity((float) (-Math.PI));

and in onSceneTouchEvent I have

mMarbleSprite.setY(pSceneTouchEvent.getY());

I could move the Sprite easily before, but since adding velocity in x direction it does not respond to swiping screen. Thanks for any help


Solution

  • If you are connecting your sprite to physics world then you have to update your body than sprite as follows:

    kinematicBody.setTransform(pSceneTouchEvent.x/PTM_RATIO, pSceneTouchEvent.y/PTM_RATIO, 0);
    

    Then you have to update sprites position every time in your update Handler as follows: get all bodies in world Now get position of body then update sprite position

    Iterator<Body> it = bxWorld.getBodies();`
        while(it.hasNext()) {
                        Body b = it.next();
                        Object userData = b.getUserData();
    
                        if (userData != null && userData instanceof Sprite) {
                            //Synchronize the Sprites position and rotation with the corresponding body
                            final Sprite sprite = (Sprite)userData;
                            final Vector2 pos = b.getPosition();
                            sprite.setPosition(pos.x * PTM_RATIO, pos.y * PTM_RATIO);
                            sprite.setRotation(-1.0f * ccMacros.CC_RADIANS_TO_DEGREES(b.getAngle()));
    
                        }   
                    }