unity Raycast2D 角色坐在角落时的问题
Unity Raycast2D problem when the character sitting on the corner
您好,我对 Raycast2D 有疑问。当角色像图片一样坐在平台上时,Raycast2D 不起作用。我已经尝试过 Raycast 和 RaycastAll。当他在拐角处时,如何检测角色下方的平台?
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) 使用多个光线投射
在您的代码中,如果玩家的中心位于平台上方,游戏只会检测平台。要始终检测平台,您应该在角色碰撞器的边界使用两个光线投射。
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) 使用触发器
在角色脚下放一个BoxCollider2D
,并设置'isTrigger'为真。当它进入另一个碰撞器时,它将调用 "OnTriggerEnter2D".
void OnTriggerEnter2D(Collider2D other)
{
Destroy(other.gameObject);
}
您好,我对 Raycast2D 有疑问。当角色像图片一样坐在平台上时,Raycast2D 不起作用。我已经尝试过 Raycast 和 RaycastAll。当他在拐角处时,如何检测角色下方的平台?
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) 使用多个光线投射
在您的代码中,如果玩家的中心位于平台上方,游戏只会检测平台。要始终检测平台,您应该在角色碰撞器的边界使用两个光线投射。
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) 使用触发器
在角色脚下放一个BoxCollider2D
,并设置'isTrigger'为真。当它进入另一个碰撞器时,它将调用 "OnTriggerEnter2D".
void OnTriggerEnter2D(Collider2D other)
{
Destroy(other.gameObject);
}