This site requires JavaScript, please enable it in your browser!
Greenfoot back
insurqassable
insurqassable wrote ...

2019/12/5

Bow Shooting

insurqassable insurqassable

2019/12/5

#
Hey there, I'm programming a little game for university reasons. In this game, the player can shoot arrows with a bow, the direction is set by using the arrow keys and you shoot, if space is pressed. The problem is, if I don't put any timed limitations to shooting, you will just shoot infinitely (if keys are hold down for any time you want). Currently I'm using a counter, that increases by one every act. If this counter hit's any number which can be divided by 30, it will allow you to shoot. But this means, if you're unlucky, you would have to hold the spacebar for about a second until an arrow get's shot. Does anyone have any idea, how to fix this, so that you will shoot a new arrow the moment you hit space, but still having a delay between shooting, if the spacebar is hold down? Current code of my shoot method:
public void shoot(){
        if(hasBow==true){
            GameWorld world=(GameWorld)getWorld();
            int cases=0;
            if(Greenfoot.isKeyDown("up")||Greenfoot.isKeyDown("right")){
                setImage("HoldingBowRight.png");
                cases=1;
            }
            if(Greenfoot.isKeyDown("down")||Greenfoot.isKeyDown("left")){
                setImage("HoldingBowLeft.png");
                cases=1;
            }
            switch(cases){
                case 1: 
                    setWalkSpeed(0);
                    break;
                default:
                    setWalkSpeed(3);
                    break;
            }
            if(Greenfoot.isKeyDown("space")&&counter%30==0){
                if(Greenfoot.isKeyDown("up")){
                    world.addObject(new Arrow(270),this.getX(),this.getY()-this.getImage().getHeight()/2);
                }
                if(Greenfoot.isKeyDown("right")){
                    world.addObject(new Arrow(0),this.getX()+this.getImage().getWidth()/2,this.getY());
                }
                if(Greenfoot.isKeyDown("down")){
                    world.addObject(new Arrow(90),this.getX(),this.getY()+this.getImage().getHeight()/2);
                }
                if(Greenfoot.isKeyDown("left")){
                    world.addObject(new Arrow(180),this.getX()-this.getImage().getWidth()/2,this.getY());
                }
            }
        }
    }
We assume hasBow==true, the counter get's increased by one in the act method. The top section just takes care about changing images and the player not being able to walk while shooting.
danpost danpost

2019/12/5

#
Remove the counter and add a boolean to track the state of the "space" key. Check for a change in the state of the key by comparing current state to previous state (held by field). When a change is detected, update the field and check its new value to determine when to shoot.
You need to login to post a reply.