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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值