C# Move 3D object ใน Space Shooter Game
Serializable เป็น code ที่เป็นตัวบอกให้แสดงค่าตัวแปรที่เป็น public ใน code component ในกรณีที่ มีอีก object ใน file เดียวกัน
หรือง่ายๆ คือการ embed class ด้วย sub properties เข้่าไปใน object เดียวกัน
[System.Serializable]
ส่วนสำคัญของการเครื่องที่จะอยู่ที่ rigidbody.velocity รับค่า Vector3 จากคีย์บอร์ด
โดยตัวแปร speed จะเป็นตัวปรับความเร็วในการเคลี่ยนที่
float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); rigidbody.velocity = movement * speed;
ตีกรอบให้วัตถุไม่เคลื่อนที่ออกไปนอกกรอบที่กำหนด คำสั่งที่สำคัญคือ Mathf.Clamp คำสั่งนี้จะเป็นการกำหนดค่าให้อยู่ระหว่างค่าที่กำหนด
rigidbody.position = new Vector3(Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax),0.0f, Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax));
เป็นคำสั่งที่ทำให้การเคลื่อนที่ดูสมจริงมากขึ้น ในกรณีที่เป็นยานอวกาศนะ เมื่อเคลื่อนที่ไปทางซ้ายจะเบนวัตถุไปทางซ้ายและมรกรณีเดียวกันกับทางขวา
โดยค่า tilt เอาไว้กำหนดกว่าจะให้เอียงมากหรือน้อย
rigidbody.rotation = Quaternion.Euler(0.0f, 0.0f, rigidbody.velocity.x * -tilt);
ภาพรวมนะจ๊ะ
using UnityEngine; using System.Collections; [System.Serializable] public class Boundary { public float xMin, xMax, zMin, zMax; } public class PlayerController : MonoBehaviour { public float speed; public float tilt; public Boundary boundary; public GameObject shot; public Transform shotSpawn; public float fireRate = 0.5F; private float nextFire = 0.0F; void Update() { if (Input.GetButton("Fire1") && Time.time > nextFire) { nextFire = Time.time + fireRate; //GameObject clone = Instantiate(shot, shotSpawn.position, shotSpawn.rotation); // as GameObject; } // กดแล้วยิง } void FixedUpdate() { float moveHorizontal = Input.GetAxis("Horizontal"); //รับค่าจาก ปุ่มบน-ล่าง float moveVertical = Input.GetAxis("Vertical"); //รับค่าจาก ปุ่มซ้าย-ขวา Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); rigidbody.velocity = movement * speed; //เคลื่อนที่วัตถุ rigidbody.position = new Vector3( Mathf.Clamp(rigidbody.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rigidbody.position.z, boundary.zMin, boundary.zMax) ); //ตีกรอบให้วัตถุไม่เคลื่อนที่ออกไปนอกกรอบที่กำหนด rigidbody.rotation = Quaternion.Euler(0.0f, 0.0f, rigidbody.velocity.x * -tilt); } }