HTML 游戏重力
一些游戏用力量将游戏组件拉向一个方向,如重力将对象拉到地面上。
重力
要将此功能添加到我们的组件构造函数中,首先添加一个 gravity
属性,它设置当前的重力。然后添加 gravitySpeed
属性,每次更新帧时都会增加:
Example
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;
}
}
尝试一下 »
击中底部
为了防止红色方块永远下降,当它击中游戏区域的底部时,停止下降:
Example
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;
}
}
尝试一下 »
加速
在游戏中,当你有力量把你拉下来的时候,你应该有一个方法来迫使组件加速。
当有人点击一个按钮时触发一个功能,使红色方块在空中飞起来:
Example
<script>function accelerate(n) {
myGamePiece.gravity = n;
}</script>
<button onmousedown="accelerate(-0.2)"
onmouseup="accelerate(0.1)">ACCELERATE</button>
尝试一下 »
一个游戏
根据我们迄今为止学到的内容制作游戏: