- Home /
Physics.Raycast sometimes does not work?
Hello,
I have some trouble using Physics.Raycast, it does not seem to work properly.
I have something like this:
var ray:Ray = Camera.main.ScreenPointToRay(Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
var hit:RaycastHit;
var is_raycast:System.Boolean = Physics.Raycast(Camera.main.transform.position, ray.direction, hit, Mathf.Infinity);
So normally is_raycast should be true if the cursor is on an object. It works most of the time. But sometimes it doesn't work, is_raycast being false.
Does anybody knows what should be the problem?
Thanks for your answers :)
Not sure, but first thought is I find it interesting that I've never seen System.Boolean before today, but today I've seen it twice here on UA : http://answers.unity3d.com/questions/479363/why-isnt-this-script-working-beginner-in-coding.html
Where are people reading/discovering System.Boolean?
var myBool : boolean = false;
myBool = true;
if ( myBool ) // same as writing -> if ( myBool == true )
{
// Do Stuff
}
second thought : Ray contains an origin and direction, why not just use :
Physics.Raycast(ray, hit, $$anonymous$$athf.Infinity);
Your script seems unconventional, but hey there's no problem in being unique!
Just curious, do you have the same problem if you use :
var ray : Ray = Camera.main.ScreenPointToRay( Input.mousePosition );
var hit : RaycastHit;
if ( Physics.Raycast(ray, hit, $$anonymous$$athf.Infinity) )
{
is_raycast = true;
}
http://docs.unity3d.com/Documentation/ScriptReference/Ray.html
http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
If there is no change, I'll delete this comment, sorry !
Is it possible you have other objects in the way that don't have colliders or otherwise block the view to your objects? $$anonymous$$aybe try the Debug.DrawRay function to duoble check.
alucardj -> Thanks for the help! However, the result is still is the same. As for "System.Boolean", well I simply didn't know at first about the simple keyword "boolean". I think the first time I used a boolean, $$anonymous$$onodevelop suggested me System.Boolean, but I'm not sure. Anyway, I'm used to write "System.Boolean" ins$$anonymous$$d of "boolean" :).
Em3rgency -> If these objects don't have colliders, how can they block the raycast? $$anonymous$$y first thought was that there must be a collider in front of my object blocking the raycast. But even if it was the case, is_raycast should be true.
Your answer
![](https://koobas.hobune.stream/wayback/20220613104739im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Raycast hits everything on the screen 2 Answers
Raycast hit done wrong using ScreenPointToRay coordinates 2 Answers
Detect Mouse in right side or left side For Player? 2 Answers
[2D] Raycast to mouse cursor = offset on Y axis 0 Answers
Prevent raycast to OnMouseOver() or OnMouseEnter() when mouse over UI 1 Answer