- Home /
Is there a way to use Physics.Raycast accurately while time.timescale is set to zero?
For a test I attached the following script to a cube at origin on a scene:
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
Time.timeScale = 0;
}
void Update()
{
gameObject.transform.position = new Vector3(0, -1, 0);
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition)))
{
print("Hit!");
} else
{
print("No Hit!");
}
}
}
While hovering over the location that the cube was before the update of the scene, the raycast is true. While hovering over the location where the cube actually appears the raycast is false. I don't know if this behavior is to be expected (Maybe the physics doesn't update the collider positions while time is stopped?) However, what have is a drag and drop kind of system of containers with 3D item representations that follow along with it in a menu. I want to be able to gather raycastHit information on the item clicked. Any help is appreciated.
As a workaround, I found that forcing the Physics to update via Physics.Simulate does seem to work (Disable auto-simulation, simulate physics, raycast, then re-enable auto-simulation), however Physics.simulate doesn't accept a time step of zero. That means that every time I want to raycast I would have to move time forward, albeit I can use a negligibly small value. So, It is a "solution", but still I would prefer something less hacky that would keep my physics constantly paused which is why I wrote this as a comment not an answer.
Answer by myzzie · May 06, 2019 at 07:35 AM
The raycast is accurate, and it does work with timescale 0. The problem here is that you're moving the object in update.
void Start()
{
Time.timeScale = 0;
gameObject.transform.position = new Vector3(0, -1, 0);
}
void Update()
{
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition)))
{
print("Hit!");
}
else
{
print("No Hit!");
}
}
I will want to move the object in update because the object will be moving during runtime not just initialization. Suppose ins$$anonymous$$d of just setting the position once the cube is moving in a circular pattern, This solution wouldn't work. I think it only works in start because start occurs before the physics update.Source