- Home /
 
Can someone explain why my Raycasting doesn't work? please :)
I want to make an object (my player) move toward a mouse click. I managed to get the player to move to the target, but I can't set the position of the target to where I click with the mouse. I found out about Raycasting, but I haven't got any experience with programming/scripting so I'm struggling.
Here's what I have: An object (my player), a quad (the ground, tagged "Ground") and a target object (to walk towards). The game is setup in 2D mode (it's a mini 2D game).
Here's the code in the script I attached to the main camera:
 void Update ()
 {
     Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
     Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
     RaycastHit hit;
     
     if (Input.GetMouseButtonDown (0)) {
         if (Physics.Raycast(ray, out hit)) {
             if (hit.collider.tag == "Ground") {
                 Debug.Log ("Touch Detected...");
             }
         }
     }
 }
 
               Any help/pointers appreciated! :)
The code looks fine. Put this between line 8 and 9 to check if your Raycast() is succeeding, and if so, what it is hitting:
  Debug.Log(hit.collider.name+", "+hit.collider.tag);
 
                 Thanks robertbu! It turns out I tagged it "ground" and not "Ground".
Answer by mohsentta · Jul 15, 2015 at 09:53 PM
this code wont work if your main camera doesn't set in your scene. get your camera in a public variable and use ScreenPointToRay
 public GameObject cam; 
 void Update ()
  {
      Ray ray = cam.camera.ScreenPointToRay (Input.mousePosition);
      Debug.DrawRay (ray.origin, ray.direction * 10, Color.yellow);
      RaycastHit hit;
      
      if (Input.GetMouseButtonDown (0)) {
          if (Physics.Raycast(ray, out hit)) {
              if (hit.collider.tag == "Ground") {
                  Debug.Log ("Touch Detected...");
              }
          }
      }
  }
 
              Your answer
 
             Follow this Question
Related Questions
Raycast2d not working C# :( 1 Answer
How to Limit Input.mousePosition or Raycast 1 Answer
Edge/Corner Stick — issue or logical error? 0 Answers
Push an object opposite direction of mouse position 0 Answers
Problem with raycast detection? 1 Answer