Jump to content
  • Advertisement
Sign in to follow this  

Moving 2D Sprite from Position 1 to Position 2

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post

Link to post
Share on other sites
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;

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!