- Home /
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. Thanx
Answer by EDevJogos · Jan 21, 2018 at 06:09 PM
You can calculate the distance between the player character and the mouse click, then check if it's less than x range.
.
Get the player character pixels coordinates with
Camera.main.WorldToScreenPoint(/*position*/);
Calculate the distance between both,
Input.mousePosition - /*character pixel coordinates*/
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.
Answer by Kabaw · Jan 21, 2018 at 06:54 PM
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: https://drive.google.com/open?id=1nfm8ojic02t_5h5hoDGL0bh2ARzooNKF
Hey @Search and @$$anonymous$$abaw Thanx it helped me a great. i did it and its working perfectly Thanx Again
Answer by husnain_rao · Jan 22, 2018 at 09:39 AM
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);
Your answer
Follow this Question
Related Questions
How can I shoot a projectile into mouse position? 2 Answers
2D Platformer – changing the cursor position when facing left or right 0 Answers
Unity 2D - Bullets don't follow mouse 1 Answer
Add Effect to a small part on a mouse click 0 Answers
Help rotating gun towards mouse position (with flipping) 1 Answer