I am coding a simulation of ball movement. I have an updateBall function which runs every 100 miliseconds to update the location of the ball.
How is the formula to find out the time in miliseconds needed to reach a given target coordinate? For example, given target x=100 y=200 the time needed to reach is approximately 5300ms.
Below is the relevant code snippet,
function calcDirection(a, b, c, d)
{ return 180 * Math.atan2(d - b, c - a) / Math.PI };
let ball = {x: 0, y: 0}
let targetX = 100;
let targetY = 200;
let velocity = 0.05;
let friction = 0.0003;
let direction = calcDirection(ball.x,ball.y,targetX,targetY); //63.43494882292201
let dx = targetX - ball.x;
let dy = targetY - ball.y;
let distance = Math.sqrt(dx*dx + dy*dy); //223.60679774997897
// runs every 100ms
function updateBall(){
if (velocity > 0) {
let pixelsPerLoop = velocity * 100;
ball.x += pixelsPerLoop * Math.cos(Math.PI/180 * direction);
ball.y += pixelsPerLoop * Math.sin(Math.PI/180 * direction);
velocity -= friction;
}
}
//answer: ( v0 (+/-) sqrt( v0^2 - 2.0*friction*dist ) )/(friction)
let v0 = velocity * 100;
let fric = friction * 100;
let p = Math.pow(v0, 2);
let q = 2.0 * fric * distance;
let r = p - q;
let s = Math.sqrt(r);
let t = ( v0 - s )/(fric);
// test run for loop times
let loop = Math.floor(t);
for (let i = 0; i < loop; i++)
updateBall();
document.getElementById('result').innerHTML = 'loop ' + loop + ', ball.x = ' + ball.x + ' ball.y = ' + ball.y;
<p id="result"></p>