I’m having a bit of trouble with Raycast
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");
}
}