简体   繁体   English

需要一种方法让我的角色在向左/向右移动时跳跃

[英]Need a way to have my character jump while moving left/right

I have already got the jumping on the y-axis running fine, but I want to be able to use 'dx' from jumping while pressing the left/right key (ex. if I am pressing right key to go right and jump while still holding it, the character will move in a "diagonal" way) 我已经让y轴上的跳跃运行良好,但是我希望能够在按下左/右键的同时使用'dx'跳跃(例如,如果我按右键向右跳并且仍然跳跃握住它,角色将以“对角线”的方式移动)

My main jumping code (timer activated when jump key is pressed): 我的主跳码(按下跳键时启动计时器):

 public void actionPerformed (ActionEvent e) {
    dy += 1;
        y_pos += dy;
    if (y_pos >= 400) {
        dy = 0;
        y_pos = 400;
       timer.stop();
    }   
    repaint();
}  

Now my KeyEvent code: 现在我的KeyEvent代码:

            if (command == KeyEvent.VK_RIGHT){
                x_pos += 5;
                right = true;
            }
            if (command == KeyEvent.VK_LEFT) {
                x_pos -= 5;
                right = false;
            }
            if (command == KeyEvent.VK_UP) {    
                if (!(timer.isRunning()))
                    dy = -20;   
                timer.start();
            }   
            dr.repaint();

Below is how I would implement the input logic. 下面是我如何实现输入逻辑。 Note that there are several choices when you want to dig further into input handling. 请注意,当您想进一步深入了解输入处理时,有几种选择。 Using this implementation, keyboard inputs are separated from the effects they have on the game world, which is handy in several ways. 使用此实现,键盘输入与它们对游戏世界的效果分开,这在几个方面很方便。 For example, the speed of the character is constant (given the timing of the game loop / movements is handled correctly) regardless of the frequency of key presses / repeats. 例如,无论按键/重复的频率如何,角色的速度都是恒定的(假设正确处理游戏循环/运动的时间)。

Anyway, some pseudo code: 无论如何,一些伪代码:

// Global:
array keysdown;
keysdown[left] = false;
keysdown[right] = false;
keysdown[up] = false;

// The all-important game loop:
while (true) {
    pollInputs();
    doMovement();
    draw();
}

function pollInputs () {
    foreach (key that you want to handle) {
        if (key.state == down) {
            keysdown[key] = true;
        } else {
            keysdown[key] = false;
        }
    }
}

function doMovement () {
    if (keysdown[left]) {
        // move character left
    } else if (keysdown[right]) {
        // move character right
    }

    if (keysdown[up]) {
        // initiate jump
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM