- Home /
How to properly convert mouse pos to world pos
I want to drag rigidbodies on the screen with the mouse. Before ranting about how this question has been answered a bunch of times, I have a question pertaining to the nature of Camera.ScreenToWorldPoint(). When I use it to convert Input.mousePosition, it gives me the x,y, and z position of the camera, not exactly the mouse. How can I get the mouse's world position and lock the z coordinate at a specific value?
Answer by Sonaten · Dec 01, 2012 at 04:25 PM
I have had great success with this script, which puts both ScreenToWorldPoint and WorldToScreenPoint to use.
 using UnityEngine;
 using System.Collections;
 public class DragAndDrop : MonoBehaviour {
     private Vector3 screenPoint, offset;
     
     void OnMouseDown() { //Select object
         screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
         offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
             Input.mousePosition.y, screenPoint.z));
     }
     void OnMouseDrag() {
         Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
         Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset - new Vector3(0,0, - 0.8561556f);
         transform.parent.position = curPosition;
     }
 }
The Script was found elsewhere on answers.unity, but I'm afraid I can't remember where.
You should be able to analyze and synthesize the code you need from this, as this script uses the distance to the screen as a lock for the z dimension.
This doesn't really explain the nature of ScreenToWorldPoint. I suspect it to be the result of the camera being a point in 3D space, with a viewplane, which we percieve to be the screen. These will of course have 3D coords and direction, even the viewplane. I find it makes sense that you'd get both x, y, and z.
Your answer
 
 
             Follow this Question
Related Questions
Drag Rigidbody 2 Answers
How do I drag an object without Y transformation? 2 Answers
On Mouse Drag Game Object follows Mouse on a single Axis. 1 Answer
Dragging camera around object using mouse issue 0 Answers
"Launch" a rigidbody 3 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                