The question is answered, right answer was accepted
Raycast hit or miss in the same situation
I have a player controller and I am sending a ray from the origin of the camera. What I am trying to do is be able to look at a safe and if I press E, a dialogue pops up. But I have a really interesting problem that I have no idea how to fix. It will work sometimes and sometimes it will just not work. The really interesting thing is that even if I don't move the cameras position or rotation AT ALL, there is still no telling whether it will execute or not.
To demonstrate this, I shot a raycast 50 times from the exact same position.
http://i.imgur.com/9ivKTEb.png
Here are my results
http://i.imgur.com/u1mWJQ9.png
And finally here is my code
void sendRay(){
Camera camera = cam.gameObject.GetComponent<Camera>();
Ray ray = cam.gameObject.GetComponent<Camera>().ScreenPointToRay(new Vector3(camera.pixelWidth * 0.5F, camera.pixelHeight * 0.5F, 0));
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 3)){
print("hit");
if(hit.transform.tag == "safe"){
safe.enter();
}
}else{
print("no hit");
}
}
Did you make sure no colliders overlap? It happened to me once, was randomly flickering on/off.
You should try what Raresh said first, as it happened to me, too. Also, it's worth checking to see if it's tag is "safe". You also have to remember that tags are case sensitive. OR, you might have 2 game objects under an empty parent or something, say the door and the main safe part. It will hit those objects(if of course they have colliders on them) and then check if their tag is "safe", if it's not then it ignores it.
I recommend you to use layer mask in the Physics.Raycast check. As Raresh says you're highly probably hitting another collider in between the camera and the target object. If you look downwards, you probably hit the player's collider.
Answer by matta9001 · Jan 30, 2016 at 05:54 PM
I had a very very weird problem, the rigidbody on my player was somehow affecting the child cameras position, and every frame it would change between two positions creating the effect of randomness, it took me a long time to solve but in the end what fixed it was selecting "Is Kinematic" in the rigidbody, yes I know it's very weird. Thanks for the help though!
Follow this Question
Related Questions
Rotated object raycasting in wrong directions!!? 3 Answers
Freeze rotation of just the box collider component 0 Answers
How to move an object on a terrain that will always stay on top of the terrain? 2 Answers
Restrict held object movement 0 Answers
Raycast doesn't interact with Tilemap Collider when in a 3D scene. 0 Answers