Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Collections.Generic;
- public class CWheel
- {
- public CWheel(Transform wheel, Boolean frontWheels)
- {
- Self = wheel;
- Visual = Self.Find("WheelGraphic");
- Collider = Self.gameObject.GetComponent<WheelCollider>();
- IsFrontWheel = frontWheels;
- }
- public void PerformUpdate(float forwardThrust, float currentSteer)
- {
- // Set torque on the rear wheels
- if (!IsFrontWheel)
- Collider.motorTorque = forwardThrust;
- // Rotate front wheels
- if (IsFrontWheel)
- {
- Quaternion steerRot = Quaternion.Euler(0, currentSteer, 0);
- Self.localRotation = steerRot;
- }
- // Perform wheel graphics update
- float rps = Collider.rpm / 60.0f;
- float angle = 360 * rps * Time.fixedDeltaTime;
- Visual.Rotate(-Vector3.up * angle);
- }
- public Transform Self;
- public Transform Visual;
- public WheelCollider Collider;
- public Boolean IsFrontWheel;
- }
- public class TheCarEngine : MonoBehaviour
- {
- public float EnginePower = 50;
- public float MaxSteerAngle = 30;
- public Transform WheelFL;
- public Transform WheelFR;
- public Transform WheelRL;
- public Transform WheelRR;
- public Transform CenterOfMass;
- public float ForceDown = 3;
- private float thrust = 0;
- private float steer = 0;
- private float angle = 0;
- private List<CWheel> Wheels = new List<CWheel>();
- // Use this for initialization
- void Start()
- {
- Boolean[] frontWheelsFlag = new Boolean[] { true, true, false, false };
- Transform[] wheelTransforms = new Transform[] { WheelFL, WheelFR, WheelRL, WheelRR };
- for (int i = 0; i < 4; i++)
- Wheels.Add(new CWheel(wheelTransforms[i], frontWheelsFlag[i]));
- rigidbody.centerOfMass = CenterOfMass.position;
- }
- // Update is called once per frame
- void Update()
- {
- ReadInput();
- }
- void ReadInput()
- {
- thrust = Input.GetAxis("Vertical");
- steer = Input.GetAxis("Horizontal");
- }
- void FixedUpdate()
- {
- var forwardThrust = thrust * EnginePower;
- float currentSteer = steer * MaxSteerAngle;
- foreach (CWheel wheel in Wheels)
- wheel.PerformUpdate(forwardThrust, currentSteer);
- // try to push down
- foreach (CWheel wheel in Wheels)
- {
- rigidbody.AddForceAtPosition(Vector3.down*ForceDown, wheel.Self.position, ForceMode.Force);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement