- Home /
 
RayCasting Mouse
Hi everyone,
I was just wondering how you would go about RayCasting a mouse in Unity, at the moment I have it attached to the camera and would like to know if it was possible to do this with the mouse. If it isnt could I Raycast via a Object that Follows the mosue.
Code : ray = new Ray (Camera.main.transform.position, Camera.main.transform.forward);
Exactly what i wanted, thanks, Would be good to move to answer
Answer by nightowl79a · Jan 26, 2015 at 11:49 AM
Have you tried:
 Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
         RaycastHit hit;
 
         if (Physics.Raycast(ray, out hit, 100))
         {
             //Do something here if the mouse is over a object?
         }
 
               Is that what you wanted to do?
Answer by arun.pandey89 · Jan 26, 2015 at 01:57 PM
If you're working for Editor only then above answer will work . If you're creating game of iOS/Android then you will need this in the end to cast ray when screen touched .
                         #if UNITY_EDITOR
                         ray = Camera.main.ScreenPointToRay (Input.mousePosition);
                         #elif (UNITY_ANDROID || UNITY_IPHONE)
                          ray = Camera.main.ScreenPointToRay (Input.GetTouch (0).position);
                         #endif
                         if (Physics.Raycast (ray, out hit, 100f)) {
                             }
                         
 
              Your answer
 
             Follow this Question
Related Questions
Another Raycast Issue. 0 Answers
Problem with raycasting, checking for ground doesn't work 3 Answers
(C#) Collider to collider2d 0 Answers
Raycasting ignoring small sized object 1 Answer
C# Raycast goes straight into the air 2 Answers