Unity(4)-碰撞检测(射线检测)

b站学习视频
链接:https://www.bilibili.com/video/BV12s411g7gU?p=181

碰撞检测
连个碰撞物
在这里插入图片描述在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

//当满足碰撞条件
    //接触的第一帧执行
    private void OnCollisionEnter(Collision other)
    {
        //事件参数类
        //other:获取对方碰撞器组件collision.collider.GetComponent<?>

        //获取第一个接触点
        ContactPoint cp = other.contacts[0];
        //cp.point 接触点的世界坐标
        //cp.normal 接触面法线
        print("OnCollisionEnter----"+other.collider.name);
    }

    //当满足触发条件
    //接触的第一帧执行
    private void OnTriggerEnter(Collider other)
    {
        //other:就是对方碰撞器组件other.GetComponent<?>
        print("OnTriggerEnter----"+other.name);
    }
    public float moveSpeed = 50;
    private void FixedUpdate()
    {
        Debug.Log(Time.frameCount+"--"+this.transform.position);
        this.transform.Translate(0,0,Time.deltaTime*moveSpeed);
    }

但如果物体移动速度过快,碰撞检测将失效
当移速为50时,能检测到在这里插入图片描述
当移速为150时,能检测到
在这里插入图片描述
当移速为250时,能检测到
在这里插入图片描述
当移速为1000时,就检测不到了
在这里插入图片描述

解决方案:开始时,使用射线去检测。

  public LayerMask mask;
    private Vector3 targetPos; //目标位置
    //如果物体移动速度过快,碰撞检测将失效
    //解决方案:开始时,使用射线去检测。
    private void Start()
    {
        //重载11
        RaycastHit hit;
        //Raycast(起点坐标,方向,受击物体信息,距离,?);
        if(Physics.Raycast(this.transform.position,this.transform.forward,out hit, 100,mask))
        {//检测到物体
            targetPos = hit.point; //击中位置
        }else
        {//没有检测到物体
            targetPos = this.transform.position + this.transform.forward * 100;
        }
    }

    private void Update()
    {
        this.transform.position = Vector3.MoveTowards(this.transform.position,targetPos,Time.deltaTime*moveSpeed);
        if ((this.transform.position-targetPos).sqrMagnitude<0.1f)
        {
            print("接触到目标点");
            Destroy(this.gameObject); //销毁子弹
        }
    }

在这里插入图片描述