Ipashilovo

Untitled

Jul 6th, 2021
692
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class AnimalMover : MonoBehaviour
  2. {
  3.     [SerializeField] Animator _animator;
  4.     [SerializeField] private float _moveSpeed;
  5.     [SerializeField] private float _rotateSpeed;
  6.  
  7.     [SerializeField] private bool _enableJoystickMode;
  8.     [SerializeField] private Joystick _joystick;
  9.  
  10.     private Vector3 _target;
  11.  
  12.     private void Update()
  13.     {
  14.         if (_enableJoystickMode)
  15.         {
  16.             JoystickMove();
  17.             JoystickRotate();
  18.         }
  19.         else
  20.         {
  21.             if (_target != default && transform.position != _target)
  22.             {
  23.                 Move();
  24.                 Rotate();
  25.             }
  26.  
  27.             if (transform.position == _target)
  28.             {
  29.                 _animator.SetBool(AnimatorAnimalController.Params.IsRun, false);
  30.             }
  31.         }
  32.     }
  33.  
  34.     private void Move()
  35.     {
  36.         transform.position = Vector3.MoveTowards(transform.position, _target, _moveSpeed * Time.deltaTime);
  37.         _animator.SetBool(AnimatorAnimalController.Params.IsRun, true);
  38.     }
  39.  
  40.     private void Rotate()
  41.     {
  42.         transform.LookAt(_target);
  43.     }
  44.  
  45.     private void JoystickMove()
  46.     {
  47.         Vector3 direction = Vector3.left * _joystick.Vertical + Vector3.forward * _joystick.Horizontal;
  48.         transform.position += direction * _moveSpeed * Time.deltaTime;
  49.     }
  50.  
  51.     private void JoystickRotate()
  52.     {
  53.         Vector3 direction = Vector3.left * _joystick.Vertical + Vector3.forward * _joystick.Horizontal;
  54.  
  55.         if (_joystick.Horizontal != 0 || _joystick.Vertical != 0)
  56.         {
  57.             Quaternion toRotation = Quaternion.LookRotation(direction, Vector3.up);
  58.             transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, _rotateSpeed * Time.deltaTime);
  59.             _animator.SetBool(AnimatorAnimalController.Params.IsRun, true);
  60.         }
  61.         else
  62.         {
  63.             _animator.SetBool(AnimatorAnimalController.Params.IsRun, false);
  64.         }
  65.     }
  66.  
  67.     public void SetTarget(Vector3 target)
  68.     {
  69.         _target = target;
  70.     }
  71.  
  72.     public void EnableJoystickMode(Joystick joystick)
  73.     {
  74.         _enableJoystickMode = true;
  75.         _joystick = joystick;
  76.     }
  77. }
RAW Paste Data