Home > Back-end >  Find minimum velocity needed to reach a given coordinate?
Find minimum velocity needed to reach a given coordinate?

Time:09-18

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 could i find out the minimum velocity needed to reach a given target coordinate? Below is the relevant code,

ball.x = 0;
ball.y = 0;

targetX = 100;
targetY = 200;

friction = 0.03;

dx = targetX - ball.x;
dy = targetY - ball.y;
distance = sqrt(dx*dx   dy*dy);
velocity = ?;

// runs every 100ms
updateBall()
{
  ball.x  = velocity;
  ball.y  = velocity;

  velocity -= friction;
}

CodePudding user response:

It seems wrong that you apply friction to both components separately - in this case ball can stop vertically but move horizontally - looks strange, doesn't it?

Is is worth to apply acceleration to velocity vector. Seems you have straight moving - so you can precalculate coeffients for both components.

Concerning needed velocity:

distance = sqrt(dx*dx   dy*dy)
v_final = v0 - a * t = 0        so   t = v0 / a
distance = v0 * t - a * t^2 / 2      substitute t and get
distance = v0^2 / (2a)        
  and finally initial velocity to provide moving at distance
v0 = sqrt(2*distance*a)

where a is acceleration proportional to your friction accordingly to elementary interval dt (100 ms ).

friction = a * dt
a = friction / dt

v0.x = v0 * dx / distance = v0 * coefX
v0.y = v0 * dy / distance = v0 * coefY

at every stage you update v value and get components

v = v - friction
v.x = v * coefX
v.y = v * coefY
  • Related