Selection Wheel Script
Антон Василевскийusing System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace Features.Build.Views
{
public class SelectionWheelView : MonoBehaviour
{
private const string MOUSE_X_AXIS = "Mouse X";
private const string MOUSE_Y_AXIS = "Mouse Y";
[SerializeField]
private RectTransform _selectionArrow;
[SerializeField]
private float _rotationStep = 5;
[SerializeField]
private float _directionMagnitude = 1f;
[SerializeField]
private float _lerpSpeed = 50f;
[SerializeField]
private int _selectionItems = 4;
[SerializeField]
private GameObject[] _selectionLevels;
[SerializeField]
private float _selectionLevelIncreaseTimer = 0.15f;
private Vector2 _currentMouseDirection;
private Vector2 _currentMouseMagnitude;
private Vector2 _currentWheelDirection;
private float _smoothedAngle;
private int _currentSelectionEdge;
private float _currentSelectionEdgeTimer;
private void Update()
{
CalculateDirection();
RotateArrow();
RotateEdges();
}
private void RotateEdges()
{
var rotationStep = 360 / _selectionItems;
var angleDegrees = Mathf.Round(_smoothedAngle / _rotationStep) * _rotationStep;
var selectionAngleDegrees = Mathf.Round(angleDegrees / rotationStep) * rotationStep;
var selectionEdge = selectionAngleDegrees / rotationStep;
var selectionEdgeInt = Mathf.RoundToInt(selectionEdge) % _selectionItems;
if (selectionEdgeInt != _currentSelectionEdge)
{
_currentSelectionEdge = selectionEdgeInt;
_currentSelectionEdgeTimer = 0;
}
_currentSelectionEdgeTimer += Time.deltaTime;
for (var i = 0; i < _selectionLevels.Length; i++)
{
var selectionLevel = _selectionLevels[i];
selectionLevel.transform.SetLocalEularZ(selectionAngleDegrees);
var show = _currentSelectionEdgeTimer > i * _selectionLevelIncreaseTimer;
selectionLevel.SetActive(show);
}
}
private void CalculateDirection()
{
var mouseAxisX = CrossPlatformInputManager.GetAxis(MOUSE_X_AXIS);
var mouseAxisY = CrossPlatformInputManager.GetAxis(MOUSE_Y_AXIS);
var mouseAxisVector = new Vector2(mouseAxisX, mouseAxisY);
_currentMouseDirection += mouseAxisVector;
_currentMouseMagnitude += new Vector2(Mathf.Abs(mouseAxisVector.x), Mathf.Abs(mouseAxisVector.y));
if (_currentMouseMagnitude.magnitude > _directionMagnitude)
{
_currentMouseDirection = _currentMouseDirection.normalized * _directionMagnitude;
_currentMouseMagnitude = _currentMouseMagnitude.normalized * _directionMagnitude;
_currentWheelDirection = _currentMouseDirection.normalized;
}
}
private void RotateArrow()
{
float angleRadians = Mathf.Atan2(-_currentWheelDirection.x, _currentWheelDirection.y);
float angleDegrees = angleRadians * Mathf.Rad2Deg;
angleDegrees = (angleDegrees + 360) % 360;
_smoothedAngle = Mathf.MoveTowardsAngle(_smoothedAngle, angleDegrees, Time.deltaTime * _lerpSpeed);
angleDegrees = Mathf.Round(_smoothedAngle / _rotationStep) * _rotationStep;
_selectionArrow.SetLocalEularZ(angleDegrees);
}
}
}
Телеграм-канал Jun GameDev