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

2021/2/27

How to start method as soon as Key is clicked

Znarf Znarf

2021/2/27

#
So I'm programming Snake rn and I have this method to change directions of the snake, the only problem is that this method is only checked once per action thus making it possible to click a button and the snake doesn't react. So the question is: Is it possible instead of checking once per move if a key is clicked to trigger a method as soon as a key is clicked? Btw that's my code: if(getRotation()==0) { if(Greenfoot.isKeyDown("s")) { turn(90); }if(Greenfoot.isKeyDown("w")) { turn(270); } } if(getRotation()==90) { if(Greenfoot.isKeyDown("a")) { turn(90); }if(Greenfoot.isKeyDown("d")) { turn(270); } } if(getRotation()==180) { if(Greenfoot.isKeyDown("w")) { turn(90); }if(Greenfoot.isKeyDown("s")) { turn(270); } } if(getRotation()==270) { if(Greenfoot.isKeyDown("d")) { turn(90); }if(Greenfoot.isKeyDown("a")) { turn(270); } }
danpost danpost

2021/2/27

#
Znarf wrote...
So I'm programming Snake rn and I have this method to change directions of the snake, the only problem is that this method is only checked once per action thus making it possible to click a button and the snake doesn't react. So the question is: Is it possible instead of checking once per move if a key is clicked to trigger a method as soon as a key is clicked? << Code Omitted >>
I can see where having multiple keys down here might be a problem. Other than that, I do not see what you explained. The code should turn the snake once any time a valid turn key is pressed. That is, if "up" or "down" is pressed while the snake is going left or right, it will turn; and similarly for "left" and "right" while snake is going up or down.
Znarf Znarf

2021/2/27

#
What I mean is that this will only turn, when this method is triggered, but Since this method is only triggered once every few Milliseconds I can press a key in between which will lead to no reaction because I pressed it at the wrong time too fast. Can I instead of using this method in act() make a Method that is triggered as sonn as a Key is pressed?
danpost danpost

2021/2/27

#
Oh, you are saying that your scenario is running at a very slow frame rate. Run at normal speed, use a int timer to regulate moving and track direction input with another int field.
You need to login to post a reply.