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

2016/10/19

Character shooting

Jillis Jillis

2016/10/19

#
Hi my character only shoots left when pressing the left arrow key. The other arrow keys do nothing, why is this?
    public void act() 
    {
        if (Greenfoot.isKeyDown("a"))
        {
            setRotation(180);
            move(10);
        }
        if (Greenfoot.isKeyDown("d"))
        {
            setRotation(0);
            move(10);
        }
        if (Greenfoot.isKeyDown("w"))
        {
            setRotation(270);
            move(10);
        }
        if (Greenfoot.isKeyDown("s"))
        {
            setRotation(90);
            move(10);
        }
        if ("left".equals(Greenfoot.getKey()))
        {
            setRotation(180);
            fire();
        }
        if ("right".equals(Greenfoot.getKey()))
        {
            setRotation(0);
            fire();
        }
        if ("down".equals(Greenfoot.getKey()))
        {
            setRotation(90);
            fire();
        }
        if ("up".equals(Greenfoot.getKey()))
        {
            setRotation(270);
            fire();
        }
    }
    private void fire()
    {
        Bullet bullet = new Bullet();
        getWorld().addObject(bullet, getX(), getY());
        bullet.setRotation(getRotation());
        bullet.move(30);
    }
Here is the bullet act
    public void act() 
    {
        move(10);
    }   
danpost danpost

2016/10/19

#
You can only use 'getKey' once per act cycle. You are using it four times here, at lines 23, 28, 33 and 38. Any key return by line 23 will not be returned again on the subsequent lines. If no more keys are waiting in the keyboard buffer, 'null' will be returned. Hence, the subsequent codes for firing never execute. Get the key once, before any checks and hold it in a String variable; then, compare the contents of the variable for the matching values:
String key = Greenfoot.getKey();
if ("up".equals(key))...
if ("down".equals(key))...
etc.
You need to login to post a reply.