getting world coordinates of mouse position

There are many questions like this, but none resolve my current problem. I’m trying to use the mouse position to set the position of the object I’m clicking in. For example, if I want to drag a box around on the x and y axis. When I use camera.ScreenToWorldPoint it keeps giving me the position of the camera rather than the mouse.

		if(Input.GetMouseButton(0)) {
			
			if(Physics.Raycast(ray,out hit,100f)) {
					
				Vector3 mouseWorld = camera.ScreenToWorldPoint(Input.mousePosition);
				//Debug.Log (mouseWorld);
				
				if(hit.collider.gameObject.tag == "dragable") {
					
					hit.transform.position = mouseWorld;
						
				}
	
			}
		
		}

you need to use Camera.ScreenPointToRay
and use the hit info to get the object’s position.

Anycase anyone is interested, I also had the same problem. I managed to resolve it by making sure of three things

  1. The Input.MousePosition.x is reversed (Screen.Width)
  2. The Input.MousePosition.y is reveresed (Screen.Height)
  3. The Z of the Vector is based from the camera position and in my case the z depth of the object that I was looking at (as they were all the same size).

Or…

Vector3 inputPosition = Input.mousePosition;
Vector3 ray = Camera.mainCamera.ScreenToWorldPoint(new Vector3(Screen.width - inputPosition.x, Screen.height - inputPosition.y, Camera.main.transform.position.z - 2f));