Search code examples
c#unity-game-enginegame-physics

Unity3d C# turret gun projectile won't move


I'm working on a gun turret. I've got everything working except having the projectile shoot out of the turret gun barrel. Currently, the only barrel used is

void Start(){
    firingPointRight = GameObject.FindGameObjectWithTag ("FiringPointRight").transform;
    firingPointLeft = GameObject.FindGameObjectWithTag ("FiringPointLeft").transform;
}

void Update() {
    if(Input.GetMouseButton(0)){
        count++;
        if (count >= maxCount)
        {
            count = 0;
            //Debug.Log ("FIRE");
            firingPointRight = GameObject.FindGameObjectWithTag ("FiringPointRight").transform;
            firingPointLeft = GameObject.FindGameObjectWithTag ("FiringPointLeft").transform;

            //  Create cannon muzzle fire effect.
            GameObject e1 = Instantiate (cannonMuzzleFire) as GameObject;
            e1.transform.position = firingPointRight.transform.position;
            e1.transform.rotation = firingPointRight.transform.rotation;

            Destroy (e1, 0.03f);

            GameObject e2 = Instantiate (cannonMuzzleFire) as GameObject;
            e2.transform.position = firingPointLeft.transform.position;
            e2.transform.rotation = firingPointLeft.transform.rotation;

            Destroy (e2, 0.03f);
            //-------------------------------------------

            //Left cannon. Fire projectile from cannon.

            //Debug.Log ("Firing Left");
            Rigidbody InstantiateedProjectile = Instantiate(cannonAmmo, firingPointLeft.transform.position, firingPointLeft.transform.rotation) as Rigidbody;
            if (InstantiateedProjectile != null)
            {
                print ("Firing projectile");
                InstantiateedProjectile.transform.Translate(Vector3.forward * cannonAmmoSpeed * Time.deltaTime);
            }

        }
    }

Solution

  • Does the projectile have a script of its own? It doesn't look like you're setting any velocity to the instantiated projectile.

    Translate() doesn't really perform much in the way of movement, other than immediately setting the new position. If the projectile has a Rigidbody component attached, then you can just directly set the velocity of the rigidbody.

    Like so:

    InstantiateedProjectile.velocity = Vector3.forward * cannonAmmoSpeed;
    

    Time.deltaTime wouldn't be used here, since it only needs to be included in calculations performed every frame.


    As a side note, you might wish to consider reusing your flare effect instead of spawning a new one every shot. You can make the effect invisible and reset it between shots instead, which would give better performance.