Skip to content

Instantly share code, notes, and snippets.

@ksnabb
Created September 29, 2014 19:07
Show Gist options
  • Save ksnabb/2fe8f693665e2f764b6e to your computer and use it in GitHub Desktop.
Save ksnabb/2fe8f693665e2f764b6e to your computer and use it in GitHub Desktop.
Calculate current position according to start point destination point speed and time
// calculate a new point according to start point, destination, speed and time.
(function(root) {
// start and destination are points given as arrays of length 2
// speed is in m/s
// time is in seconds
var currentPosition = function(start, destination, speed, time) {
var distanceTravelled = speed * time;
// calulate the diff x and diff y to be travelled
var diffx = destination[0] - start[0];
var diffy = destination[1] - start[1];
// calculate the direction in degrees
var degrees;
if(diffx === 0) {
if(diffy < 0) {
// just deturn start point with the distance travelled reduced from y
start[1] -= distanceTravelled;
return start;
} else {
start[1] += distanceTravelled;
return start;
}
} else {
degrees = Math.atan(diffy / diffx);
}
// calculate the x distance travelled
var xTravelled = Math.sin(degrees) * distanceTravelled;
var yTravelled = Math.cos(degrees) * distanceTravelled;
return [xTravelled, yTravelled];
};
root.currentPosition = currentPosition;
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment