我的角色怎么能向左箭头键或右键的方向跳跃?

Posted

技术标签:

【中文标题】我的角色怎么能向左箭头键或右键的方向跳跃?【英文标题】:How can my character jump in the direction of the left arrow key or right key? 【发布时间】:2020-06-07 04:12:37 【问题描述】:

这是我的代码。每当我按下左箭头键时,当我按下空格键时,它会停止并跳跃,并且不再向左移动(与右箭头键相同)。

    stop();
    var Gravity = 5;
    var yLimit = 400 - char.height;
var friction = .9;
var velocity = 100;
var djctr = 0;
stage.addEventListener(Event.ENTER_FRAME, entFrame);
stage.addEventListener(KeyboardEvent.KEY_DOWN, control);

function control(event:KeyboardEvent)
    if(char.y >= yLimit || djctr == 2)
        if(event.keyCode == 32 && djctr !=2)
            char.y -= velocity;
            char.x += 7;
            djctr+=2;
        else if (event.keyCode == 32 && djctr == 2)
            char.y -= velocity * .50;
            djctr+=2;
            

    

    if(event.keyCode == 37)
            char.x -= 7;
    else if(event.keyCode == 39)
            char.x += 7;
    
    

function entFrame(e:Event)
    char.y += Gravity;
    if(char.y >= yLimit)
        char.y = 400-char.height;
        djctr = 0;
        
    

【问题讨论】:

【参考方案1】:

我为移动控制所做的是拥有两个阶段的 KeyboardEvent 侦听器(KEY_DOWN 和 KEY_UP),以及一个每帧运行的计时器。键盘事件不处理控制,它们只处理更改静态值,例如keyLeftIsDownkeyRightIsDown(在您的情况下,您也可以在按下空格键时处理),而 Timer 侦听器是处理控制的对象。这可能是这样的:

private var keyLeftIsDown:Boolean;
private var keyRightIsDown:Boolean;

//The '60' in '1000 / 60' is the frames per second the program runs in. Change it as needed
private var movementTimer:Timer = new Timer(1000 / 60);

private function initialize():void 
    stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
    stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
    timer.addEventListener(TimerEvent.TIMER, movementUpdate);
    timer.start();


private function keyDown(e:KeyboardEvent):void 
    if (e.keyCode == Keyboard.LEFT) 
        keyLeftIsDown = true;
    
    else if (e.keyCode == Keyboard.RIGHT) 
        keyRightIsDown = true;
    
    else if (e.keyCode == Keyboard.SPACE) 
        //jump code goes here
    


private function keyUp(e:KeyboardEvent):void 
    if (e.keyCode == Keyboard.LEFT) 
        keyLeftIsDown = false;
    
    else if (e.keyCode == Keyboard.RIGHT) 
        keyRightIsDown = false;
    


private function movementUpdate(e:TimerEvent):void 
    if (keyLeftIsDown && !keyRightIsDown) 
        char.x -= char.speed;
    
    else if (keyRightIsDown && !keyLeftIsDown) 
        char.x += char.speed;
    

这样,即使代码正在处理跳跃,字符也会沿 x 方向移动!

【讨论】:

以上是关于我的角色怎么能向左箭头键或右键的方向跳跃?的主要内容,如果未能解决你的问题,请参考以下文章

如何检测 C++ 中的组合键输入?

鼠标连点器怎么用?

用鼠标左键绘制折线,利用鼠标中键或右键终止绘制

Unity中,3D角色的移动(斜面上)、跳跃、冲刺

我安装的centos6.4版本,为啥在桌面上点击鼠标左键或右键,指针就变成了一个很小的点,几乎看不见?

Pygame:如何在不按任何键的情况下使精灵面对相同的方向