【问题标题】:Why is my raycast not detecting the object?为什么我的光线投射没有检测到物体?
【发布时间】:2021-04-23 12:27:30
【问题描述】:

我目前在一个项目中,我需要检测一个物体是否在另一个物体的前面,所以如果是这样,物体就不能移动,因为一个物体在它前面,如果不是,物体可以移动. 所以我在这里使用光线投射,如果光线击中某物,我会将布尔值变为真。在我的场景中,光线命中但从未将其变为真实。 我确定我的两个对象都是 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);
}

【问题讨论】:

  • 打印对撞机的名字吗?它是否调试日志“Behind true”?测试的时候用“//”了吗?
  • 我相信您在Raycast2D 调用中的参数有误。尝试阅读my other post,其中详细解释了每个参数。我认为您没有正确设置方向,因为您正在向方向添加位置并将其相乘。方向不一定要归一化,但通常是这样。这可能是您的问题,为什么您会得到意想不到的结果。

标签: unity3d 2d raycasting collider


【解决方案1】:

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

您正在传递从DrawLine 复制的内容

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

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

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

应该是

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

【讨论】:

  • 感谢您的回答,我发现了我的问题,谢谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-01-21
  • 2022-01-20
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2022-06-15
  • 2022-01-09
  • 2015-04-24
相关资源
最近更新 更多