I'm making a little game where you are a spaceship and you fly around in 2d using the A and D key to rotate and the W key to accelerate. Now my problem is if i turn my ship it doesn't go into the right direction, it is very random actually...

    public void update(GameContainer gc, int i) throws SlickException {
    Input input = gc.getInput();
    if(input.isKeyDown(Input.KEY_D)) {
        rotationDegree += 20;

    if(input.isKeyDown(Input.KEY_A)) {
        rotationDegree -= 20;

/// if(rotationDegree > 360) rotationDegree = 0;
//  if(rotationDegree < 0) rotationDegree = 360;
     rotationRadian = Math.toRadians(rotationDegree); 
    if(input.isKeyDown(Input.KEY_W)) {
         position.x = (float) (position.x + 3*Math.sin(rotationRadian/25));
         position.y = (float) (position.y + 3*Math.cos(rotationRadian/25));
  • 2
    \$\begingroup\$ Why are you dividing rotationRadians by 25? \$\endgroup\$ Commented Dec 15, 2013 at 14:30
  • \$\begingroup\$ Maybe you should check out this for rotating a vector: codepaste.net/zmjfkr \$\endgroup\$
    – RandyGaul
    Commented Dec 15, 2013 at 23:50

2 Answers 2


Here try this:

Vec2 Vec2::Rotated( real radians ) const
  real c = std::cos( radians );
  real s = std::sin( radians );

  real xp = x * c - y * s;
  real yp = x * s + y * c;

  return Vec2( xp, yp );

This shows how to rotate a vector given a scalar. You can use this knowledge to rotate a vector into the direction of the ship. You can then scale this vector (if it is normalized) by a distance (like speed) and move the ship along this vector.


I believe that you need to use cosine for x and sine for y , so it would be

position.x = (float) (position.x + 3*Math.cos(rotationRadian/25));
position.y = (float) (position.y + 3*Math.sin(rotationRadian/25));

But I don't know why you would divide by 25.

  • \$\begingroup\$ i divided by 25 to test something forget to take it out... i tried your code but it looks like the image is rotating slower than the pace at which it actually turns so by the time the image is 40 degrees, it is heading the way it should go when it had rotated 80 degrees.. (sorry for poor english and explanation) \$\endgroup\$
    – user39947
    Commented Dec 15, 2013 at 17:13

You must log in to answer this question.

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