Last active
April 19, 2021 07:57
-
-
Save Plnda/87a81b965cee0e322b31f15cb0553689 to your computer and use it in GitHub Desktop.
3th person
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ThirdPersonCameraController : MonoBehaviour | |
{ | |
[SerializeField] | |
private Animator _animator; | |
[SerializeField] | |
private Rigidbody _rigidbody; | |
[SerializeField] | |
private float _cameraRotationSpeed = 1.0f; | |
[SerializeField] | |
private Transform characterTransform; | |
[SerializeField] | |
private Transform targetTransform; | |
[SerializeField] | |
private float _movementSpeed = 1.0f; | |
private bool _isTargeting => Input.GetMouseButton(1); | |
private float _vertical => Input.GetAxis("Vertical"); | |
public Vector3 nextPosition; | |
public Quaternion nextRotation; | |
private Vector2 _look => new Vector2(Input.GetAxis("Mouse X"), -Input.GetAxis("Mouse Y")); | |
private Vector2 _move => new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")); | |
private void Start() | |
{ | |
Cursor.visible = false; | |
Cursor.lockState = CursorLockMode.Locked; | |
} | |
void OnAnimatorMove() | |
{ | |
_rigidbody.MovePosition(nextPosition); | |
} | |
private void FixedUpdate() | |
{ | |
targetTransform.rotation *= Quaternion.AngleAxis(_look.x * _cameraRotationSpeed, Vector3.up); | |
targetTransform.rotation *= Quaternion.AngleAxis(_look.y * _cameraRotationSpeed, Vector3.right); | |
var angles = targetTransform.localEulerAngles; | |
angles.z = 0; | |
//Clamp the Up/Down rotation | |
if (angles.x > 180 && angles.x < 280) | |
{ | |
angles.x = 280; | |
} | |
else if (angles.x < 180 && angles.x > 80) | |
{ | |
angles.x = 80; | |
} | |
targetTransform.localEulerAngles = angles; | |
float moveSpeed = _movementSpeed / 100f; | |
Vector3 position = (characterTransform.forward * _move.y * moveSpeed) + (characterTransform.right * _move.x * moveSpeed); | |
nextPosition = characterTransform.position + position; | |
if (_move.magnitude > 0) | |
{ | |
_rigidbody.rotation = Quaternion.Euler(0, targetTransform.rotation.eulerAngles.y, 0); | |
targetTransform.transform.localEulerAngles = new Vector3(angles.x, 0, 0); | |
} | |
_animator.SetFloat("Horizontal", _move.x, 0.05f, Time.deltaTime); | |
_animator.SetFloat("Vertical", _move.y, 0.05f, Time.deltaTime); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment