Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class TopDownPlayerController : MonoBehaviour
- {
- public Transform camTransform;
- [Header("ROTATE ON MOVE")]
- public bool rotatePlayerOnMove;
- [Header("MOVEMENT")]
- public float moveSpeed;
- [Header("ROTATION")]
- public float playerRotateSpeed;
- public float camRotateSpeed;
- [Header("CAMERA")]
- public Vector3 cameraOffset;
- public float camFollowSpeed;
- public float camTiltAngle;
- Vector3 moveInput;
- float camYRotation;
- float lastCamYRotation;
- bool cameraHasRotated;
- void Start()
- {
- camYRotation = camTransform.eulerAngles.y;
- lastCamYRotation = camYRotation;
- }
- void Update()
- {
- HandleInput();
- MovePlayer();
- UpdateCameraPosition();
- HandleCameraRotation();
- cameraHasRotated = Mathf.Abs(camYRotation - lastCamYRotation) > 0.01f;
- lastCamYRotation = camYRotation;
- }
- void HandleInput()
- {
- moveInput = Vector3.zero;
- if (Input.GetKey(KeyCode.W)) moveInput += Vector3.forward;
- if (Input.GetKey(KeyCode.S)) moveInput += Vector3.back;
- if (Input.GetKey(KeyCode.A)) moveInput += Vector3.left;
- if (Input.GetKey(KeyCode.D)) moveInput += Vector3.right;
- }
- void MovePlayer()
- {
- if (moveInput.sqrMagnitude < 0.01f) return;
- Vector3 camForward = Quaternion.Euler(0, camYRotation, 0) * Vector3.forward;
- Vector3 camRight = Quaternion.Euler(0, camYRotation, 0) * Vector3.right;
- Vector3 worldMove = (camForward * moveInput.z + camRight * moveInput.x).normalized;
- transform.position += worldMove * moveSpeed * Time.deltaTime;
- worldMove.y = 0;
- bool isMovingForward = moveInput.z > 0.1f;
- bool shouldRotate = rotatePlayerOnMove || cameraHasRotated || isMovingForward;
- if (!shouldRotate) return;
- Quaternion targetRot = Quaternion.LookRotation(worldMove);
- transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRot, playerRotateSpeed * Time.deltaTime);
- }
- void HandleCameraRotation()
- {
- float camInput = 0f;
- if (Input.GetKey(KeyCode.Q)) camInput = -1f;
- if (Input.GetKey(KeyCode.E)) camInput = 1f;
- if (camInput != 0f) camYRotation += camInput * camRotateSpeed * Time.deltaTime;
- }
- void UpdateCameraPosition()
- {
- Quaternion camYRot = Quaternion.Euler(0f, camYRotation, 0f);
- Vector3 targetPos = transform.position + camYRot * cameraOffset;
- camTransform.position = Vector3.Lerp(camTransform.position, targetPos, camFollowSpeed * Time.deltaTime);
- Vector3 lookTarget = transform.position + Vector3.up * 1.5f;
- camTransform.rotation = Quaternion.Euler(camTiltAngle, camYRotation, 0f);
- camTransform.LookAt(lookTarget);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment