Search code examples
libgdxtouchpad

Setting Linear Velocity for a body using TouchPad in LIBGDX


I have been following tutorial from this link for implementing touchpad in LIBGDX. I want to set the linear velocity for a body using touchpad . I tried updating the position as per this tutorial but the body is not moving smoother.

This is my code for setting up linear velocity,

public void knobinput(float dt)
{
 if(touchpad.getKnobPercentX()>0)
{
    gamehero.heroBody.setLinearVelocity(1.4f, 0);
}
else
{
    gamehero.heroBody.setLinearVelocity(-1.4f, 0);
}
}

When I implement this logic, the body started moving though I didn't give any inputs through touchpad. I want to set the linear velocity as per the above code when the knob is turned right and left but, I didn't know how to check if the knob is turned right or left. Please help. Thanks in advance.


Solution

  • You do not handle the situation when the touchpad is in it's zero position - I mean you have no code for stopping body there. Take a look at this fragment:

        else
        {
            gamehero.heroBody.setLinearVelocity(-1.4f, 0);
        }
    

    Even if you do not move the touchpad body has some velocity set.

    The best approach would be to set velocity directly based on touchpad position without any conditions like:

        gamehero.heroBody.setLinearVelocity(SPEED * touchpad.getKnobPercentX(), 
                                            SPEED * touchpad.getKnobPercentY());
    

    It will handle zero position of touch pad (and body will have (0, 0) velocity set as it should) and it's speed will be based on touchpad's position value also (what does mean that if you move a touchpad a little body will move slowly and if you will move touchpad to the edge it will move with maximum speed - also as it should I guess).

    SPEED variable should be the max speed that you need. In this case you can set SPEED = 1.4f for example.