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.

red line directly to target, white takes a detour

Here's my code:

    if(x1 > x){
    }else if(x1 < x){
    if(y1 > y){
    }else if(y1 < y){
    sleep(); // Thread.sleep(200)
// x1 y1 - mouse position
// x, y - sprite position

What am I missing?


1 Answer 1


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();
  • \$\begingroup\$ Thanks! Ok maybe there are game engine that have a vector class with a normalization method? \$\endgroup\$ Sep 14, 2014 at 15:02
  • \$\begingroup\$ @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. \$\endgroup\$
    – Pip
    Sep 14, 2014 at 15:11
  • \$\begingroup\$ Also how my sprite will know that he should move by movementVec vector? \$\endgroup\$ Sep 14, 2014 at 15:11
  • \$\begingroup\$ 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? \$\endgroup\$ Sep 14, 2014 at 15:14
  • \$\begingroup\$ 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. \$\endgroup\$
    – House
    Sep 14, 2014 at 15:27

You must log in to answer this question.

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