AwesomeBob2341
AwesomeBob2341

Reputation: 135

Shooting a projectile towards mouse location in Unity

I'm in the process of creating a 2D game where the player needs to click to shoot. Wherever the mouse cursor is on the screen is the direction to which the projectile will move. I was able to get the projectile to instantiate and to the mouse location, but the projectile follows the mouse which is not what I want.

public class LetterController : MonoBehaviour {

    private List<GameObject> letters = new List<GameObject>();
    public GameObject letterPrefab;
    public float letterVelocity;

    // Use this for initialization
    private void Start()
    {
    }

    // Update is called once per frame
    void Update ()
    {
         Vector3 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    if (Input.GetMouseButtonDown(0))
    {
        GameObject letter = (GameObject)Instantiate(letterPrefab, transform.position, Quaternion.identity);
        letters.Add(letter);
    }

    for (int i = 0; i < letters.Count; i++)
    {
        GameObject goLetter = letters[i];

        if (goLetter != null)
        {
            goLetter.transform.Translate(direction * Time.deltaTime * letterVelocity );

            Vector3 letterScreenPosition = Camera.main.WorldToScreenPoint(goLetter.transform.position);
            if (letterScreenPosition.y >= Screen.height + 10 || letterScreenPosition.y <= -10 || letterScreenPosition.x >= Screen.width + 10 || letterScreenPosition.x <= -10)
            {
                DestroyObject(goLetter);
                letters.Remove(goLetter);
                }
            }
        }
    }
}

I watched several YouTube videos and looked at a few Unity forums, but the solutions either gave me errors, or they gave me different problems like only shooting on one axis or shooting on the opposite axes

Upvotes: 6

Views: 3375

Answers (1)

LordWilmore
LordWilmore

Reputation: 2912

As per your comment, Update() is called once per frame, and within each frame you are getting the position of the mouse at that time, so it is always tending towards the new mouse position.

So what you need to do is to take the mouse position when the action is fired, and use that until the action is complete/cancelled.

Upvotes: 5

Related Questions