So what I’m trying to accomplish is adding a debug line to a spring so I don’t have to blindly guess where my player will end up when they hit it. Right now the spring is launching the player at transform.up * force, and what I’d like to do is calculate the trajectory from that.
I’m having a bit of a hard time finding anything specifically on this as everything I find is either entirely in 2D or is based on distance between two points rather than on the angle and force of the velocity.
Right now I have variables set up for the player’s gravity, mass, and drag, but what I need to know is how to A) calculate how far the player will be sent based on those combined with the angle and force of the spring, and B) draw either the path or the destination in scene view while the game isn’t in play mode.
Check out this site, it has the formulas you will need to use.
First off, barring non-linear gravitational force application (around a sphere) and external forces (wind), trajectory calculations fundamentally ARE two-dimensional. Trajectory can be separated into horizontal and vertical segments.
Without factoring in drag (as that makes potential calculations exceptionally more complicated) or obstructions, I’ll refer you to [a previous answer I provided on this subject][1]. There, I outline predicting the basic trajectory going from point A to point B based on time-to-target, a specific angle, or a specific launch speed (the second and third of which have potential failure states if they can’t actually reach the target).
To display the basic path that the object will take (generally ignoring obstructions, but factoring in drag), you can recreate the per-frame physics updates and draw your line based on the resulting array of positions:
// C#
// Vector3 position - The starting position for the launch
// Vector3 velocity - The initial velocity
// Vector3 gravity - e.g. Physics.gravity
// float drag - The "drag" value on the Rigidbody
// float time - The amount of time to demonstrate in the trajectory preview
public static Vector3[] PreviewTrajectory(Vector3 position, Vector3 velocity, Vector3 gravity, float drag, float time)
{
float timeStep = Time.fixedDeltaTime;
int iterations = Mathf.CeilToInt(time / timeStep);
if(iterations < 2)
{
Debug.LogError("PreviewTrajectory(Vector3, Vector3, Vector3, float, float): Unable to preview trajectory shorter than Time.fixedDeltaTime * 2");
return new Vector3[0];
}
Vector3[] path = new Vector3[iterations];
Vector3 pos = position;
Vector3 vel = velocity;
path[0] = pos;
float dragScale = Mathf.Clamp01(1.0f - (drag * timeStep));
for(int i = 1; i < iterations; i++)
{
vel = vel + (gravity * timeStep);
vel *= dragScale;
pos = pos + (vel * timeStep);
path *= pos;*
-
}*
-
return path;*
}
[1]: 3D Trajectory Prediction - Questions & Answers - Unity Discussions