Files
CarTest/Assets/Scripts/WheelController.cs

70 lines
2.5 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WheelController : MonoBehaviour
{
[SerializeField] WheelCollider frontRightWheelCollider;
[SerializeField] WheelCollider frontLeftWheelCollider;
[SerializeField] WheelCollider rearRightWheelCollider;
[SerializeField] WheelCollider rearLeftWheelCollider;
//wheel meshes
[SerializeField] Transform frontRightWheel;
[SerializeField] Transform frontLeftWheel;
[SerializeField] Transform rearRightWheel;
[SerializeField] Transform rearLeftWheel;
public float acceleration = 500f;
public float breakingForce = 300f;
public float maxTurnAngle = 15f;
private float currentAcceleration = 0f;
private float currentBrakeForce = 0f;
private float currentTurnAngle = 0f;
private void FixedUpdate() {
//forward reverse input
currentAcceleration = acceleration * Input.GetAxis("Vertical");
//breaking input
if(Input.GetKey(KeyCode.Space)){
currentBrakeForce = breakingForce;
}else{
currentBrakeForce = 0f;
}
//apply acceleration to front wheels| (this determines which wheel drive is the car (fwd, awd, rwd))
rearRightWheelCollider.motorTorque = currentAcceleration;
rearLeftWheelCollider.motorTorque = currentAcceleration;
//break applies to all four wheels
frontRightWheelCollider.brakeTorque = currentBrakeForce;
frontRightWheelCollider.brakeTorque = currentBrakeForce;
frontRightWheelCollider.brakeTorque = currentBrakeForce;
frontRightWheelCollider.brakeTorque = currentBrakeForce;
//steering
currentTurnAngle = maxTurnAngle * Input.GetAxis("Horizontal");
frontLeftWheelCollider.steerAngle = currentTurnAngle;
frontRightWheelCollider.steerAngle = currentTurnAngle;
//update wheel meshes
UpdateWheel(frontLeftWheelCollider, frontLeftWheel);
UpdateWheel(frontRightWheelCollider, frontRightWheel);
UpdateWheel(rearLeftWheelCollider, rearLeftWheel);
UpdateWheel(rearRightWheelCollider, rearRightWheel);
}
private void UpdateWheel(WheelCollider collider, Transform wheel){
//get collider state
Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation); //puts it into position and rotation
//set wheel state
wheel.position = position;
wheel.rotation = rotation;
}
}