I was doing the basic layout of my game when I encountered a strange behavior : Physics.Raycast was not working at all. I checked and rechecked, then start browsing my old friend google.
I found that forum post : http://forum.unity3d.com/threads/57223-Buggy-Physics.Raycast-fails-for-moving-objects (and it's associated question on this site : http://answers.unity3d.com/questions/18927/) and I have not yet tested the FixedUpdate solution for the same reasons Wolfram was not too found of it.
Anyway, I try all the other variations in Update in LateUpdate without any luck. So I added a button to toggle the movement, and as soon as everything stop moving, Physics.Raycast works again.
I made an exemple in case I'm missing something. You can download it here :
http://static.zenshard.net/RayCastBug.rar
I striped it down to the minimum I could manage (2 scripts, one scene, a couple of gameobjects).
[EDIT] Here is the code for the 2 scripts.
The first one simply rotates another gameobject around it (think planet orbits)
public class Satelite : MonoBehaviour
{
public GameObject SateliteObject;
public float Speed;
public bool MovementEnabled = true;
// Update is called once per frame
void Update ()
{
MoveSatelite();
}
void LateUpdate()
{
// MoveSatelite();
}
private void MoveSatelite()
{
if (SateliteObject != null && MovementEnabled)
{
SateliteObject.transform.RotateAround(transform.position, transform.up, Time.deltaTime * Speed);
}
}
}
The second handles the ray casting :
public class HandleRay : MonoBehaviour
{
public Ray ray;
void Update ()
{
// ThrowRay();
}
void LateUpdate()
{
ThrowRay();
}
private void ThrowRay()
{
if (Input.GetMouseButtonUp(0))
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast (ray, out hit, Mathf.Infinity))
{
Debug.DrawLine (Camera.main.transform.position, hit.point, Color.red);
Debug.Log(hit.point);
Debug.Log("hit: " + hit.transform.name);
}
}
Debug.DrawRay(ray.origin, ray.direction, Color.red);
}
void OnGUI()
{
if(GUI.Button(new Rect(10,10,100,20), "Toogle movement"))
{
foreach(var s in FindObjectsOfType(typeof(Satelite)))
{
((Satelite)s).MovementEnabled = !((Satelite)s).MovementEnabled;
}
}
}
}