# Moving in the direction of rotation?

This topic is 1486 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am working on a 2D project that requires rotation and moving in the direction of rotation. I have managed to get the image to rotate but I am not able to move the image in the direction of rotation. I have had this problem for a couple of days now. Here is a snippet of the source code:

Object Info

static float shipx =  300f;

static float shipy =  300f;

static int shipspeed = 20;

Update Method

if(input.isKeyDown(Input.KEY_UP))

{

// What I am using to move in the direction of rotation, but I'm not having any luck.
shipx +=  (float) (shipspeed * Math.toRadians(Math.cos(angle)));

shipy +=  (float) (shipspeed * Math.toRadians(Math.sin(angle)));

System.out.println("X: " + shipx + " " + "Y: " + shipy);

}

else if(input.isKeyDown(Input.KEY_DOWN))

{

shipy += shipspeed;

}

else if(input.isKeyDown(Input.KEY_RIGHT))

{

angle += rotation;

Ship.setCenterOfRotation(Ship.getWidth() / 2, Ship.getHeight() / 2);

Ship.setRotation((float) angle);

}

else if(input.isKeyDown(Input.KEY_LEFT))

{

angle -= rotation;

Ship.setCenterOfRotation(Ship.getWidth() / 2, Ship.getHeight() / 2);

Ship.setRotation((float) angle);

}

I am not using any vector math or anything, just simple trig. Feel free to ask for more information if needed. Thanks.

##### Share on other sites

It looks like toRadians() should be inside cos(), not outside. The same for sinus.

##### Share on other sites

shipx +=  (float) (shipspeed * Math.toRadians(Math.cos(angle)));

shipy
+=  (float) (shipspeed * Math.toRadians(Math.sin(angle)));

should probably be:

shipx +=  (float) (shipspeed * Math.cos(Math.toRadians(angle)));

shipy +=  (float) (shipspeed * Math.sin(Math.toRadians(angle)));

EDIT: lol great minds. just a moment to late to be first with it =P

Edited by ryutenchi

##### Share on other sites

Hello guys, thanks for the quick responses I really appreciate it. I implemented what you guys suggested and I am still not getting the desired result. Here is extra information.

double rotation = 1.570796;
static double angle = Math.toRadians(Math.atan(shipx / shipy));

shipx +=  (float) (shipspeed * Math.cos(Math.toRadians(angle)));
shipy +=  (float) (shipspeed * Math.sin(Math.toRadians(angle)));

##### Share on other sites

I am not using any vector math or anything, just simple trig. Feel free to ask for more information if needed. Thanks.

Atan2 is not simple trig. Then you take the angle returned from atan2 and use it to call sin, cos.

This is one of my pet peeves.

USE VECTOR MATHS.

You turn a direction into an angle, then turn your angle into a direction. Is there any need for that? No USE VECTORS.

##### Share on other sites

What Paradigm Shifter said. Also, if you ever use angles, stick to radians. You seem to make lots of mistakes in converting between radians and degrees (the one pointed out by the first two responses, plus another one in converting the result of Math.atan to radians, when I am sure it was in radians to begin with). There is just no need to do any of those conversions.

If you don't know how to do something with vectors, ask.

##### Share on other sites

Alright so I am trying to utilize vectors math more in my projects. This is what I have so far...

Variables Data:

// Ship;
static float shipx =  300f;
static float shipy =  300f;
static float shipspeedx = 1f;
static float shipspeedy = 1f;
Vector2f Current = new Vector2f(shipx, shipy);
Vector2f Velocity = new Vector2f(shipspeedx, shipspeedy);

Update Method:

if(input.isKeyDown(Input.KEY_UP))
{
}

Problem is though the ship is moving diagonally. My plan is to make my resultant vector vertical so the ship moves up, but I think I was once told that resultant vectors can't be vertical.

##### Share on other sites

Vectors can be vertical you only get problems with tangents as they approach infinity, which vectors avoid. Vector away, hip hip array.

##### Share on other sites

Yeah, you want some sort of vector that represents direction, preferably normalized, then you can just do things like

if(input.isKeyDown(Input.KEY_UP))
{

this.velocity += this.direction * this.thrustAmt;

}

Though technically it would probably work better if you were adjusting the acceleration, and you probably want a deltaTime in there, and a cap to the velocity.

##### Share on other sites

@ferrous, thanks for the reply.

I am confused at what the

this
keyword does in Java. From my understanding its similar to C++ reference operator (&) ? Is this correct?

##### Share on other sites

I am confused at what the

this
keyword does in Java. From my understanding its similar to C++ reference operator (&) ? Is this correct?

Ein?? Wouldn't it by similar to the C++ this' keyword?

