因此,我正在尝试克隆超级马里奥兄弟以进行练习。我正在创建世界1-1。一切都运转良好:我可以移动,敌人可以移动并被杀死,街区可以按预期进行交互。但是这时我正在使用对撞机,它们在这里和那里引起了一些问题,而且我也找不到办法让敌人面对对撞机时朝相反的方向移动。因此,我看着其他人,发现他们正在使用射线广播。然后决定自己尝试。敌人的剧本没有问题。
敌人脚本
private void RayCast()
{
// Getting the max distance by using the size of the collider and creating the ray itself
float rayMaxDistance = GetComponent<BoxCollider2D>().bounds.size.x/2;
Ray2D ray = new Ray2D(transform.position, Vector2.right);
// This way ray will be casted in the direction the enemy goes.
if (rb.velocity.x > 0)
{
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, rayMaxDistance);
if (hit.collider != null)
{
if (hit.collider.gameObject.tag != "Player")
{
// Moving in the opposite direction
rb.velocity = Vector2.zero;
rb.AddForce(-movementVector, ForceMode2D.Impulse);
}
}
//Debug.DrawRay(ray.origin, ray.direction, Color.red);
}
// This way ray will be casted in the direction the enemy goes.
else if (rb.velocity.x < 0)
{
ray.direction = Vector3.left;
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, rayMaxDistance);
if (hit.collider != null)
{
if (hit.collider.gameObject.tag != "Player")
{
// Moving in the opposite direction
rb.velocity = Vector2.zero;
rb.AddForce(movementVector, ForceMode2D.Impulse);
}
}
//Debug.DrawRay(ray.origin, ray.direction, Color.red);
它按预期工作,但是当我尝试在Mario上使用它时,它不起作用。
角色脚本中的部分。 (尚未完成,因为现在甚至无法正常工作)
private void ActivateLuckyBlock()
{
float maxRayDistance = GetComponent<BoxCollider2D>().bounds.size.y/2;
Ray2D ray = new Ray2D(transform.position, Vector2.up);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, maxRayDistance);
if (hit.collider != null)
{
Debug.Log("There is something");
}
}
我一直在通过互联网寻找任何答案,但是找不到任何答案。我不知道我在做什么错。它甚至还不是一个完整的实现,只是想测试一下。尽管如此,它还是行不通的。请在我发疯之前帮助我。
答案 0 :(得分:1)
射线原点应位于边界的中心,并尝试为maxRayDistance添加一些额外的空间(bounds.extents等于bounds.size / 2:documentation for bounds.extent)
float maxRayDistance = GetComponent<BoxCollider2D>().bounds.extents.y + 0.001f;
Ray2D ray = new Ray2D(GetComponent<BoxCollider2D>().bounds.center, Vector2.up);
尝试更改Debug.Log,这将使您知道射线投射所击中的对象的名称:
Debug.Log("Raycast hit:" + hit.collider.name);
如果仍然有问题,请创建一个公共layerMask变量,为要射线投射的对象创建并添加一个层:
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, maxRayDistance, layerMask);
通过更新或固定更新调用该函数:
它看起来应该像这样:
public LayerMask luckyBlockMask;
void Update()
{
ActivateLuckyBlock();
}
private void ActivateLuckyBlock()
{
float maxRayDistance = GetComponent<BoxCollider2D>().bounds.extents.y + 0.1f;
Ray2D ray = new Ray2D(GetComponent<BoxCollider2D>().bounds.center, Vector2.up);
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, maxRayDistance,
luckyBlockMask);
if (hit.collider != null)
{
Debug.Log("Raycast hit:" + hit.collider.name);
}
}