javascript蜈蚣,按键不工作

javascript Centipede, key press not working

本文关键字:工作 蜈蚣 javascript      更新时间:2024-06-18

我在Khan Academy教程中用javascript构建了蜈蚣。然后我想好了如何将其放入网络浏览器中。但是,按键不起作用。我曾尝试更改keyCode值,并将一些函数定义更改为"void",但都没有成功。该应用程序使用processing.js来工作。以下是js中处理密钥的部分:

var Player = function(x,y,size,speed){
    this.x = x;
    this.y = y;
    this.size = size;
    this.speed = speed;
    this.update = function(){
        if(keys[LEFT]){
        this.x -= this.speed;
        }
        if(keys[RIGHT]){
        this.x += this.speed;
        } 
        if(keys[DOWN]){
        this.y += this.speed;
        }
        if(keys[UP]){
        this.y -= this.speed;
        }
        if(keys[76] && bulletDelay < 0){
        var b = new Bullet(this.x, this.y, 5,5);
        bullets.push(b);
        bulletDelay = 40;
        }

       if (this.x < 0){
         this.x = 0;
        }
       if (this.x > width){
         this.x = width;
       }
       if (this.y > 800){
         this.y = 800;
       }
   //This adjusts the max height the player can move up on y-axis. Adjust to make more like Atari version
   if (this.y < 100) {
    this.y = 100;
   }
   noStroke();
   fill(0,255,0);
    ellipse(this.x, this.y, this.size, this.size);
};
};

我把它整理好了。需要从更改按键按压和按键释放功能

var keyPressed = function(){

void keyPressed() . . .

类似于keyReleased函数

语法

if(keys[LEFT])

应该是

if(keyCode == LEFT)

参见Processing.js keyCode参考和密钥

编辑1:对于特殊键(箭头、空格),应使用keyCode而不是key