- Home /
Question on Negating Physics Drag
Hello everyone, if / how I could make a non-kinematic rigid body be able to accelerate at a set rate regardless of drag. Essentially taking something like this:
thisRigidbody.AddForce (acellerationSpeed, ForceMode.Acceleration);
And having it become something like this:
thisRigidbody.AddForce (acellerationSpeed + the current Drag value retarding acceleration, ForceMode.Acceleration);
What I'm trying to achieve: Essentially I have a non-kinematic rigid body boat, and I would like to be able to have it accelerate at a constant rate regardless of Drag up to a maximum speed (or a % of that max speed), but still have drag so that when the acceleration conditions are no longer met, the boat will slow down (and I can change how fast it does that with Drag).
You'll see below that I have done a simple if / else where if the boat is accelerating the Drag is 0, then when the player is trying to slow down, Drag is applied. It works until the boat turns, and of course at that point since Drag is 0 it will drift endlessly...so it has some drawbacks.
void Update ()
{
if(slider.value > 0f && thisRigidbody.velocity.z < (maxSpeed * slider.value) && thisRigidbody.velocity.z < maxSpeed)
{
//thisRigidbody.drag = 0f;
time += Time.fixedDeltaTime;
//Debug.Log ("maxspeed * slider.value is:" + (maxSpeed * slider.value));
thisRigidbody.AddForce (acellerationSpeed, ForceMode.Acceleration);
}
/*
else if (thisRigidbody.velocity.z > (maxSpeed * slider.value))
{
thisRigidbody.drag = 0.2f;
}
*/
Debug.Log ("Current fixed time is: " + time);
Debug.Log ("Current Cube Velocity is: " + thisRigidbody.velocity);
}
Any ideas are appreciated, thank you for reading.
You can directly add velocity to the rigidbody lets assume you want to move your boat in z direction
rigidBody.velocity = new Vector3(0,0,acellerationSpeed);
This willmake your boat go in a constant speed.
And when you want to slow down your boat just reduce the velocity
True enough, I was just hoping to not have to worry about slowing the object down manually...I probably just being lazy.
Answer by Bunny83 · Oct 07, 2014 at 12:33 PM
It's way easier to apply a directed drag yourself:
void FixedUpdate()
{
var vel = rigidbody.velocity;
var localVel = transform.InverseTransformDirection(vel);
var drift = localVel;
// remove the forward component when accelerating
if (accelerating)
drift.z = 0;
// transform back to worldspace and invert
var drag = -transform.TransformDirection(drift);
drag *= someDragFactor * Time.deltaTime;
rigidbody.velocity = vel + drag;
}
This is just some kind of pseudo code. "accelerating" is your condition if you accelerate at the moment and "someDragFactor" is a float you might want to modify to control the amount of drag.
Note: When dealing with continous forces or velocity you should do your calculations in FixedUpdate. FixedUpdate is the physics update loop. It ensures a constant behaviour regardless of the framerate.