user3402719
user3402719

Reputation: 155

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: this is how it looks when I first draw the rays

But when I rotate the car by 90 degrees it looks like this:

rotated by 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

Upvotes: 1

Views: 424

Answers (1)

derHugo
derHugo

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

Related Questions