
บทเรียนเกี่ยวกับ Unity 3D สำหรับเขียนเกม 3 มิติ กับการศึกษาเรื่องของการใช้ Script ด้วย JavaScript เพื่อทบสอบการชนกันของวัตถุ หรือตรวจสอบ Collision Detection
แนะนำว่าให้ศึกษาบทเรียนก่อนหน้าก่อนจะปฏิบัติตามในบทเรียนนี้
- เริ่มต้นเขียนเกม 3D ด้วย Unity
- เขียนเกม 3D ด้วย Unity การจัดการ Game Object ในเกม
- เขียนเกม 3D ด้วย Unity เรียกใช้งาน Physics กับ Rigidbody
สร้าง GameObject ขึ้นมาใหม่ตามตัวอย่างดังนี้

ไปที่ตัว Cube ที่เราสร้่างมาก่อน สังเกตที่ Tab ชื่อ Project ให้ทำการ คลิกที่ Create เลือกสร้างไฟล์ Javascript

สร้างไฟล์ Javascript ขึ้นมาตั้งชื่อว่า falling

คลิกที่ไฟล์ falling.js ขึ้นมาแก้ไข ให้ใส่คำสั่งดังนี้ลงไป
function OnCollisionEnter(){ Debug.Log("Hit!"); }

เป็นคำสั่งที่ แสดง Log ว่า Hit! เมื่อวัตถุของเรา (Cube) ตกกระทบบางสิ่งใน GameScene ที่เราสร้างไว้ ทำการเอาไฟล์นี้ไปใช้กับ Cube ให้คลิกเลือก GameObjects ชื่อ Cube อีกครั้งทำการ Add Component ใหม่ ถ้าสังเกตดีๆ เราจะพบ Component ที่ชื่อว่า falling ปรากฏขึ้นมา

ทดลอง Run ตัว GameScene ของเราแล้วดูการตกของวัตถุ อย่าลืมใส่ RigidBody ของบทเรียนก่อนหน้านะครับ


จะเห็นว่าการตกกระทบโดนอะไรบางอย่างจะมีการแจ้งว่า “Hit!” เสมอ ให้เราตั้งชื่อ กำแพงที่เราสร้างด้วย Cube ใหม่ว่า Wall1, Wall2, Wall3 และตั้งชื่อ Plane สำหรับพื้นที่เราเล่น

แก้ไข falling.js ให้เป็นดังนี้
function OnCollisionEnter(theCollision : Collision){ if(theCollision.gameObject.name == "plane"{ Debug.Log("Hit the plane"); }else if(theCollision.gameObject.name == "Wall1"){ Debug.Log("Hit the wall1"); }else if(theCollision.gameObject.name == "Wall2"){ Debug.Log("Hit the wall2"); }else if(theCollision.gameObject.name == "Wall3"){ Debug.Log("Hit the wall3"); } }
ทดสอบ Run เกมของเราอีกครั้ง สังเกต Log ที่มันหล่นลงไป


เรียบร้อยไม่อยากเลยใช่ไหมครับ บทเรียนนี้ การใส่คำสั่ง Javascript เบื้องต้นสำหรับ Unity3D ตัวอย่างของ Video สำหรับทดสอบนั้นจะเป็นดังนี้ครับ