- Home /
Moving an object to the location of a mouse click...
I've created a simple script that allows me to move the object the script is attached to to the coordinates of the mouse. However, when I began to click around, the object wouldn't go to the exact point of the mouse click but instead followed it at a distance. I'm kind of stumped on this problem, so I'll just provide the script and hope someone here knows a better way to do what I'm trying to do.
function Update () { if (Input.GetButtonDown ("Fire1")) { transform.position = Vector3(Input.mousePosition.x, 0, Input.mousePosition.y); } }
I want to use your script but could you tell me what mousePosition is please and thanks (:
Answer by Tetrad · Jun 22, 2010 at 02:32 PM
Use this: http://unity3d.com/support/documentation/ScriptReference/Camera.ScreenPointToRay.html
plus this: http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html
Screen position (i.e. Input.mousePosition) don't translate 1-to-1 to world coordinates (i.e. what transform.position is).
There are a lot of questions surrounding this here. Try this http://answers.unity3d.com/search?q=drag
Ok, thanks for getting back to me. I've modified my script using your info and some ideas from another script I found here. I used Raycasthit to place the object, but now I can't figure out how to constrain it to the x and z axis. Is it possible to do some using raycasting?
Well when you do your raycast, you'll end up with a point that it hit. Just take that point (a Vector3), and set the y value to whatever your object's current y value is before setting that point to your position.
Answer by Calesurf · Jun 14, 2014 at 12:25 AM
The bottom corner of the screen is 0,0 and if you click in the corn the object would go to 0,0. If you click anywhere else it would go to some crazy number. I had the same problem still haven't figured it out.