- Home /
How to get mouse cordinates on mouse click on the screen
im building Bubbles game, i need to detect mouse click event on screen and to project a Bubble from the center of the buttom of the screen,to the clicking point, i got no problem with creating the momvent once i know the cordinates.
How do i detect the clickng event and how do i translate it to the world cordinates?
Answer by CostelloNicho · Nov 27, 2012 at 11:01 PM
The function you are looking for is:
camera.ScreenToWorldPoint()
This will allow you to convert a position from screen space to world space. Now you need to take the screen space of the mouse and convert that like so:
camera.ScreenToWorldPoint( Input.mousePosition );
In order to detect that event you can listen to it in an update function like so:
void Update(){
if (Input.GetButtonDown ("Fire1")) {
currentMouseClickWorldSpace = camera.ScreenToWorldPoint( Input.mousePosition );
}
}
Answer by landon912 · Nov 27, 2012 at 11:00 PM
var cameraloc:Camera;
var mousePos:Vector3;
var worldPos:Vector3;
cameraloc = GameObject.Find("Camera").GetComponent(Camera);
mousePos = Input.mousePosition;
worldPos = cameraloc.ScreenToWorldPoint(mousePos);
This will return a world position of the place where you clicked, it works except you have to manually set the z axis.
worldPos.z = .....
Answer by CgShady · Nov 27, 2012 at 11:04 PM
You can do this in OnGUI () with if (Event.current.type == EventType.MouseDown) { Vector2 pos = Event.current.mousePosition ; }
or in Update () with if (Input.GetMouseButtonDown()) { Vector2 pos = Input.mousePosition ; }
in some situation, you may have to invert the Y component pos.y = Screen.height - pos.y ;
Hope this helps.