0
\$\begingroup\$

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;
        System.out.println(rotationDegree);
    }

    if(input.isKeyDown(Input.KEY_A)) {
        rotationDegree -= 20;
        System.out.println(rotationDegree);
    }

/// 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));
         System.out.println(position.x);
         System.out.println(position.y);
    }
}
\$\endgroup\$
  • 2
    \$\begingroup\$ Why are you dividing rotationRadians by 25? \$\endgroup\$ – Jacek Przemieniecki Dec 15 '13 at 14:30
  • \$\begingroup\$ Maybe you should check out this for rotating a vector: codepaste.net/zmjfkr \$\endgroup\$ – RandyGaul Dec 15 '13 at 23:50
1
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

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.

| improve this answer | |
\$\endgroup\$
  • \$\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 Dec 15 '13 at 17:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.