Hello. I’m moving my gameobject around using the following line of code: rb.AddForce(Quaternion.Euler(-slopeAngle, cam.eulerAngles.y, 0) * inputVector * moveSpeed, ForceMode.Impulse);
Long story short, for my purposes AddForce seems to be the only viable option to move the character (as opposed to setting the velocity or position manually)
The obvious problem with this is that force is just added forever and the character accelerates to infinity and beyond
the first obvious solution would be to increase the drag, but the problem is I want jumping to be snappy, but high drag prevents this
So the second obvious solution would be to clamp the velocity, which I tried with the following line:
`rb.velocity = Vector3.ClampMagnitude(rb.velocity, maxSpeed);
`
but for some reason I still get some velocity. even if I set maxSpeed to zero. I tried putting this line in Update, FixedUpdate, LateUpdate, and a Coroutine with WaitForFixedUpdate, but no dice. I tried to manually clamp the velocity’s x, y, and z using Mathf.Clamp, with no luck. Could someone lend a hand?
I got it! This is a marriage of the two ideas given to me by @Captain_Pineapple : rb.AddForce(Quaternion.Euler(-slopeAngle, cam.eulerAngles.y, 0) * inputVector * (maxSpeed - rb.velocity.magnitude) * moveSpeed * Time.deltaTime, ForceMode.Impulse);
Since you can’t apply a complete clamp after applying force, you have to slow down how much force you apply, and this scales with how close you are to the max speed. The movement is beautifully smooth, plays nice with physics, and had no camera jitter. Thank you everyone for your help!
That is indeed a smart solution. I feel kinda dumb now :D
Firstly check that the clamping should be done after the application of forces, that is near the end of update function. After that, just male sure that your maxSpeed value is not being overridden by inspector values.
Thank you for your response. I tried putting it in FixedUpdate, LateUpdate, A Courutine that waits for the end of FixedUpdate, and I tried putting it both at the beginning and the end of Update, with no luck. I even tried putting it in all those spots at once out of desperation, to no avail. And thanks for checking; my maxSpeed value is set to 0 in the inspector. raising the max value does make it speed up (going from way too fast to stupid fast), so the code is having some effect, but it cant clamp to the value I tell it to
That is indeed a smart solution. I feel kinda dumb now :D
– Captain_Pineapple