using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Movement : MonoBehaviour
{
private Rigidbody _rigidbody;
[SerializeField] private float _moveSpeed = 2f;
[SerializeField] private float _jump = 2f;
//rotation
private float _targetRotation = 0.0f;
private float _rotationVelocity;
public float RotationSmoothTime = 0.12f;
private GameObject _mainCamera;
private void Awake()
{
if (_mainCamera == null)
{
_mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
}
}
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
}
public void Move(Vector3 dir)
{
if (dir == Vector3.zero) return;
_targetRotation = _mainCamera.transform.eulerAngles.y + Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg;
float rotation = Mathf.SmoothDampAngle(transform.eulerAngles.y, _targetRotation, ref _rotationVelocity,
RotationSmoothTime);
transform.rotation = Quaternion.Euler(0.0f, rotation, 0.0f);
Vector3 targetDirection = Quaternion.Euler(0.0f, _targetRotation, 0.0f) * Vector3.forward;
var WorldDir = targetDirection.normalized;
_rigidbody.MovePosition(transform.position + WorldDir * (_moveSpeed * Time.deltaTime));
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(dir),
_rotationSpeed * Time.deltaTime);
}
public void Jump()
{
_rigidbody.AddForce(Vector3.up * _jump, ForceMode.Impulse);
}
}
Mathf.Atan2(dir.x, dir.z) * Rad2Deg를 통해 입력받은 Vector값의 각도를 구할 수 있습니다!
public static float SmoothDamp(
float current,
float target,
ref float currentVelocity,
float smoothTime,
[DefaultValue("Mathf.Infinity")] float maxSpeed,
[DefaultValue("Time.deltaTime")] float deltaTime)
{
smoothTime = Mathf.Max(0.0001f, smoothTime);
float num1 = 2f / smoothTime;
float num2 = num1 * deltaTime;
float num3 = (float) (1.0 / (1.0 + (double) num2 + 0.47999998927116394 * (double) num2 * (double) num2 + 0.23499999940395355 * (double) num2 * (double) num2 * (double) num2));
float num4 = current - target;
float num5 = target;
float max = maxSpeed * smoothTime;
float num6 = Mathf.Clamp(num4, -max, max);
target = current - num6;
float num7 = (currentVelocity + num1 * num6) * deltaTime;
currentVelocity = (currentVelocity - num1 * num7) * num3;
float num8 = target + (num6 + num7) * num3;
if ((double) num5 - (double) current > 0.0 == (double) num8 > (double) num5)
{
num8 = num5;
currentVelocity = (num8 - num5) / deltaTime;
}
return num8;
}
currentVelocity는 위와 같이 계산됩니다!