- Home /
The question is answered, right answer was accepted
Get world coordinates from mouse click
Questions like this have been asked before but not quite in the context im looking for. I need to find the world coordinates of a point that is clicked on a screen. I can only get this working when clicking on a gameObject, but I want it to find the coordinates whether or not there is.anything to click there.
The answers to this are assu$$anonymous$$g a 3D project, but the question makes a lot more sense in a 2D context.
Vector2 clickLocation = Camera.main.ScreenToWorldPoint(Input.mousePosition);
works well for this in 2D space
Answer by AlucardJay · Jan 08, 2013 at 01:50 PM
As you have probably read, using a raycast will return the hit.point in the world-space. If you are not clicking on a collider, then how far away from the camera should your input return a world-space position. It would be like pointing at the sky and saying "put a star there", where? how far away?
If you don't have a collider to raycast against for depth reference, but you know the distance from the camera you would like the point to be, you can use Ray :
#pragma strict
public var distance : float = 4.5;
function Update() {
CastRayToWorld();
}
function CastRayToWorld() {
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var point : Vector3 = ray.origin + (ray.direction * distance);
Debug.Log( "World point " + point );
}
FYI: The ray created by Camera.ScreePointToRay() starts at the near clip plane, not at the camera position, so you need to subtract that from the 'distance' if 'distance' is critical. Camera.ScreenToWorldPoint() is another way to make this conversion.
I see. You gave me one step deeper insight. Thanks. Anyway, this is so confusing matter....
@alucardj How do you get the coordinates in variables
Answer by whydoidoit · Jan 08, 2013 at 01:48 PM
There is no necessary coordinate of a position clicked on the screen - you have to click something to give you a perspective and distance. Normally what you would have is a very large plane representing the ground and see where on that you clicked.
Nice response, that is what I was trying to portray with my point to the sky analogy =]