Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [RequireComponent(typeof(Transform), typeof(Player))]
- public class CharMovement : MonoBehaviour
- {
- public float maxLinearVelocity = 5f;
- [SerializeField] private float _turnSpeed = 360f;
- [SerializeField] private float _rotationTolerance = 0.1f; //radius
- private Player _playerStats;
- public Camera _cam;
- private Vector3 _mousePos;
- public Transform _transform;
- private void Start()
- {
- _playerStats = GetComponent<Player>();
- _transform = GetComponent<Transform>();
- maxLinearVelocity = _playerStats.speed;
- }
- void Update()
- {
- maxLinearVelocity = _playerStats.speed;
- Look();
- }
- private void FixedUpdate()
- {
- Move();
- }
- public void Move()
- {
- var input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
- Vector3 forward = transform.forward * input.z * Time.fixedDeltaTime;
- Vector3 right = transform.right * input.x * Time.fixedDeltaTime;
- Vector3 heading = (forward + right).normalized;
- _transform.forward = heading;
- _transform.position += maxLinearVelocity * Time.fixedDeltaTime * heading;
- }
- public void Look()
- {
- Plane plane = new (Vector3.up, Vector3.zero);
- Ray ray = _cam.ScreenPointToRay(Input.mousePosition);
- if (plane.Raycast(ray, out float distance))
- {
- _mousePos = ray.GetPoint(distance);
- }
- else { return; }
- // Calcola la direzione di rotazione verso il mouse
- Vector3 lookDir = (_mousePos - _transform.position).normalized;
- lookDir.y = 0;
- if (lookDir.sqrMagnitude < 0.01f)
- return; // check for zero vector?
- float angle = Mathf.Atan2(lookDir.x, lookDir.z) * Mathf.Rad2Deg;
- Quaternion targetRotation = Quaternion.Euler(0, angle, 0);
- // Tolerance check
- float angleDifference = Quaternion.Angle(_transform.rotation, targetRotation);
- if (angleDifference < _rotationTolerance)
- return; // Tolerance stop
- _transform.rotation = Quaternion.RotateTowards(_transform.rotation, targetRotation, _turnSpeed);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement