- Home /
 
Make it to where pressing a button on screen doesn't shoot a projectile?
I'm making a mobile game, that has a jump button and a tap to shoot system. My problem is that whenever you click the jump button on screen, the player will shoot at it, causing them to suffer delay, which makes a jump shoot maneuver not really work.
Here's the code for shooting:
 void Update()
         {
             if (Input.touchCount > 0) {
      
                  if (Input.GetTouch (0).phase == TouchPhase.Began) {
                      
                      if (Time.time > shotStart + shotCooldown)
                     {
                     anim.SetTrigger("Shooting");
                     Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
                     Vector2 dir = touchPos - (new Vector2(transform.position.x, transform.position.y));
                     dir.Normalize ();
                     GameObject bullet = Instantiate (bomb, transform.position, Quaternion.identity)as GameObject;
                     bullet.GetComponent<Rigidbody2D> ().velocity = dir * bulletSpeed; 
                     shotStart = Time.time;
 }
 }
 
               Thanks in advance~
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by TCMOREIRA · Mar 24, 2020 at 10:00 AM
You should verify if the current touch position is inside the desired gameplay area. You can achieve that by using colliders, a rect or simply a canvas. Then you'd have an auxiliary method to check for that collision.
That'd look a little bit like:
 ⠀
 void Update()
          {
              if (Input.touchCount > 0) {
       
                   if (Input.GetTouch (0).phase == TouchPhase.Began) {
                       
                       if (Time.time > shotStart + shotCooldown)
                      {
                      anim.SetTrigger("Shooting");
                      Vector2 touchPos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
                      Vector2 dir = touchPos - (new Vector2(transform.position.x, transform.position.y));
                      
                      // Here's the new and altered part
                      if ( ! IsInsidePlayArea(touchPos.x, touchPos.y))
                          return;
 
                      dir.Normalize ();
                      GameObject bullet = Instantiate (bomb, transform.position, Quaternion.identity)as GameObject;
                      bullet.GetComponent<Rigidbody2D> ().velocity = dir * bulletSpeed; 
                      shotStart = Time.time;
  }
  }
  ⠀
 
               Also a little side recommendation:
You really should cache your bullets inside some data-structure, preferably an object-pool
I hope this helps!
Your answer