- Home /
Precalculate force before applying it.
I am trying to add a force to an object up to a certain level, and am currently using the following to make sure I only add force up to a certain level
if (currentThrustSpeed < maxThrustSpeed) {
ship.AddRelativeForce (Vector2.up * thrustSpeed*Time.deltaTime);
}
where currentThrustSpeed = rigidbody2D.velocity.magnitude
This works great, the only problem is when I turn the ship and try to add a force that would ultimatley reduce the currentThrustSpeed it can't, because the currentThrustSpeed > maxThrustSpeed.
So what I am wondering is if there is a way to precalculate a force so that I can do a check similiar to
if(newforce.magnitude < currentVelocity){
Answer by AlwaysSunny · Apr 23, 2015 at 04:51 AM
You can use Vector3.Dot() on your normalized velocity and normalized requested force to get meaningful data about the relationship between the two.
Ideally, you don't want to just make a yes-or-no decision about whether to apply a force. Rather, you should scale the force you will apply based on its relationship to the velocity. At "maximum velocity" any force applied in that direction gets nullified, any force in the opposite direction gets the full force. Other changes in velocity can be limited based on some envelope which prioritizes keeping the velocity magnitude under a certain "soft" threshold. You use the dot product of the two to determine where you sample on the envelope curve. Use an AnimationCurve to establish the envelope.
It'll look something like:
// if velocity.magnitude is greater than some "soft" limit
// maybe like 80% of the desired "hard" limit
// we need to consider clamping any forces we apply...
float dot = Vector3.Dot( velocity.normalized, request.normalized );
dot = (dot+1)*0.5f; // normalize dot to 0..1 range
float scalar = envelope.Evaluate(dot);
request = request.normalized * maxForce * scalar;
Your answer
Follow this Question
Related Questions
AddForce(C#) not works 5 Answers
Apply force then slowly back off 4 Answers
Why can't Animation run functions with Rigidbody.AddForce? 1 Answer
Add Force: Increase Speed of Ball periodically 3 Answers
Bullet add force to ragdoll help 0 Answers