- Home /
ConstantForce and making an object have a constant velocity
Hi there, I've been experimenting with trying to move a rigidbody at a constant velocity.
Initially I applied a force in FixedUpdate, then scaled up the drag of the object relative to it's velocity, so the faster it is the more drag is applied:
referenceToRB.AddForce (Vector3.right * 5.0f, ForceMode.Force);
float drag = ReturnNormalisedVelocity () * maxDrag;
drag = Mathf.Clamp(drag, 0.0f, maxDrag);
referenceToRB.drag = drag;
However the object kept accelerating. I also tried an alternative method and called the following in void Start () - so one call:
referenceToRB.AddForce (Vector3.right * 5.0f, ForceMode.VelocityChange);
Again the object kept accelerating. But I then read about a little known class called ConstantForce - just what I was looking for (or so I thought):
http://docs.unity3d.com/Documentation/ScriptReference/ConstantForce.html
constantForce.force = Vector3.right * 5.0f;
However, the object still doesn't appear to be traveling at a constant velocity (it keeps increasing in velocity). I've turned off other forces such as gravity and set the the object and the object it moves across physics materials to 'ice', but still it behaves the same.
Am I misunderstanding the point of this function or just using it incorrectly?
Thanks Ant
Answer by Fattie · Sep 28, 2013 at 09:55 AM
TBC Are you aware you can simply set the velocity?
if you want to make it emergent, just do this:
targetVelocity = whatever meters per second
tolerance = 0.05 //say 5 %
vt = targetVelocity*tolerance
currentSpeed
if ( currentSpeed < targetVelocity-vt )
slightly increase the force, break
if ( currentSpeed > targetVelocity+vt)
slightly decrease the force, done
that's it. you could vary the drag in realtime, and the "pilot" above will compensate
do this in FixedUpdate (purely for calculation convenience) or do it in Update (and apply the frame time appropriately)
PS are you familiar with ConstantForce (look inspector and doco). it can be useful in situations like this
Thanks for the response. The problem I'm having is that if I use a force to move the object (even with your above code) the object moves but also 'judders' as if it's moving a little differently each time (the result being it appears as if it's shaking as it moves which is very awkward to watch) - I'm assu$$anonymous$$g this isn't an expected behaviour?
Alternatively, if I use transform.Translate, it's perfectly smooth....so I don't know why the movement would look so bad?
I think I should add that the forces are doing exactly what you should expect them to do. If you apply a constant force to an object in the real world, it won't suddenly move at a constant speed, it will accelerate up to a maximum, and then move at a constant speed. The only reason it doesn't keep accelerating is because there is a frictional force acting against it. Forces accelerate objects, they don't move them directly.