Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class CarBetter : MonoBehaviour {
- public float maxSpeed = 100;
- public float enginePower = 200;
- public float minTurnForce = 1f;
- public float maxTurnForce = 4f;
- public float lateralGrip = 30;
- bool onGround;
- Vector3 oPosition;
- Quaternion oRotation;
- float h,v;
- void Start () {
- oPosition = transform.position;
- oRotation = transform.rotation;
- }
- void OnCollisionStay(Collision col)
- {
- if (Vector3.Angle(transform.up, Vector3.up) < 65)
- {
- onGround = true;
- }
- }
- void FixedUpdate()
- {
- if (onGround)
- {
- Vector3 localVelocity = transform.InverseTransformDirection(rigidbody.velocity);
- float currentSpeed = Mathf.Abs(localVelocity.z);
- float inverseSpeedFactor = Mathf.InverseLerp( maxSpeed, 0, currentSpeed );
- float accelPower = enginePower * inverseSpeedFactor;
- Vector3 accelForce = transform.forward * accelPower * v;
- Vector3 gripForce = -transform.right * lateralGrip * localVelocity.x;
- Vector3 sumForce = accelForce + gripForce;
- Vector3 turnTorque = currentSpeed * transform.up * h * Mathf.Lerp(minTurnForce, maxTurnForce, inverseSpeedFactor);
- rigidbody.AddForce( sumForce );
- rigidbody.AddTorque( turnTorque );
- Debug.DrawRay(transform.position, sumForce*0.1f, Color.red);
- }
- onGround = false;
- }
- void Update () {
- if (Input.GetKeyDown("r")) { Reset(); }
- v = Input.GetAxis("Vertical");
- h = Input.GetAxis("Horizontal");
- }
- void Reset()
- {
- transform.position = oPosition;
- transform.rotation = oRotation;
- rigidbody.velocity = Vector3.zero;
- rigidbody.angularVelocity = Vector3.zero;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment