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.

| improve this question | | | | |
\$\endgroup\$
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));
    } 
// ...
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ Optimizing away a subtraction... I'd like to see what kind of performance impact that makes :) \$\endgroup\$ – MichaelHouse Mar 5 '15 at 18:24
  • \$\begingroup\$ @jzx While introducing clarity you also changed logic, obscuring what said clarity is :) \$\endgroup\$ – Lars Viklund Mar 5 '15 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 '15 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.

| improve this answer | | | | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.