ล่าสุดการพัฒนาเว็บบทเรียน
 

HTML เกมแรงโน้มถ่วง


เกมบางเกมมีกองกำลังที่ดึงองค์ประกอบเกมในทิศทางเดียวเช่นแรงโน้มถ่วงดึงวัตถุกับพื้นดิน




แรงดึงดูด

ในการเพิ่มฟังก์ชั่นนี้เพื่อตัวสร้างองค์ประกอบของเราครั้งแรกเพิ่ม 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 ;
    }
}
ลองตัวเอง»

ตีด้านล่าง

เพื่อป้องกันไม่ให้ตารางสีแดงจากการล้มตลอดหยุดตกเมื่อ hits พื้นที่ด้านล่างของเกม:

ตัวอย่าง

    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>
ลองตัวเอง»

เกม

ทำให้เกมเป็นไปตามสิ่งที่เราได้เรียนรู้เพื่อให้ห่างไกล:

ตัวอย่าง

ลองตัวเอง»