46
Graphics / Making a player change direction??
« on: September 12, 2011, 06:12:05 am »
Of course if you want to move the player to the clicked coords, you already have both beginning and endpoints, so you don't need angles.
The movement vector is newpoint - oldpoint. So in this case, newpoint would be the place the user clicked, and oldpoint would be the player's current position.
You then want to translate that into a "unit vector", which is a just a vector with a length of 1. You do this by dividing x and y by the length of the movement vector.
The length can be found with good old pythagorean's theroum:
So... in review, all of the above can be accomplished simply:
The movement vector is newpoint - oldpoint. So in this case, newpoint would be the place the user clicked, and oldpoint would be the player's current position.
You then want to translate that into a "unit vector", which is a just a vector with a length of 1. You do this by dividing x and y by the length of the movement vector.
The length can be found with good old pythagorean's theroum:
Code: [Select]
c*c = a*a + b*b
// or in this case:
c = sqrt( a*a + b*b );
So... in review, all of the above can be accomplished simply:
Code: [Select]
Vector2f newpoint; // the clicked position
Vector2f oldpoint; // the player's current position
Vector2f motion = newpoint - oldpoint; // the movement vector
float len = sqrt(motion.x * motion.x + motion.y * motion.y); // length of the movement vector
Vector2f unit = motion / len;
// that's it! Now to move the player in that direction, you just apply the speed:
playerposition += unit * speed;