Unity 碰撞的产生与监听

物体可以产生碰撞是因为有Comllider组件

 不同的物体有不同的Comllider组件

 真正产生碰撞的是这个绿色边框

 总结:1、两个物体发生碰撞都要有碰撞体

            2、两个物体有一个必须有Rigidbody(刚体)组件,否则都是不受物体系统的影响,不会移动,当然也不会产生碰撞

脚本检测碰撞的话,放在谁身上?只要是碰撞物体都可以

例:模拟火焰落地爆炸

扫描二维码关注公众号,回复: 15788565 查看本文章

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

public class FireTest : MonoBehaviour
{

    //创建一个爆炸预设体
    public GameObject prefab;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    //监听发生碰撞
    private void OnCollisionEnter(Collision collision) {
        //创建一个爆炸物体
        Instantiate(prefab, transform.position, Quaternion.identity);
        //销毁自身
        Destroy(gameObject);
        //获取碰撞到的物体
        Debug.Log(collision.gameObject.name);
    }

    //持续碰撞中(两个物体挨在一起)
    private void OnCollisionStay(Collision collision) {
        
    }

    //结束碰撞
    private void OnCollisionExit(Collision collision) {
        
    }

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

public class ExplosionTest : MonoBehaviour
{
    float timer = 0;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        //加一个定时器消灭爆炸物体
        timer += Time.deltaTime;
        if (timer > 1)
        {
            Destroy(gameObject);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/ssl267422/article/details/128840480