Question

I have a very strange Raycast behaviour. Theare are 2 moving objects in my game. I use raycast in the Update method to find out if the second object is near. But sometimes raycast return false in obviously "true" situations. Can somebody help me to fix this issue? Thanks a lot!

enter image description here

    // Returns false, but should be true
    var middle = Physics.Raycast(Car.SensorPointRight.position, 
                                 Car.CarObject.right, out middleHitsInfo, 
                                (DistanceBetweenPaths - _carColliderOffset));

    if (IsUserCar)
        DebugHepler.Ray(Car.SensorPointRight.position, 
                        Car.CarObject.right * (DistanceBetweenPaths - _carColliderOffset),
                        middle ? Color.red : Color.white);
Was it helpful?

Solution

In unity3d, colliders are updated only after the FixedUpdate() method runs, so that might be why your objects aren't being hit by the raycast.

It's usually better to keep all transformations of gameObjects with colliders in FixedUpdate(), that way the raycast should work as expected.

For starters simply try moving the code you mentioned in your question from the Update() method to the FixedUpdate() method (If you don't have one, simply create one).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top