- Home /
when mouse click a gameobject ,how can I get the position of mouse click gameobject
when mouse click a gameobject ,how can I get the position of mouse click gameobject. I want drag a gameobject and move
Answer by zannghast · Oct 22, 2010 at 07:04 AM
The answer would depend on whether you wanted to get the position of the mouse click in screen coordinates or game world/space coordinates.
If it was the former, getting the position in screen coordinates usually means using something like:
Vector3 clickedPosition = Input.mousePosition;
If it was the latter, then you'd need to use something like the code below to get the position of the mouse click in game world/space coordinates:
Vector3 clickedPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
To know more about other Input functions, head on over to the official Scripting reference page here: Link
thk you!it's latter!I want to get the coordinates when ray hit
Glad you got what you were looking for. Be sure to have your camera oriented correctly, though. $$anonymous$$oving objects in a 3D space based on the 2D coordinates of the mouse usually implies you've already decided on how the objects will move in the game and designed any specific translation of the 2D mouse coordinates. If you need elaboration on what I just said, just tell me and I'd be glad to help you out, although I might not be able to answer immediately in the next couple of days.
By the way, now that you've mentioned using a ray, you could use Camera.main.ScreenPointToRay(Input.mousePosition) ins$$anonymous$$d.
thank you ,I am a beginner from China. I want to drag a gameobject with mouse. but the position of object must be same with mouseposition. I try to use ScreenPointToRay(Input.mousePosition),but the value of return is ray. I have not knew how to get effect what I want to . can you give me some tips? thank you very much!
Hi Showken, this would largely depend on how you intend the player to view your game. For instance, do you use a purely 2D side-scrolling camera like in LittleBigPlanet for instance. Or maybe a purely top-down view like in the EVAC-City Tutorial. Or do you use a semi top-down approach (sort of like isometric) like in Sonic 3D for the $$anonymous$$ega Drive.
The answer to your question with regards to 'moving' your gameobject would depend on how complex your camera setup is. If you could post more details about that, it would help people assist you better hehe.
Answer by GFX47 · Apr 04, 2011 at 02:31 PM
Here's a complete solution for right click detection: http://blog.gfx47.com/2011/04/04/detect-right-click-on-game-objects-in-unity3d/ Hope that will help! ;)
Your answer
Follow this Question
Related Questions
ScreenToWorldPoint error 3 Answers
Wrong world point mouse position 1 Answer
Rotate sprite to face direction of movement 1 Answer
Drag-and-drop gameObject inversely proportional to mouse speed? 0 Answers
screenToWorld not working 1 Answer