- Home /
Question by
boroj · Mar 13, 2021 at 06:12 PM ·
physicsprogramming
Having trouble implementing drag force
Hi! I am having trouble with implementing drag force when writing code for projectile motion for a ball that gets shot away. I only use differential equations to create movement and the gravitational and drag force, meaning no rigidbody component is involved. However, while the code for the gravitational force does its job, the code for the drag force makes the ball go back and forth. The ball never really moves in one direction and I am banging my head against the wall trying figure it out how to make it work. I wonder if anyone here could maybe help me? Here is the code:
void Start()
{
Mass = 0.3f;
DragCoeff = 0.47f;
Density = 1.2f;
radius = GetComponent<SphereCollider>().radius;
CrossSectionalArea = Mathf.Pow(radius, 2) * Mathf.PI;
Position = transform.position;
factors = 0.5f* DragCoeff * Density * CrossSectionalArea;
GravityForce = new Vector3(0, -9.81f*Mass, 0);
Velocity = new Vector3(0, 5, 0) + Camera.main.transform.forward * 20;
}
// Update is called once per frame
void FixedUpdate()
{ NormalizedVelocity = Velocity/Velocity.magnitude;
DragForce = factors * Mathf.Pow(Velocity.magnitude, 2)* - NormalizedVelocity;
NetForce = GravityForce + DragForce; //- DragForce;
Momentum = Momentum + NetForce * Time.fixedDeltaTime;
Velocity = Velocity + Momentum/Mass * Time.fixedDeltaTime;
Position = Position + Velocity * Time.fixedDeltaTime;
transform.position = Position;
}
Comment