I’ve got a little problem with Raycasting in Unity 2019.2.11f1. In my Update() I’m running a Camera.ScreenPointToRay (Input.mousePosition) to detect what the user is pointing at. At first, this works fine but after a few seconds it stops working. After debugging and using Debug.DrawRay () I found out that the origin of the Ray is constantly moved downwards although the camera position doesn’t change which in result leads to the Ray not hitting the objects the user is mousing over. Here’s a gif that shows the Debug.DrawRay () in red:
Does anybody know what might lead to this behaviour?
For the sake of completeness here’s the code snippet I’m running.
Do you have physics operating on the camera (or its parent, etc), and are you setting its position in Update? If so, I think your camera is literally falling. Try setting its velocity to 0 or setting the rigidbody to kinematic.
Unity’s frame execution goes: physics/FixedUpdate (any number of times), Update, LateUpdate, rendering. What I think is happening is that the posted code is being run before the camera’s position-setting code. So:
Physics happens, your camera falls slightly, and its downward velocity increases slightly (gravity)
Raycast code runs, using the “fallen” position.
Camera code runs, resetting its position but not affecting the velocity
Render
Then as step 1 is repeated more and more, the 1 frame’s worth of falling distance becomes greater and greater as the velocity increases.
I didn’t think that would be the case because neither the Camera itself nor its parent object are moved. I don’t know whether you can see that in the gif (in the Scene View or the small Game View on the right) but none of them are changing position at any given time. (For clarification: the purple cone is the parent object and you might be able to see the Camera icon indicating the position of the camera on the very top of it.) I double-checked that in the inspector: both Transform Components always show the same position throughout the whole process.
That being said, I just went into the project and activated the “Is Kinematic” checkbox on the parent Rigidbody Component and it actually prevented the aforementioned behaviour. But why does the Ray origin think that the Camera position changed when it doesn’t?
Look closely at the step by step process I outlined in the first post. When watching in the editor, you don’t see any of the intermediate stages. You only see step 4. (The values you see in the editor will be updated at the same time as rendering happens.)
It does change, but it gets changed back before rendering happens.