Question

All I need is to claculate the new coordinites of a player based on a click and have the player move towards it smoothly. For example player is at (20, 20) and you click at (50, 80) how would i get it to move smoothly. I have tried many different thing mostly based on the pythagorean formula trying to calculate the new coord's by finding the hypotenuse then finding the same triangle with a smaller hypotenuse but there must be an easier way.

Was it helpful?

Solution

You can:

  1. Calculate the slope of the line segment formed by the origin and destination.
  2. For each time period until you reach the destination, adjust the new coordinate based on the slope calculated in step 1.

OTHER TIPS

Although I program in javascript, you should be able to read and understand it

function move(x1,y1,x2,y2,speed){//executed each time frame. Returns coords as array [x,y]
   if(!speed)speed=1;
   var dis=Math.sqrt(Math.pow(x1-x2)+Math.pow(y1-y2));
   return [(x1-x2)/dis*speed,(y1-y2)/dis*speed];
}

The speed is constant at however many units per frame and it will stop when it reaches its destination. It might shake a little but that can be easily fixed.

EDIT: I forgot to mention. This function returns velocity. Not the coordinates

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top