Reputation: 155
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:
But when I rotate the car by 90 degrees it looks like this:
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
Upvotes: 1
Views: 424
Reputation: 90570
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
Upvotes: 2