1 回答

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);
}
- 1 回答
- 0 關注
- 170 瀏覽
添加回答
舉報