บทนำ (Overview)
จากบทความที่แล้ว (How to create the game with Phaser framework (Part1)) ได้กล่าวถึงการเรียกใช้ “Phaser framework” และโครงสร้างของไดเรกทรอรี่และไฟล์ตัวอย่าง จากนั้นก็นำมาสร้าง “Game World” หรือกรอบของ Game ที่จะเขียนลงไปรวมถึงชื่อ Function และพารามิเตอร์แต่ตัวเพื่อใช้ในการสร้าง “Game World” ต่อไป
ในบทความนี้จะทำการโหลดรูปต่าง ๆ ที่อยู่ในโฟลเดอร์ “/assets” ที่จำเป็นต่อการสร้าง “Game” ของเราเข้ามาก่อน โดยการโหลดนั้นจะยังไม่ถูกแสดงบนหน้าจอ “Web Browser”
ขั้นตอน (Steps)
- เปิดไฟล์ “part2.html”
- จากคราวที่แล้วจะพบว่าส่วนของ ฟังก์ชันก์ “preload” จะหว่างเราจะแทนที่คำสั่งดังต่อไปนี้
<script type="text/javascript"> var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { game.load.image('sky', 'assets/sky.png'); game.load.image('ground', 'assets/platform.png'); game.load.image('star', 'assets/star.png'); game.load.spritesheet('dude', 'assets/dude.png', 32, 48); } function create() { } function update() { } </script>
- “game” คือชื่อตัวแปรที่ถูกสร้างมาเป็น “Game World” ของเรา จาก “new Phaser.Game“
- ดังนั้นตัวแปร “game” จึงมีความสามารถเรียกใช้ “method” ต่างจาก “Phaser.Game” ที่กำหนดไว้ได้ ในที่นี้เลือกใช้ “method” ของ “game.load” เพื่อโหลดรูปภาพเข้ามาใช้งาน
- เพราะฉะนั้นการโหลดอะไรก็ตามเข้ามาสู่ใน “Game World” จะต้องอยู่ใน “function preload()“
- จากใน “function preload()” เราทำการโหลด 4 assets โดยรูปที่เป็นภาพเดี่ยว 3 รูป และเป็นรูปใช้สำหรับภาพเคลื่อนไหว 1 รูป (sprite sheet)
- โดยรูปภาพเดี่ยวจะเรียกใช้ “properties” ชื่อ “images” และ มีพารามิเตอร์ดังนี้
game.load.image('ชื่ออ้างอิง', 'folder/image.png');
- ส่วนรูป “sprite sheet” จะเรียกใช้ “properties” ชื่อ “images” และ มีพารามิเตอร์ดังนี้
game.load.spritesheet('ชื่ออ้างอิง', 'folder/image.png', ความกว้างของ frame, ความยาวของ frame);
- ทดสอบเปิดใน “Web Browser” จะพบว่ายังเป็นจอดำ ๆ เหมือนบทความที่แล้ว
บทความที่เกี่ยวข้อง
- How to create the game with Phaser framework (Part1) – Start Game World
- How to create the game with Phaser framework (Part2) – Function preload()
- How to create the game with Phaser framework (Part3) – Display Images
- How to create the game with Phaser framework (Part4) – Function create()
- How to create the game with Phaser framework (Part5) – Physics
- How to create the game with Phaser framework (Part6) – Collide
- How to create the game with Phaser framework (Part7) – Control
- How to create the game with Phaser framework (Part8) – Animation
- How to create the game with Phaser framework (Part9) – Star Shines
- How to create the game with Phaser framework (Part10) – Keep Star
- How to create the game with Phaser framework (Part11) – Count Score