- Home /
How to get pixel position when clicking an object ?
Hello,
The (0,0) position of an object texture is in the left-bottom of the object, suppose i clicked on the object in that exact position, how can i get these (0,0) ?
i tried to do something like this but it wasn't precise :
objectPoint = Camera.main.WorldToScreenPoint (transform.position);
objectSize = new Vector3 (targetTexture.width, targetTexture.height, 0);
mousePoint = Input.mousePosition;
PixelPoint.x = mousePoint.x - (objectPoint.x - (objectSize.x / 2));
PixelPoint.y = mousePoint.y - (objectPoint.y - (objectSize.y / 2));
thank you
Answer by robertbu · Jan 23, 2014 at 01:21 AM
Generally this is done using Raycasting. You Raycast against the texture using one of the versions of Raycast that take a RaycastHit structure as a parameter. One of the things RaycastHit returns is the RaycastHit.textureCoord. This is the UV coordinate of the hit on the texture. UV coordinates go from 0 to 1, so you have to multiple the width and height by textureCoord.x aand textureCoord.y respectively to get the pixel position.
$$anonymous$$y savior like usual ^_^ !! this sounds to be the perfect approach, even that am not very familiar with Raycasting, i will try it and tell if it worked or not, thank you very much
and this give the perfect result,
void Update ()
{
if (!Input.Get$$anonymous$$ouseButton (0))
return;
RaycastHit hit;
if (!Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hit))
return;
Renderer renderer = hit.collider.renderer;
$$anonymous$$eshCollider meshCollider = hit.collider as $$anonymous$$eshCollider;
if (renderer == null || renderer.shared$$anonymous$$aterial == null || renderer.shared$$anonymous$$aterial.mainTexture == null || meshCollider == null)
return;
Texture2D tex = (Texture2D)renderer.material.mainTexture;
Vector2 pixelUV = hit.textureCoord;
print ((int)(pixelUV.x * renderer.material.mainTexture.width) + "--" + (int)(pixelUV.y * renderer.material.mainTexture.height));
}
Is there any solution we can handle this with Physics2D ?
Your answer
Follow this Question
Related Questions
Getting to move object with mouse position? 0 Answers
How do I get mouse position in game units? 3 Answers
freeze position on click 1 Answer
Spawn Objects Where i click 2 Answers