- Home /
How to detect the position of a texture that is clicked
Hi guys,
I'm very new to Unity and I have what seems to be quite a simple scenario, that I'm just not too sure how to solve.
I am making a 2D game and am building a menu system that has an image. The image is (for example) 1000px wide. I want to be able to click on anywhere within the image and ascertain the X position of the click (left click using the mouse). For example, if I clicked in the middle of the image, I'd know the X position was 500px.
I've heard of physics 2D ray caster and think it could help me here but I'm not sure how to implement this.
I have my main camera and I've added the physics raycaster 2d to it but not sure how to implement the code on the image to say, if I'm clicked get the position.
Thanks for any help in advance! :-)
Answer by siaran · May 03, 2015 at 01:09 PM
Why don't you use a button?
then, have some function like
public void OnButtonClicked(){
float x = Input.mousePosition.x;
}
that you call on the button click event? Raycasting is really not necessary here.
Great! That might work for me! Would that give me the X pos relative to the object clicked? Like 500px being the position when half way is clicked in a 1000px width object? thanks!
no, that would give you the screen position of the mouse, but you should be able to convert those to the position relative to your button easily enough...
You'll simply need to know the left-most (screen) x position of your button. Should be easy enough to obtain (if you don't know how, read the docs or google, that information should be easy to find.)
then you'd do something like
float left$$anonymous$$ost = rectTransform.x - rectTransform.width/2; //Not actual correct code! don't use this.
float x = Input.mousePosition.x - left$$anonymous$$ost;