# How can I move an object in a direction other than the ordinals?

I want to move a game object from its current position to the mouse position, but my current code only ever moves in one of the eight ordinal directions. In other words, I want it to move along the red path, but I only know how to move it along the white path. Here's my code:

while(cont){
if(x1 > x){
x++;
}else if(x1 < x){
x--;
}
if(y1 > y){
y++;
}else if(y1 < y){
y--;
}
frame.repaint();
}
// x1 y1 - mouse position
// x, y - sprite position


What am I missing?

The white vector is the correct vector with the code you have. If you're only ever adding integers to your position, the movement is going to be at increments of 45 degrees. That's restricted to orthogonal and diagonal movement only. If you want free movement you should be normalizing the movement vector.

Check to see if the libraries you're using have a vector class with a normalization method, or create your own. Then you can move your sprite by the normalized vector:

Vector2 movementVec = (target-position).normalized();

• Thanks! Ok maybe there are game engine that have a vector class with a normalization method? Sep 14, 2014 at 15:02
• @user3334375 to that effect, most game engines should have normalized vector capaabilities, but it shouldn't be that hard to do yourself using angles and possibly some equations such as the Pythagorean Theorem.
– Pip
Sep 14, 2014 at 15:11
• Also how my sprite will know that he should move by movementVec vector? Sep 14, 2014 at 15:11
• Yes I understand, but how can my sprite move by movementVec? I think that sprite movement represent x and y coordinates but what I need to do with movementVec? Sep 14, 2014 at 15:14
• Just like you've done in your code, you add the movement vector to the position of the sprite. So, for X for example, instead of ++ you'll use += movementVec.x. Sep 14, 2014 at 15:27