Unity 触发

首先先让物体移动起来,小技巧(将摄像机与视线保持一致,选中摄像机,点击游戏物体对象,选中对齐视图)

 移动物体脚本

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

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

    // Update is called once per frame
    void Update()
    {
        //水平轴
        float horizontal = Input.GetAxis("Horizontal");
        //垂直轴
        float vertical = Input.GetAxis("Vertical");
        //向量
        Vector3 dir = new Vector3(horizontal, 0, vertical);
        //朝向量方向移动 注意Update是帧,想要转成秒的话 * Time.deltaTime 就可以了
        transform.Translate(dir * 2 * Time.deltaTime);
    }
}

两个物体之间触发的话,需要触发物体勾选上“是触发器”,当勾选上“是触发器”的物体时,该物体就不受碰撞的影响,因此另一个物体就可以穿过了

 例如:走进这个正方体,这个长方体消失

 

 脚本CubeControl挂载到正方体上(触发的物体)

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

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

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

    //碰撞
    /*private void OnCollisionEnter(Collision collision) {
        //这样才能拿到碰撞信息
        //collision.Collider
    }*/

    //触发
    private void OnTriggerEnter(Collider collider) {
        //collider:进入触发的这个碰撞器,谁进入触发这里就是谁的碰撞器

        GameObject door = GameObject.Find("Door");
        if (door != null)
        {
            //改为非激活
            door.SetActive(false);
        }
    }

    private void OnTriggerStay(Collider collider) {
        
    }

    private void OnTriggerExit(Collider collider) {
        
    }
}

猜你喜欢

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