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

2019/1/14

Shooting in Multi-Player mode

KSH-Aeppli KSH-Aeppli

2019/1/14

#
I want to code a game where two players try to hit the same thing. The code for the shooting of Player 1 looks like this:
if ("down".equals(Greenfoot.getKey())) {
            Bullet bullet =  new  Bullet();
            int x = getX();
            int y = getY();
            int r = getRotation();
            bullet.setRotation(r);
            getWorld().addObject(bullet, x, y);
        }
I'm using the getKey()-method instead of the isKeyDown()-method because latter one doesn't seem to work properly: the first one just shoots once, and the second one shoots as long as the key is pressed. For Player 2 the code is almost the same, but using the "space"-key instead of the "down"-key. But Greenfoot doesn't react on this. It only reacts when Player 1 is dead and does not exist anymore. Any idea what is the problem and how to solve it? Or any different idea how to do two players shooting?
danpost danpost

2019/1/14

#
KSH-Aeppli wrote...
Any idea what is the problem and how to solve it? Or any different idea how to do two players shooting?
Any input key will only be fetched once with getKey. That means both players cannot use it individually. Otherwise, only one will get the key and it will not be there for the other one. You can use isKeyDown, but you must use it with a tracking field so that you can detect when the key state changes:
// using the following fields
private boolean shotKeyDown;
private String shotKey = "space"; // assigned however

// using code like this
if (Greenfoot.isKeyDown(shotKey) != shotKeyDown) // did state of key change?
{
    shotKeyDown = !shotKeyDown; // tracking (recording state change)
    if (shotKeyDown) // is new state that key is down?
    {
        shoot();
    }
}
KSH-Aeppli KSH-Aeppli

2019/1/15

#
Thank you, this works perfectly!
You need to login to post a reply.