เกมแรงโน้มถ่วง
เกมบางเกมมีแรงที่ดึงส่วนประกอบของเกมไปในทิศทางเดียว เช่น แรงโน้มถ่วงดึงวัตถุลงกับพื้น
แรงโน้มถ่วง
หากต้องการเพิ่มฟังก์ชันนี้ให้กับตัวสร้างส่วนประกอบ ขั้นแรกให้เพิ่ม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>
เกม
สร้างเกมจากสิ่งที่เราได้เรียนรู้ไปแล้ว: