Unity——射线检测

定义

参数对应起始点、终点、碰撞信息、射线长度、可碰撞的层,函数返回值为布尔;

   Physics.Raycast(Vector3 origin, Vector3 direction, RaycastHit hitInfo, float distance, int LayerMask);

其中,起始点和终点参数可以封装在ray中:

        //transform.forward为物体自身z轴朝向,会随物体旋转改变,Vector3.forward为固定的世界空间z轴
        Ray = new Ray(transform.position,transform.forward);
        Physics.Raycast(Ray, RaycastHit hitInfo,float distance, int LayerMask);

注意:碰撞的物体一定要有碰撞体,不然检测不到;
注意:碰撞的物体一定要有碰撞体,不然检测不到;
注意:碰撞的物体一定要有碰撞体,不然检测不到;

QueryTriggerInteraction.Ignore:如果勾选is trigger,就会忽略碰撞事件;

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

public class GunRay : MonoBehaviour
{
    public Ray ray;
    [SerializeField]
    private float maxDistance=100;
    RaycastHit hitInfo;
    public LayerMask mask;
    private void Update()
    {
        //transform.forward为物体自身z轴朝向,会随物体旋转改变,Vector3.forward为固定的世界空间z轴
        ray = new Ray(transform.position, transform.forward);
        if (Physics.Raycast(ray, out hitInfo, maxDistance, mask, QueryTriggerInteraction.Ignore))
        {
            Debug.Log(hitInfo.collider.gameObject.name);
            Debug.DrawLine(transform.position, hitInfo.point, Color.red);
        }
        else {
            Debug.DrawLine(transform.position, transform.position+ transform.forward*100, Color.yellow);
        }
    }
}

一次性碰撞路径上所有物体:

 hits = Physics.RaycastAll(ray,maxDistance,mask);
        Debug.DrawLine(transform.position, transform.position + transform.forward * 100, Color.red);
        foreach (RaycastHit hit in hits)
            hit.collider.gameObject.GetComponent<Renderer>().material = highlightMat;        

种树

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

public class Placement : MonoBehaviour
{
    //不设置层的话射线会被cube挡住,或者可以将cube的碰撞体关掉
    public LayerMask planeLayer;
    public GameObject tree;
    void Update()
    {
        //将鼠标的位置信息从屏幕坐标系转换到ray类型;ray就是从屏幕到鼠标位置的射线
        //这里操作的是cube中心点的位置,可以设置一个空物体,将两个物体归零,然后cube设为空物体的子物体,并将cube向上移动0.5个单位,脚本给空物体,这样操作的就是cube的底部中心点
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //Mathf.Infinity无限长
        if (Physics.Raycast(ray, out RaycastHit hitInfo, Mathf.Infinity,planeLayer)) {
            tree.transform.position = hitInfo.point;
            tree.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal); //初始为向上,旋转到接触平面的法向量
        }

        if (Input.GetMouseButtonDown(0)) {
            Instantiate(tree, hitInfo.point, Quaternion.FromToRotation(Vector3.up, hitInfo.normal));
        }
    }
}

其他应用

自动寻路;
降落伞(官方Demo);
点击物体显示信息等等;

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值