##### Share on other sites
Hello.
Firstly, I would suggest sticking to your first attempt: changing an angle and using that angle to determine the X and Y components to move your ship with.

Secondly, I believe your input logic is incorrect. You are checking each successive key only if the previous ones are not pressed. The keys in this case are depending on the state of the previous ones, and they usually shouldn't.

You should instead act separately on each key, or at least not chain them all in the same IF block:

boolean upKey	 =	input.isKeyDown( INPUT.KEY_UP )
boolean downKey	 =	input.isKeyDown( INPUT.KEY_DOWN )
boolean rightKey =	input.isKeyDown( INPUT.KEY_RIGHT )
boolean leftKey	 =	input.isKeyDown( INPUT.KEY_LEFT )

// Only work the "up" action if UP is pressed and DOWN is NOT pressed.
if( upKey && !downKey ) {

shipX += ( float ) ( shipSpeed * Math.cos( Math.toRadians( angle ) ) )
shipY += ( float ) ( shipSpeed * Math.sin( Math.toRadians( angle ) ) )

System.out.println( "X: " + shipX + " " + "Y: " + shipY );

}

// Only work the "down" action if DOWN is pressed and UP is NOT pressed.
if( downKey && !upKey ) {

// Note you still need the components in the same direction as the ship, only negated.
shipX -= ( float ) ( shipSpeed * Math.cos( Math.toRadians( angle ) ) )
shipY -= ( float ) ( shipSpeed * Math.sin( Math.toRadians( angle ) ) )

}

// Only work the "right" action if RIGHT is pressed and LEFT is NOT pressed.
if( rightKey && !leftKey ) {

angle += rotation;

Ship.setCenterOfRotation( Ship.getWidth() / 2, Ship.getHeight() / 2 );
Ship.setRotation( ( float ) angle );

}

// Only work the "left" action if LEFT is pressed and RIGHT is NOT pressed.
if( leftKey && !rightKey ) {

angle -= rotation;

Ship.setCenterOfRotation( Ship.getWidth() / 2, Ship.getHeight() / 2 );
Ship.setRotation( ( float ) angle );

}
Edited by Kryzon

##### Share on other sites

Why not just split that up to two If/elses?  It's the same logic, minus the redundant boolean checking.

if( rightKey )
{
}
// Only work the "left" action if LEFT is pressed and RIGHT is NOT pressed.
else if( leftKey )
{
}

EDIT:  After having my coffee, it seems you just want to have it do nothing when both arrow keys are held down, which is mostly a non-concern, but if you really wanted a non-event to happen you can rearrange to be even cleaner;

float angle = 0.0f;
if( rightKey )
{
angle += rotation;
}
if( leftKey )
{
angle -= rotation;
}
if(angle != ApproximatelyZero )
{
Ship.setCenterOfRotation( Ship.getWidth() / 2, Ship.getHeight() / 2 );
Ship.setRotation( ( float ) angle );
}
Edited by ferrous

##### Share on other sites

if( rightKey )
{
angle += rotation;
}
else if( leftKey )
{
angle -= rotation;
}

Hello.
In this case I believe the right key would have dominance.
Consider the left key being pressed and the ship turning in the left direction. If the right key is then pressed, the ship will start turning to the right whether left is still pressed or not.
It is a particular behaviour that I don't like. Consequently, I prefer to remove it. Edited by Kryzon

##### Share on other sites

You can get around that by doing

if(right pressed) ang velocity += some amount;

if(left pressed) ang velocity -= some amount

newang = oldang + ang velocity

##### Share on other sites

if( rightKey )
{
angle += rotation;
}
else if( leftKey )
{
angle -= rotation;
}
Hello.
In this case I believe the right key would have dominance.
Consider the left key being pressed and the ship turning in the left direction. If the right key is then pressed, the ship will start turning to the right whether left is still pressed or not.
It is a particular behaviour that I don't like. Consequently, I prefer to remove it.

Yeah, sorry, half assed cut and paste job, lose the 'else' as the poster above outlined.

The nice part is that if you ever move to an analog stick or other fuzzy device, it's trivially easy to swap to.

Edited by ferrous

##### Share on other sites

I appreciate the reply's Kryzon and ferrous.

@Kryzon, I am curious on why you recommended the first attempt better because Paradigm Shifter recommended I use vectors, which is a good suggestions for future projects.

In terms of controls, I want my controls to be similar to the original asteroid where the UP arrow key is the only button that accelerates the ship right, left, up, down, left or right depending on the direction of rotation. I made a direction vector that had the ship coordinates:

Vector2f Direction = new Vector2f(shipx, shipy);

then used the Direction vector to render the ship:

public void render(GameContainer gc, Graphics g)
{
g.drawImage(Ship, Direction.x, Direction.y);
}

