- Home /
Get Pixel Coordinate When Click On 2D Object
Hei all,,
Sorry if this has been asked before, but I couldn't find a good solution to it yet.
I have one object for example cube. When I clicked on that cube, I wanna get pixel coordinate of the point where I clicked there .
Could you help me guys? Please... I dont have idea to solve.
Thanks
Answer by · Sep 28, 2010 at 12:30 AM
Raycast from the camera to mouse position and use the RaycastHit.point to get the impact position. Then use Camera.WorldToScreenPoint to get the screenspace (pixel coordinate) of the impact.
function Update ()
{
if ( Input.GetMouseButtonDown(0) )
{
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit, 100.0))
{
var hitPos : Vector3 = Camera.main.WorldToScreenPoint(hit.point);
Debug.Log(hitPos);
}
}
}
You'll usually have better success finding answers if you break it down to its basic parts. The raycast (object selection) script came from another answer, and there are plenty of other questions about converting world space to screen space.
Thank you marowi, I'm already try it, but I got error message like this :
$$anonymous$$issingComponentException: There is no 'Camera' attached to the "display" game object, but a script is trying to access it. You probably need to add a Camera to the game object "display". Or your script needs to check if the component is attached before using it.
I've try to put camera in that cuba but still doesnt work. Do you have any idea?
;D
Apologies! The WorldToScreenPoint function was assu$$anonymous$$g that the script was on the Camera object. I've added '.main' so it will find the camera tagged as $$anonymous$$ainCamera.
AHAAAAA... THank you! Its works!!! Thanks alot $$anonymous$$arowi ;D
No worries! Remember to vote up answers that help you, and mark it as 'correct' if it solves your problem (by clicking on the tick next to the arrows). Cheers.