I'm working on a game using Libgdx, I've create my world, bodies, fixtures etc. Everything is functional everything is working perfectly but the problem is my body just can left-right-up or down and I do not want to just do this, I want my body go toward to its front side, so it will be like that; User press "D" and Body (player) rotate around and user press "W" body should go wherever its looking direction.

The picture maybe will tell you what is the problem more clearly.

sample move forward pic

I do not think to share any code blocks because I didn't write any specific code, I just wrote body properties etc. you know. But here is my update method;

     public void update(float dt) {
       if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
            player.getBody().setLinearVelocity(0f, 0.5f);
       if (Gdx.input.isKeyPressed(Input.Keys.D)) {

And if it is possible, I don't want to use body.setTransform() method for move my bodies.


1 Answer 1


Let's take your image as an example and make a triangle out of it (no hate on drawing skills haha).


By treating this problem like a triangle we can apply some trigonometry to this problem and calculate X and Y assuming we know Velocity and a (angle) (which we do!).


float velocity = ...; // Your desired velocity of the car.
float angle = body.getAngle(); // Body angle in radians.

float velX = MathUtils.cos(angle) * velocity; // X-component.
float velY = MathUtils.sin(angle) * velocity; // Y-component.

body.setLinearVelocity(velX, velY);

I'm not awfully good at explaining (feel free to edit my answer if you wish), so I'm going to reference you to the Wikipedia entry for Trigonometric Functions if you wish to read more on the subject.

  • \$\begingroup\$ Thank you for your reply, this help me so much actually It is exactly what I am looking for and I will mark it as answer. It's working perfectly BUT another problem is as if my body's look at the side right direction, so, when I press 'W' it's going to right side but it should go to the top side so wrong rotated how can I solved this ? Is there a way to set it like setOrign() method ? And this picture will help you to got it. the picture \$\endgroup\$ Aug 10, 2016 at 10:27
  • \$\begingroup\$ Could you try using float angle = -body.getAngle()(negative angle) and see if this fixes it? \$\endgroup\$
    – Charanor
    Aug 11, 2016 at 15:16
  • \$\begingroup\$ Thanks for your suggestion it didn't work, anyway I rotated my bodies when I create them and it is working now. I hope it will not give a problem in the future. Thanks a lot again. \$\endgroup\$ Aug 11, 2016 at 15:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .