欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Unity碰撞检测实操

程序员文章站 2024-03-15 22:21:42
...

1.解决的问题

通过OnDrawGizmos 使使用Physics.OverlapSphere 在编辑器或运行模式中可以方便的查看其范围

在Physics.OverlapSphere中加入扇形检测 ,效率更高

使用Debug.DrawLine(transform.position, transform.position+ right, Color.red); 绘制一些红线方便调试

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

public class test_jiance : MonoBehaviour {
    public float _max;

    //自视野自定义
    float minDistance = 2f;
    float minAngle = 40f;

    // Use this for initialization
    void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
      //注意:使用Physics.OverlapSphere 检测与被检测的物体需要加载rigibody 脚本
        var cols= new List<Collider>( Physics.OverlapSphere(transform.position, _max));
        //ebug.DrawLine(transform.position, pos, Color.red); ;

        cols.ForEach((s) =>
        {
            Debug.Log(s.name);
            SelfShiYe(s.gameObject.transform.position);
        }
            );
        

        


    }
    void SelfShiYe(Vector3 _tarPos)
    {

        float distance = Vector3.Distance(transform.position, _tarPos);

        //主角相对于目标的向量
        Vector3 srcLocalVect = _tarPos - transform.position;


        //获取正前方的点
        Vector3 forwardLocalPos = transform.forward * 1 + transform.position;

        //获取正方向向量
        Vector3 forwardLocalVect = forwardLocalPos - transform.position;
        forwardLocalVect.y = 0;

        //计算角度
        float angle = Vector3.Angle(srcLocalVect, forwardLocalVect);
        Vector3 left = Quaternion.Euler(0,-1* minAngle, 0) * transform.forward * 2;
        Vector3 right = Quaternion.Euler(0,  minAngle, 0) * transform.forward * 2;

        Debug.DrawLine(transform.position, transform.position+ left, Color.red); ;
        Debug.DrawLine(transform.position, transform.position+ right, Color.red); ;
        if (distance < minDistance && angle < minAngle / 2)
        {
            Debug.LogError("In EyeSight");
        }
    }
    //  绘制一个球
    void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, _max);
    }
}