The raycast works fine, the problem is that you have two entities that try to take control of your gameObject position - the dynamic rigidbody and the navMeshAgent. They both have their internal positions and try to synchronize it with transform. It’s quite possible that when both are present, they get desynced and their relative positions change. Just go to the scene view when this error manifests and see if the navMeshAgent, rigidbody+collider and the visible mesh (or whatever you are using) are in the same position or not.
This makes sense - the NavMeshAgent tries to interpolate the position on a path on a navMesh, the rigidbody has its own opinion on where the object should be, and they are incompatible. So you must pick one of them to “own” the position. (Or, you could disable position updates of both and handle it entirely in your script)
I’d say that if you want to have a rigidbody behaviour, then you want to keep the rigidbody behaviour… and disable the navmesh position update. You can actually disable the position update on the navMeshAgent, but it will still internally move towards the target - it just won’t move the gameObject. Now I am not sure what’s the best way to handle this, but one thing I’d suggest is to set the navMeshAgent velocity and acceleration to zero, disable the position update, then every FixedUpdate tell the navMesh your new position from the physics, and finally, take the navMeshAgent’s desired direction that comes from its path and calculate forces to move your rigidbody that way.
If there’s some built-in solution to this conflict, anyone pls enlighten me. But I am not aware of it.
I to am experiencing this issue and have yet to find a solution. It seems that my raycast collides for some arbitrary amount of seconds and then stops working. I'm currently using Physics.Raycast() but I have also tested with a sphere cast. My code was set up as follows Physics.Raycast(mainPosition, dirOne, out hitOne); Please help!
– Swear