Jump to content

  • Log In with Google      Sign In   
  • Create Account


Moving 2D Sprite from Position 1 to Position 2


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 Froggggy   Members   -  Reputation: 100

Like
0Likes
Like

Posted 25 January 2012 - 08:09 PM

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.

Sponsor:

#2 roadysix   Members   -  Reputation: 290

Like
1Likes
Like

Posted 25 January 2012 - 08:27 PM

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;
}





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS