# Rotate GameObject When Mouse/Player is Within Certain Distance From it

Hello,
I am trying to make a simple 2D app where a ball is fired from a cannon and directed to the target. The cannon is meant to rotate in the direction of the player’s finger, and up until now, I was using mousePosition, and that worked fine. However, I’d like to have this enabled only when the finger/mouse cursor is within a certain distance from the cannon. I was thinking of having a button attached to the cannon GM, and have the cannon do its rotating when the player is hovering over the button (I was thinking the button UI would also let me do a highlighting effect when the player is close enough to rotate the cannon). I’m still learning the ropes when it comes to programming, and don’t even know if this is the best way to do this.

This is what I have to rotate the cannon, I’d like for it to check if the player is in the button’s area before executing the code:

``````Vector3 difference = Camera.main.ScreenToWorldPoint (Input.mousePosition) - transform.position;
difference.Normalize ();
float rotZ = Mathf.Atan2 (difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler (0f, 0f, rotZ + rotOffset);
``````

Any help is appreciated, and thanks in advance!

If you already have a working script that rotates your object towards your cursor, you could simply use use Vector3.Distance (or Vector2.Distance). Doing this via UI is also possible, but probably harder as scaling this UI item correctly to your object might be difficult on the various resolutions posible…

Something like this:

``````if (Vector3.Distance(Vector3.zero, difference) < 2)
// You should get here if you are less then 2 units away...
``````

Another thing which might be better in your case sinse you already calculated the difference is Vector3.magnitude

``````if (difference.magnitude < 2)
// You should get here if you are less then 2 units away...
``````

ps. This check should abviously happen before normalizing the difference though