Chuẩn bị
- Cài đặt Unity phiên bản 2019.4.1f trở lên.
- Tải Unity package: DiceGameProject.zip
Thành phẩm
Hướng dẫn
Tạo project 3D trên Unity

Import Package




Run project
Sau khi import package thành công, nhấn F5 để chạy test game.

Giải thích Scripts
Dice.cs Scripts
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Dice : MonoBehaviour { static Rigidbody m_Ridgidbody; static Vector3 m_DiceVelocity; // Use this for initialization void Start () { m_Ridgidbody = GetComponent (); } // Update is called once per frame void Update () { m_DiceVelocity = m_Ridgidbody.velocity; if (Input.GetKeyDown (KeyCode.Space) || Input.GetMouseButton(0)) { Color color = new Color(1f, 1f, 1f); DiceNumberText.setText(0); DiceNumberText.setColor(color); float dirX = Random.Range (0, 500); float dirY = Random.Range (0, 500); float dirZ = Random.Range (0, 500); transform.position = new Vector3 (0, 5.5f, 3f); transform.rotation = Quaternion.identity; //m_Ridgidbody.AddForce (transform.up * 100); m_Ridgidbody.AddTorque (dirX, dirY, dirZ); } } public static Vector3 getDiceVelocity() { return m_DiceVelocity; } }
Scripts xử lý sự kiện chuột hoặc bàn phím để thiết lập lại vị trí và thêm vào một lực momen xoắn ngẫu nhiên cho xúc xắc. Đồng thời sẽ thiết lập lại màu cho việc hiển thị số điểm.
DiceCheckSide.cs Scripts
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DiceCheckSide : MonoBehaviour { Vector3 m_DiceVelocity; // Update is called once per frame void FixedUpdate () { m_DiceVelocity = Dice.getDiceVelocity(); } void OnTriggerStay(Collider col) { switch (col.gameObject.name) { case "Side1": DiceNumberText.setText(3); break; case "Side2": DiceNumberText.setText(4); break; case "Side3": DiceNumberText.setText(1); break; case "Side4": DiceNumberText.setText(2); break; case "Side5": DiceNumberText.setText(6); break; case "Side6": DiceNumberText.setText(5); break; } if (m_DiceVelocity == new Vector3(0f, 0f, 0f)) { Color color = new Color(0.09f, 0.9f, 0.02f); DiceNumberText.setColor(color); } } }
Scripts xử lý va chạm giữa xúc xắc với nền, và trả về giá trị của xúc xắc để hiển thị điểm. Đồng thời khi xúc xắc đứng yên thì thiết lập màu mới cho số điểm hiển thị.
DiceNumberText.cs Scripts
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DiceNumberText : MonoBehaviour { static Text m_Text; static int m_DiceNumber; // Use this for initialization void Start () { m_Text = GetComponent (); } // Update is called once per frame void Update () { m_Text.text = m_DiceNumber.ToString (); } public static void setText(int number) { m_DiceNumber = number; } public static void setColor(Color color) { m_Text.color = color; } }
Scripts xử lý việc hiển thị màu và giá trị điểm của xúc xắc.