Unity中模拟爆炸的力_# Unity相关技术

首先介绍两个API:
——相交球检测:Physics.OverlapSphere(Vector3 position, float radius, [int layerMask])
position:球心
radius:半径
layerMask:检测的层
返回球型半径之内(包括半径)的所有碰撞体,缺点就是radius不方便测试

 

——添加爆炸力:rigi.AddExplosionForce(float explosionForce,Vector3 explosionPosition, float explosionRadius,[float upwardsModifier = 0.0f], [ForceMode mode = ForceMode.Force])
explosionForce:爆炸力的大小
explosionPosition:爆炸点
explosionRadius:爆炸半径

using UnityEngine;

public class Test : MonoBehaviour
{
    //爆炸
    private void Boom()
    {
        Collider[] collider = Physics.OverlapSphere(transform.position, 5);
        foreach (Collider c in collider)
        {
            if (c.tag == "Item")
            {
                c.GetComponent<Rigidbody>().AddExplosionForce(400, transform.position, 5);
            }
        }
    }
}

AddExplosionForce只能对于3D刚体使用,而2D刚体并没有这个API,我们可以自行编写一个简单的模拟爆炸效果:

using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    public List<GameObject> item = new List<GameObject>(); //所有物体

    public float force; //力的大小

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Explosion();
        }
    }

    //爆炸
    public void Explosion()
    {
        //获取目场景中要爆炸的所有物体的中心点
        float minX = item[0].transform.position.x;
        float maxX = item[0].transform.position.x;
        float minY = item[0].transform.position.y;
        float maxY = item[0].transform.position.y;
        for (int i = 0; i < item.Count; i++)
        {
            if (item[i].transform.position.x < minX)
            {
                minX = item[i].transform.position.x;
            }
        }
        for (int i = 0; i < item.Count; i++)
        {
            if (item[i].transform.position.x > maxX)
            {
                maxX = item[i].transform.position.x;
            }
        }
        for (int i = 0; i < item.Count; i++)
        {
            if (item[i].transform.position.y < minY)
            {
                minY = item[i].transform.position.y;
            }
        }
        for (int i = 0; i < item.Count; i++)
        {
            if (item[i].transform.position.y > maxY)
            {
                maxY = item[i].transform.position.y;
            }
        }
        Vector2 midPos = new Vector2((maxX + minX) / 2, (maxY + minY) / 2);

        //模拟力
        foreach (GameObject temp in item)
        {
            //物体与爆炸中心的距离(越近的受到的爆炸力越大)
            float dis = Mathf.Abs(Vector2.Distance(food.transform.position, midPos));
            Vector2 v = midPos - (Vector2) temp.transform.position;
            Vector2 dir = v.normalized;
            temp.GetComponent<Rigidbody2D>().gravityScale = 1;
            temp.GetComponent<Rigidbody2D>().velocity = -dir * (force - dis);
        }
    }
}