Untitled

 avatar
unknown
plain_text
2 years ago
2.7 kB
9
Indexable
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CarMovement : MonoBehaviour
{
    public Transform centerOfMass;

    [SerializeField] WheelCollider FrontRight;
    [SerializeField] WheelCollider FrontLeft;
    [SerializeField] WheelCollider BackRight;
    [SerializeField] WheelCollider BackLeft;

    [SerializeField] Transform FrontRightTr;
    [SerializeField] Transform FrontLeftTr;
    [SerializeField] Transform BackRightTr;
    [SerializeField] Transform BackLeftTr;

    public float accelearation = 1000f;
    public float brakeForce = 750f;
    public float maxSteerAngle = 45f;
    public Rigidbody car;
    private Rigidbody _rigidbody;

    private void Start()
    {

        _rigidbody = GetComponent<Rigidbody>();
        _rigidbody.centerOfMass = centerOfMass.localPosition;
    }


    private float currentAcceleration = 0f;
    private float currentBrakeForce = 0f;
    private float currentSteerAngle = 0f;
   
    public float maxSpeed = 40;

    private void FixedUpdate()
    {
        Debug.Log(car.velocity.magnitude);
        if (car.velocity.magnitude > maxSpeed)
        {
            car.velocity = Vector3.ClampMagnitude(car.velocity, maxSpeed);
        }
        //Brake
        if (Input.GetKey(KeyCode.Space))
        {
            currentBrakeForce = brakeForce;
            






        }
        else
        {
            currentBrakeForce = 0f;
        }



        //Acceleration to back wheels (move forward)

        currentAcceleration = accelearation * Input.GetAxis("Vertical");

        BackLeft.motorTorque = currentAcceleration;
        BackRight.motorTorque = currentAcceleration;


        //Brake
        BackLeft.brakeTorque = currentBrakeForce;
        BackRight.brakeTorque = currentBrakeForce;
        FrontLeft.motorTorque = currentBrakeForce;
        FrontRight.motorTorque = currentBrakeForce;




        //Steering

        currentSteerAngle = maxSteerAngle * Input.GetAxis("Horizontal");

        FrontLeft.steerAngle = currentSteerAngle;
        FrontRight.steerAngle = currentSteerAngle;


        UpdateWheel(FrontLeft, FrontLeftTr);
        UpdateWheel(FrontRight, FrontRightTr);
        UpdateWheel(BackRight, BackRightTr);
        UpdateWheel(BackLeft, BackLeftTr);
        

    }
    void UpdateWheel(WheelCollider col, Transform trans)
    {
        Vector3 position;
        Quaternion rotation;

        col.GetWorldPose(out position, out rotation);
        
        trans.position = position;
        trans.rotation = rotation;
    }

}
Editor is loading...