0
\$\begingroup\$

I made my character shoot but the amount of bullets he shoots is way too much. I'm trying to add a delay between bullets. I've tried this:

int shootTime = System.currentTimeMllis();

public void tick() {
    if(input.shoot && System.currentTimeMillis() - shootTime > 1000)
    {
        shootTime = (int) System.currentTimeMillis();
        shots.addBullet(new Bullet(xPos, yPos + 50));
    } 
  ........
  ........
}

I'm sure I'm doing something stupid but this is not working.

\$\endgroup\$
2

2 Answers 2

0
\$\begingroup\$

currentTimeMllis returns a long for the number of milliseconds since Jan 7, 1970 (~1,425,579,434,000 at the time of this post!), not an int since program start, so that might be one problem.

Also, minor point of clarity, I'd suggest using something like:

long nextShot = 0;
long recoilTime = 1000;

public void tick() {
    if(input.shoot && System.currentTimeMillis() > nextShot)
    {
        nextShot = System.currentTimeMillis() + recoilTime;
        shots.addBullet(new Bullet(xPos, yPos + 50));
    } 
// ...
\$\endgroup\$
3
  • \$\begingroup\$ Optimizing away a subtraction... I'd like to see what kind of performance impact that makes :) \$\endgroup\$
    – House
    Mar 5, 2015 at 18:24
  • \$\begingroup\$ @jzx While introducing clarity you also changed logic, obscuring what said clarity is :) \$\endgroup\$ Mar 5, 2015 at 18:50
  • \$\begingroup\$ Not really. if((a-b)>c) is much simpler than if(a>b). Also, using a variable (recoilTime) instead of a constant number tells you what that number is for. It's a pattern at least as old as Quake - see nextThink moddb.com/groups/quakedb/tutorials/quake-c-think-and-nextthink. \$\endgroup\$
    – jzx
    Mar 5, 2015 at 19:02
1
\$\begingroup\$

How many milliseconds since Jan 1 1970? About 1425579436439. That's more than fits in a integer. You need to use a long.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .