java - 如何使用两种不同的方法在按键时更改玩家角色的 x 值

标签 java keyboard char move keypress

代码的第一部分,包含按键输入、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/

相关文章:

c++ - 将 vector 元素串联成一个 32 位字

字符数组自行截断(K&R1-16&1-17)

c - 在c中逐字读取缓冲区

java - 带 post 数据的 android HTTP 请求

java - 如何在关闭JInternalFrame之前询问 "Are you sure?"?

java - AWS lambda无法发送smtp电子邮件

iphone - 如何在 iOS 中创建自定义键盘,如表情符号

java - 如何使用 Java 接口(interface)?

java - Android AdjustResize 无法正确调整大小

linux - 如何启动键盘映射项目