followed ferrous advice and normalized the Direction in the update method so I could use the vector to focus on the direction instead of the magnitude

public void update(GameContainer gc, int delta)
{

if(Pressed Key Up)
{
Direction.normalize();
Velocity.y += Direction.y + thrust;
}

}

when that didn't work I used the following method

Variables

static float shipx = 300f;
static float shipy = 300f;
static float posx = shipx;
static float posy = shipy;
static float speedx = 0.3f;
static float speedy = 0.3f;
Vector2f SpaceShip = new Vector(shipx, shipy);
Vector2f Direction = new Vector2f(posx, posy);
Vector2f Velocity = new Vector2f(speedx, speedy);

Render Method

public void render(GameContainer gc, Graphics g)
{
g.drawImage(Ship, SpaceShip.x, SpaceShip.y);
}

Update Method

public void update(GameContainer gc, int delta)
{

if(Pressed Key Up)
{
Direction.normalize();
SpaceShip.x += Velocity.x * Direction.x;
SpaceShip.y += Velocity.y * Direction.y;
}

}

Pretty confused on how I should properly execute this?

Edited by Czar05

##### Share on other sites

@Kryzon, I am curious on why you recommended the first attempt better because Paradigm Shifter recommended I use vectors, which is a good suggestions for future projects.

Hello.
In my experience the first approach is simpler, so it works best when you're starting on this subject.
Note that it still uses vectors: Your position is a vector; the velocity that you are adding to this position is also a vector, one that was rotated (or transformed) based on the angle that the ship is facing.

In terms of controls, I want my controls to be similar to the original asteroid where the UP arrow key is the only button that accelerates the ship right, left, up, down, left or right depending on the direction of rotation.

I don't understand this statement very much.

I made a direction vector that had the ship coordinates:

Vector2f Direction = new Vector2f(shipx, shipy);
then used the Direction vector to render the ship:
public void render(GameContainer gc, Graphics g)
{
g.drawImage(Ship, Direction.x, Direction.y);
}
followed ferrous advice and normalized the Direction in the update method so I could use the vector to focus on the direction instead of the magnitude
public void update(GameContainer gc, int delta)
{

if(Pressed Key Up)
{
Direction.normalize();
Velocity.y += Direction.y + thrust;
}
}

It's not working because every time the UP key is hit, you are normalizing the same vector that you're using to draw the ship. If the ship had started at the center of the screen, like [400, 300] in an 800x600 screen, the ship would then be placed at something like [0.8, 0.6] after the Direction vector is normalized. I also think you should name that Position, not Direction.

Pretty confused on how I should properly execute this?

