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

2020/4/27

Is it possible to change a players keystrokes while the scenario is running?

Fiona Fiona

2020/4/27

#
Hi Guys!! As the title suggests I was wondering whether it is possible to change a players keystrokes while the scenario is running? I have a world called controls and I want to be able to modify keystrokes without having to go into the code of actors. Below is the movement code for my Nancy actor class who is one of two playable characters.
    private void nancyMotion()
    {
        if (Greenfoot.isKeyDown("w"))
        {
            move(10);
        }
        if (Greenfoot.isKeyDown("a"))
        {
            turn(-10);
        }
        if (Greenfoot.isKeyDown("s"))
        {
            move(-10);
        }
     if (Greenfoot.isKeyDown("d"))
        {
            turn(10);
        }

    }
danpost danpost

2020/4/27

#
You cannot change them if they are given as literals ("a", "w", "s" and "d"). However, if you use retained variables (fields) for them ... yes. Then, you just change the field values.
Fiona Fiona

2020/4/27

#
How do you use retained variables for my controls?
danpost danpost

2020/4/27

#
Fiona wrote...
How do you use retained variables for my controls?
Fields are variables declared within the class, but outside of any methods:
String upKey = "w";
// others

private void nancyMotion()
{
    if (Greenfoot.isKeyDown(upKey)) move(10);
    // others
Fiona Fiona

2020/4/28

#
So i've changed it all to field variables how do I make it so keystrokes and modifiable while the scenario is running
danpost danpost

2020/4/28

#
Fiona wrote...
So i've changed it all to field variables how do I make it so keystrokes and modifiable while the scenario is running
Add a method to the class that will change them to new values:
public void setKeys(String up, String left, String down, String right)
{
    upKey = up;
    leftKey = left;
    downKey = down;
    rightKey = right;
}
Then in, let's say, your world, you will be able to call the method on the Nancy object and supply new keys. Let newUp, newLeft, newDown and newRight be String variables containing the new keys:
Nancy nancy = (Nancy)getObjects(Nancy.class).get(0);
nancy.setKeys(newUp, newLeft, newDown, newRight);
You need to login to post a reply.