ゲームの重力
一部のゲームには、重力がオブジェクトを地面に引っ張るような、ゲームコンポーネントを一方向に引っ張る力があります。
重力
この機能をコンポーネントコンストラクターに追加するには、最初に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)">ACCELERATE</button>
ゲーム
これまでに学んだことに基づいてゲームを作成します。