Unity射线检测实例

写作时间:2019/8/18

射线检测是游戏开发中常用的功能,下面提供两个射线检测的实现脚本

脚本1
在场景当中新建一个空物体,将脚本赋予该物体,运行程序,如果按下鼠标左键时,其所在位置产生的射线和物体相交,那么物体颜色发生改变

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

public class Manager : MonoBehaviour
{
    void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;
            bool isCollider = Physics.Raycast(ray,out hit);
            if(isCollider)
            {
                hit.collider.gameObject.GetComponent<Renderer>().material.color = Color.black;
            }
        }
    }
}

脚本2
将该脚本赋给某个具体对象,当鼠标放在上面时,物体变色,移开时变成另外一种颜色

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

public class Capsule : MonoBehaviour
{
    private void OnMouseEnter()
    {
        GetComponent<Renderer>().material.color = Color.red;
    }

    private void OnMouseExit()
    {
        GetComponent<Renderer>().material.color = Color.white;
    }
}
发布了11 篇原创文章 · 获赞 2 · 访问量 3945

猜你喜欢

转载自blog.csdn.net/weixin_42405831/article/details/99704500