遊戲重力
有些遊戲會有力將遊戲元件拉向一個方向,就像重力將物體拉向地面一樣。
重力
要將此功能新增到我們的元件建構函式中,首先新增一個 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>
自己動手試一試 »
一個遊戲
根據我們目前所學到的知識製作一個遊戲