Search code examples
javagame-physics

How to limit player activity?


I have a simple game where a player shoots some bullets. However, I want to make it so that the player can only shoot a bullet every x seconds. How would I do this?

I have tried to do it by taking the average time between bullets and saying that if average time is less than one second don't let the space bar (the control for shooting) work. However, I don't know how to make the space bar not work, AND that would mean a player could just not shoot for a wile and then shoot a lot of bullets at once.

The method for shooting looks something like this:

public void keyPressed(KeyEvent e) {
    if (!keysDown.contains(e.getKeyCode()))
        keysDown.add(new Integer(e.getKeyCode()));

This adds the integer of the key value to an array, which is then read here:

if (keysDown.contains(KeyEvent.VK_SPACE)) {
        b = new Bullets(x);
        bullCount.add(b);
        System.out.println(bullCount.get(0).getY());
        System.out.println ("There are " + bullCount.size() + "bullets alive.");
        //elapsed = System.nanoTime() - start;
        //if ((elapsed / bulletCount) < 1000000000) {


       //this is where I would say 'no more bullets shot until 
       //average time in   nanoseconds is more than 1 second!' but I don't know how


        //}

Solution

  • Make a global variable ie: long lastShot.
    When user shot, check if (System.currentTimeMilis()-lastShot>5000) before you allow him to shoot.
    If it is ok to shoot, store the lastShot = System.currentTimeMilis(); and do the real shot.
    If not, don't allow him to shoot.
    Here is an example in pseudo-code:

    class SomeClass {
       private long lastShot;
    
       public void userPressedShot() {
           if (System.currentTimeMillis()-lastShot>5000) {
                lastShot = System.currentTimeMillis();
                doTheRealShot(); 
           }       
           // Ignored till 5000 miliseconds from last shot
       }
    
    }