Raycast problem

I’m having a bit of trouble with Raycast :expressionless:

I have a car driving around a track. There are barriers on the the left and right side.
If the car makes contact with the barrier on the right side, I want to turn on my sparks_right particles on the right side, and of course I want to do the same for the sparks_left particles on the left.

Although the distances returned by the raycast don’t seem to be consistent.
Sometimes the car detects the barrier is closer on the left, while other times it detects the barrier is closer on the right, regardless of which side of the track I’m on.

Can you spot anything wrong?

void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag == "Barrier")
        {
            // Do a raycast left and right to see which barrier is closest..
            float leftDistanceToBarrier = 100;
            float rightDistanceToBarrier = 100;

            RaycastHit hitLeft;
            RaycastHit hitRight;

            if (Physics.Raycast(transform.position, new Vector3(1, 0, 0), out hitLeft, 100))
            {
                if (hitLeft.collider.gameObject.tag == "Barrier")
                    leftDistanceToBarrier = hitLeft.distance;
            }
            if (Physics.Raycast(transform.position, new Vector3(-1, 0, 0), out hitRight, 100))
            {
                if (hitRight.collider.gameObject.tag == "Barrier")
                    rightDistanceToBarrier = hitRight.distance;
            }
            
            if (leftDistanceToBarrier < rightDistanceToBarrier)
                TurnOnSparks("left");
            if (rightDistanceToBarrier < leftDistanceToBarrier)
                TurnOnSparks("right");
        }
    }

No Idea.
I have been thinking of a solution for the past 10 minutes. No dice tho. Sorry.

Good luck.

Dang, and here I thought it would be one of those simple ones where u just say hey… change that… and it works :frowning:

You can also take the direction of the relativeVelocity, transfer it to the car’s local direction (if it’s not already, the scripting reference doesn’t say either way), and decide which sparks to activate off of that. You can even find the force of the collision to alter the number of particles.

In regard to your original post, you are using global directions rather than local for raycasting. Use transform.right/-transform.right or encapsulate them in transform.TransformDirection.

Thanks Dman I will give that a try.