Home > other >  Why does AddForce require different syntax for 2d compared to 3d?
Why does AddForce require different syntax for 2d compared to 3d?

Time:11-12

I just changed over one of my objects from 3d to 2d, and while doing so I noticed that my AddForce script for movement broke. After fixing some syntax I noticed that it required me to enter in the Vector2 as a Vector 2, instead of simply (1f, 0) for example. Why is this different from AddForce for a 3d object, where I can add a force with (1f, 0, 0). I can work around it by making a new Vector2 but it feels clunky comparatively.

CodePudding user response:

In the real world, not everything has a good reason. This is one such example. Rigidbody has two available interfaces for AddForce (https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html), while Rigidbody2D has just one (https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html).

Could Unity team also add a second interface to Rididbody2D? Of course, easy. But they didn't. Just because. That's why.

However, nothing prevents you from doing it yourself. C# supports extension methods, i.e. you can add a new method to an existing class. In your case, create a script like this:

using UnityEngine;

public static class MyExtensionClass {

    public static void AddForce(this Rigidbody2D rb2D, float x, float y, ForceMode mode = ForceMode.Force) {
        rb2D.AddForce(new Vector2(x, y), mode);
    }
}

Just put it somewhere in your assets folder, and now you can simply use AddForce(x,y) from any other file from your project, effectively adding a new method to Rigidbody2D class. That's it.

CodePudding user response:

The Rigidbody requires a Vector2 because it makes sense to only want to move a 2-dimensional rigidbody in 2 dimensions.

  • Related