- Home /
Transform coordinates where the cursor clicks...
Using the mouse in Unity is something that seems to brings me trouble.
Could anyone tell me how to 'get' the xyz coordinates when the mouse clicks a location in the unity-space? Because i want to use these coordinates in a variable
Basicly: Var targetLocation = [Mouse-click coordinates]
When mouse button down x, y, z = location
I will then use the 'targetLocation' variable as i want.
Help?
Hope i made sense, Tom.
Answer by stingman · Jul 09, 2012 at 11:56 PM
Use Raycasting. Example from the docs:
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, 100)) {
print ("Hit something");
}
Read more on it here: http://docs.unity3d.com/Documentation/ScriptReference/Physics.Raycast.html
All you need to do is return a Vector3 of where the mouse clicks
Answer by Muuskii · Jul 10, 2012 at 12:56 AM
I use something like this:
private Plane targetingPlane; //raycast to this plane to find where the mouse is pointing
Vector3 getCursor() //Raycasts from current mouse position to the targetting plane, returns the resulting Vector3
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition ); // Construct a ray from the current mouse coordinates
float hitdistance;
if (targetingPlane.Raycast (ray, out hitdistance )) return ray.GetPoint(hitdistance);
return transform.position + transform.forward; //just in case ;)
}
void Start ()
{
targetingPlane.SetNormalAndPosition(transform.up, transform.position);
}
This is in c# because that's primarily what I use.
Hope that helps! :)
I use JS, but i reckon i can figure out somthiung similar from looking at how your script works, thanks :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613073934im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Update position of an object to match a high velocity object and still allow OnMouseOver() 1 Answer
Mouse click changes spawn location how do you do it? 4 Answers
Checking the position of the mouse cursor in 3d space 2 Answers
Movement In A Mobile Game 2 Answers
How do I create a shape that rotates from one pivot point, to always point towards the mouse cursor? 2 Answers