Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class Car : MonoBehaviour
- {
- private const string VERTICAL = "Vertical";
- private const string HORIZONTAL = "Horizontal";
- [SerializeField] private float _speed, _rotationSpeed;
- [SerializeField] private float _maxSpeed, _maxRotationSpeed;
- private Rigidbody2D _rigidbody2D;
- private static float Vertical => Input.GetAxis(VERTICAL);
- private static float Horizontal => Input.GetAxis(HORIZONTAL);
- private void Start() =>
- _rigidbody2D = GetComponent<Rigidbody2D>();
- private void FixedUpdate()
- {
- Acceleration();
- MoveCar();
- StopCar();
- }
- private void Acceleration()
- {
- // набор скорости
- if (_rotationSpeed <= _maxRotationSpeed) _rotationSpeed += Horizontal;
- if (_speed <= _maxSpeed) _speed += Vertical;
- }
- private void MoveCar()
- {
- // управление
- var move = new Vector2(0f, _speed);
- if (_speed != 0)
- {
- _rigidbody2D.AddRelativeForce(move, ForceMode2D.Force);
- _rigidbody2D.AddTorque(-_rotationSpeed);
- }
- }
- private void StopCar()
- {
- // торможение
- if (Vertical == 0)
- {
- if (_speed > 0) _speed -= 2;
- else if (_speed <= 0) _speed = 0;
- }
- if (Horizontal == 0)
- {
- if (_rotationSpeed > 0) _rotationSpeed -= 0.5f;
- else if (_rotationSpeed <= 0) _rotationSpeed = 0;
- }
- }
- }
Add Comment
Please, Sign In to add comment