Moving 2D Sprite from Position 1 to Position 2

Started by
0 comments, last by CodeCriminal 12 years, 2 months ago
I having a little trouble with moving sprites from position to position via mouse click. This was the first way I did it:

if (position1.X < position2.X)
position1.X += 1f;
if (position1.Y < position2.Y)
position1.Y += 1f;


The problem with that was obvious: the sprite would move diagonally, then horizontally/vertically to position2, so I had to try something new.

After that failed, I created a moveX and moveY variables:

moveX = (position2.X - position1.X) / position2.Y;
moveY = (position2.Y - position1.Y) / position2.Y;


The problem with this method is that it is continuously updating position1.X/Y creating a slight curve in the movement.

In the end, I'm not getting a straight-to position to position.
Advertisement
Sounds to me like your requirements are; upon mouse click a sprite should move towards the area clicked at a constant rate.
Heres how to do it:

* First, in some sort of mouse click event save the position clicked, we will call this position target of type Vector2
* Second, you need to find the direction your sprite should move in with a tiny bit of vector math, like so:-

Vector2 direction = (target - position); // gives the direction needed to travel from position to target
direction.Normalize( ); // we need it as a unit vector

* Finally, you want to move your sprite towards the clicked point by incrementing the position by the direction vector multiplied by some constant (in your case this seems to be 1f so we dont even need to do the multiplication but ill put it in there anyway as a speed scalar

position += direction * speed

and that will get you what (I think) you want.

EDIT: oh, sorry i forgot, to stop the sprite when it reaches its destination just check to see if the sprite is within a radius == speed from the target if so set the position = target and the speed / direction to zero.. like so:


if ((target-position).Length( ) <= speed)
{
position = target;
speed = 0;
}

This topic is closed to new replies.

Advertisement