Hi!
I want to try to add an acceleration function or property to Rigidbody2D in the same line as how Rigidbody2D has the velocity property. So far I’m not sure how to run it continuously unless I call it in an Update function somewhere.
public static class RigidBodyExtensions{
public static void acceleration(this Rigidbody2D rb, float accX, float accY)
{
rb.velocity += new Vector2(accX * Time.deltaTime, accY * Time.deltaTime);
}
}
How would I make it so that it updates the velocity every frame similar to how Rigidbody2D.velocity updates the position every frame?
That’s how you do it. Put your every-frame physics code in FixedUpdate.
I mean, how do you have it run every frame from the extension? Like when you set the velocity of a Rigidbody, you don’t need to put it in an Update function because it updates the position automatically somewhere. I want to have it set so I can write:
Rigidbody2D rb = new Rigidbody2d();
rb.acceleration = 50f;
Then have it update automatically every frame from the extension.
You can’t. Extension methods are not going to get magically called every frame. Only certain MonoBehaviour methods have such magic.
You need to create your own MonoBehaviour subclass that adds this acceleration behavior. And then you’d set .acceleration on that type, not on Rigidbody2d.
2 Likes