0
\$\begingroup\$

I'm trying to change the ConstantForce of a gameobject upon collision with a tagged object:

public class MyScript() { public ConstantForce fakeGravity; private void Awake() { fakeGravity = GetComponent<ConstantForce>(); } private void OnTriggerEnter(Collider other) { if (other.CompareTag("IncreaseGravity")) { fakeGravity.force = new Vector3(0.0f, 5.0f, 0.0f); } } } 

This causes a sudden change in the ConstantForce, but what I would really like is to apply this force gradually from 0 to 5, so that it feels more natural. How could this be achieved?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Instead of using the standard Unity ConstantForce component, you could create your own component which is not so constant but increases its force over time.

Untested code example:

public class IncreasingForce : MonoBehaviour { public Vector3 finalForce; public float timeUntilFinalForce; private float timeExisting; private Rigidbody myRigidbody; void Start() { myRigidbody = GetComponent<Rigidbody>(); } void Update() { timeExisting += Time.deltaTime; float timeFactor = timeExisting / timeUntilFinalForce; Vector3 currentForce = Vector3.Lerp(Vector3.zero, finalForce, timeFactor); myRigidbody.AddForce(currentForce); } } 

This component increases the force linearly between 0 and the final force as soon as it is added to the game object. If you want more control over the way the force changes over time, then you could control the magnitude of the force with an AnimationCurve.

\$\endgroup\$
1
  • \$\begingroup\$ Thank you, that solution works great and is very customizable! \$\endgroup\$ Commented Feb 18, 2022 at 14:06

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.