射线实现扇形检测

参考了一篇博客,简要写了下demo,代码如下

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

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

    }

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

    [Range(0, 360)]
    public float angle = 90f;                       //检测前方角度范围
    [Range(0, 100)]
    public float distance = 25f;                    //检测距离
    public float rotatePerSecond = 90f;             //每秒旋转角度

    [Range(1, 50)]
    public float accuracy = 1f;                     //检测精度

    private bool Look()
    {
        float subAngle = angle / accuracy;          //每条射线需要检测的角度范围
        for (int i = 0; i < accuracy; i++)
            if (LookAround(Quaternion.Euler(0, -angle / 2 + i * subAngle + Mathf.Repeat(rotatePerSecond * Time.time, subAngle), 0), distance, Color.blue))
                return true;
        return false;
    }


    //射出射线检测是否有Player
    public bool LookAround(Quaternion eulerAnger,float _lookRange, Color DebugColor)
    {
        Debug.DrawRay(transform.position, eulerAnger * transform.forward.normalized * _lookRange, DebugColor);
        RaycastHit hit;
        if (Physics.Raycast(transform.position, eulerAnger * transform.forward, out hit, _lookRange)/* && hit.collider.CompareTag("Player")*/)
        {
            Debug.Log(hit.transform);
            return true;
        }
        return false;
    }
}

实现效果如图:

单次检测如下:


    //放射线检测
    private bool Look()
    {
        var _len = 30;

        一条向前的射线
        if (LookAround(Quaternion.identity, _len, Color.green))
            return true;

        var _lookAngle = 90;
        var _lookAccurate = 5;

        //多一个精确度就多两条对称的射线,每条射线夹角是总角度除与精度
        float subAngle = (_lookAngle * 0.5f) / _lookAccurate;
        for (int i = 0; i <_lookAccurate; i++)
        {
            if (LookAround(Quaternion.Euler(0, -1 * subAngle * (i + 1), 0), _len, Color.green)
                || LookAround(Quaternion.Euler(0, subAngle * (i + 1), 0), _len, Color.green))
            return true;
        }

        return false;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值