90 lines
2.8 KiB
C#
90 lines
2.8 KiB
C#
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class CarFPSController : MonoBehaviour
|
|
{
|
|
public Transform car;
|
|
private float currentSpeed = 0f;
|
|
public float acceleration = 2f;
|
|
public float deceleration = 4f; // Deceleration rate when no input is applied
|
|
public float carMaxSpeed = 5f;
|
|
public float rotationSpeed = 3f;
|
|
public bool canDrive = true;
|
|
public bool canGetOutOfCar;
|
|
private bool playerIsTeleportedOutOfCar;
|
|
private Rigidbody carRigidbody;
|
|
|
|
[Header("Teleport points")]
|
|
[SerializeField] private Transform outOfCarTeleportPoint;
|
|
|
|
void Start()
|
|
{
|
|
carRigidbody = car.GetComponent<Rigidbody>();
|
|
}
|
|
|
|
void Update()
|
|
{
|
|
float horizontalInput = Input.GetAxis("Horizontal");
|
|
float verticalInput = Input.GetAxis("Vertical");
|
|
|
|
// Rotate the car only when verticalInput input is active
|
|
if (Mathf.Abs(verticalInput) > 0.1f && canDrive)
|
|
{
|
|
// Rotate the car based on the horizontal input
|
|
car.transform.Rotate(Vector3.up * horizontalInput * rotationSpeed);
|
|
}
|
|
|
|
// Apply acceleration when moving
|
|
if (verticalInput != 0 && canDrive)
|
|
{
|
|
float targetSpeed = carMaxSpeed * verticalInput;
|
|
|
|
if (currentSpeed < targetSpeed)
|
|
{
|
|
currentSpeed += acceleration * Time.deltaTime;
|
|
}
|
|
else
|
|
{
|
|
currentSpeed -= deceleration * Time.deltaTime;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
// Apply deceleration when no input is applied
|
|
currentSpeed = Mathf.Max(0, currentSpeed - deceleration * Time.deltaTime);
|
|
}
|
|
|
|
if (!canDrive)
|
|
{
|
|
if (currentSpeed <= 0f && !playerIsTeleportedOutOfCar)
|
|
{
|
|
if (Input.GetKeyDown(KeyCode.E))
|
|
{
|
|
TeleportPlayerOutOfCar();
|
|
playerIsTeleportedOutOfCar = true;
|
|
}
|
|
}
|
|
}
|
|
// Calculate movement based on the vertical input
|
|
Vector3 moveDirection = car.transform.forward * currentSpeed;
|
|
carRigidbody.linearVelocity = moveDirection;
|
|
}
|
|
|
|
public void OutOfGas()
|
|
{
|
|
canDrive = false;
|
|
}
|
|
|
|
private void TeleportPlayerOutOfCar()
|
|
{
|
|
PlayerManager.GetInstance().playerGameObj.transform.SetParent(null);
|
|
PlayerManager.GetInstance().playerGameObj.transform.position = outOfCarTeleportPoint.position;
|
|
PlayerManager.GetInstance().playerGameObj.transform.rotation = outOfCarTeleportPoint.rotation;
|
|
//Enable PlayerMovement and Camera related stuff:
|
|
PlayerManager.GetInstance().EnablePlayerMovement();
|
|
PlayerManager.GetInstance().PlayerCharacterController.enabled = true;
|
|
PlayerManager.GetInstance()._cameraMovement.DisableCarCameraMovement();
|
|
}
|
|
}
|