89 lines
2.7 KiB
C#
89 lines
2.7 KiB
C#
using Obstacle;
|
|||
|
|
using UnityEngine;
|
||
|
|
|
||
|
|
namespace Player
|
||
|
|
{
|
||
|
|
[RequireComponent(typeof(Rigidbody))]
|
||
|
|
public class PlayerCarController : MonoBehaviour
|
||
|
|
{
|
||
|
|
[Header("Скорость движения")]
|
||
|
|
public float forwardSpeed = 20f;
|
||
|
|
public float sideSpeed = 15f;
|
||
|
|
public float horizontalLimit = 4.5f;
|
||
|
|
|
||
|
|
[Header("Управление")]
|
||
|
|
public float swipeSensitivity = 1.5f;
|
||
|
|
|
||
|
|
[Header("Визуальный наклон ")]
|
||
|
|
[Tooltip("На сколько градусов поворачивается нос машины при перестроении")]
|
||
|
|
public float maxTiltAngle = 15f;
|
||
|
|
[Tooltip("Как быстро машина выравнивается обратно")]
|
||
|
|
public float tiltSpeed = 10f;
|
||
|
|
|
||
|
|
private Rigidbody _rb;
|
||
|
|
private bool _isAlive = true;
|
||
|
|
|
||
|
|
private float _targetX;
|
||
|
|
private Vector2 _lastInputPosition;
|
||
|
|
|
||
|
|
void Start()
|
||
|
|
{
|
||
|
|
_rb = GetComponent<Rigidbody>();
|
||
|
|
_isAlive = true;
|
||
|
|
_targetX = transform.position.x;
|
||
|
|
}
|
||
|
|
|
||
|
|
void Update()
|
||
|
|
{
|
||
|
|
if (!_isAlive) return;
|
||
|
|
|
||
|
|
if (Input.GetMouseButtonDown(0))
|
||
|
|
{
|
||
|
|
_lastInputPosition = Input.mousePosition;
|
||
|
|
}
|
||
|
|
else if (Input.GetMouseButton(0))
|
||
|
|
{
|
||
|
|
float deltaX = Input.mousePosition.x - _lastInputPosition.x;
|
||
|
|
_lastInputPosition = Input.mousePosition;
|
||
|
|
|
||
|
|
// Сдвигаем целевую точку X
|
||
|
|
_targetX += (deltaX / Screen.width) * swipeSensitivity * 10f;
|
||
|
|
|
||
|
|
_targetX = Mathf.Clamp(_targetX, -horizontalLimit, horizontalLimit);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
void FixedUpdate()
|
||
|
|
{
|
||
|
|
if (!_isAlive) return;
|
||
|
|
|
||
|
|
Vector3 currentPos = _rb.position;
|
||
|
|
|
||
|
|
float newX = Mathf.MoveTowards(currentPos.x, _targetX, sideSpeed * Time.fixedDeltaTime);
|
||
|
|
|
||
|
|
Vector3 moveTarget = new Vector3(newX, currentPos.y, currentPos.z + forwardSpeed * Time.fixedDeltaTime);
|
||
|
|
|
||
|
|
_rb.MovePosition(moveTarget);
|
||
|
|
|
||
|
|
float deltaX = newX - currentPos.x;
|
||
|
|
float direction = deltaX / (sideSpeed * Time.fixedDeltaTime);
|
||
|
|
|
||
|
|
// Поворачиваем нос машины в сторону движения
|
||
|
|
Quaternion targetRotation = Quaternion.Euler(0, direction * maxTiltAngle, 0);
|
||
|
|
_rb.MoveRotation(Quaternion.Lerp(_rb.rotation, targetRotation, tiltSpeed * Time.fixedDeltaTime));
|
||
|
|
}
|
||
|
|
|
||
|
|
private void OnCollisionEnter(Collision collision)
|
||
|
|
{
|
||
|
|
if (!_isAlive) return;
|
||
|
|
|
||
|
|
if (collision.gameObject.GetComponent<TrafficCar>() != null ||
|
||
|
|
collision.gameObject.GetComponent<StaticObstacle>() != null)
|
||
|
|
{
|
||
|
|
_isAlive = false;
|
||
|
|
GameEvents.OnPlayerDied?.Invoke();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|