Another mouse position question...
Hey Everyone,
I have a UI.Image with a Collider2D so I can click the image and fire an event. What I need to return is the mouse position relative to the box collider or the UI.image (they share the same xy space). So if I click on that UI image, I will get the pixel coordinates relative to the image and positive from Top Left (0,0).
Can anyone help me... I've been searching for days and trying all kinds of different ways, but nothing works. I want to click on the green map and return the x y of that click relative to the object.
Thanks for your help :)
Answer by Jeshira · Jan 25, 2018 at 10:50 PM
N.B: Untested code :
void Update(){
Vector2 mapHit;
if(Input.GetMouseDown(0))
mapHit = GetMapHit();
}
Vector2 GetMapHit(){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(!Physics.Raycast(ray, out hit, 100))
return null;
return hit.textureCoord;
}
Usually coords start from bottom-left. So :
Vector2 BottomToTopCoord(Vector2 _coord, int _height){
_coord.x = _height - _coord.x;
return _coord;
}
To modify to previous code :
Vector2 GetMapHit(){
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(!Physics.Raycast(ray, out hit, 100))
return null;
Renderer r = hit.transform.GetComponent<Renderer>();
Texture2D t = (Texture2D)r.material.mainTexture;
return BottomToTopCoord(hit.textureCoord, (int)t.height);
}
Your answer
Follow this Question
Related Questions
create an object at runtime on mouseclick position 0 Answers
File.WriteAllBytes problem 0 Answers
Help scaling camera using VR Touch Controllers 0 Answers
Unity lookat at finger position 3D C# 0 Answers
Bullet to Mouse Position? 1 Answer