Unity:AddExplosionForce转换为2D [英] Unity: AddExplosionForce to 2D

查看:84
本文介绍了Unity:AddExplosionForce转换为2D的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的脚本更改为2D c#脚本.我知道AddExplosionForce不是UnityEngine.Rigidbody2D的成员,所以我如何才能将其更改为2D脚本,并且仍然在所有方向上都施加相同的力.(基本上是相同的操作,但以2D进行)谢谢!这是我的脚本:

I want to change my script into a 2D c# script. I know that AddExplosionForce is not a member of UnityEngine.Rigidbody2D so how can I change this in to a 2D script and still have the same force applied fro all directions. (basically do the same but in 2D) Thank you! Here's my script:

#  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);
}

推荐答案

我不知道内置什么内容,但实际上很容易实现.这是使用扩展方法的示例:

There is nothing built in I know of, but it is actually quite easy to implement. Here is an example using extension method:

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一样简单地使用它,例如,使用您的代码:

Now you can simply use it as you would use 3D rigidbody AddExplosionForce, for example with your code:

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

这篇关于Unity:AddExplosionForce转换为2D的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