简体   繁体   English

与 3d 相比,为什么 AddForce 需要不同的 2d 语法?

[英]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.我刚刚将我的一个对象从 3d 更改为 2d,在这样做时,我注意到我的 AddForce 运动脚本坏了。 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.在修复了一些语法后,我注意到它要求我输入 Vector2 作为 Vector 2,而不是简单的 (1f, 0) 例如。 Why is this different from AddForce for a 3d object, where I can add a force with (1f, 0, 0).为什么这与 3d 对象的 AddForce 不同,在那里我可以用 (1f, 0, 0) 添加力。 I can work around it by making a new Vector2 but it feels clunky comparatively.我可以通过制作一个新的 Vector2 来解决这个问题,但它相对来说比较笨重。

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 ). Rigidbody 有两个可用的 AddForce 接口( https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html ),而 Rigidbody2D 只有一个( https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html )。

Could Unity team also add a second interface to Rididbody2D? Unity 团队是否也可以为 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. C# 支持扩展方法,即您可以向现有类添加新方法。 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.只需将它放在您的资产文件夹中的某个位置,现在您可以简单地从项目的任何其他文件中使用 AddForce(x,y),有效地向 Rigidbody2D 类添加一个新方法。 That's it.就是这样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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