javascript - 统一: AddExplosionForce to 2D

标签 javascript c# unity3d

我想将脚本更改为二维 C# 脚本。我知道 AddExplosionForce 不是 UnityEngine.Rigidbody2D 的成员,所以我怎样才能将其更改为 2D 脚本并仍然对所有方向施加相同的力。 (基本上做同样的事情,但在 2D 中)谢谢!这是我的脚本:

#  pragma strict

var explosionStrength : float = 100;

 function OnCollisionEnter(_other: Collision) 
{
if (_other.collider.gameObject.name == "Bouncy object")
   _other.rigidbody.AddExplosionForce(explosionStrength, this.transform.position,5);
}

最佳答案

据我所知,没有内置任何东西,但实际上很容易实现。下面是一个使用扩展方法的例子:

using UnityEngine;

public static class Rigidbody2DExt {

    public static void AddExplosionForce(this Rigidbody2D rb, float explosionForce, Vector2 explosionPosition, float explosionRadius, float upwardsModifier = 0.0F, ForceMode2D mode = ForceMode2D.Force) {
        var explosionDir = rb.position - explosionPosition;
        var explosionDistance = explosionDir.magnitude;

        // Normalize without computing magnitude again
        if (upwardsModifier == 0)
            explosionDir /= explosionDistance;
        else {
            // From Rigidbody.AddExplosionForce doc:
            // If you pass a non-zero value for the upwardsModifier parameter, the direction
            // will be modified by subtracting that value from the Y component of the centre point.
            explosionDir.y += upwardsModifier;
            explosionDir.Normalize();
        }

        rb.AddForce(Mathf.Lerp(0, explosionForce, (1 - explosionDistance)) * explosionDir, mode);
    }
}

现在您可以像使用 3D 刚体 AddExplosionForce 一样简单地使用它,例如在您的代码中:

public class Test : MonoBehaviour {
    public float explosionStrength  = 100;

    void OnCollisionEnter2D( Collision2D _other) 
    {
        if (_other.collider.gameObject.name == "Bouncy object")
            _other.rigidbody.AddExplosionForce(explosionStrength, this.transform.position,5);
    }
}

查看演示: https://dl.dropboxusercontent.com/u/16950335/Explosion/index.html

来源: https://dl.dropboxusercontent.com/u/16950335/Explosion/AddExplosionForce2D.zip

关于javascript - 统一: AddExplosionForce to 2D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34250868/

相关文章:

c# - 将非根游戏对象移动/携带到另一个场景

c# - 试图建立一个完整的计算机名称的网址

c# - 为多个实例保存 PlayerPrefs

android - 适用于 Unity 的 Facebook SDK 3.1.2 - 在 Android 设备上登录时遇到问题

javascript - OpenLayers、Bing、连续 map 图层

c# - iTextSharp IOException "Trailer not found"

c# - 字典键的类型安全?

javascript - 如何从 JavaScript 中的字符串中去除 HTML 标签?

javascript - jQuery 找不到指定 id 的 div

javascript - 如何使用带有可选参数命名的Apply调用函数?