天天看點

Unity(4)-碰撞檢測(射線檢測)

b站學習視訊

連結:https://www.bilibili.com/video/BV12s411g7gU?p=181

碰撞檢測

連個碰撞物

Unity(4)-碰撞檢測(射線檢測)
Unity(4)-碰撞檢測(射線檢測)
Unity(4)-碰撞檢測(射線檢測)
Unity(4)-碰撞檢測(射線檢測)
//當滿足碰撞條件
    //接觸的第一幀執行
    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時,能檢測到

Unity(4)-碰撞檢測(射線檢測)

當移速為150時,能檢測到

Unity(4)-碰撞檢測(射線檢測)

當移速為250時,能檢測到

Unity(4)-碰撞檢測(射線檢測)

當移速為1000時,就檢測不到了

Unity(4)-碰撞檢測(射線檢測)

解決方案:開始時,使用射線去檢測。

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); //銷毀子彈
        }
    }
           
Unity(4)-碰撞檢測(射線檢測)