首页 > 解决方案 > key.code = 37 和 key.code = 39 不起作用

问题描述

我试图根据用户按下的箭头(左或右)左右移动佳能。这是我的代码:

size(400, 400, P2D);

//Constructor canon
var Canon = function(canonX, canonY, W){
fill(0, 0, 0);

    this.canonX = canonX;
    this.canonY = canonY;
    this.W = W;
};

//CANON MOVELEFT
Canon.prototype.moveLeft = function(){
    this.canonX -= 5;
};
Canon.prototype.moveRight = function(){
    this.canonX += 5;
};

//DRAW CANON
Canon.prototype.drawCanon = function(){
    quad(this.canonX - this.W/5, this.canonY + this.W * 2, this.canonX + 4/5 * this.W, 
this.canonY + 2 * this.W, this.canonX + 3 * this.W/5, this.canonY, this.canonX, this.canonY);
    ellipse(this.canonX + this.W/10 * 3, this.canonY + 2 * this.W, this.W, this.W/ 5 * 3);
    //wheels
    fill(138, 109, 23);
    ellipse(this.canonX - this.W/50 * 12, this.canonY + this.W/50 * 102, this.W/5 * 2, this.W/5 * 6);
    ellipse(this.canonX + this.W/50 * 42, this.canonY + this.W/50 * 102, this.W/5 * 2, this.W/5 * 6);

};

var canon = new Canon(199, 200, 50);
draw = function() {
    background(255, 255, 255);
    if(keyIsPressed && key.code === 37){
        canon.moveLeft();
    }
    else if(keyIsPressed && key.code === 39){
        canon.moveRight();
    }
    canon.drawCanon();

};

我尝试使用 32 的 e keyCode(用于空格)作为函数 moveLeft() 和 moveRight() 的条件。但不是左右箭头的keyCode......有人可以帮助我吗?

标签: javascriptprocessing.js

解决方案


推荐阅读