# 3D trajectoiry prediction miscalculations

Discussion in 'Scripting' started by AlessandroCavaglia, Jul 9, 2020.

1. ### AlessandroCavaglia

Joined:
Sep 19, 2019
Posts:
1
Hello, i'm trying to render a line on the trajectory that my object will take, i have made a sample code that works but is really unprecise, i have followed some tutorial but many of them don't take in count the mass of the object and the drag so i hat to improvise, here is my code:

Code (CSharp):
1. Vector3 calculate(Vector3 velocity, float time, Vector3 position,Rigidbody body)
2.         {
3.             Vector3 Vxz = velocity;
4.             Vxz.y = 0f;
5.             float drag = 1f - (time * body.drag);
6.             Vector3 result = position + velocity * time;
7.             result.y=  ((-0.5f * Math.Abs(Physics.gravity.y) * (time * time)) + (velocity.y * time) + position.y) *drag;
8.             return result;
9.         }
I call this function for every point of the line and it gives a rough idea of where the object will be going, usually the object goes less further than the line, does anybody know what is wrong?

2. ### rubcc95

Joined:
Dec 27, 2019
Posts:
33
Well, you're only applying the drag at result.y. Drag brakes Rigidbody at all directions, thats why your gameobject goes less further than your calcs. Try with this:
Code (CSharp):
1.     Vector3 Calculate(Vector3 velocity, float time, Vector3 position, Rigidbody body)
2.     {
3.         float drag = 1f - (time * body.drag);
4.         if (drag < 0) drag = 0;
5.         Vector3 result = ((0.5f * Physics.gravity * Mathf.Pow(time, 2)) + (velocity * time) + position) * drag;
6.         return result;
7.     }
I don't know what Vector3 Vxz was doing there, so I removed it. Math.Abs takes an extra calculation, and would have some issue if you change your gravity to a positive number. Gravity by default is negative, so with a minus sign at the start of the multiplication is enough.
Since Physics.gravity at x and z is by default 0... the formula will keep as your initial one (position + velocity * time) at this axis, but with the drag applied. Also if you like to change the gravity of your environment, calcs will be right.

3. ### rubcc95

Joined:
Dec 27, 2019
Posts:
33
Forgot to say you that Rigidbody mass doesn't affect to the path followed. It only affects to how much velocity the Rigidbody gets when a force is applied... So this tutorial you followed are right, we don't have to take it in count if we know the velocity.
For a velocity calculation if you applies a ForceMode.Impulse, the initial velocity is the acceleration at Newton formulations:
rb.velocity = Vector3 force / rb.mass;

unityunity