Search code examples
javalibgdxbox2d

LibGDX Java set velocity at an angle


I have a problem with setting the velocity for a Body object at a certain angle (I want the body to move in a straight line at a given speed at a certain angle). The Body#setLinearVelocity method requires the X and Y directions. I don't know how to get these values from an angle (form -180 to 180 degrees). I will be grateful for your help!


Solution

  • To convert an angle to coordinates (of length 1) you can use this:

    // angle needs to be in radians. If it's in degrees multiply it by Math.PI / 180f
    angle = angleDegree * Math.PI / 180f;
    x = Math.cos(angle);
    y = Math.sin(angle);
    

    Then add these parameters to the setLinearVelocity method.