Roulette/Assets/Scripts/Spinner.cs
2023-03-06 16:48:12 +05:30

107 lines
3.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using TMPro;
public class Spinner : MonoBehaviour
{
public static Spinner instance;
void Awake(){
instance =this;
}
public static int LandedNumber{get; private set;}
public static UnityEvent<int> OnSpinStopped = new UnityEvent<int>();
public Transform wheel;
public Vector3 rotationAxis;
public float CurrentRotation { get{ return (wheel.rotation * rotationAxis).magnitude;}}
[Tooltip("Initial Spin force")]
public float SpinForce = 10;
[Tooltip("How smooth the speed goes up")]
public float SpinSmoothness = 1f;
public float SpinSmoothnessMax = 1f;
[Tooltip("How smooth the speed goes down")]
public float Friction = 0.005f;
[Tooltip("When should the wheel stop")]
public float StopSpeed =0.01f;
public int offset = -4;
public int CurNumber;
public float CurrentSpeed {get; private set;}
public TMP_Text numText;
public GameObject btnSpin;
void Start()
{
Debug.Log(RouletteManager.RouletteNumbers.Length);
}
bool pushing = false;
// Update is called once per frame
void FixedUpdate()
{
HandleFriction();
wheel.Rotate(rotationAxis * CurrentSpeed);
CurNumber = GetLandedNumber();
}
void HandleFriction(){
if(pushing){return;}
if(CurrentSpeed > 0){
if(CurrentSpeed < StopSpeed){
CurrentSpeed=0;
m_onSpinStopped();
}else{
CurrentSpeed -= Friction;
}
}
}
public void Spin(){
if(RouletteManager.GetBetsValue() <= 0){return;}
RouletteManager.spinning = true;
StartCoroutine(spin());
}
IEnumerator spin(){
btnSpin.SetActive(false);
pushing=true;
numText.text ="";
float m_spinSmoothness = Random.Range(SpinSmoothness, SpinSmoothnessMax);
while(CurrentSpeed < SpinForce){
CurrentSpeed += m_spinSmoothness;
yield return new WaitForFixedUpdate();
}
pushing = false;
}
private void m_onSpinStopped(){
RouletteManager.spinning = false;
LandedNumber = GetLandedNumber();
Debug.Log($"Landed on {LandedNumber}");
numText.text = LandedNumber.ToString();
if(LandedNumber == -1){numText.text = "00";}
OnSpinStopped.Invoke(LandedNumber);
btnSpin.SetActive(true);
}
int GetLandedNumber(){
float fraction = ((wheel.eulerAngles.z) / 360f) * (float)RouletteManager.RouletteNumbers.Length;
int index= Mathf.RoundToInt(fraction) + offset;
if(index < 0){
index = RouletteManager.RouletteNumbers.Length + index - 1;
}else if(index >= RouletteManager.RouletteNumbers.Length){
index = index - RouletteManager.RouletteNumbers.Length;
}
int m_LandedNumber = RouletteManager.RouletteNumbers[index];
return m_LandedNumber;
}
}