【发布时间】: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