[英]How do I keep raycast relative to the object its bound to?
I have a car game and I would like to use raycast to detect other obstacles and do stuff if the ray hits.我有一个汽车游戏,我想使用光线投射来检测其他障碍物并在光线命中时做一些事情。 The problem is after the car does a 90 degree turn the raycast move in a way I did not intend them to, like this:问题是在汽车进行 90 度转弯后,光线投射以一种我不希望它们的方式移动,如下所示:
But when I rotate the car by 90 degrees it looks like this:但是当我将汽车旋转 90 度时,它看起来像这样:
I'd like the rays to remain as they are in the first image regardless of the rotation of the car.无论汽车旋转如何,我都希望光线保持在第一张图像中。
Here is the code to cast the rays and to draw them:这是投射光线并绘制它们的代码:
private void OnDrawGizmos()
{
sensorStartPosition1 = transform.position + new Vector3(1f, 0.6f, 0f);
sensorStartPosition2 = transform.position + new Vector3(-1f, 0.6f, 0f);
Gizmos.DrawRay(sensorStartPosition1, transform.TransformDirection(Vector3.right) * 3.5f);
Gizmos.DrawRay(sensorStartPosition2, transform.TransformDirection(Vector3.left) * 3.5f);
}
private void RunSensors()
{
RaycastHit hit1;
sensorStartPosition1 = transform.position + new Vector3(1f, 0.6f, 0);
//dTS = detect traffic signs
Ray dTS = new Ray(sensorStartPosition1, transform.TransformDirection(Vector3.right));
if(Physics.Raycast(dTS, out hit1, sensorLen ))
{
}
Debug.DrawRay(sensorStartPosition1, transform.TransformDirection(Vector3.right) * 3.5f);
RaycastHit hit2;
sensorStartPosition2 = transform.position + new Vector3(-1f, 0.6f, 0);
// dLIT1 = detect left incoming traffic
Ray dLIT1 = new Ray(sensorStartPosition2, transform.TransformDirection(Vector3.left));
if(Physics.Raycast(dLIT1, out hit2, sensorLen))
{
}
Debug.DrawRay(sensorStartPosition1, transform.TransformDirection(Vector3.left) * 3.5f);
}
what am I doing wrong?.. thanks in advance我做错了什么?..提前谢谢
You calculate the two start positions with an offset along the global world space X axis regardless of the rotation in无论在
sensorStartPosition1 = transform.position + new Vector3(1f, 0.6f, 0f);
//...
sensorStartPosition2 = transform.position + new Vector3(-1f, 0.6f, 0f);
instead rather calculate them like而是像这样计算它们
sensorStartPosition1 = transform.position + transform.right * 1f + transform.up * 0.6f;
//...
sensorStartPosition2 = transform.position + transform.right * -1f + transform.up * 0.6f;
Or simply或者干脆
sensorStartPosition1 = transform.position + transform.rotation * new Vector3(1f, 0.6f, 0f);
//...
sensorStartPosition2 = transform.position + transform.rotation * new Vector3(-1f, 0.6f, 0f);
Btw instead of顺便说一句,而不是
transform.TransformDirection(Vector3.right)
transform.TransformDirection(Vector3.left)
you can also simply use你也可以简单地使用
transform.right
-transform.right
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.