using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerCarInput : MonoBehaviour
{
public float Power;
public float Angle;
public CarInput input;
public Wheel[] wheels;
private float throttleInput;
private float throttleDamp;
private float steeringInput;
private float steeringDamp;
public float dampenSpeed;
private KmhCounter kmhCounter;
[SerializeField] private bool IsPlayer2;
private void Awake()
{
kmhCounter = FindObjectOfType<KmhCounter>();
input = new CarInput();
}
private void OnEnable()
{
input.Enable();
if (!IsPlayer2)
{
input.Car.Throttle.performed += ApplyThrottle;
input.Car.Throttle.canceled += ReleaseThrottle;
input.Car.Steering.performed += ApplySteering;
input.Car.Steering.canceled += ReleaseSteering;
}
else
{
input.Car.ThrottleP2.performed += ApplyThrottle;
input.Car.ThrottleP2.canceled += ReleaseThrottle;
input.Car.SteeringP2.performed += ApplySteering;
input.Car.SteeringP2.canceled += ReleaseSteering;
}
}
private void Update()
{
AngleBasedOnSpeed();
throttleDamp = DampenedInput(throttleInput, throttleDamp);
steeringDamp = DampenedInput(steeringInput, steeringDamp);
}
private void OnDisable()
{
input.Disable();
}
private float DampenedInput(float input, float output)
{
return Mathf.Lerp(output, input, Time.deltaTime * dampenSpeed);
}
private void ApplyThrottle(InputAction.CallbackContext value)
{
throttleInput = value.ReadValue<float>();
}
private void ReleaseThrottle(InputAction.CallbackContext value)
{
throttleInput = 0;
}
private void ApplySteering(InputAction.CallbackContext value)
{
steeringInput = value.ReadValue<float>();
}
private void ReleaseSteering(InputAction.CallbackContext value)
{
steeringInput = 0;
}
private void FixedUpdate()
{
foreach (Wheel wheel in wheels)
{
wheel.Accelerate(throttleDamp * Power);
wheel.Turn(steeringDamp * Angle);
}
}
private void AngleBasedOnSpeed()
{
Angle = 30 - kmhCounter.speed * 0.1f;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Wheel : MonoBehaviour
{
public bool isPowered;
public bool canTurn;
public GameObject Visual;
public float steeringAngle;
private WheelCollider wheelCollider;
private void Start()
{
wheelCollider = GetComponent<WheelCollider>();
}
private void Update()
{
Vector3 position;
Quaternion rotation;
wheelCollider.GetWorldPose(out position, out rotation);
Visual.transform.position = position;
}
public void Accelerate(float power)
{
if (isPowered)
{
wheelCollider.motorTorque = power;
}
}
public void Turn(float angle)
{
if (canTurn)
{
wheelCollider.steerAngle = angle;
}
}
public void Brake(float power)
{
wheelCollider.brakeTorque = power;
}
}