Pro_Unit

Car

Jun 12th, 2022 (edited)
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.54 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. public class Car : MonoBehaviour
  4. {
  5.     private const string VERTICAL = "Vertical";
  6.     private const string HORIZONTAL = "Horizontal";
  7.  
  8.     [SerializeField] private float _speed, _rotationSpeed;
  9.     [SerializeField] private float _maxSpeed, _maxRotationSpeed;
  10.  
  11.     private Rigidbody2D _rigidbody2D;
  12.  
  13.     private static float Vertical => Input.GetAxis(VERTICAL);
  14.     private static float Horizontal => Input.GetAxis(HORIZONTAL);
  15.  
  16.     private void Start() =>
  17.         _rigidbody2D = GetComponent<Rigidbody2D>();
  18.  
  19.     private void FixedUpdate()
  20.     {
  21.         Acceleration();
  22.         MoveCar();
  23.         StopCar();
  24.     }
  25.  
  26.     private void Acceleration()
  27.     {
  28.         // набор скорости
  29.         if (_rotationSpeed <= _maxRotationSpeed) _rotationSpeed += Horizontal;
  30.         if (_speed <= _maxSpeed) _speed += Vertical;
  31.     }
  32.  
  33.     private void MoveCar()
  34.     {
  35.         // управление
  36.         var move = new Vector2(0f, _speed);
  37.  
  38.         if (_speed != 0)
  39.         {
  40.             _rigidbody2D.AddRelativeForce(move, ForceMode2D.Force);
  41.             _rigidbody2D.AddTorque(-_rotationSpeed);
  42.         }
  43.     }
  44.  
  45.     private void StopCar()
  46.     {
  47.         // торможение
  48.         if (Vertical == 0)
  49.         {
  50.             if (_speed > 0) _speed -= 2;
  51.             else if (_speed <= 0) _speed = 0;
  52.         }
  53.  
  54.         if (Horizontal == 0)
  55.         {
  56.             if (_rotationSpeed > 0) _rotationSpeed -= 0.5f;
  57.             else if (_rotationSpeed <= 0) _rotationSpeed = 0;
  58.         }
  59.     }
  60. }
Add Comment
Please, Sign In to add comment