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

2017/3/23

How to spam a key

20009557 20009557

2017/3/23

#
Hello. I want to be able to move the object by rapidly pressing alternate keys. However, whenever I hold down a button, the object keeps moving, which is not what I want. This is my code for moving. public void movement() { int x = getX(); int y = getY(); int r = 2; // String key = Greenfoot.getKey(); if (key == null) return; if ("s".equals(key)){ x+=2; } if ("a".equals(key)) { x+=2; } setLocation(x,y); }
danpost danpost

2017/3/23

#
You will need to track which key was last pressed:
1
2
3
4
5
6
7
8
9
//instance field
private String lastKey = "";
 
// in code
if (("s".equals(key) && !"s".equals(lastKey)) || ("a".equals(key) && !"a".equals(lastKey)))
{
    lastKey = key;
    x += 2;
}
You need to login to post a reply.