unity3d - 为什么我的光线投射没有检测到物体?
问题描述
我目前在一个项目中,我需要检测一个物体是否在另一个物体的前面,所以如果是这样,物体就不能移动,因为一个物体在它前面,如果不是,物体可以移动。所以我在这里使用光线投射,如果光线击中某物,我会将布尔值变为真。在我的场景中,光线会击中但从未将其变为真实。我确定我的两个对象都是 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);
}
解决方案
虽然Debug.DrawLine
需要一个开始位置和一个结束位置,但 aPhysics2D.Raycast
需要一个开始位置和一个方向。
您正在传递从DrawLine
this.transform.position + this.transform.up * rayLength
这是一个位置,而不是一个方向(或者至少它将是一个完全无用的方向)!你的调试线和你的光线投射可能会走向完全不同的方向!
除此之外,您让线条具有长度rayLength
,但在您的光线投射中您传入2f
.
应该是
Physics2D.Raycast(transform.position, transform.up, rayLength)
推荐阅读
- swift - 文件大小不在带有视频的标题中 计算进度所需的大小
- html - 为什么 Safari 会切断此文本的顶部?
- elasticsearch - Elasticsearch 只查找数值
- excel - 如何使用 Excel 在 Outlook 365 Exchange 中引用组或共享日历?
- spring-boot - gradle spring-boot bootDistTar 自定义脚本成tar包
- django - 使用 Django 进行多个 API 调用并循环更新
- html - 如何删除 li 元素之间的空格?
- java - 如何解决错误:java.lang.ClassNotFoundException:io.netty.util.concurrent.GenericFutureListener?
- python - Python:2个相等的数组在相同的操作后不相等
- socket.io - 将 Flutter 应用程序与 socket.io 服务器连接起来