I would do something along these lines. I don't know Java, so you'll have to interpret the following:
public class Ship {

public float moveSpeed = 1.0f;
public float turnSpeed = 1.5f;

public float angle = 0f;
public Vector2f position;

public Sprite shipSprite;

public Ship( posX, posY ) {

position = new Vector2f( posX, posY );
shipSprite = new Sprite( ..... );

}

public update( GameContainer gc, int delta ) {

if( input.isKeyDown( INPUT.KEY_RIGHT ) {

angle += turnSpeed;

}

if( input.isKeyDown( INPUT.KEY_LEFT ) {

angle -= turnSpeed;

}

shipSprite.setCenterOfRotation( Ship.getWidth() / 2, Ship.getHeight() / 2 );
shipSprite.setRotation( ( float ) angle );

if( input.isKeyDown( INPUT.KEY_UP ) ) {

position.x += moveSpeed * Math.cos( Math.toRadians( angle ) );
position.y += moveSpeed * Math.sin( Math.toRadians( angle ) );

}

}

public render( GameContainer gc, Graphics g ) {

g.drawImage( shipSprite, position.x, position.y );

}

}
You should post this sort of question in the Game Programming forum, where it will receive more attention.
Make sure to specify that you're using Java: http://www.gamedev.net/forum/11-game-programming/ Edited by Kryzon

##### Share on other sites

@ferrous, thanks for the reply.

I am confused at what the

this
keyword does in Java. From my understanding its similar to C++ reference operator (&) ? Is this correct?

this keyword in Java refers to the given class of where the this keyword was written inside.

For example, if the this keyword was stated in the Dog class, the this keyword refers to the Dog class.

To make you understand how the this keyword works in Java, let's say you have an instance variable called life that is of type int in the Dog class.

you would write "this.life" in the Dog class to refer to the instance variable called life of that class called Dog.

this.life refers to the instance variable called life

public class Dog
{

// instance variable
private int life;

// life as a parameter of the Dog constructor
public Dog(life)
{

// parameter assigns to the instance variable
this.life = life;

}

Alternatively, you do not even need to write this.life to refer to the instance variable if and only if the instance variable and parameters are not the same name.

Edited by warnexus

##### Share on other sites

Thanks @warnexus, I have a better understanding of the

this
keyword.

##### Share on other sites

Ok here we go:

Imagine you have a ship with a position and a speed

class Ship
{
public:
vec2 position;
vec2 direction;
vec2 velocity;
}
Ship ship;

Ignoring the bad OO setup, we now want to rotate the ship, and the move the ship.
// Rotate vector by an angle
// remember to either create a new vector by doing this, or make a copy of the old one, as you require both x and y
ship.direction = vec2(cos(angle) * ship.direction.x - sin(angle) * ship.direction.y,
sin(angle) * ship.direction.x + cos(angle) * ship.direction.y);
// .. and we don't need to normalize, because cos() and sin() already makes it unit length 1

// If we are using the ships engines, we are adding thrust
// Add speed towards the direction the ship is facing
float thrust = 0.1f;
ship.velocity += ship.direction * thrust;

// And move the ship by its constant velocity each 'tick'
ship.position += ship.velocity;

// Let's check if our round ship is too close to a round object
float ship_radius = 2.0f;
float object_radius = 2.0f;

// create new vector which we will be measuring the length off of
// another method is to use an existing distance() function from a library
float dist = (ship.position - object.position).length();
// or..
float dist = distance(ship.position, object.position);

{
// the ship is too close to the object
// here we can calculate a tangent and bounce the ship if we wanted too
}

I just wrote that up, so there may be errors

It's also not the best way to rotate a ship, admittedly. It works though!

Edited to fix some issues.

Edited by Kaptein

##### Share on other sites

vec2 speed;

The vector is called velocity'; `speed' is the length of the velocity.

Ignoring the bad OO setup, we now want to rotate the ship, and the move the ship.
// To rotate by an angle, first get old angle
old_angle = atan2(direction.y, direction.x);
// Add new angle
ship.direction.x = cos(angle + old_angle);
ship.direction.y = sin(angle + old_angle);
// .. and we don't need to normalize, because cos() and sin() already makes it unit length 1

That is pretty awful. That's the method I came up to do rotations when I was 11. I think it was OK as a first effort by a kid, but it's ridiculously wasteful.

This is much more reasonable:

rotated.x = cos(angle) * original.x - sin(angle) * original.y;
rotated.y = sin(angle) * original.x + cos(angle) * original.y;

And you should probably encode the rotation as (cos(angle), sin(angle)) instead of just the angle. In that case applying a rotation is four products and two additions, instead of the really expensive calls to atan2(), sin() and cos().

If you represent (x, y) by the complex number (x + y*i), the formula is simply

rotated = original * (cos(angle) + sin(angle) * i)

And if your rotation was already stored as a unit-length complex number, it would simply be

rotated = original * rotation;

// Let's check if our round ship is too close to a round object
float ship_radius = 2.0f;
float object_radius = 2.0f;

// create new vector which we will be measuring the length off of
// another method is to use an existing distance() function from a library
float dist = (ship.position - object.position).length();
// or..
float dist = distance(ship.position, object.position);

{
// the ship is too close to the object
// here we can calculate a tangent and bounce the ship if we wanted too
}

You should compute the square of the distance and compare that to the square of the sum of the radii. That way you avoid computing an expensive square root.

##### Share on other sites

Some things to think about in addition to Alvaro's good points:

You should probably cap the ship's Velocity, or it's going to get going uncontrollably fast.  (The easiest way is to check the length of the velocity vector, if it's over some maximum value, then normalize your velocity vector and multiply it by the maximum value)

You should probably decay the ship's Velocity, so it will slow down when not receiving any thrust.  (If you're not doing true space physics)  Easiest way is to just take the current velocity and multiply it by some number less than 1, like 0.9 or something.  Play with a value til you get one you like.

Depending on the max velocity, you may want to do a more complicated form of collision, if you're moving fast enough and the other object's radius is small enough, you'll move 'through' it.

EDIT:  And you should probably have a delta time in your calculations as well, or you'll get different behavior depending on how fast the computer running the program is.

Edited by ferrous

##### Share on other sites

I didn't know the rotation thing, actually. Speed was a mistake (, I know better).

Many thanks for the pointers, it was meant as a good basis to get something moving and rotating on the screen.

So, no delta and no velocity caps.

I will edit. (I did not end up optimizing the distance_squared thing, simply because the concept is most important.)

Edited by Kaptein

##### Share on other sites

Turns out I was on the right course on the first couple of attempts. My problem was really an image issue not a mathematical one. Lol

Thank you everybody for all your input. Each one of your responses was insightful and I appreciate your thoughtful responses.