我想将我的脚本更改为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);
}
答案 0 :(得分:4)
我所知道的并没有内置,但它实际上很容易实现。以下是使用扩展方法的示例:
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
答案 1 :(得分:1)
关于这个的答案很好,但是,它对我不起作用。那是在他使用的 Forcemode2D
中。据我所知,Forcemode2D.Force
仅适用于长时间执行的强制。但是,爆炸效果更像是,例如。一个跳跃。所以我只是将 Forcemode2D.Force
更改为 Forcemode2D.Impulse
,现在它可以工作了^^
这是新代码
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);
}
}
无论如何谢谢你 o /