98 lines
2.3 KiB
C#
Raw Normal View History

2026-01-28 20:57:35 +05:30
using System.Collections;
using UnityEngine;
public class Dice : MonoBehaviour
{
private Rigidbody rb;
private bool rolling;
[SerializeField] private DiceSide[] diceSides;
[SerializeField] private float sideValueTime = 1.2f;
[Header("Physics Randomness")]
[SerializeField] private float baseSpinForce = 900f;
[SerializeField] private float sideForce = 0.18f;
[SerializeField] private float liftForce = 0.1f;
// private BoardController boardController;
// public void Init(BoardController boardController)
// {
// this.boardController = boardController;
// transform.localScale = Vector3.one * 0.05f;
// transform.rotation = Random.rotation;
// }
void Awake()
{
rb = GetComponent<Rigidbody>();
rb.useGravity = false;
}
public void Roll()
{
if (!rolling)
StartCoroutine(RollRoutine());
}
IEnumerator RollRoutine()
{
rolling = true;
// 🔥 MICRO DELAY → breaks physics sync between dice
yield return new WaitForSeconds(Random.Range(0.01f, 0.06f));
rb.useGravity = true;
// 🔥 PER-DICE FORCE MULTIPLIER
float spinMultiplier = Random.Range(0.8f, 1.25f);
// 🔹 RANDOM TORQUE
rb.AddTorque(
Random.Range(-baseSpinForce, baseSpinForce) * spinMultiplier,
Random.Range(-baseSpinForce, baseSpinForce) * spinMultiplier,
Random.Range(-baseSpinForce, baseSpinForce) * spinMultiplier,
ForceMode.Impulse
);
// 🔹 RANDOM SIDE FORCE
Vector3 sideDir = new Vector3(
Random.Range(-1f, 1f),
0f,
Random.Range(-1f, 1f)
).normalized;
rb.AddForce(sideDir * sideForce, ForceMode.Impulse);
// 🔹 SMALL UPWARD FORCE
rb.AddForce(Vector3.up * liftForce, ForceMode.Impulse);
yield return new WaitForSeconds(sideValueTime);
int value = GetDiceValue();
// if (boardController != null)
// boardController.OnDiceResult(value);
// else
// Debug.LogError("DiceSpawner NULL");
rolling = false;
}
int GetDiceValue()
{
foreach (DiceSide side in diceSides)
{
if (side.OnGround())
return side.sideValue;
}
return 1;
}
}