Сделал базовое управление машиной и персонажем
This commit is contained in:
1 parent
10d42b72b8
commit
48753f65fb
152 files changed
+15117
-174
No files matched your search
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: d6f2d9e40ca94a6f91b1d7ae12a13b99
|
||||
timeCreated: 1789819363
|
||||
@@ -0,0 +1,112 @@
|
||||
using UnityEngine;
|
||||
|
||||
public enum DriveType { FWD, RWD, AWD } // Передний, Задний, Полный привод
|
||||
|
||||
[RequireComponent(typeof(Rigidbody))]
|
||||
public class CarController : MonoBehaviour
|
||||
{
|
||||
[Header("Drive Settings")]
|
||||
public DriveType driveType = DriveType.AWD;
|
||||
[SerializeField] private float motorForce = 1500f;
|
||||
[SerializeField] private float brakeForce = 3000f;
|
||||
[SerializeField] private float maxSteerAngle = 30f;
|
||||
|
||||
[Header("Arcade Feel")]
|
||||
[SerializeField] private Transform centerOfMass; // Заниженный центр тяжести
|
||||
|
||||
[Header("Wheel Colliders")]
|
||||
[SerializeField] private WheelCollider frontLeftCollider;
|
||||
[SerializeField] private WheelCollider frontRightCollider;
|
||||
[SerializeField] private WheelCollider rearLeftCollider;
|
||||
[SerializeField] private WheelCollider rearRightCollider;
|
||||
|
||||
[Header("Wheel Meshes (для визуализации)")]
|
||||
[SerializeField] private Transform frontLeftMesh;
|
||||
[SerializeField] private Transform frontRightMesh;
|
||||
[SerializeField] private Transform rearLeftMesh;
|
||||
[SerializeField] private Transform rearRightMesh;
|
||||
|
||||
private Rigidbody rb;
|
||||
private float currentMotorForce;
|
||||
private float currentBrakeForce;
|
||||
private float currentSteerAngle;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
rb = GetComponent<Rigidbody>();
|
||||
if (centerOfMass != null)
|
||||
{
|
||||
rb.centerOfMass = centerOfMass.localPosition; // Смещаем центр масс вниз для аркадности
|
||||
}
|
||||
}
|
||||
|
||||
// Метод вызывается из другого скрипта (ввода)
|
||||
public void ProcessInput(float verticalInput, float horizontalInput, bool isBraking)
|
||||
{
|
||||
currentSteerAngle = maxSteerAngle * horizontalInput;
|
||||
currentMotorForce = verticalInput * motorForce;
|
||||
currentBrakeForce = isBraking ? brakeForce : 0f;
|
||||
}
|
||||
|
||||
private void FixedUpdate()
|
||||
{
|
||||
HandleMotor();
|
||||
HandleSteering();
|
||||
ApplyBraking();
|
||||
UpdateWheelPoses();
|
||||
}
|
||||
|
||||
private void HandleMotor()
|
||||
{
|
||||
// Распределяем крутящий момент в зависимости от типа привода
|
||||
switch (driveType)
|
||||
{
|
||||
case DriveType.FWD: // Передний (недостаточная поворачиваемость, стабилен)
|
||||
frontLeftCollider.motorTorque = currentMotorForce;
|
||||
frontRightCollider.motorTorque = currentMotorForce;
|
||||
break;
|
||||
case DriveType.RWD: // Задний (склонен к заносам / дрифту)
|
||||
rearLeftCollider.motorTorque = currentMotorForce;
|
||||
rearRightCollider.motorTorque = currentMotorForce;
|
||||
break;
|
||||
case DriveType.AWD: // Полный (отличный старт и сцепление)
|
||||
float halfForce = currentMotorForce / 2f;
|
||||
frontLeftCollider.motorTorque = halfForce;
|
||||
frontRightCollider.motorTorque = halfForce;
|
||||
rearLeftCollider.motorTorque = halfForce;
|
||||
rearRightCollider.motorTorque = halfForce;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleSteering()
|
||||
{
|
||||
frontLeftCollider.steerAngle = currentSteerAngle;
|
||||
frontRightCollider.steerAngle = currentSteerAngle;
|
||||
}
|
||||
|
||||
private void ApplyBraking()
|
||||
{
|
||||
frontLeftCollider.brakeTorque = currentBrakeForce;
|
||||
frontRightCollider.brakeTorque = currentBrakeForce;
|
||||
rearLeftCollider.brakeTorque = currentBrakeForce;
|
||||
rearRightCollider.brakeTorque = currentBrakeForce;
|
||||
}
|
||||
|
||||
private void UpdateWheelPoses()
|
||||
{
|
||||
UpdateWheelPose(frontLeftCollider, frontLeftMesh);
|
||||
UpdateWheelPose(frontRightCollider, frontRightMesh);
|
||||
UpdateWheelPose(rearLeftCollider, rearLeftMesh);
|
||||
UpdateWheelPose(rearRightCollider, rearRightMesh);
|
||||
}
|
||||
|
||||
private void UpdateWheelPose(WheelCollider collider, Transform mesh)
|
||||
{
|
||||
if (mesh == null) return;
|
||||
|
||||
collider.GetWorldPose(out Vector3 pos, out Quaternion rot);
|
||||
mesh.position = pos;
|
||||
mesh.rotation = rot;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 100e57e4683949049302153c3df8055c
|
||||
timeCreated: 1789819686
|
||||
@@ -0,0 +1,65 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class CarOrbitCamera : MonoBehaviour
|
||||
{
|
||||
[Header("Цель")]
|
||||
[SerializeField] private Transform target; // Корневой объект машины
|
||||
[SerializeField] private Vector3 targetOffset = new Vector3(0, 1.2f, 0); // Смещение центра (чтобы смотреть на крышу, а не под колеса)
|
||||
|
||||
[Header("Настройки орбиты")]
|
||||
[SerializeField] private float distance = 5.5f; // Дистанция от машины
|
||||
[SerializeField] private float mouseSensitivity = 150f; // Чувствительность мыши
|
||||
|
||||
[Header("Ограничения (чтобы камера не уходила под землю)")]
|
||||
[SerializeField] private float yMinLimit = 0f; // Минимальный угол (0 = уровень земли)
|
||||
[SerializeField] private float yMaxLimit = 80f; // Максимальный угол (вид сверху)
|
||||
|
||||
private float currentX = 0f; // Поворот по горизонтали
|
||||
private float currentY = 20f; // Поворот по вертикали (начинаем с легкого наклона)
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// При старте (или посадке) задаем начальный угол, чтобы камера смотрела в ту же сторону, куда и капот
|
||||
if (target != null)
|
||||
{
|
||||
currentX = target.eulerAngles.y;
|
||||
}
|
||||
}
|
||||
|
||||
// Вызывается после того, как все объекты (включая машину) уже сдвинулись
|
||||
private void LateUpdate()
|
||||
{
|
||||
if (target == null) return;
|
||||
|
||||
// 1. Читаем движение мыши
|
||||
currentX += Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
|
||||
currentY -= Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
|
||||
|
||||
// 2. Ограничиваем угол по вертикали, чтобы камера не перекрутилась через крышу или не ушла в асфальт
|
||||
currentY = Mathf.Clamp(currentY, yMinLimit, yMaxLimit);
|
||||
|
||||
// 3. Вычисляем новое вращение камеры на основе углов
|
||||
Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
|
||||
|
||||
// 4. Вычисляем точку, вокруг которой крутимся (центр машины + смещение вверх)
|
||||
Vector3 focusPoint = target.position + targetOffset;
|
||||
|
||||
// 5. Вычисляем финальную позицию камеры: отходим назад от фокусной точки на расстояние distance
|
||||
Vector3 position = focusPoint - (rotation * Vector3.forward * distance);
|
||||
|
||||
// 6. Применяем позицию и вращение
|
||||
transform.position = position;
|
||||
transform.rotation = rotation;
|
||||
}
|
||||
|
||||
// Метод для вызова из скрипта VehicleInteraction (опционально)
|
||||
// Чтобы камера всегда сбрасывалась ровно за машину, когда игрок садится в неё
|
||||
public void ResetCameraAngles()
|
||||
{
|
||||
if (target != null)
|
||||
{
|
||||
currentX = target.eulerAngles.y;
|
||||
currentY = 20f;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3eb72160ab004995bc77130c1806ee13
|
||||
timeCreated: 1789825076
|
||||
@@ -0,0 +1,93 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(CarController))]
|
||||
public class VehicleInteraction : MonoBehaviour, IInteractable
|
||||
{
|
||||
[Header("Cameras & Setup")]
|
||||
[SerializeField] private GameObject carCamera; // Камера от 3-го лица для авто
|
||||
[SerializeField] private Transform exitPoint; // Точка, где спавнится игрок при выходе (возле левой двери)
|
||||
|
||||
private CarController carController;
|
||||
private GameObject playerInstance;
|
||||
private bool isPlayerInside = false;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
carController = GetComponent<CarController>();
|
||||
carCamera.SetActive(false); // Выключаем камеру авто на старте
|
||||
}
|
||||
|
||||
// Реализация интерфейса IInteractable
|
||||
public void Interact(GameObject interactor)
|
||||
{
|
||||
if (!isPlayerInside)
|
||||
{
|
||||
EnterVehicle(interactor);
|
||||
}
|
||||
}
|
||||
|
||||
public string GetPrompt()
|
||||
{
|
||||
return "Сесть в машину (E)";
|
||||
}
|
||||
|
||||
private void EnterVehicle(GameObject player)
|
||||
{
|
||||
isPlayerInside = true;
|
||||
playerInstance = player;
|
||||
|
||||
// Отключаем игрока (тело, скрипты, его камеру)
|
||||
playerInstance.SetActive(false);
|
||||
|
||||
// Включаем камеру машины
|
||||
carCamera.SetActive(true);
|
||||
}
|
||||
|
||||
private void ExitVehicle()
|
||||
{
|
||||
isPlayerInside = false;
|
||||
|
||||
// Останавливаем машину при выходе
|
||||
carController.ProcessInput(0f, 0f, true);
|
||||
|
||||
// Включаем камеру игрока и отключаем камеру машины
|
||||
carCamera.SetActive(false);
|
||||
|
||||
CharacterController charController = playerInstance.GetComponent<CharacterController>();
|
||||
if (charController != null)
|
||||
{
|
||||
charController.enabled = false;
|
||||
}
|
||||
|
||||
// 2. Перемещаем игрока
|
||||
playerInstance.transform.position = exitPoint.position;
|
||||
|
||||
// 3. Включаем CharacterController обратно
|
||||
if (charController != null)
|
||||
{
|
||||
charController.enabled = true;
|
||||
}
|
||||
|
||||
playerInstance.SetActive(true);
|
||||
playerInstance = null;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
if (!isPlayerInside) return;
|
||||
|
||||
// Если игрок в машине, читаем ввод
|
||||
float vertical = Input.GetAxis("Vertical");
|
||||
float horizontal = Input.GetAxis("Horizontal");
|
||||
bool isBraking = Input.GetKey(KeyCode.Space);
|
||||
|
||||
// Передаем управление в физику машины
|
||||
carController.ProcessInput(vertical, horizontal, isBraking);
|
||||
|
||||
// Обработка выхода из машины
|
||||
if (Input.GetKeyDown(KeyCode.E))
|
||||
{
|
||||
ExitVehicle();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bf303cb78d154d429f7c0c90338cec80
|
||||
timeCreated: 1789819810
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: cb7191cd571f4b29b09140c0787d0f56
|
||||
timeCreated: 1789819619
|
||||
@@ -0,0 +1,8 @@
|
||||
using UnityEngine;
|
||||
|
||||
public interface IInteractable
|
||||
{
|
||||
// Передаем ссылку на игрока, чтобы объект знал, кто с ним взаимодействует
|
||||
void Interact(GameObject interactor);
|
||||
string GetPrompt();
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 5da3094495bf4ea2a8c39ac8fcf67557
|
||||
timeCreated: 1789819376
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 21024185f8ef48cbba28354e34565425
|
||||
timeCreated: 1789818491
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c62998bcb5b44a948aa3df20fbca06fa
|
||||
timeCreated: 1789819562
|
||||
@@ -0,0 +1,30 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerInteractor : MonoBehaviour
|
||||
{
|
||||
[SerializeField] private float interactRange = 3f;
|
||||
[SerializeField] private LayerMask interactableLayer; // Создайте слой "Interactable" в Unity
|
||||
|
||||
private void Update()
|
||||
{
|
||||
// Пускаем луч из центра экрана
|
||||
Ray ray = new Ray(transform.position, transform.forward);
|
||||
|
||||
if (Physics.Raycast(ray, out RaycastHit hit, interactRange, interactableLayer))
|
||||
{
|
||||
IInteractable interactable = hit.collider.GetComponentInParent<IInteractable>();
|
||||
|
||||
if (interactable != null)
|
||||
{
|
||||
// Здесь в будущем можно выводить UI текст interactable.GetPrompt() на экран
|
||||
|
||||
if (Input.GetKeyDown(KeyCode.E))
|
||||
{
|
||||
// Передаем корневой объект игрока (не камеру)
|
||||
Debug.Log("Кнопка нажата");
|
||||
interactable.Interact(transform.root.gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 55f66c5b12bc40f08c38b6fad86ad694
|
||||
timeCreated: 1789819467
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 590a609c93d0458ba9144576ebbcebd7
|
||||
timeCreated: 1789819518
|
||||
@@ -0,0 +1,39 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerInputHandler : MonoBehaviour
|
||||
{
|
||||
[Header("Components")]
|
||||
[SerializeField] private PlayerMovement playerMovement;
|
||||
[SerializeField] private PlayerLook playerLook;
|
||||
|
||||
private void Update()
|
||||
{
|
||||
HandleMovementInput();
|
||||
HandleLookInput();
|
||||
}
|
||||
|
||||
private void HandleMovementInput()
|
||||
{
|
||||
// Читаем оси WASD. GetAxisRaw дает более резкое, отзывчивое управление без инерции.
|
||||
float horizontal = Input.GetAxisRaw("Horizontal");
|
||||
float vertical = Input.GetAxisRaw("Vertical");
|
||||
|
||||
// Нормализуем вектор, чтобы игрок не двигался быстрее по диагонали
|
||||
Vector2 moveInput = new Vector2(horizontal, vertical).normalized;
|
||||
|
||||
if (playerMovement != null)
|
||||
playerMovement.ProcessMove(moveInput);
|
||||
}
|
||||
|
||||
private void HandleLookInput()
|
||||
{
|
||||
// Читаем движение мыши
|
||||
float mouseX = Input.GetAxis("Mouse X");
|
||||
float mouseY = Input.GetAxis("Mouse Y");
|
||||
|
||||
Vector2 lookInput = new Vector2(mouseX, mouseY);
|
||||
|
||||
if (playerLook != null)
|
||||
playerLook.ProcessLook(lookInput);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 00826943886c407c952993731de997e0
|
||||
timeCreated: 1789818508
|
||||
@@ -0,0 +1,33 @@
|
||||
using UnityEngine;
|
||||
|
||||
public class PlayerLook : MonoBehaviour
|
||||
{
|
||||
[Header("Look Settings")]
|
||||
[SerializeField] private float mouseSensitivity = 150f;
|
||||
[SerializeField] private Transform playerBody;
|
||||
|
||||
private float xRotation = 0f;
|
||||
|
||||
private void Start()
|
||||
{
|
||||
// Блокируем курсор в центре экрана и скрываем его
|
||||
Cursor.lockState = CursorLockMode.Locked;
|
||||
Cursor.visible = false;
|
||||
}
|
||||
|
||||
public void ProcessLook(Vector2 input)
|
||||
{
|
||||
float mouseX = input.x * mouseSensitivity * Time.deltaTime;
|
||||
float mouseY = input.y * mouseSensitivity * Time.deltaTime;
|
||||
|
||||
// Расчет наклона камеры с ограничением, чтобы нельзя было сломать шею
|
||||
xRotation -= mouseY;
|
||||
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
|
||||
|
||||
// Применяем вращение камеры (вверх/вниз)
|
||||
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
|
||||
|
||||
// Вращаем само тело игрока (влево/вправо)
|
||||
playerBody.Rotate(Vector3.up * mouseX);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 4662192a51344c429f6fb8cb1730a7e2
|
||||
timeCreated: 1789818561
|
||||
@@ -0,0 +1,42 @@
|
||||
using UnityEngine;
|
||||
|
||||
[RequireComponent(typeof(CharacterController))]
|
||||
public class PlayerMovement : MonoBehaviour
|
||||
{
|
||||
[Header("Movement Settings")]
|
||||
[SerializeField] private float moveSpeed = 4f;
|
||||
[SerializeField] private float gravity = -9.81f;
|
||||
|
||||
[Header("Ground Check")]
|
||||
[SerializeField] private Transform groundCheck;
|
||||
[SerializeField] private float groundDistance = 0.4f;
|
||||
[SerializeField] private LayerMask groundMask;
|
||||
|
||||
private CharacterController controller;
|
||||
private Vector3 velocity;
|
||||
private bool isGrounded;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
controller = GetComponent<CharacterController>();
|
||||
}
|
||||
|
||||
public void ProcessMove(Vector2 input)
|
||||
{
|
||||
// Проверка касания земли (сфера на уровне ног)
|
||||
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
|
||||
|
||||
if (isGrounded && velocity.y < 0)
|
||||
{
|
||||
velocity.y = -2f; // Небольшое прижатие к земле для стабильного спуска по склонам
|
||||
}
|
||||
|
||||
// Движение относительно локальных координат игрока
|
||||
Vector3 move = transform.right * input.x + transform.forward * input.y;
|
||||
controller.Move(move * (moveSpeed * Time.deltaTime));
|
||||
|
||||
// Применение гравитации
|
||||
velocity.y += gravity * Time.deltaTime;
|
||||
controller.Move(velocity * Time.deltaTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bf210e4b179e4c4a93ffda4241a24602
|
||||
timeCreated: 1789818546
|
||||
Reference in new issue
Block a user