Unity 关于刚体模拟爆炸效果使用的方法

Unity刚体要模拟爆炸效果,可以使用AddExplosionForce方法。

它有3个语法:

public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius); //默认upwardsModifie=0.0f,ForceMode.Force模式

public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifier); //默认

public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifie, ForceMode mode); //ForceMode.Force模式

其中,

  • explosionForce:爆炸力的大小。
  • explosionPosition:爆炸的位置。
  • explosionRadius:爆炸的半径,决定了作用在刚体上的力的衰减程度,为0表示无穷大。
  • upwardsModifier:向上的修正系数,可以用来模拟爆炸的冲击波。
  • mode:力的模式,
    有 ForceMode.Force:施加一个持续的爆炸力在刚体上。
    ForceMode.Impulse:爆炸力以一个瞬间冲量施加在刚体上。
    ForceMode.Acceleration:爆炸力以一个持续的加速度施加在刚体上 。
    ForceMode.VelocityChange:爆炸力以一个改变刚体速度的冲量施加在刚体上。

如简答模拟一个爆炸效果,编写如下脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RigAddExplosionForce : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.A))
        {
            Simulatedexplosion();
        }
    }

    void Simulatedexplosion()
    {
        检测以物体为中心,半径为10的周围所有碰撞体
        Collider[] colliders = Physics.OverlapSphere(transform.position, 10);

        Debug.Log(colliders.Length);

        foreach (var temp in colliders)
        {
            //只施加爆炸力tag为explosion的刚体
            if (temp.tag == "explosion")
            {
                temp.GetComponent<Rigidbody>().AddExplosionForce(500f, transform.position, 10f);
            }            
        }
    }
}

 添加到场景中的物体中,运行后,效果如下:

Unity使用AddExplosionForce方法模拟爆炸力

猜你喜欢

转载自blog.csdn.net/mr_five55/article/details/135047744