代码的第一部分,包含按键输入、vk_down 等。我根本不允许更改,第二部分是我的代码。我需要知道如何执行玩家的 move ,其中 x 和 y 在 Performaction() 方法中的位置,同时使用附加到代码第一部分中的 setkey 函数的字符。我不知道如何正确链接它们。目前没有错误,但当我玩时,角色不 move
它也已经拥有所有的 keyevent 导入等
提前致谢
public void keyPressed(KeyEvent ke) {
// Below, the setKey method is used to tell the Player object which key is
// currently pressed.
// The Player object must keep track of the pressed key and use it for
// determining the direction
// to move.
// Important: The setKey method in Player must not move the Player.
if (ke.getKeyCode() == KeyEvent.VK_LEFT)
this.player.setKey('L', true);
if (ke.getKeyCode() == KeyEvent.VK_RIGHT)
this.player.setKey('R', true);
if (ke.getKeyCode() == KeyEvent.VK_UP)
this.player.setKey('U', true);
if (ke.getKeyCode() == KeyEvent.VK_DOWN)
this.player.setKey('D', true);
if (ke.getKeyCode() == KeyEvent.VK_ESCAPE)
this.continueGame = false;
return;
}
<小时/>
char c;
public void performAction() {
if (c == 'L') {
this.x += -10000;
}
}
public void setKey(char c, boolean b) {
}
最佳答案
如果我理解正确的话:
public void performAction(char c) {
switch (c) {
case "L": this.x += -10000; break;
case "R": this.x += 10000; break;
case "U": this.y += 10000; break;
case "D": this.y += -10000; break;
}
}
public void setKey(char c, boolean b) {
// do some stuff
// ...
performAction(c);
}
更新: 使用当前字符的私有(private)字段:
class SomeClass {
// ...
// Keep the value
private char c; // (5)
public void performAction() {
// Read the value
switch (this.c) {
case "L": this.x += -10000; break;
case "R": this.x += 10000; break;
case "U": this.y += 10000; break;
case "D": this.y += -10000; break;
}
}
public void setKey(char c, boolean b) {
// ...
// Having used 'this.' you can invoke variable of the class (aka 'field')
// which declared at 5 line.
//
// Assign a new value to the field.
this.c = c;
performAction();
}
}
关于java - 如何使用两种不同的方法在按键时更改玩家角色的 x 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56105313/