Search code examples
c#unity-game-engineprojectile

How to fire on Mouse Button?


I'm trying to do my first platformer at Unity. And have some problem with projectile. I found a tutorial, how create a projectile moving, but without trigger on Fire button. It is possible to change this script for firing on button? I tried to make it with if statement, but then projectile move only ones, it doesn't fly :(

public class projectile : MonoBehaviour
{
    public GameObject player;
    public GameObject target;

    private float playerX;
    private float targetX;

    private float dist;
    private float nextX;
    private float baseY;
    private float height;

    public float speed = 10f; 


    void Start()
    {
        player = GameObject.FindGameObjectWithTag("Player");
        target = GameObject.FindGameObjectWithTag("Enemy");
    }

    void Update()
    {  
       Fire();           
    }

    public static Quaternion LookAtTarget(Vector2 rotation)
    {
        return Quaternion.Euler(0, 0, Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg); 
    }

    private void Fire()
    {       
        playerX = player.transform.position.x;
        targetX = target.transform.position.x;

        dist = targetX - playerX;
        nextX = Mathf.MoveTowards(transform.position.x, targetX, speed * Time.deltaTime);
        baseY = Mathf.Lerp(player.transform.position.y, target.transform.position.y, (nextX - playerX) / dist);
        height = 2 * (nextX - playerX) * (nextX - targetX) / (-0.25f * dist * dist);

        Vector3 movePosition = new Vector3(nextX, baseY + height, transform.position.z);
        transform.rotation = LookAtTarget(movePosition - transform.position);

        if (transform.position == target.transform.position)
        {
              Destroy(gameObject);
            
        }
    }
}

Solution

  • What's in the Update method happens every frame, so you need to create a manual trigger (bool isFired).

    The idea is that when isFired is false, nothing happens. Then, when isFired turns to true, the projectile starts moving.

    Your Fire method actually makes the projectile move so you should rename it to Move and in Update you call Move only when the projectile is fired.

    public class projectile : MonoBehaviour
    {
        // At the start, the projectile is not fired
        bool isFired = false;
    
        void Update()
        {
            // If the player presses a button, the projectile is fired
            if (Input.GetMouseButtonDown(0)) isFired = true;
            // Only if the projectile is fired, it should moves
            if (isFired) Move();
        }
    
        void Move()
        {
            // Here you have the content of your Fire method
        }
    }