Restrict mouse click area

hey Firends! Can i restrict my mouse to click whithin a specific region.
Actualy i m working on a shooting game when i click on screen it fires on the direction. it fires when i click any where in the screen. i want it to b fired only when mouse is clicked near my player.

You can calculate the distance between the player character and the mouse click, then check if it’s less than x range.

  1. Get the player character pixels coordinates with Camera.main.WorldToScreenPoint(/*position*/);
  2. Calculate the distance between both, Input.mousePosition - /*character pixel coordinates*/
  3. Just check if the distance is less than x value in pixels, for exemple 150f;


Note. make the result value of distance absolute with Mathf.Abs(); or use Vector3.Distance() to calculate it.


Also consider storing a reference to the main camera and use it instead of Camera.main.

Hi @husnain_rao,

Search’s answer is correct. I’ve also created a simple Unity project where you can visualize the solution to your problem.

Link: Mouse Range - Google Drive

Hey @Search I did,nt understand this can u please Integrate in it

Vector2 myPos;
		Vector2 target = Camera.main.ScreenToWorldPoint( new Vector2(Input.mousePosition.x,  Input.mousePosition.y) );//Get mouse Poz
		myPos = new Vector2(transform.position.x,transform.position.y);//get player pos
		Vector2 direction = target - myPos;//assume direction
		direction.Normalize();//make direction normalise
		GameObject ball = (GameObject) Instantiate( prefab, myPos, Quaternion.identity);//instantiate gameobject from prefab vriable, on player position
		ball.GetComponent<Rigidbody2D> ().velocity = direction * FireSpeed; //through object
		yield return new WaitForSeconds (3f);//wait for 3 seconds to destroy newly created object
		Destroy (ball);