was*_*ol2 5 javascript c# unity-game-engine
我想将我的脚本更改为 2D 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);
}
Run Code Online (Sandbox Code Playgroud)
据我所知,没有内置任何内容,但实际上很容易实现。这是使用扩展方法的示例:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以像使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅演示: https://dl.dropboxusercontent.com/u/16950335/Explosion/index.html
来源: https ://dl.dropboxusercontent.com/u/16950335/Explosion/AddExplosionForce2D.zip
| 归档时间: |
|
| 查看次数: |
12373 次 |
| 最近记录: |