I am making a 2d game in which a ball (B)is fired in air and it is attracted to an (A)object by a force with a constant magnitude and i have to predict the path which the ball will follow after it is fired. What i know is the initial position of the ball ,the velocity with which it(B) is fired ,mass of the ball, acceleration which (A) will produce in B . And i want to know where the ball will be after t sec if it is fired with a velocity v, direction in which the ball fired is also known.
Its different than planets as the force by which they are attracted varies with distance but here force is constant.
I just want to know the math to calculate the ball’s position after t seconds in a 2d plane. Thanks in advance!!
This answer assumes you’re using built-in physics interactions based around FixedUpdate() timing and AddForce() to move the object toward the source of gravity.
For the timespan you’re looking to represent t
, multiply that by the number of physics frames you’re going to predict 1.0f / Time.fixedDeltaTime
. That’s how many calculations you’ll want to make. For example, using Unity’s default of 50 physics frames per second, this would mean 500 calculations for a 10-second prediction.
Then, for each predicted frame, make the changes to the object’s predicted velocity v
and add that to the new predicted position p
.
Vector2 v = startingVelocity;
Vector2 p = startingPosition;
Vector2 o = attractorObject.transform.position;
Vector2 g = attractorGravityForce;
float physRate = 1.0f / Time.fixedDeltaTime;
for(int i = 0; i < timespan * physRate; i++)
{
// Apply gravity
v += ((o - p).normalized * g) * Time.fixedDeltaTime;
// Update position
p += v * Time.fixedDeltaTime;
}
Every time p is updated per loop is a new position it would be in at the end of each frame. Write those into an array or List and you have a basic trajectory prediction.
To note: The key difference between non-constant and constant force is normalizing the vector between the two objects. Once normalized and given a fixed force, distance no longer applies.