我想将脚本更改为二维 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/