首页 > 解决方案 > 为什么我的光线投射没有检测到物体?

问题描述

我目前在一个项目中,我需要检测一个物体是否在另一个物体的前面,所以如果是这样,物体就不能移动,因为一个物体在它前面,如果不是,物体可以移动。所以我在这里使用光线投射,如果光线击中某物,我会将布尔值变为真。在我的场景中,光线会击中但从未将其变为真实。我确定我的两个对象都是 2D 对撞机,而我的光线投射是 2DRaycast,我之前在物理 2D 中添加了勾选“在对撞机中开始查询”,因此我的光线不会检测到我投射它的对象。请救救我。这是我的代码:

float rayLength = 1f;
private bool freeze = false;
private bool moving = false;
private bool behindSomeone = false;
Rigidbody2D rb2D;
public GameObject cara_sheet;
public GameObject Monster_view;
public GameObject monster;

void Start()
{
    rb2D = GetComponent<Rigidbody2D>();
}

void Update()
{
    Movement();
    DetectQueuePos();
}

private void Movement()
{
    if(freeze || behindSomeone) 
    {
        return;
    }

    if(Input.GetKeyDown(KeyCode.Space))
    {
        Debug.Log("Move");
        moving = true;
        //transform.Translate(Vector3.up * Time.deltaTime, Space.World);
    }
    
    if(moving)
    {
        transform.Translate(Vector3.up * Time.deltaTime, Space.World);
    }
     
}

private void OnTriggerEnter2D(Collider2D collision)
{
    
    if (!collision.CompareTag("Bar"))
    {
        return;
    }

    StartCoroutine(StartFreeze());
    
}

public void DetectQueuePos()
{
    RaycastHit2D hit = Physics2D.Raycast(this.transform.position, this.transform.position + this.transform.up * rayLength, 2f);
    Debug.DrawLine(this.transform.position, this.transform.position + this.transform.up * rayLength, Color.red, 2f);

    if (hit.collider != null)
    {
        print(hit.collider.name);
    }

    if(hit.collider != null)
    {   
        Debug.Log("Behind true");
        //Destroy(hit.transform.gameObject);
        behindSomeone = true;
        
    }
}

IEnumerator StartFreeze()
{
    yield return new WaitForSeconds(1f);
    rb2D.constraints = RigidbodyConstraints2D.FreezeAll;
    freeze = true;
    moving = false;

    cara_sheet.SetActive(true);
    Monster_view.SetActive(true);
}

示例截图

标签: unity3d2draycastingcollider

解决方案


虽然Debug.DrawLine需要一个开始位置和一个结束位置,但 aPhysics2D.Raycast需要一个开始位置和一个方向

您正在传递从DrawLine

this.transform.position + this.transform.up * rayLength

这是一个位置,而不是一个方向(或者至少它将是一个完全无用的方向)!你的调试线和你的光线投射可能会走向完全不同的方向!

除此之外,您让线条具有长度rayLength,但在您的光线投射中您传入2f.

应该是

Physics2D.Raycast(transform.position, transform.up, rayLength)

推荐阅读