Restricting click to move within a circles radius

Hi guys,

I’ve been designing a click to move game. The player clicks on the screen to move their target to that position. I’ve imposed a limit on how far the player can move in one click. The code works EXCEPT for when the game first starts up. Here is the sample code before I explain any further:

using UnityEngine;
using System.Collections;

public class playermove : MonoBehaviour {
	
	// Use this for initialization
	void Start () {
		
	}

	// Update is called once per frame
	void Update () {

		if ((Input.touchCount > 0 && Input.GetTouch (0).phase == TouchPhase.Began) || (Input.GetMouseButtonDown (0))) {
			Vector3 mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);

			//check for obstacles
			RaycastHit2D hit = Physics2D.Raycast (transform.position, mousePosition - transform.position, (mousePosition - transform.position).magnitude);
			Debug.DrawRay (transform.position, mousePosition - transform.position, Color.green, 50, false);
			if (hit.collider == null) {

				//look to target
				Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
				Vector3 dir = Input.mousePosition - pos;
				float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
				transform.rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
				float dist = dir.magnitude;
				if (dist <= 170) {
					
					//walk to targe
					transform.position = mousePosition;
				}
			}
			else {
				Debug.Log (hit.collider.name);
			}
		}
	}
}

I suspect the problem is in the //look to target section.
When I first load up the game, the sprite will not move unless I click really close to it. After that it moves fine within it’s range.
I’ve debugged out some data and it appears on start up the magnitude of vector 3 “dir” is increased by about 50. this means when i click within it’s expected range it is way over the cutoff point of 170.

I’ve been trying to figure out why this is happening but i’m pretty stumped. I’m quite new to all this so i’m sure it’s fairly obvious but i’ve been hung up for a few days. I think it’s to do with my mouse. position. Or i’m forgetting to declare something in void start or void awake.

any help would be much appreciated.

Solved it. Was nothing to do with my previous assumptions. I’d just forgotten to limit the player sprites movement to a specific level on the z-axis.

I put

mousePosition.z = 0;

after I’d defined my mousePosition as the screentoworldpoint.