93 lines
2.6 KiB
C#
93 lines
2.6 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.Events;
|
|
using TMPro;
|
|
|
|
public class Spinner : MonoBehaviour
|
|
{
|
|
|
|
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;
|
|
|
|
void Start()
|
|
{
|
|
Debug.Log(RouletteManager.RouletteNumbers.Length);
|
|
}
|
|
bool pushing = false;
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
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(){
|
|
StartCoroutine(spin());
|
|
}
|
|
|
|
IEnumerator spin(){
|
|
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(){
|
|
|
|
LandedNumber = GetLandedNumber();
|
|
Debug.Log($"Landed on {LandedNumber}");
|
|
numText.text = LandedNumber.ToString();
|
|
|
|
|
|
|
|
OnSpinStopped.Invoke(LandedNumber);
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|