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

HTML เคลื่อนไหวเกม

ด้วยวิธีการใหม่ของส่วนประกอบการวาดภาพที่อธิบายไว้ในบทที่เกมการหมุนการเคลื่อนไหวที่มีความยืดหยุ่นมากขึ้น


วิธีการย้ายวัตถุ?

เพิ่ม 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);
    }
}
ลองตัวเอง»

ใช้แป้นพิมพ์

วิธีการที่ไม่สี่เหลี่ยมสีแดงย้ายเมื่อใช้แป้นพิมพ์? แทนการย้ายขึ้นและลงและจากทางด้านข้างสี่เหลี่ยมสีแดงเคลื่อนที่ไปข้างหน้าเมื่อคุณใช้ "up" ลูกศรและหันซ้ายและขวาเมื่อกดซ้ายและขวาลูกศร

ตัวอย่าง

ลองตัวเอง»