HTML 游戏重力



  • 定义和使用

    有些游戏的力会将游戏组件拉向一个方向,就像重力把物体拉到地面上一样
  • Gravity 属性

    要将此功能添加到组件构造函数中,首先添加一个 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;
        }
    }
    当击中一个新的障碍物时,使用一个声音来制造一个新的障碍物:
    var myGamePiece;
    var myObstacles = [];
    var mySound;
    
    function startGame() {
        myGamePiece = new component(30, 30, "red", 10, 120);
        mySound = new sound("bounce.mp3");
        myGameArea.start();
    }
    
    function updateGameArea() {
        var x, height, gap, minHeight, maxHeight, minGap, maxGap;
        for (i = 0; i < myObstacles.length; i += 1) {
            if (myGamePiece.crashWith(myObstacles[i])) {
                mySound.play();
                myGameArea.stop();
                return;
            }
        }
    
    ...
    
    }
    尝试一下
  • 触底

    为了防止红方永远下落,当红方击中游戏区域底部时停止坠落:
    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>
    尝试一下
    根据我们目前所学的知识制作一个游戏:一个游戏示例