Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why does timeBetweenShots = 0 if shotsPerSecond > 1

im making a game where you shoot up at things falling down and i want to make a system where you can upgrade how fast you can shoot. I’ve made a script where it gets the shotsPerSecond variable (integer variable that determines how many times you can shoot a second) and does 1 / shotsPerSecond to get timeBetweenShots (float variable that determines the time between each shot depending on the shotsPerSecond variable. So if shotsPerSecond was 2 it would do 1 / 2 and would come out to 0.5 and would and then it would only let you shoot if the timer was greater then 0.5)

public class Bullet_Shoot : MonoBehaviour
{
    public GameObject bullet;
    [SerializeField] private float timer;
    public int shotsPerSecond = 1;
    public float timeBetweenShots;

    private void Start()
    {
        timer = 100;
        timeBetweenShots = 1 / shotsPerSecond;
    }

    void Update()
    {
        timer += Time.deltaTime;

        if(Input.GetButtonDown("Shoot1")  && timer >= timeBetweenShots)
        {
            Instantiate(bullet, gameObject.transform.position, Quaternion.identity);
            timer = 0;
        }
    }
}

But whats happening is whenever shotsPerSecond is greater than 1 timeBetweenShots just comes out to 0. Does anyone know why?

i tried rearranging some code but nothing has worked at all.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s called integer division. An integer divided by another integer is still… an integer. Therefore when doing division with integers for both operands any floating point (decimal) portion of the result is truncated and lost.

I also see this code assigns the result to a float. However, each expression within a full statement must be able to stand alone, so the 1 / shotsPerSecond expression must fully resolve as an integer before the result can be assigned to the timeBetweenShots float value.

You can fix this by ensuring at least one of the division operands is also a floating point value. That way you’re no longer doing integer division:

timeBetweenShots = 1.0 / shotsPerSecond;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading