Game 重力

❮ 前章へ 次章へ ❯

いくつかのゲームには、重力がオブジェクトを地面に引き寄せるような、ゲームコンポーネントを一方向に引っ張る力を持つものががあります。




重力

この機能を component コンストラクタに追加するには、まず現在の重力を設定する 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;
    }
}
Try it Yourself »

底に当たる

赤い四角が永遠に落ちないようにするには、ゲームエリアの底に当たったときに落るのを止めます:

    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;
        }
    }

Try it Yourself »

加速する

ゲームにおいて、下に引き落とす力があるときは、コンポーネントを加速させるメソッドが必要です。

ボタンをクリックしたときに関数をトリガーし、赤い四角を空中に浮遊させます:

<script>
function accelerate(n) {
    myGamePiece.gravity = n;
}
</script>

<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>
Try it Yourself »

ゲーム

これまでに学んだことに基づいてゲームを作りましょう:

Try it Yourself »
❮ 前章へ 次章へ ❯