[英]Need to increment by 1 every time key is pressed-JavaFx
Every time I press a key, Right in this case, I need my p1Start value, in this case the p1StartX to increment by 1. This is used to "Draw" a path in a 2D array of type rectangle. 每次我按下一个键,在这种情况下,向右,我都需要我的p1Start值,在这种情况下,我的p1StartX值增加1。这用于“绘制”矩形2D数组中的路径。
My problem is, it only increments once. 我的问题是,它只会增加一次。 How can I fix this? 我怎样才能解决这个问题?
scene2.setOnKeyPressed(e -> {
int p1StartX = 5;
int p1StartY = 25;
int p2StartX = 60;
int p2StartY = 25;
if (e.getCode() == KeyCode.LEFT) {
p1.setDirection(1);
p1.update();
} else if (e.getCode() == KeyCode.RIGHT) {
p1StartX++;
gameGrid[p1StartY][p1StartX].setFill(p1.getPlayerClr());
System.out.println("Player 1: Right");
}
This happens because p1StartX
is defined inside the scope of your listener. 发生这种情况是因为p1StartX
是在侦听器范围内定义的。
Move it to a class member (static or not - up to your design...) - and things will be OK 将其移至类成员(静态或非静态-根据您的设计...)-一切都会好起来的
Moreover, I'm pretty sure this goes for all of your defined int
values. 而且,我很确定这适用于所有定义的int
值。
Like so: 像这样:
//some class definition...
private int p1StartX;
//Use a constructor to init the value of p1StartX.
...
scene2.setOnKeyPressed(e -> {
....
p1StartX++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.