我开发了一个汽车引擎脚本,我想使用光线投射来避开障碍物。问题是当我调用raycast时它指向(0,0,0)世界坐标,虽然我提到了从我的对象前进的方向。
public float sensorLength = 10f;
public float frontSensorPosition = 3.65f; // distance from the center of
//the car to its front
public float frontSideSensorPosition = 1.1f;
private void FixedUpdate () {
Sensors();
ApplySteer();
Drive();
CheckWayPointDistance();
}
private void Sensors()
{
RaycastHit hit;
Vector3 sensorStartPos = transform.position;
sensorStartPos.z += frontSensorPosition;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(sensorStartPos, fwd, out hit, sensorLength))
{
}
Debug.DrawLine(sensorStartPos, hit.point, Color.green);
}
答案 0 :(得分:1)
你的代码看起来很好,除了你试图从起点pos到世界空间的零点画线,为什么总是0,0,0?因为你还没有击中某些东西,如果光线投射没有击中任何东西,那么hit.point将保持0,0,0
调试线路的好方法是检查“我们遇到了什么?”'
这里是完整的例子
private void Sensors()
{
RaycastHit hit;
Vector3 sensorStartPos = transform.position;
sensorStartPos.z += frontSensorPosition;
Vector3 fwd = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(sensorStartPos, fwd, out hit, sensorLength))
{
//if it a surface, then Draw Red line to the hit point
Debug.DrawLine(sensorStartPos, hit.point, Color.red);
} else
{
//If don't hit, then draw Green line to the direction we are sensing,
//Note hit.point will remain 0,0,0 at this point, because we don't hit anything
//So you cannot use hit.point
Debug.DrawLine(sensorStartPos, sensorStartPos + (fwd * sensorLength), Color.green);
}
}
如果没有点击它会绘制绿线,但我们不会使用hit.point,因为它仍然为零。
击中时会画出红线 请告诉我这项工作是否成功,或告诉我它是否