Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections.Generic;
- using UnityEngine.Events;
- public class ObjectRoster : MonoBehaviour {
- public bool isControlling;
- public float spacing = 1;
- public float angleOffset = 180;
- public float snapDelay = .5f;
- public float snapTimer;
- [SerializeField]
- GameObject _previousGameObject;
- public RosterEvent onChangeObject;
- List<GameObject> gameObjects = new List<GameObject>();
- #region Properties
- protected int CurrentTurretIndex {
- get {
- if(gameObjects.Count == 0) return -1;
- return (int)(NearestAngle / SectionAngle);
- }
- }
- public GameObject CurrentGameObject {
- get {
- return CurrentTurretIndex > -1 ? gameObjects[CurrentTurretIndex] : null;
- }
- }
- public float NearestAngle {
- get { return WrapAngle(Mathf.Round(transform.localEulerAngles.y / SectionAngle) * SectionAngle); }
- }
- public float SectionAngle {
- get { return gameObjects.Count > 0 ? 360f / gameObjects.Count : 0; }
- }
- #endregion
- public virtual void AddGameObject(GameObject gameObject) {
- gameObjects.Add(gameObject);
- }
- protected virtual void Update() {
- if(isControlling) {
- float scroll = Input.GetAxis("Mouse ScrollWheel");
- if(Mathf.Abs(scroll) > float.Epsilon)
- Spin(Input.GetAxis("Mouse ScrollWheel") * 5);
- }
- if(gameObjects.Count > 0) {
- if(snapTimer > 0)
- snapTimer = Mathf.Max(snapTimer - Time.deltaTime, 0);
- if(snapTimer == 0) {
- Quaternion toAngle = Quaternion.Euler(transform.localEulerAngles.x, NearestAngle, transform.localEulerAngles.z);
- transform.rotation = Quaternion.RotateTowards(transform.localRotation, toAngle, Time.deltaTime * Quaternion.Angle(transform.localRotation, toAngle) * Mathf.PI);
- SetCurrentGameObject();
- }
- float angle = SectionAngle;
- for(int i = 0; i < gameObjects.Count; i++) {
- float currentAngle = angle * i;
- Vector3 position = new Vector3(Mathf.Sin(currentAngle * Mathf.Deg2Rad), 0, Mathf.Cos(currentAngle * Mathf.Deg2Rad));
- gameObjects[i].transform.position = transform.position + (transform.rotation * Quaternion.Euler(0, angleOffset, 0) * position * spacing);
- }
- }
- }
- public virtual void Spin(float speed) {
- if(snapTimer == 0)
- SetCurrentGameObject(null);
- snapTimer = snapDelay;
- transform.Rotate(0, speed, 0, Space.Self);
- }
- protected virtual void SetCurrentGameObject() {
- SetCurrentGameObject(CurrentGameObject);
- }
- protected virtual void SetCurrentGameObject(GameObject gameObject) {
- if(_previousGameObject == gameObject) return;
- _previousGameObject = gameObject;
- if(onChangeObject != null) onChangeObject.Invoke(gameObject);
- }
- protected static float WrapAngle(float angle) {
- float value = angle %= 360;
- if(value < 0) angle += 360;
- return angle;
- }
- [System.Serializable]
- public class RosterEvent : UnityEvent<GameObject> { }
- }
Advertisement
Add Comment
Please, Sign In to add comment