The time between the shot of the bullets

Mine is not working, the bullet is coming out, but then it stays at one point and not moving forward, its says that, it need the variables of the bullets, and heres my script:

What is supposed to move your bullet? Did you set a constant force? If there are errors you should post the complete message from the log. Also please do not post scripts as images, but add a screenshot of your bullet gameobject in the inspector instead.

you are instantiating the bullet but not added a force to it so will not move.

1 Answer

1

void Update()
{
//If fire button is pressed and we can shoot again
if (Input.GetKey(fireButton) && shootAgain)
{
//Create a copy of the bullet
GameObject copyOfBulletPrefab = (GameObject) Instantiate(bulletPrefab, transform.position, transform.rotation);
//Add forces to the bullet
copyOfBulletPrefab.GetComponent().AddForce(Vector3.forward * shootingPower);
//Set shooter position in bullet
//copyOfBulletPrefab.SendMessage(“SetShooterPosition”, transform.position);

        //We can't shoot again
        shootAgain = false;   
    }

    //If we can't
    if (!shootAgain)
    {
        //Add to the shootTimer
        shootTimer += Time.deltaTime;

        //If the shootTimer is greater than value:
        if(shootTimer > 60 / roundsPerMinute)
        {
            //We can shoot again
            shootAgain = true;
            //Reset the timer
            shootTimer = 0.0f;
        }
    }
}

One of the correct ways to shoot a projectile:

Create a copy.
It’s very important to create a copy of your bullet. Otherwise you might be running code on a gameobject that is already in the scene or is not even in the scene yet.

Apply forces.
Because we create a bullet in just 1 frame, we cant apply any translations or position changes, thats why a rigidbody is being used. Just “add force” in the “direction” you want and let the bullet do the rest.

Send message to bullet
You might be wondering, what’s up with the SendMessage? We’ll this isnt a must, but it could be very useful to you. Shooting a lot of bullets will create a lot of gameobjects in your scene. By destroying the ones that are too far away, you can keep the gameobjects to a minimum. So as a little bonus, here’s the code you can add to your bullets:

private Vector3 shootPosition;
public float destroyAtDistance = 10f;

public void SetShooterPosition(Vector3 position)
{
    shootPosition = position;
}

public void Update()
{
    //Calculate distance between shooter and bullet
    float distance = Vector3.Distance(shootPosition, transform.position);
    //If we reached the distance:
    if(distance > destroyAtDistance)
    {
        //Destroy the bullet
        Destroy(this.gameObject);
    }
}

Hope i gave you enough information!

Yes, that's the problem. I did it too and worked.