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! :slight_smile:

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...");
             }
         }
     }
 }