Gravity 属性
要将此功能添加到组件构造函数中,首先添加一个 gravity 属性,该属性设置当前的重力。然后添加一个 gravitySpeed 属性,该属性在每次更新帧时都会增加:
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
}
}
当击中一个新的障碍物时,使用一个声音来制造一个新的障碍物:
var myGamePiece;
var myObstacles = [];
var mySound;
function startGame() {
myGamePiece = new component(30, 30, "red", 10, 120);
mySound = new sound("bounce.mp3");
myGameArea.start();
}
function updateGameArea() {
var x, height, gap, minHeight, maxHeight, minGap, maxGap;
for (i = 0; i < myObstacles.length; i += 1) {
if (myGamePiece.crashWith(myObstacles[i])) {
mySound.play();
myGameArea.stop();
return;
}
}
...
}
尝试一下