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

2017/1/12

Shooting only once

nat12 nat12

2017/1/12

#
So I made my shooting code (Spawns bullet once space is pressed) However, the problem is that it will spawn the object over and over if space is down. I tried using getKey, and now it will only spawn the bullet over and over if I'm only moving in one direction. Let's say it fixed it 50%, as it no longer does it when I move in multiple directions. Moving code:
    public void playerMove()
    {
        int dx=0, dy=0;
        if(Greenfoot.isKeyDown("up")) dy--;
        if(Greenfoot.isKeyDown("down")) dy++;
        if(Greenfoot.isKeyDown("right")) dx++;
        if(Greenfoot.isKeyDown("left")) dx--;

        if (dx == 0 && dy == 0) return;
        switch(dx)
        {
            case -1:
            setRotation(180-45*dy);
            break;

            case 0:
            setRotation(180-90*dy);
            break;

            case 1:
            setRotation(45*dy);
            break;
        }
        move(speed);
    }
Shooting code:
    public void shoot()
    {
        if ("space".equals(Greenfoot.getKey()))
        {
            PlayerBullet playerbullet = new PlayerBullet();
            getWorld().addObject(playerbullet, getX(), getY());
            playerbullet.setRotation(getRotation());
            
        }
    }
danpost danpost

2017/1/12

#
You should use 'isKeyDown' instead of 'getKey'. Since it was spawning a bullet every act cycle, you just need to add an int timer to slow it down (so it can skip so many act cycles before shooting again).
You need to login to post a reply.