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

2017/4/16

Anyway to press a button through code?

MySimpleBox MySimpleBox

2017/4/16

#
Is there anyway in greenfoot that through code I can say that this key is now pressed? i.e. if (Greenfoot.isKeyDown("d")) { }
danpost danpost

2017/4/16

#
MySimpleBox wrote...
Is there anyway in greenfoot that through code I can say that this key is now pressed?
I do not see any reason why you would need to do that. If you could explain the situation and exactly what you are trying to do here as far as having two ways to trigger a down-key state, it would help immensely.
Yehuda Yehuda

2017/4/16

#
danpost wrote...
MySimpleBox wrote...
Is there anyway in greenfoot that through code I can say that this key is now pressed?
I do not see any reason why you would need to do that.
The only thing I can think of is that there is multiple places with that 'if' so it would be simpler to just have that 'if' be considered true even if it's not. But really instead of 'pressing a button through code' just run through the same code that's inside that if statement. Like this:
if (Greenfoot.isKeyDown("d")) {
    dPressed();
}

private void dPressed() {
    // code that you want to do when 'D' is pressed
    
    // now you can call this method whenever you want to run the code that's in it
    // instead of 'pressing a button through code'
}
MySimpleBox MySimpleBox

2017/4/20

#
I am creating a basic 'AI' and instead of having another actor, or copy and pasting code I would like to be able to use the 'AI's' code in the Player 2 actor (in a game) i.e. its controls are up, down, left right instead of coding in the actions I would instead like to just say 'this key is pressed' in code to re-use the P2 code without much more code (P2 is AI, if singleplayer option is chosen).
danpost danpost

2017/4/20

#
I think the closest you will get is getting values for 'dx' and 'dy' (the directions to move along each axis). I know that for me, the Robot class does not work. So, you would have something like this:
int dx = 0, dy = 0;
if (isAI())
{
    // determine direction to move by setting dx and dy values to one of { -1, 0, 1 }
    // maybe keeping last values and adjusting them would help to prevent oscillating movement
    // turning at edges would help to keep from sticking to them
}
else
{
    if (Greenfoot.isKeyDown("right")) dx++;
    if (Greenfoot.isKeyDown("left")) dx--;
    if (Greenfoot.isKeyDown("down")) dy++;
    if (Greenfoot.isKeyDown("up")) dy--;
]
Then determine if can move in given direction (this may have to be done for the AI in the isAI block so the AI actor does not look too dumb). Then regulate the move, if needed, and move.
You need to login to post a reply.