游戏重力
有些游戏中存在将游戏组件拉向一个方向的力,例如重力将物体拉向地面。
重力
如需将此特性添加到我们的组件构造函数中,请首先添加一个 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;
}
}
触底
为了防止红色方块永远下落,我们需要在它到达游戏区域底部时停止下落:
实例
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
}
}
加速
在游戏中,当有一个力把方块拉下来时,您应该设计一个方法来迫使组件加速。
当有人点击按钮时触发一个函数,让红色方块飞到空中:
实例
<script>
function accelerate(n) {
myGamePiece.gravity = n;
}
</script>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">加速</button>
一个游戏
根据我们迄今为止所学到的知识制作一个游戏:
实例
请单击加速按钮开始游戏。
能活多久?请使用加速按钮保持在空中。