I’ve the following code snippets:
void Update()
{
if (Input.GetMouseButtonDown(0)) // Make sure the user pressed the mouse down
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
bool intersect = Physics.Raycast(ray, out hit);
if (intersect)
{
if (!hit.rigidbody)
{
Utility.Log(typeof(Fpc), "Not RigidBody");
return;
}
if (hit.rigidbody.isKinematic)
{
Utility.Log(typeof(Fpc), "Kinematic");
return;
}
Utility.Log(typeof(Fpc), "current=" + gameObject.name + " " + hit.ToString() + " hit=" + hit.rigidbody.name);
}
else
{
Utility.Log(typeof(Fpc), "No Hit");
}
} // if
} // Update
I have a cube with attached RigidBody on top of a plane/ground.
It occasionally behaves as expected. I use the Standard Assets First Person Controller (FPC) and attach the above script to the FPC.
However, it sometimes keeps telling me that there is no hit even I hit the cube at the center.
What did I do wrong?
Thanks in advance for your help.
MORE INFO:
I added a few more log statements as the following:
Vector3 mousePosition = Input.mousePosition;
Ray ray = theCamera.ScreenPointToRay(mousePosition);
Utility.Log(typeof(Fpc), mousePosition.ToString());
Utility.Log(typeof(Fpc), ray.ToString());
I got the following output:
Fpc.(490.0, 240.0, 0.0)
UnityEngine.Debug:Log(Object)
Fpc.Origin: (0.0, 1.0, -4.7), Dir: (0.0, -0.1, 1.0)
UnityEngine.Debug:Log(Object)
Fpc.(490.0, 240.0, 0.0)
UnityEngine.Debug:Log(Object)
Fpc.Origin: (0.0, -12.4, -4.7), Dir: (0.0, -0.1, 1.0)
UnityEngine.Debug:Log(Object)
Notice the same mousePosition (490.0, 24.0, 0.0) produce different Ray origin: (0.0, 1.0, -4.7) vs (0.0, -12.4, -4.7)
Why is that?
EVEN MORE INFO:
I added
Debug.Log(“Camera.main.transform.position” + Camera.transform.position.ToString());
I notice that the Camera.main.transform.position keeps changing specifically the y position keeps going down negative.
Why is that?