Tanoda
AvatarController.cs
Go to the documentation of this file.
1using UnityEngine;
2
3namespace TriLibCore.Samples
4{
6 public class AvatarController : MonoBehaviour
7 {
9 public static AvatarController Instance { get; private set; }
10
14 private const float MaxSpeed = 2f;
15
19 private const float Acceleration = 5f;
20
24 private const float Friction = 2f;
25
29 private const float RotationSpeed = 60f;
30
35
40
44 public GameObject InnerAvatar;
45
49 private Vector3 _cameraOffset;
50
54 private float _speed;
55
59 private Vector3 _cameraHeightOffset;
60
61
65 private float _currentVelocity;
66
68 private void Awake()
69 {
70 Instance = this;
71 _cameraHeightOffset = new Vector3(0f, CharacterController.height * 0.8f, 0f);
72 _cameraOffset = Camera.main.transform.position - transform.position;
73 }
74
76 private void Update()
77 {
78 var input = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
79 var direction = Camera.main.transform.TransformDirection(input);
80 direction.y = 0f;
81 direction.Normalize();
82 var targetEulerAngles = direction.magnitude > 0
83 ? Quaternion.LookRotation(direction).eulerAngles
84 : transform.rotation.eulerAngles;
85 var eulerAngles = transform.rotation.eulerAngles;
86 eulerAngles.y = Mathf.SmoothDampAngle(eulerAngles.y, targetEulerAngles.y, ref _currentVelocity,
87 Time.deltaTime * RotationSpeed * input.magnitude);
88 transform.rotation = Quaternion.Euler(eulerAngles);
89 _speed += input.magnitude * (Acceleration * MaxSpeed) * Time.deltaTime;
90 _speed -= Friction * MaxSpeed * Time.deltaTime;
91 _speed = Mathf.Clamp(_speed, 0f, MaxSpeed);
92 CharacterController.SimpleMove(transform.forward * _speed);
93 Animator.SetFloat("SpeedFactor", _speed / MaxSpeed);
94 var pivotedPosition = Quaternion.AngleAxis(AssetViewerBase.Instance.CameraAngle.x, Vector3.up) *
95 Quaternion.AngleAxis(-AssetViewerBase.Instance.CameraAngle.y, Vector3.right) *
96 _cameraOffset;
97 Camera.main.transform.position = transform.position + _cameraHeightOffset + pivotedPosition;
98 Camera.main.transform.LookAt(transform.position + _cameraHeightOffset);
99 }
100 }
101}
Represents a base class used in TriLib samples.
Vector2 CameraAngle
Current camera pitch and yaw angles.
static AssetViewerBase Instance
Gets the Asset Viewer Singleton instance.
Represents a class used to control an avatar on TriLib samples.
static AvatarController Instance
The Avatar Controller Singleton instance.
CharacterController CharacterController
Avatar character controller.
Animator Animator
Avatar animator.
GameObject InnerAvatar
Game object that wraps the actual avatar.