亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

unity Raycast2D 角色坐在角落時的問題

unity Raycast2D 角色坐在角落時的問題

Go
忽然笑 2022-11-21 20:12:08
您好,我對 Raycast2D 有疑問。當角色像圖片一樣坐在平臺上時,Raycast2D 不起作用。我已經嘗試過 Raycast 和 RaycastAll。當他在拐角處時,我如何檢測角色下方的平臺?https://imgur.com/z7VMRq5 if(Input.GetMouseButton(0))    {        RaycastHit2D[] hit = Physics2D.RaycastAll(transform.position, -Vector2.up, 2f, layerMask);        if(hit[0].collider != null)        {            Destroy(hit[0].collider.gameObject);        }    }
查看完整描述

1 回答

?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

1)使用多個光線投射

在您的代碼中,如果您的玩家的中心站在平臺上方,游戲只會檢測平臺。要始終檢測平臺,您應該在角色對撞機的邊界使用兩個光線投射。


void Update()

{

    // Cast the rays

    castRays(transform.localScale.x / 2f);

}


private void castRays(float distanceFromCenter)

{

    // Return if the ray on the left hit something

    if(castRay(new Vector2(-distanceFromCenter, 0f) == true) { return; }

    // Return if the ray on the right hit something

    else if(castRay(new Vector2(distanceFromCenter, 0f) == true) { return; }

}



private bool castRay(Vector2 offset)

{

    RaycastHit2D hit; // Stores the result of the raycast


    // Cast the ray and store the result in hit

    hit = Physics2D.Raycast(transform.position + offset, -Vector2.up, 2f, layerMask);


    // If the ray hit a collider...

    if(hit.collider != null)

    {

        // Destroy it

        Destroy(hit.collider.gameObject);


        // Return true      

        return true;

    }


    // Else, return false

    return false;

}

可選:如果平臺比玩家小或為了安全起見,您可以將射線重新包含在中心。


2)使用觸發器

將 aBoxCollider2D放在角色的腳下并將“isTrigger”設置為 true。當它進入另一個碰撞器時,它將調用“OnTriggerEnter2D”。


void OnTriggerEnter2D(Collider2D other)

{

    Destroy(other.gameObject);

}


查看完整回答
反對 回復 2022-11-21
  • 1 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號