我试图用javacript创建游戏。我的对象可以在画布中的任何4个方向移动。我试图让它沿对角线移动。有任何想法如何做到这一点。
this.move = function () {
counter++;
// Determine if the action is move action
if (KEY_STATUS.left || KEY_STATUS.right || KEY_STATUS.down || KEY_STATUS.up || KEY_STATUS.shift || KEY_STATUS.ctrl) {
// The ship moved, so erase it's current image so it can
// be redrawn in it's new location
this.context.clearRect(this.x, this.y, this.width, this.height);
// Update x and y according to the direction to move and
// redraw the ship. Change the else if's to if statements
// to have diagonal movement.
if (KEY_STATUS.left) {
this.x -= this.speed;
if (this.x <= 0) // Keep player within the screen
this.x = 0;
}
else if (KEY_STATUS.right) {
this.x += this.speed;
if (this.x >= this.canvasWidth - this.width) this.x = this.canvasWidth - this.width;
}
else if (KEY_STATUS.up) {
console.log(this.y);
this.y -= this.speed;
if (this.y < 0) this.y = 0;
// if (this.y <= this.canvasHeight / 4 * 3) this.y = this.canvasHeight / 4 * 3;
}
else if (KEY_STATUS.down) {
this.y += this.speed;
if (this.y >= this.canvasHeight - this.height) this.y = this.canvasHeight - this.height;
console.log(this.canvasHeight);
console.log(this.height);
}
else if (KEY_STATUS.shift) {
this.speed += 2;
}
else if (KEY_STATUS.ctrl) {
if (this.speed > 2) {
this.speed -= 2;
}
else {
this.speed = 2;
}
}
// Finish by redrawing the ship
this.draw();
}
if (KEY_STATUS.space && counter >= fireRate) {
this.fire();
counter = 0;
}
};
所以基本上对角移动它应该例如do;
this.x += this.speed;
但同时做:
this.y += this.speed;
答案 0 :(得分:0)
你必须调整你的其他条件,如果条件为if,在它可以进入多个方向的情况下。
例如,您可能不想在同一侧上下或左右移动。因此,在这些情况下,您保持type: 'category',
position: 'left',
ticks: {
条件。否则,只需将else if条件更改为if条件。
我假设您也无法同时按下else if
和shift
。
以下是您的代码的外观。
control