简体   繁体   中英

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

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.

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, ie 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.

Rigidbody 需要 Vector2,因为只想在 2 维中移动 2 维刚体是有意义的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM