Skip to content

Instantly share code, notes, and snippets.

@LuviKunG
Created March 9, 2022 16:37
Show Gist options
  • Save LuviKunG/d01ba5c5880dfbed26e2b2e8f9d45d9d to your computer and use it in GitHub Desktop.
Save LuviKunG/d01ba5c5880dfbed26e2b2e8f9d45d9d to your computer and use it in GitHub Desktop.
Simple Character Controller using in Unity Engine with new Input System.
using UnityEngine;
using UnityEngine.InputSystem;
namespace Prototype
{
[RequireComponent(typeof(CharacterController))]
public sealed class SimpleCharacterController : MonoBehaviour
{
[SerializeField]
private CharacterController m_characterController = default;
[SerializeField]
private Transform m_characterTransform = default;
[SerializeField]
private Transform m_headTransform = default;
[SerializeField]
private float m_speedLookHorizontal = 0.0f;
[SerializeField]
private float m_speedLookVertical = 0.0f;
[SerializeField]
private float m_speedMovement = 0.0f;
[SerializeField]
private InputAction m_inputLook = default;
[SerializeField]
private InputAction m_inputMovement = default;
private float m_lookAxisVertical;
private Vector3 m_motion;
private void Start()
{
UpdateHeadPosition();
}
private void OnEnable()
{
m_inputLook.Enable();
m_inputMovement.Enable();
}
private void OnDisable()
{
m_inputLook.Disable();
m_inputMovement.Disable();
}
private void Update()
{
Vector2 controlAxis = m_inputMovement.ReadValue<Vector2>() * m_speedMovement;
m_motion = m_characterTransform.rotation * new Vector3(controlAxis.x, 0, controlAxis.y);
Vector2 lookAxis = m_inputLook.ReadValue<Vector2>();
m_characterTransform.rotation *= Quaternion.Euler(0, lookAxis.x * m_speedLookHorizontal, 0);
m_lookAxisVertical = Mathf.Clamp(m_lookAxisVertical - lookAxis.y * m_speedLookVertical, -90.0f, 90.0f);
m_headTransform.localRotation = Quaternion.Euler(m_lookAxisVertical, 0, 0);
}
private void FixedUpdate()
{
if (m_motion.magnitude > 0)
{
m_characterController.Move(m_motion * Time.fixedDeltaTime);
}
}
private void UpdateHeadPosition()
{
m_headTransform.localPosition = new Vector3(0, m_characterController.height - m_characterController.radius, 0);
}
#if UNITY_EDITOR
private void Reset()
{
if (m_characterController == null)
m_characterController = GetComponent<CharacterController>();
}
private void OnValidate()
{
if (m_speedMovement < 0.0f)
m_speedMovement = 0.0f;
if (m_headTransform != null && m_characterTransform != null)
UpdateHeadPosition();
}
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment