Trying to move my projectile forward.

Hello! This maybe it’s a very simple question, but I can’t figure it out right now.

If I have my code without Input Keycode, it’s working good. But when I put the projectile inside Input Keycode it’s just go forward litle bit everytime i press on “Space”.

I’m doing an Top Down Game (RPG).

public class PlayerSpells : MonoBehaviour 
{
    public GameObject projectile;
    public float projectileSpeed;

    // Use this for initialization
    void Start () 
    {
   
    }
   
    // Update is called once per frame
    void Update () 
    {
        if (Input.GetKeyDown (KeyCode.Space)) 
        {
            projectile.transform.Translate (Vector3.forward * projectileSpeed * Time.deltaTime);
        }
    }

}

Because that’s exactly what your code is doing. If the space button is down, you’re moving the projectile a little. And when the space button isn’t down, you’re not moving it at all.

You could fix that by introducing a state variable:

public class PlayerSpells : MonoBehaviour
{
    private bool projectileWasFired = false;

    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.Space))
        {
            projectileWasFired = true;
        }
       
        if (profojectileWasFired)
        {
            projectile.transform.Translate (Vector3.forward * projectileSpeed * Time.deltaTime);
        }
    }
}
1 Like

Ohh thanks a lot, so I needed to use bools for this. Thanks alot!

We should point out that the more standard solution for this is to have the projectile move itself — I don’t think having the PlayerSpells script both launch and move the projectile will lead to much happiness.

So, the projectile should have a “MoveForward” script that simply calls transform.Translate on itself, moving itself forward at a constant rate in its Update event. Then PlayerSpells doesn’t need to worry about it; it just instantiates the projectile prefab, and forgets about it.

The exception would be if you really do want an old-school “guided projectile” (man, there’s a gaming concept I haven’t seen in decades!). In other words, if turning your player should cause any projectiles still in flight to turn as well. That’s what the script above does, but I don’t know if it’s actually what you want. But in that case, either the player must move the projectile, or the projectile would need to look at the player to figure out which way to go.

3 Likes

Thanks for the answer, I did fix so the projectile shots that way I’m looking. I did make a other script that you said.

It looks like this: It’s not great but I’m happy :slight_smile:

https://www.youtube.com/watch?v=of0XXWaeAW8