การเคลื่อนไหวของเกม
ด้วยวิธีใหม่ในการวาดภาพส่วนประกอบที่อธิบายในบท Game Rotation การเคลื่อนไหวจะยืดหยุ่นมากขึ้น
วิธีการย้ายวัตถุ?
เพิ่มspeed
คุณสมบัติให้กับตัวcomponent
สร้าง ซึ่งแสดงถึงความเร็วปัจจุบันของส่วนประกอบ
ทำการเปลี่ยนแปลงวิธีการบางอย่าง เพื่อคำนวณตำแหน่ง ของnewPos()
ส่วนประกอบตามspeed
และangle
โดยค่าเริ่มต้น ส่วนประกอบจะหงายขึ้น และโดยการตั้งค่าคุณสมบัติความเร็วเป็น 1 ส่วนประกอบจะเริ่มเคลื่อนที่ไปข้างหน้า
ตัวอย่าง
function component(width, height, color, x, y) {
this.gamearea = gamearea;
this.width = width;
this.height = height;
this.angle = 0;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
พลิกตัว
เรายังต้องการที่จะสามารถเลี้ยวซ้ายและขวาได้ สร้างคุณสมบัติใหม่ที่เรียกว่าmoveAngle
ซึ่งระบุค่าเคลื่อนที่ปัจจุบันหรือมุมการหมุน ในnewPos()
วิธีการคำนวณ
angle
ตามmoveAngle
คุณสมบัติ:
ตัวอย่าง
ตั้งค่าคุณสมบัติ moveangle เป็น 1 และดูว่าเกิดอะไรขึ้น:
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.angle = 0;
this.moveAngle = 1;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
ใช้คีย์บอร์ด
สี่เหลี่ยมสีแดงเคลื่อนไหวอย่างไรเมื่อใช้แป้นพิมพ์ แทนที่จะเลื่อนขึ้นและลง และจากด้านหนึ่งไปอีกด้านหนึ่ง สี่เหลี่ยมสีแดงจะเคลื่อนที่ไปข้างหน้าเมื่อคุณใช้ลูกศร "ขึ้น" และหมุนไปทางซ้ายและขวาเมื่อกดลูกศรซ้ายและขวา