- Home /
Dragging a GameObject with mouse
so I'm trying to create a script to make a GameObject follow the mouse when pressed. I've tried to work with the functions MouseDown and MouseDragged.
I'm having alot of problems and I think I got it all wrong.
what are the variables that refers to the X and Y coordinates of the mouse? and is there any built-in script for the thing I want? it's really strange for me that I'm not able to find one, this should be a basic thing.
Answer by mattssonon · Aug 22, 2013 at 01:09 PM
You need to convert screen points, which is what the mouse uses, to world points, which is what the game object is using. You can do this by using Camera.ScreenToWorldPoint()
.
So in the MouseDrag
event, you would do something like this:
transform.position = Camera.main.ScreenToWorldPoint(Event.mousePosition);
If you don't want the Game Object to move on its z-axis (the mouse position is in 2D), do something like this:
transform.position = new Vector3(Camera.main.ScreenToWorldPoint(Event.mousePosition).x, Camera.main.ScreenToWorldPoint(Event.mousePosition).y, transform.position.z);
Your answer
Follow this Question
Related Questions
Drag GameObject only in a specific area 1 Answer
Fixing "Drag GameObject with mouse" script 1 Answer
Controlling an animation by dragging a gameObject with the mouse 0 Answers
Resize / Scale, Drag, Move a Plane at Runtime by Mouse action 2 Answers
How do i disable my buttons while dragging ScrollRect? 0 Answers