Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- #pragma warning disable 0414
- public enum ControlMode { simple = 1, touch = 2 }
- public class BikeControl:MonoBehaviour {
- public bool racingModified = false;
- public bool isAI = false;
- public static BikeControl Instance;
- public bool isAutorotatorEnable=true;
- public ControlMode controlMode = ControlMode.simple;
- //Original code was so fucking messy, adding more stuff is literally the best option
- public float AI_ACCEL = 0f;
- public float AI_STEER = 0f;
- public float AI_BRAKE = 0f;
- public float AI_HANDBRAKE = 0f;
- // Wheels Setting /////////////////////////////////
- public bool FallOnCrash = false;
- public BikeWheels bikeWheels;
- [System.Serializable]
- public class BikeWheels {
- public ConnectWheel wheels;
- public WheelSetting setting;
- }
- [System.Serializable]
- public class ConnectWheel {
- public Transform wheelFront; // connect to Front Right Wheel transform
- public Transform wheelBack; // connect to Front Left Wheel transform
- public Transform AxleFront; // connect to Back Right Wheel transform
- public Transform AxleBack; // connect to Back Left Wheel transform
- }
- [System.Serializable]
- public class WheelSetting {
- public bool AutomaticRadius = true;
- public float Radius = 0.25f; // the radius of the wheels
- public float Weight = 3f; // the weight of a wheel
- public float Distance = 0.2f;
- }
- // Lights Setting /////////////////////////////////
- public BikeLights bikeLights;
- [System.Serializable]
- public class BikeLights {
- public Light[] brakeLights;
- }
- // Bike sounds /////////////////////////////////
- public BikeSounds bikeSounds;
- [System.Serializable]
- public class BikeSounds {
- public AudioSource lowCrash;
- public AudioSource nitro;
- public AudioSource switchGear;
- public AudioSource skidding;
- }
- // Bike Particle /////////////////////////////////
- public BikeParticles bikeParticles;
- private GameObject[] Particle = new GameObject[4];
- [System.Serializable]
- public class BikeParticles {
- public GameObject brakeParticlePerfab;
- public ParticleSystem shiftParticle1,shiftParticle2;
- }
- [System.Serializable]
- public class HitGround {
- public string tag = "street";
- public AudioClip groundSound;
- public Color brakeColor;
- }
- // Bike Engine Setting /////////////////////////////////
- public BikeSetting bikeSetting;
- public float steeringSpeed = 8f;
- [System.Serializable]
- public class BikeSetting {
- public bool showNormalGizmos = false;
- public HitGround[] hitGround;
- public Transform bikeSteer;
- public float springs = 7000.0f;
- public float dampers = 10.0f;
- public float bikePower = 70;
- public float shiftPower = 100;
- public float brakePower = 500;
- public Vector3 shiftCentre = new Vector3(0.0f,-0.6f,0.0f); // offset of centre of mass
- public Vector3 shiftSpeed = new Vector3(0.0f,-0.5f,-0.8f); // offset of centre of mass
- public float maxSteerAngle = 30.0f; // max angle of steering wheels
- public float maxTurn = 1.5f;
- public float shiftDownRPM = 1500.0f; // rpm script will shift gear down
- public float shiftUpRPM = 4000.0f; // rpm script will shift gear up
- public float idleRPM = 700.0f; // idle rpm
- public float stiffnessFront = 0.1f; // for wheels, determines slip
- public float stiffnessFrontSide = 0.1f; // give both wheels separate slip values.
- public float stiffnessBack = 0.1f;
- public float stiffnessBackSide = 0.1f;
- public bool automatic = true; // automatic, if true bike shifts auto
- public float[] gears = { -10f,9f,6f,4.5f,3f,2.5f }; // gear ratios (index 0 is reverse)
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- private Quaternion SteerRotation;
- [HideInInspector]
- public bool grounded = true;
- private float MotorRotation;
- [HideInInspector]
- public bool crash;
- public float _steer = 0f;
- public float steer {
- get{ return _steer; }
- set{
- //Debug.Log("Steer being set.." + Time.deltaTime);
- _steer = value;
- }
- }
- //[HideInInspector]
- //public float steer = 0; // steering -1.0 .. 1.0
- //[HideInInspector]
- public float steer2;
- //[HideInInspector]
- public float accel = 0.0f; // accelerating -1.0 .. 1.0
- //AI only.
- public float brake = 0f;
- private bool shifmotor;
- [HideInInspector]
- public float curTorque = 100f;
- [HideInInspector]
- public float powerShift = 100;
- [HideInInspector]
- public bool shift;
- private float torque = 100f; // the base power of the engine (per wheel, and before gears)
- [HideInInspector]
- public float speed = 0.0f;
- public bool healthEnabled = false;
- public float health = 1f;
- public bool enableCarReset = true;
- private float lastSpeed = -10.0f;
- // table of efficiency at certain RPM, in tableStep RPM increases, 1.0f is 100% efficient
- // at the given RPM, current table has 100% at around 2000RPM
- float[] efficiencyTable = { 0.6f,0.65f,0.7f,0.75f,0.8f,0.85f,0.9f,1.0f,1.0f,0.95f,0.80f,0.70f,0.60f,0.5f,0.45f,0.40f,0.36f,0.33f,0.30f,0.20f,0.10f,0.05f };
- // the scale of the indices in table, so with 250f, 750RPM translates to efficiencyTable[3].
- float efficiencyTableStep = 250.0f;
- private float shiftDelay = 0.0f;
- // shortcut to the component audiosource (engine sound).
- private AudioSource audioSource;
- [HideInInspector]
- public int currentGear = 1;
- [HideInInspector]
- public float motorRPM = 0.0f;
- private float wantedRPM = 0.0f;
- private float w_rotate;
- public GameObject preStartMenu;
- public GameObject initMenuButtons;
- public GameObject leftRigbhtButtons;
- public GameObject touchometer;
- public GameObject debugBar;
- private Skidmarks m_skidmarks;
- private ParticleEmitter m_skidSmoke;
- public float skidMarkMin = 0.2f;
- public float skidSmokeMin = 0.4f;
- public float skidMarkMax = 10f;
- public float skidMarkOffset = 0.1f;
- public float skidVolumeMultiplier = 1.0f;
- public float skidVolumeSpeed = 2.48f;
- private float skidVolume = 0f;
- private float skidVolumeTarg = 0f;
- ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- public float skidValue{
- get{ return skidVolume; }
- }
- private WheelComponent[] wheels;
- private class WheelComponent {
- public Transform wheel;
- public Transform axle;
- public WheelCollider collider;
- public Vector3 startPos;
- public float rotation = 0.0f;
- public float maxSteer;
- public bool drive;
- public float pos_y = 0.0f;
- //MOD
- public bool cachedGrounded = false;
- public string cachedTag = "Untagged";
- }
- public Transform camTarget;
- public Transform followTarget;
- public Transform dashTarget;
- //Nope, move it to start, so we can set isAI via script
- //void Awake() {
- // Instance = this;
- //}
- public float getSpeed(){
- return speed;
- }
- public float getHealth(){
- return 1;
- }
- private WheelComponent SetWheelComponent(Transform wheel,Transform axle,bool drive,float maxSteer,float pos_y) {
- WheelComponent result = new WheelComponent();
- GameObject wheelCol = new GameObject(wheel.name + "WheelCollider");
- wheelCol.transform.parent = transform;
- wheelCol.transform.position = wheel.position;
- wheelCol.transform.eulerAngles = transform.eulerAngles;
- pos_y = wheelCol.transform.localPosition.y;
- wheel.gameObject.AddComponent<WheelCollider>();
- WheelCollider col = (WheelCollider)wheelCol.AddComponent(typeof(WheelCollider));
- col.transform.localScale = wheel.localScale;
- col.radius = wheel.GetComponent<WheelCollider>().radius;
- //Destroy(wheel.transform.GetComponent<WheelCollider>());
- result.drive = drive;
- result.wheel = wheel;
- result.axle = axle;
- result.collider = wheelCol.GetComponent<WheelCollider>();
- result.pos_y = pos_y;
- result.maxSteer = maxSteer;
- result.startPos = axle.transform.localPosition;
- return result;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- //bool useTilt = false;
- bool useTilt{
- get{
- return !isAI && CarMain.accelerometerControls;
- }
- }
- private bool lastUseTilt = false;
- bool moveUp = false;
- bool moveDown = false;
- bool moveLeft = false;
- bool moveRight = false;
- bool nitro = false;
- float moveLeftValue = 0f;
- float moveRightValue = 0f;
- float moveUpValue = 0f;
- float moveDownValue = 0f;
- float stepForValue = 0.1f;//0.01f;
- Vector3 startPos;
- Quaternion startRotate;
- public void OnTiltPress() {
- //useTilt = true;
- //StartMenu.Instance.StartGame(true);
- preStartMenu.SetActive(false);
- initMenuButtons.SetActive(true);
- leftRigbhtButtons.SetActive(false);
- touchometer.SetActive(true);
- //Game.isRunning = true;
- }
- public void OnArrowsPress() {
- //useTilt = false;
- preStartMenu.SetActive(false);
- initMenuButtons.SetActive(true);
- leftRigbhtButtons.SetActive(true);
- //StartMenu.Instance.StartGame(false);
- touchometer.SetActive(true);
- //Game.isRunning = true;
- }
- public void PressNitroBtn() {
- shift = true;
- Debug.Log("press nitro");
- }
- public void ReleaseNitroBtn() {
- shift = false;
- Debug.Log("release nitro");
- }
- public void PressMoveUpBtn() {
- moveUp = true;
- }
- public void ReleaseMoveUpBtn() {
- moveUpValue = 0f;
- moveUp = false;
- }
- public void PressMoveDownBtn() {
- moveDown = true;
- }
- public void ReleaseMoveDownBtn() {
- moveDownValue = 0f;
- moveDown = false;
- }
- public void PressMoveLeftBtn() {
- moveLeft = true;
- }
- public void ReleaseMoveLeftBtn() {
- moveLeftValue = 0f;
- moveLeft = false;
- }
- public void PressMoveRightBtn() {
- moveRight = true;
- }
- public void ReleaseMoveRightBtn() {
- moveRightValue = 0f;
- moveRight = false;
- }
- public void ToggleControlTypeBtn() {
- //useTilt = !useTilt;
- moveRightValue = 0f;
- moveRight = false;
- moveLeftValue = 0f;
- moveLeft = false;
- leftRigbhtButtons.SetActive(!leftRigbhtButtons.activeInHierarchy);
- //StartMenu.Instance.showLeftRightButtons(!useTilt);
- }
- private int cooldownCount = 0;
- public void Reload() {
- resetVehicle( false );
- }
- public void resetVehicle( bool toStart = false ){
- //gameObject.transform.position = startPos;
- //gameObject.transform.rotation = startRotate;
- //gameObject.rigidbody.velocity = Vector3.zero;
- //
- if(carResetCooldown > 0f){
- carResetCooldown = 1;
- cooldownCount ++;
- if ( cooldownCount < 3 ){
- return;
- }else if ( cooldownCount == 3 ){
- Vector3 vecUp = ( this.transform.forward * -1 );
- vecUp.y = Mathf.Abs( vecUp.y );
- this.transform.forward = vecUp;
- this.transform.localEulerAngles = Vector3.zero;
- this.GetComponent<Rigidbody>().velocity = Vector3.zero;
- this.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
- return;
- }else if ( cooldownCount == 4 ){
- this.transform.position = startPos;
- this.transform.localEulerAngles = Vector3.zero;
- this.GetComponent<Rigidbody>().velocity = Vector3.zero;
- this.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
- return;
- }
- }else{
- cooldownCount = 0;
- }
- CrashLogger.registerRestore( ((Screen_Manager.currentlyStunt)?0:1), this.transform.position, this.transform.forward, this.transform.up, false );
- carResetCooldown = 1.0f;
- this.transform.localEulerAngles = new Vector3(0,this.transform.localEulerAngles.y,0);
- if ( toStart ){
- if ( LevelManager.getNearestRestorePoint( this.transform.position ) ){
- this.transform.position = LevelManager.lastRestorePoint;
- }else{
- if ( myController != null ){
- this.transform.position = myController.startPosition;
- }else{
- Debug.LogError("Bike: Nowhere to restore!");
- }
- }
- }else{
- this.transform.position += new Vector3(0.5f, 1.6f, 0.5f);
- }
- this.GetComponent<Rigidbody>().velocity = Vector3.zero;
- this.GetComponent<Rigidbody>().angularVelocity = Vector3.zero;
- }
- public void sendToCamera(){
- CamSmoothFollow.nextCenterOfMass = GetComponent<Rigidbody>().transform;
- CameraSwitch.nextDashTarget = dashTarget;
- CameraSwitch.nextFollowTarget = followTarget;
- }
- private Motorcycle_Controller myController;
- void Start() {
- if ( !isAI ){
- Instance = this;
- sendToCamera();
- }
- lastUseTilt = useTilt;
- m_skidmarks = FindObjectOfType(typeof(Skidmarks)) as Skidmarks;
- if (m_skidmarks){
- m_skidSmoke = m_skidmarks.GetComponentInChildren<ParticleEmitter>() as ParticleEmitter;
- }else{
- if ( Application.loadedLevel > 0 ){
- Debug.Log("No skidmarks in this scene.");
- }
- }
- myController = Motorcycle_Controller.getMCFromParent( this.transform );
- SteerRotation = bikeSetting.bikeSteer.localRotation;
- wheels = new WheelComponent[2];
- wheels[0] = SetWheelComponent(bikeWheels.wheels.wheelFront, bikeWheels.wheels.AxleFront, false, bikeSetting.maxSteerAngle, bikeWheels.wheels.AxleFront.localPosition.y);
- wheels[1] = SetWheelComponent(bikeWheels.wheels.wheelBack, bikeWheels.wheels.AxleBack, true, bikeSetting.maxSteerAngle, bikeWheels.wheels.AxleBack.localPosition.y);
- startPos = transform.position;
- startRotate = transform.rotation;
- updateWheelValues();
- audioSource = (AudioSource)GetComponent(typeof(AudioSource));
- if(audioSource == null) {
- Debug.Log("No audio please add one");
- }
- }
- public void updateWheelValues(){
- int currentWheelID = 0;
- foreach(WheelComponent w in wheels) {
- WheelCollider col = w.collider;
- col.suspensionDistance = bikeWheels.setting.Distance;
- JointSpring js = col.suspensionSpring;
- js.spring = bikeSetting.springs;
- js.damper = bikeSetting.dampers;
- col.suspensionSpring = js;
- if(!bikeWheels.setting.AutomaticRadius)
- col.radius = bikeWheels.setting.Radius;
- col.mass = bikeWheels.setting.Weight;
- float iceFactor = 1.0f;
- //if ( myController != null && GameManager.playerInGame ){
- // if ( myController._in_mud ){
- // iceFactor *= 0.1f;
- // }
- //}
- WheelFrictionCurve fc = col.forwardFriction;
- fc.asymptoteValue = 5000.0f;
- fc.extremumSlip = 2.0f;
- fc.asymptoteSlip = 20.0f;
- if ( currentWheelID == 0 ){
- fc.stiffness = bikeSetting.stiffnessFront;// * iceFactor;
- }else{
- fc.stiffness = bikeSetting.stiffnessBack;// * iceFactor;
- }
- col.forwardFriction = fc;
- fc = col.sidewaysFriction;
- fc.asymptoteValue = 7500.0f;
- fc.asymptoteSlip = 2.0f;
- if ( currentWheelID == 0 ){
- fc.stiffness = bikeSetting.stiffnessFrontSide * iceFactor;
- }else{
- //Don't skid while we're upside down
- if ( myController._in_gravity ){
- fc.stiffness = bikeSetting.stiffnessBackSide;
- }else{
- fc.stiffness = getRearSlide() * iceFactor;
- }
- }
- col.sidewaysFriction = fc;
- currentWheelID++;
- }
- }
- public AnimationCurve rearSlideCurve; //rear friction based on speed.
- public AnimationCurve frictionDecreaseWithLeanCurve; //leaning to slide a bit
- public AnimationCurve rearTurnCurve; //dampen rear turning based on speed
- public AnimationCurve pitchTurnCurve; //dampen turning when driving upa slope
- public AnimationCurve bankTurnCurve; //dampen turning when on a banked surface
- public AnimationCurve bankPowerCurve; //engine power when on banked surface.
- public bool useRearSteer = true;
- public float getClampedSpeedPercent(){
- float percent = Mathf.Clamp01( Mathf.Abs(speed / 300));
- return percent;
- }
- public float getRearSlide(){
- float returnVal = rearSlideCurve.Evaluate( getClampedSpeedPercent() );
- if ( handbrakeButton ) returnVal *= 0.48f;
- float tiltPercent = Mathf.Clamp01( (Mathf.Abs(MotorRotation) / 60) );
- //float before = tiltPercent;
- float tiltMultiplier = frictionDecreaseWithLeanCurve.Evaluate( tiltPercent );
- returnVal *= tiltMultiplier;
- //float middle = tiltMultiplier;
- returnVal += ( Mathf.Abs( surfaceAngle / 90 ) );
- returnVal = Mathf.Clamp01( returnVal );
- //Debug.Log(" F M A " + before.ToString("F2") + " " + middle.ToString("F2") + " " + returnVal.ToString("F2") );
- return returnVal;
- }
- // handle shifting a gear up
- public void ShiftUp() {
- float now = Time.timeSinceLevelLoad;
- // check if we have waited long enough to shift
- if(now < shiftDelay)
- return;
- // check if we can shift up
- if(currentGear < bikeSetting.gears.Length - 1) {
- if(!bikeSounds.switchGear.isPlaying && !AppSoundManager.MuteSfx)
- bikeSounds.switchGear.GetComponent<AudioSource>().Play();
- currentGear++;
- // we delay the next shift with 1s. (sorry, hardcoded)
- shiftDelay = now + 1.0f;
- }
- }
- // handle shifting a gear down
- public void ShiftDown() {
- float now = Time.timeSinceLevelLoad;
- // check if we have waited long enough to shift
- if(now < shiftDelay)
- return;
- // check if we can shift down (note gear 0 is reverse)
- if(currentGear > 0) {
- if(!bikeSounds.switchGear.isPlaying && !AppSoundManager.MuteSfx)
- bikeSounds.switchGear.GetComponent<AudioSource>().Play();
- currentGear--;
- // we delay the next shift with 1/10s. (sorry, hardcoded)
- shiftDelay = now + 0.1f;
- }
- }
- //Jesus christ, why was this static?
- private float timeOfLastNotifiedHit = 0f;
- public void OnCollisionEnter(Collision collision) {
- if ( myController != null && myController.isInTeam ){
- if ( Time.time > timeOfLastNotifiedHit + 0.5f ){
- if ( MissionManager.notifyHit( myController, collision ) ){
- timeOfLastNotifiedHit = Time.time;
- }
- }
- }
- if ( collision.contacts.Length > 0 ){
- if ( !(collision.contacts[0].thisCollider is WheelCollider) && !(collision.contacts[0].otherCollider is WheelCollider) ){
- Vector3 rv = collision.relativeVelocity;
- if ( rv.magnitude > 10 ){
- CrashLogger.registerCrash( ((Screen_Manager.currentlyStunt)?0:1), collision.contacts[0].point, collision.relativeVelocity, collision.relativeVelocity.magnitude );
- }
- }
- }
- bikeSounds.lowCrash.Play();
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- private bool forwardButton = false;
- private bool backwardButton = false;
- private bool leftButton = false;
- private bool rightButton = false;
- private bool handbrakeButton = false;
- public bool isLeftDown{ get{ return leftButton;} }
- public bool isRightDown { get{ return rightButton;} }
- public bool isForwardDown{ get{ return forwardButton;} }
- public bool isBackwardDown{ get{ return backwardButton;} }
- public bool isHandbrakedown{ get{ return handbrakeButton;} }
- public void setKey (string key, bool state){
- switch(key)
- {
- case "forward":
- forwardButton = state;
- break;
- case "backward":
- backwardButton = state;
- break;
- case "left":
- leftButton = state;
- break;
- case "right":
- rightButton = state;
- break;
- case "handbrake":
- handbrakeButton = state;
- break;
- }
- }
- public bool isOnMud(){
- if ( wheels == null || wheels.Length == 0 ) return false;
- foreach(WheelComponent Wheel in wheels) {
- if ( Wheel.cachedGrounded && Wheel.cachedTag == "MUD" ){
- return true;
- }
- }
- return false;
- }
- public bool isOnRoad(){
- if ( wheels == null || wheels.Length == 0 ) return false;
- foreach(WheelComponent Wheel in wheels) {
- if ( Wheel.cachedGrounded && Wheel.cachedTag == "Road" ){
- return true;
- }
- if ( Wheel.cachedGrounded && Wheel.cachedTag == "MUD" ){
- return true;
- }
- }
- return false;
- }
- public float relativeSteeringSpeed = 0f;
- public float uprightTorque = 200;
- public float tStickyFactor = 10000f;
- private float flipRotate = 0.0f;
- private bool OnGround = false;
- void Update() {
- #if UNITY_EDITOR
- if ( Input.GetKeyUp(KeyCode.F) ){
- useRearSteer = !useRearSteer;
- Instructor.flash( "Editor: " + TT.red("Attencione!") );
- Instructor.flash("Using steer helper=" + useRearSteer.ToString());
- }
- if ( Input.GetKey(KeyCode.G) ){
- debugPitch();
- }
- #endif
- carResetCooldown -= Time.deltaTime;
- OnGround = false;
- myController.wheelFLdown = false;
- myController.wheelFRdown = false;
- myController.wheelRLdown = false;
- myController.wheelRRdown = false;
- int wheelId = 0;
- WheelHit wombat = new WheelHit();
- foreach(WheelComponent Wheel in wheels) {
- if(Wheel.collider.isGrounded) {
- OnGround = true;
- Wheel.cachedGrounded = true;
- Wheel.collider.GetGroundHit( out wombat );
- Wheel.cachedTag = wombat.collider.tag;
- if ( wheelId == 0 || wheelId == 1 ){
- myController.wheelFLdown = true;
- myController.wheelFRdown = true;
- }else{
- myController.wheelRLdown = true;
- myController.wheelRRdown = true;
- }
- }else{
- Wheel.cachedGrounded = false;
- Wheel.cachedTag = "Untagged";
- }
- wheelId++;
- }
- accel = 0f;
- //shift = false;
- relativeSteeringSpeed = Time.deltaTime * steeringSpeed;
- if ( useTilt != lastUseTilt ){
- leftButton = false;
- rightButton = false;
- moveLeftValue = 0;
- moveRightValue = 0;
- moveLeft = false;
- moveRight = false;
- Debug.Log("Tilt changed...");
- }
- if ( !isAI ){
- #if !UNITY_EDITOR
- if(moveUp || forwardButton){
- accel = 1f;
- }
- if(moveDown || backwardButton){
- accel = -1f;
- }
- if (shift && speed > 5 && shifmotor)
- {
- accel = 1f;
- }
- if(!useTilt){
- steer = Mathf.MoveTowards(steer, ( (moveRight||rightButton) ? 1f : (moveLeft||leftButton) ? -1f : 0f), relativeSteeringSpeed);
- } else {
- if ( Input.acceleration != null ){
- float valueLR = Input.acceleration.x;
- if(valueLR > 0f)
- {
- //Debug.Log("LR GR ZERO " + Input.acceleration + " " + valueLR);
- if(moveLeft||leftButton)
- {
- moveLeft = false;
- moveLeftValue = 0f;
- }
- moveRight = true;
- moveRightValue = valueLR;
- steer = Mathf.MoveTowards(steer, moveRightValue, relativeSteeringSpeed);
- }
- else if (valueLR < 0f)
- {
- //Debug.Log("LR LT ZERO " + Input.acceleration + " " + valueLR);
- if(moveRight||rightButton)
- {
- moveRight = false;
- moveRightValue = 0f;
- }
- moveLeft = true;
- moveLeftValue = valueLR;
- steer = Mathf.MoveTowards(steer, moveLeftValue, relativeSteeringSpeed);
- }
- else
- {
- //Debug.Log("LR EQ ZERO" + Input.acceleration + " " + valueLR);
- moveLeft = false;
- moveRight = false;
- moveLeftValue = 0f;
- moveRightValue = 0f;
- steer = Mathf.MoveTowards(steer, 0f, relativeSteeringSpeed);
- }
- } else{ //! null
- //Debug.Log("Null accelerometer controls " + Time.time.ToString("F2") );
- }
- }
- #else
- //Debug.Log("pS " + steer + " " + relativeSteeringSpeed + " " + steeringSpeed + "Tt " + Time.deltaTime );
- if(!crash) {
- float steerTarg = 0;
- if( ( !isAI && ( Input.GetKey(KeyCode.LeftArrow) || Input.GetKey(KeyCode.A) )) || leftButton ) {
- steer = Mathf.MoveTowards(steer,-1f,relativeSteeringSpeed);
- //steer += relativeSteeringSpeed;
- steerTarg = -1f;
- }
- else if( ( !isAI && ( Input.GetKey(KeyCode.RightArrow) || Input.GetKey(KeyCode.D) )) || rightButton ) {
- steer = Mathf.MoveTowards(steer,1f,relativeSteeringSpeed);
- //steer -= relativeSteeringSpeed;
- steerTarg = 1;
- }
- else {
- steer = Mathf.MoveTowards(steer,0f,relativeSteeringSpeed * 10);
- steerTarg = 0;
- }
- //steer += ( steerTarg - steer ) * relativeSteeringSpeed;
- //Debug.Log(" S " + steer + " " + relativeSteeringSpeed + " " + steeringSpeed + "Tt " + Time.deltaTime );
- if(!moveUp && !moveDown){
- accel = Input.GetAxis("Vertical");
- }
- if ( forwardButton ){
- accel = 1f;
- }
- if ( backwardButton ){
- accel = -1f;
- }
- //if(!shift)
- //shift = Input.GetKey(KeyCode.LeftShift) | Input.GetKey(KeyCode.RightShift);
- } else {
- steer = 0;
- }
- #endif
- }else{ // *IS* AI
- steer = AI_STEER;
- accel = AI_ACCEL;
- handbrakeButton = (AI_HANDBRAKE>0f);
- brake = AI_BRAKE;
- //brake handled elsewhere
- }
- lastUseTilt = useTilt;
- // handle automatic shifting
- if(bikeSetting.automatic && (currentGear == 1) && (accel < 0.0f)) {
- if(speed < 1.0f)
- ShiftDown(); // reverse
- }
- else if(bikeSetting.automatic && (currentGear == 0) && (accel > 0.0f)) {
- if(speed < 5.0f)
- ShiftUp(); // go from reverse to first gear
- }
- else if(bikeSetting.automatic && (motorRPM > bikeSetting.shiftUpRPM) && (accel > 0.0f)) {
- // if (speed > 20)
- ShiftUp(); // shift up
- }
- else if(bikeSetting.automatic && (motorRPM < bikeSetting.shiftDownRPM) && (currentGear > 1)) {
- ShiftDown(); // shift down
- }
- if((currentGear == 0)) {
- bikeSetting.shiftCentre.z = -accel / 5.0f;
- if(speed < bikeSetting.gears[0] * -10)
- accel = -accel; // in automatic mode we need to hold arrow down for reverse
- }
- else {
- bikeSetting.shiftCentre.z = -(accel / currentGear) / 3.0f;
- }
- steer2 = Mathf.LerpAngle(steer2,steer * -bikeSetting.maxSteerAngle,Time.deltaTime * 10.0f);
- MotorRotation = Mathf.Lerp(MotorRotation,steer2 * bikeSetting.maxTurn * (Mathf.Clamp(speed / 100,0.0f,1.0f)),Time.deltaTime * 5.0f);
- if(bikeSetting.bikeSteer){
- bikeSetting.bikeSteer.localRotation = SteerRotation * Quaternion.Euler(0,wheels[0].collider.steerAngle,0); // this is 90 degrees around y axis
- }
- if(!crash) {
- /*
- Quaternion deltaRotation;
- flipRotate = (transform.eulerAngles.z > 90 && transform.eulerAngles.z < 270) ? 180.0f : 0.0f;
- deltaRotation= Quaternion.Euler(0f,0f,-fixDegrees(transform.localEulerAngles.z) + (MotorRotation));
- float NewX = Mathf.Clamp(fixDegrees(rigidbody.rotation.eulerAngles.x),-60f,60f);
- if(OnGround) {
- NewX = rigidbody.rotation.eulerAngles.x;
- }
- if(isAutorotatorEnable) {
- rigidbody.MoveRotation(Quaternion.Euler(NewX,fixDegrees(rigidbody.rotation.eulerAngles.y),fixDegrees(rigidbody.rotation.eulerAngles.z)) * deltaRotation);
- // 1 tilt forward, -1 tilt back
- Vector3 AngVelo = rigidbody.angularVelocity;
- float NewAngularVeloX = ((Mathf.InverseLerp(60f,-60f,NewX) * 2) - 1); // -1 - 1
- if(!OnGround) {
- AngVelo.x = (AngVelo.x * (Mathf.Abs(NewAngularVeloX) >= 0.4f ? NewAngularVeloX * 1.5f : 1f));
- rigidbody.angularVelocity = AngVelo;
- }
- }
- */
- }//!crash
- }
- public static Vector3 getLocalRadians(Quaternion rotation)
- {
- float pitch = Mathf.Atan2(2*rotation.x*rotation.w - 2*rotation.y*rotation.z, 1 - 2*rotation.x*rotation.x - 2*rotation.z*rotation.z);
- float yaw = Mathf.Atan2(2*rotation.y*rotation.w - 2*rotation.x*rotation.z, 1 - 2*rotation.y*rotation.y - 2*rotation.z*rotation.z);
- float roll = Mathf.Asin(2*rotation.x*rotation.y + 2*rotation.z*rotation.w);
- return new Vector3(pitch, yaw, roll);
- }
- public static Vector3 getLocalDegrees(Quaternion rotation)
- {
- Vector3 radResult = getLocalRadians(rotation);
- return new Vector3(radResult.x * Mathf.Rad2Deg, radResult.y * Mathf.Rad2Deg, radResult.z * Mathf.Rad2Deg);
- }
- //Works when rotated around the Y axis
- public float getRollDegrees(){
- float oVal = GetComponent<Rigidbody>().transform.localEulerAngles.z;
- while (oVal < 0 ) oVal += 360;
- while (oVal >= 360) oVal -= 360;
- if ( oVal > 180 ) oVal -= 360;
- return oVal;
- }
- //Did you reformat this by the way? it's my code but not my code style. weird.
- private float fixDegrees(float iVal) {
- float oVal = iVal;
- while(oVal < 0)
- oVal += 360;
- while(oVal > 360)
- oVal -= 360;
- if(oVal > 180)
- oVal -= 360;
- return oVal;
- }
- public void putCameraOnViewLoop() {
- }
- //==============================
- public int barrelRollPos = 0;
- public int flipPos = 0;
- public bool flipped = false;
- public GameObject bonusText;
- string[] stuntText;
- public float stuntTimer = 0f;
- public float lastStuntTime = 0f;
- public int stuntComboCount = 0;
- public int totalStuntComboTime = 9;
- public bool leftWheelsStuntActive = false;
- public bool rightWheelsStuntActive = false;
- public bool jumpStuntActive = false;
- //===============================
- public Vector3 lastCarPosition = Vector3.zero;
- private bool gotLastPosition = false;
- private float jumpDistanceTimer = 0f;
- private float rightWheelsDistance = 0f;
- private float leftWheelsDistance = 0f;
- private float driftDistance = 0f;
- private bool driftingActive = false;
- private bool lastStuntWasDrift = false; //prevent constant drifting
- private bool wasBoosting = false;
- private bool driftCanceled = false;
- //private bool jumpCanceled = false;
- private float jumpStartHeight = 0f;
- private float highestJumpHeight = 0f;
- private bool highJumpActive = false;
- private bool justInAir = false;
- public bool simpleStunts = true;
- private float carResetCooldown = 0f;
- public void checkStunts(){
- Transform thisTransform = this.transform;
- if ( !simpleStunts ) return;
- if ( carResetCooldown > 0 ) return;
- if ( SimpleBonusHandler.Instance == null ) return;
- if ( !gotLastPosition ){
- lastCarPosition = thisTransform.position;
- gotLastPosition = true;
- }
- Vector3 delta = (thisTransform.position - lastCarPosition);
- delta.Scale( new Vector3( 1, 0, 1 ) ) ;
- float distanceSinceLastFrame = delta.magnitude;
- bool mustCancel = mobileHUD_handler.pendingRestore;
- mobileHUD_handler.pendingRestore = false;
- bool[] gWheel = myController.checkWheelsGrounded();
- //bool allGrounded = gWheel[0] && gWheel[1] && gWheel[2] && gWheel[3];
- bool allUnGrounded = !gWheel[0] && !gWheel[1] && !gWheel[2] && !gWheel[3];
- bool oneGrounded = gWheel[0] || gWheel[1] || gWheel[2] || gWheel[3];
- if( allUnGrounded && !mustCancel && myController.body.velocity.magnitude > 0.01f ){
- jumpDistanceTimer += distanceSinceLastFrame;
- jumpStuntActive = jumpDistanceTimer > 15f;
- if( jumpStuntActive ){
- //createBonusText( "Jump " + jumpDistanceTimer.ToString("F2") + "m", jumpDistanceTimer );
- if ( !isAI ) SimpleBonusHandler.Instance.registerJump( 0, jumpDistanceTimer );
- }
- } else {
- if(jumpStuntActive){
- //jumpCanceled = false;
- SimpleBonusHandler.Instance.finishedJump( 0 );
- jumpStuntActive = false;
- }
- jumpDistanceTimer = 0;
- }
- if ( allUnGrounded && !mustCancel ){
- justInAir = true;
- float heightDelta = thisTransform.position.y - jumpStartHeight;
- //highJumpActive = heightDelta > 8f;
- if ( heightDelta > 8f || highestJumpHeight > 8f ) highJumpActive = true;
- if ( highJumpActive ){
- if ( heightDelta > highestJumpHeight || (Motorcycle_Controller.playerCar != null && Motorcycle_Controller.playerCar.canFly) ){
- highestJumpHeight = heightDelta;
- }
- if ( !isAI )SimpleBonusHandler.Instance.registerJump( 1, highestJumpHeight );
- }
- }else{
- }
- if ( oneGrounded || mustCancel ){
- if ( highJumpActive ){
- highJumpActive = false;
- SimpleBonusHandler.Instance.finishedJump( 1 );
- }
- //reset the high jump
- jumpStartHeight = thisTransform.position.y;
- highestJumpHeight = 0f;
- //reset the flips
- if ( justInAir ){
- justInAir = false;
- SimpleBonusHandler.Instance.finishedJump( 2 );
- }
- }
- //Flippyfliptime
- if ( mustCancel ) flipPos = 0;
- // The car is doing a flip
- if((transform.eulerAngles.x < 35 && flipped == false) || (transform.eulerAngles.x >= 270 && flipped == false) && !mustCancel){
- // Car front is pointing bottom left to top left (Tested and working)
- if(flipPos == 4){
- // The car rolled from the right angle position and finished in the left angle position
- if ( !isAI )SimpleBonusHandler.Instance.registerJump( 2, 1 );
- lastStuntWasDrift = false;
- }
- // If the car flips from this angle then it will be a forward flip
- flipPos = 1;
- } else if((transform.eulerAngles.x < 35 && flipped == true) || (transform.eulerAngles.x >= 270 && flipped == true)){
- // Car front is pointing bottom right to top right (Tested and working)
- if(flipPos == 3){
- // The car rolled from the left angle position and finished in the right angle position
- if ( !isAI )SimpleBonusHandler.Instance.registerJump( 2, 1 );
- lastStuntWasDrift = false;
- }
- // If the car flips from this angle then it will be a backward flip
- flipPos = 2;
- } else {
- // Were flipping!
- // This is a flip not a roll, cancel the current rolls
- barrelRollPos = 0;
- if(flipPos == 1){
- //Debug.Log("Flip started [forward]!");
- // Set the flip pos to 3 so if we enter the > 200 angle we know we did a full flip
- flipPos = 3;
- } else if(flipPos == 2) {
- //Debug.Log("Flip started [backward]!");
- // Set the flip pos to 4 so if we enter the < 160 angle we know we did a full flip
- flipPos = 4;
- }
- }
- if ( mustCancel ) barrelRollPos = 0;
- // Car is doing a barrel roll
- if(transform.eulerAngles.z < 140){
- flipped = false;
- if(barrelRollPos == 4){
- // The car rolled from the right angle position and finished in the left angle position
- //createBonusText("right roll", stuntTimer);
- if ( !isAI )SimpleBonusHandler.Instance.registerJump( 2, 1 );
- lastStuntWasDrift = false;
- }
- // If the car rolls from this angle then it will be a left roll
- barrelRollPos = 1;
- } else if(transform.eulerAngles.z > 220){
- flipped = false;
- if(barrelRollPos == 3){
- // The car rolled from the left angle position and finished in the right angle position
- //createBonusText("left roll", stuntTimer);
- SimpleBonusHandler.Instance.registerJump( 2, 1 );
- lastStuntWasDrift = false;
- }
- // If the car rolls from this angle then it will be a right roll
- barrelRollPos = 2;
- } else {
- flipped = true; // Is the y axis flipped?
- // Were rolling!
- if(barrelRollPos == 1){
- //Debug.Log("Barrel roll started [rolling left]!");
- // Set the barrel pos to 3 so if we enter the > 200 angle we know we did a full roll
- barrelRollPos = 3;
- } else if(barrelRollPos == 2) {
- //Debug.Log("Barrel roll started [rolling right]!");
- // Set the barrel pos to 4 so if we enter the < 160 angle we know we did a full roll
- barrelRollPos = 4;
- }
- }
- lastCarPosition = thisTransform.position;
- }
- /// <summary>
- /// Fixes an angle between -180 and 180 degrees
- /// </summary>
- private float fixAngle( float inAngle ){
- while ( inAngle > 360 ) inAngle -= 360;
- while (inAngle < 0 ) inAngle += 360;
- if ( inAngle > 180 ) inAngle -= 360;
- return inAngle;
- }
- public void debugPitch(){
- }
- public float relativeAngleSign( Vector3 normalVector, Vector3 otherVector, Vector3 referenceVector ){
- //Gonna need some kinda perpendicular reference value
- Vector3 perpen = Vector3.Cross( normalVector, referenceVector );
- //float angle2 = Vector3.Angle( referenceVector, otherVector );
- return Mathf.Sign( Vector3.Dot( perpen, otherVector ) );
- }
- private float getCurTorque( bool shiftInstead = false ){
- float outVal = bikeSetting.bikePower;
- if ( shiftInstead ) outVal = bikeSetting.shiftPower;
- float bankVal = Mathf.Clamp01( Mathf.Abs( surfaceAngle / 90f ) );
- float pitchVal = Mathf.Clamp01( Mathf.Abs( currentPitch / 90f ) );
- float first = (bankVal + pitchVal) * 0.5f;
- outVal *= bankPowerCurve.Evaluate( first );
- //outVal *= bankPowerCurve.Evaluate( bankVal );
- //outVal *= bankPowerCurve.Evaluate( pitchVal );
- //Debug.Log(" FOO " + first.ToString("F2") + " " + outVal.ToString("F2") );
- return outVal;
- }
- private int lastSkidIndex = -1;
- private bool lastBoosting = false;
- private float surfaceAngle = 0f;
- private float currentPitch = 0f;
- void FixedUpdate() {
- if ( !StateManager.shouldThingsTick ) return;
- //#if UNITY_EDITOR
- updateWheelValues();
- if ( !isAI ){
- checkStunts();
- }
- //#endif
- bool boosting = !(myController._boostTime <=0 ); //phrased it this way 'cause the zero looks like a happy smiley
- if ( boosting && !lastBoosting ){
- PressNitroBtn();
- }else if ( !boosting && lastBoosting ){
- ReleaseNitroBtn();
- }
- lastBoosting = boosting;
- speed = GetComponent<Rigidbody>().velocity.magnitude * 3.6f;
- //float outForce= -tStickyFactor;
- if ( myController != null && GameManager.playerInGame ){
- if ( myController._in_gravity || (grounded && Mathf.Abs(surfaceAngle) < 70) ){
- GetComponent<Rigidbody>().AddForce( -Physics.gravity * GetComponent<Rigidbody>().mass * 1.05f );
- GetComponent<Rigidbody>().AddForce( this.transform.up * -9.81f * GetComponent<Rigidbody>().mass * 1.05f );
- }
- //if ( grounded && Mathf.Abs(surfaceAngle) < 70 ){
- // rigidbody.AddForce( -Physics.gravity * rigidbody.mass );
- // rigidbody.AddForce( this.transform.up * -9.81f * rigidbody.mass );
- //}
- }
- float delta = Time.fixedDeltaTime;
- //rigidbody.centerOfMass = bikeSetting.shiftCentre;
- GetComponent<Rigidbody>().centerOfMass = camTarget.localPosition;
- foreach(Light brakeLight in bikeLights.brakeLights) {
- if(accel < 0 || speed < 1.0f) {
- brakeLight.intensity = Mathf.Lerp(brakeLight.intensity,8,0.1f);
- } else {
- brakeLight.intensity = Mathf.Lerp(brakeLight.intensity,0,0.1f);
- }
- }
- //applyupright
- //Apply upright force and optionally account for surface angle
- surfaceAngle = 0f; //clear it here and not above, because fucntions above
- //might want to use the cached value
- if ( !crash ){
- WheelHit frontHit;
- WheelHit backHit;
- bool frontDown = false;
- bool backDown = false;
- frontDown = wheels[0].collider.GetGroundHit( out frontHit );
- backDown = wheels[1].collider.GetGroundHit( out backHit );
- if ( frontDown && backDown ){
- /*
- //For the relative funcion
- Vector3 otherAngle = this.transform.up;
- Vector3 referenceVector = frontHit.point - backHit.point;
- */
- Vector3 combinedNormal = frontHit.normal * 0.5f + backHit.normal * 0.5f;
- Vector3 pointsVector = frontHit.point - backHit.point;
- Vector3 actualPerpendicular = Vector3.Cross( pointsVector, combinedNormal );
- Vector3 theoreticalPerpendicular = Vector3.Cross( pointsVector, Vector3.up );
- surfaceAngle = Vector3.Angle( actualPerpendicular, theoreticalPerpendicular );
- float signValue = Mathf.Sign( actualPerpendicular.y );
- surfaceAngle *= signValue;
- surfaceAngle = Mathf.Clamp( surfaceAngle, -90f, 90f );
- //surfaceAngle *= 0.8f;
- //float angle2 = surfaceAngle;
- //Debug.Log("A2 " + surfaceAngle );
- }
- bool ignoreRotation = (myController._in_gravity) && grounded;
- float currentRotation = getLocalDegrees(transform.rotation).z;
- float wantedRotation = MotorRotation;
- //if ( !ignoreRotation ){
- wantedRotation -= (surfaceAngle * 0.8f * 0.8f);
- //}else{
- // Debug.Log("ignoring rotation thingie");
- //}
- float deltaZ = wantedRotation - currentRotation; //(wantedRotation - currentRotation)
- if ( Mathf.Abs( currentRotation ) > 0.01f && !ignoreRotation ){
- GetComponent<Rigidbody>().AddTorque( Quaternion.identity * this.transform.forward * deltaZ * uprightTorque );
- }
- }
- // the RPM we try to achieve.
- wantedRPM = (5500.0f * accel) * 0.1f + wantedRPM * 0.9f;
- float rpm = 0.0f;
- int motorizedWheels = 0;
- bool floorContact = false;
- int currentWheel = 0;
- // calc rpm from current wheel speed and do some updating
- foreach(WheelComponent w in wheels) {
- WheelHit hit;
- WheelCollider col = w.collider;
- // only calculate rpm on wheels that are connected to engine
- if(w.drive) {
- rpm += col.rpm;
- motorizedWheels++;
- }
- if ( !isAI ){
- if(accel < 0.0f) {
- wantedRPM = 0.0f;
- col.brakeTorque = bikeSetting.brakePower;
- } else {
- col.brakeTorque = accel == 0 ? col.brakeTorque = 200 : col.brakeTorque = 1;
- }
- }else{
- col.brakeTorque = bikeSetting.brakePower * brake;
- }
- if(shift && speed > 5 && shifmotor) {
- if(transform.localEulerAngles.x > 320) {
- bikeSetting.shiftCentre.y = bikeSetting.shiftSpeed.y;
- bikeSetting.shiftCentre.z = bikeSetting.shiftSpeed.z;
- } else {
- //makes no sense unless there's some kinda getter/setter there.
- //bikeSetting.shiftCentre = bikeSetting.shiftCentre;
- }
- if(powerShift == 0) { shifmotor = false; }
- powerShift = Mathf.MoveTowards(powerShift,0.0f,0.3f);
- bikeSounds.nitro.volume = Mathf.Lerp(bikeSounds.nitro.volume,1.0f,0.1f);
- if(!bikeSounds.nitro.isPlaying && !AppSoundManager.MuteSfx) {
- bikeSounds.nitro.GetComponent<AudioSource>().Play();
- }
- curTorque = powerShift > 0 ? getCurTorque(true) : getCurTorque();
- bikeParticles.shiftParticle1.emissionRate = Mathf.Lerp(bikeParticles.shiftParticle1.emissionRate,powerShift > 0 ? 50 : 0,0.2f);
- bikeParticles.shiftParticle2.emissionRate = Mathf.Lerp(bikeParticles.shiftParticle2.emissionRate,powerShift > 0 ? 50 : 0,0.2f);
- } else {
- //bikeSetting.shiftCentre = bikeSetting.shiftCentre;
- if(powerShift > 20){
- shifmotor = true;
- }
- bikeSounds.nitro.volume = Mathf.MoveTowards(bikeSounds.nitro.volume,0.0f,0.02f);
- if(bikeSounds.nitro.volume == 0){
- bikeSounds.nitro.Stop();
- }
- powerShift = Mathf.MoveTowards(powerShift,100.0f,0.1f);
- curTorque = getCurTorque();
- bikeParticles.shiftParticle1.emissionRate = Mathf.Lerp(bikeParticles.shiftParticle1.emissionRate,0,0.2f);
- bikeParticles.shiftParticle2.emissionRate = Mathf.Lerp(bikeParticles.shiftParticle2.emissionRate,0,0.2f);
- }
- w.rotation = Mathf.Repeat(w.rotation + delta * col.rpm * 360.0f / 60.0f,360.0f);
- w.wheel.localRotation = Quaternion.Euler(w.rotation,0.0f,0.0f);
- // let the wheels contact the ground, if no groundhit extend max suspension distance
- Vector3 lp = w.axle.localPosition;
- //getGroundHit?
- if(col.GetGroundHit(out hit)) {
- bikeSounds.lowCrash.volume = Mathf.Lerp(bikeSounds.lowCrash.volume,0.0f,0.02f);
- if(bikeParticles.brakeParticlePerfab) {
- if(Particle[currentWheel] == null) {
- Particle[currentWheel] = Instantiate(bikeParticles.brakeParticlePerfab,w.wheel.position,Quaternion.identity) as GameObject;
- Particle[currentWheel].name = "WheelParticle";
- Particle[currentWheel].transform.parent = transform;
- Particle[currentWheel].AddComponent<AudioSource>();
- }
- var pc = Particle[currentWheel].GetComponent<ParticleSystem>();
- bool WGrounded = false;
- if(WGrounded && speed > 10) {
- pc.enableEmission = true;
- Particle[currentWheel].GetComponent<AudioSource>().volume = 1.0f;
- if(!Particle[currentWheel].GetComponent<AudioSource>().isPlaying && !AppSoundManager.MuteSfx)
- Particle[currentWheel].GetComponent<AudioSource>().Play();
- }else {
- pc.enableEmission = false;
- Particle[currentWheel].GetComponent<AudioSource>().volume = Mathf.Lerp(Particle[currentWheel].GetComponent<AudioSource>().volume,0,Time.deltaTime * 10.0f);
- }
- }
- lp.y -= Vector3.Dot(w.wheel.position - hit.point,transform.TransformDirection(0,1,0) / transform.lossyScale.x) - (col.radius);
- lp.y = Mathf.Clamp(lp.y,-10.0f,w.pos_y);
- floorContact = floorContact || (w.drive);
- if(!crash) {
- GetComponent<Rigidbody>().angularDrag = 20.0f;
- } else {
- GetComponent<Rigidbody>().angularDrag = 0.0f;
- }
- grounded = true;
- //col.GetGroundHit
- } else {
- bikeSounds.lowCrash.volume = Mathf.Lerp(bikeSounds.lowCrash.volume,1.0f,0.01f);
- //if(Particle[1] != null) {
- if(Particle[currentWheel] != null) {
- var pc = Particle[currentWheel].GetComponent<ParticleSystem>();
- Particle[currentWheel].GetComponent<AudioSource>().volume = 0;
- pc.enableEmission = false;
- }
- grounded = false;
- GetComponent<Rigidbody>().AddForce(0,-500,0);
- lp.y = w.startPos.y - bikeWheels.setting.Distance;
- }
- currentWheel++;
- w.axle.localPosition = lp;
- }//foreach Wheel
- // calculate the actual motor rpm from the wheels connected to the engine
- // note we haven't corrected for gear yet.
- if(motorizedWheels > 1) {
- rpm = rpm / motorizedWheels;
- }
- // we do some delay of the change (should take delta instead of just 95% of
- // previous rpm, and also adjust or gears.
- motorRPM = 0.95f * motorRPM + 0.05f * Mathf.Abs(rpm * bikeSetting.gears[currentGear]);
- if(motorRPM > 5500.0f)
- motorRPM = 5200.0f;
- // calculate the 'efficiency' (low or high rpm have lower efficiency then the
- // ideal efficiency, say 2000RPM, see table
- int index = (int)(motorRPM / efficiencyTableStep);
- if(index >= efficiencyTable.Length)
- index = efficiencyTable.Length - 1;
- if(index < 0)
- index = 0;
- // calculate torque using gears and efficiency table
- float newTorque = curTorque * bikeSetting.gears[currentGear] * efficiencyTable[index];
- //Debug.Log(" NT " + this + " " + newTorque);
- //Apply wheel steering
- int currentWheelID = 0;
- // go set torque to the wheels
- foreach(WheelComponent w in wheels) {
- WheelCollider col = w.collider;
- // of course, only the wheels connected to the engine can get engine torque
- if(w.drive) {
- // only set torque if wheel goes slower than the expected speed
- if(Mathf.Abs(col.rpm) > Mathf.Abs(wantedRPM) || (currentGear == 0 && speed > 10)) {
- // wheel goes too fast, set torque to 0
- col.motorTorque = 0;
- }else {
- //
- float curTorqueCol = col.motorTorque;
- col.motorTorque = curTorqueCol * 0.9f + newTorque * 0.1f;
- }
- }
- currentPitch = getLocalDegrees( this.transform.rotation ).x;
- float clampedPitch = Mathf.Clamp01( Mathf.Clamp(Mathf.Abs(currentPitch),0,90) / 90 );
- float pitchTurnMultiplier = pitchTurnCurve.Evaluate( clampedPitch );
- //Debug.Log(" CLP PTM " + clampedPitch + " " + pitchTurnMultiplier);
- float clampedBank = Mathf.Clamp01( Mathf.Clamp(Mathf.Abs(surfaceAngle),0,90) / 90 );
- float bankedTurnMultiplier = bankTurnCurve.Evaluate( clampedBank );
- if ( myController._in_gravity ){
- bankedTurnMultiplier = 1f;
- }
- float SteerAngle = Mathf.Clamp((speed / transform.lossyScale.x) / bikeSetting.maxSteerAngle,1.0f,bikeSetting.maxSteerAngle);
- if ( currentWheelID == 0 ){
- col.steerAngle = steer * (w.maxSteer / SteerAngle) * pitchTurnMultiplier * bankedTurnMultiplier;
- }else{
- //Apply a small amount of turn to the rear wheel to make this fucker turn properly.
- float speedVal = getClampedSpeedPercent();
- float rearTurnMultiplier = rearTurnCurve.Evaluate( speedVal );
- //Debug.Log("RTM " + rearTurnMultiplier);
- WheelHit g;
- if ( col.GetGroundHit( out g ) ){
- //float relSlip = Mathf.InverseLerp(col.sidewaysFriction.extremumSlip, col.sidewaysFriction.asymptoteSlip, g.sidewaysSlip );
- float absSlip = Mathf.Abs( g.sidewaysSlip );
- float clampedSkid = Mathf.Clamp( absSlip, 0, skidMarkMax );
- float clampedSkidPercent = clampedSkid / skidMarkMax;
- bool soundPlaying = false;
- if ( clampedSkidPercent > skidMarkMin ){
- //Vector3 flattenedSpeed = rigidbody.velocity;
- Vector3 outPoint = ( g.point + Vector3.up * 0.1f ) + ( GetComponent<Rigidbody>().velocity * skidMarkOffset) ;
- lastSkidIndex = m_skidmarks.AddSkidMark( outPoint , g.normal, clampedSkidPercent, 0.24f, lastSkidIndex );
- if ( clampedSkidPercent > skidSmokeMin ){
- soundPlaying = true;
- skidVolumeTarg = (clampedSkidPercent - skidSmokeMin) * (1/0.6f) * skidVolumeMultiplier;//hacky
- m_skidSmoke.Emit( outPoint, Vector3.up * 0.01f, 1, 1, Color.white, Random.Range(0f,360f), Random.Range(-10f,10f) );
- }
- }
- if ( !soundPlaying ){
- skidVolumeTarg = 0f;
- }
- skidVolume += ( skidVolumeTarg - skidVolume ) * Time.fixedDeltaTime * skidVolumeSpeed;
- if ( skidVolume > 0.05f ){
- if ( !bikeSounds.skidding.isPlaying ){
- bikeSounds.skidding.Play();
- }
- bikeSounds.skidding.volume = skidVolume;
- }else {
- if ( bikeSounds.skidding.isPlaying ){
- bikeSounds.skidding.Stop();
- }
- }
- }else{
- lastSkidIndex = -1; //reset it
- }
- //
- if ( !useRearSteer ) rearTurnMultiplier = 0f;
- col.steerAngle = steer * (w.maxSteer / -SteerAngle * rearTurnMultiplier * pitchTurnMultiplier * bankedTurnMultiplier);
- }//frontwheel, backwheel
- currentWheelID++;
- }//foreach wheel (steering)
- // if we have an audiosource (motorsound) adjust pitch using rpm
- if(audioSource != null) {
- // calculate pitch (keep it within reasonable bounds)
- float pitch = Mathf.Clamp(1.0f + ((motorRPM - bikeSetting.idleRPM) / (bikeSetting.shiftUpRPM - bikeSetting.idleRPM)),1.0f,10.0f);
- audioSource.pitch = pitch;
- audioSource.volume = Mathf.MoveTowards(audioSource.volume,1.0f,0.02f);
- }
- if(crash) {
- transform.GetComponent<Rigidbody>().centerOfMass = Vector3.zero;
- }
- }
- /////////////// Show Normal Gizmos ////////////////////////////
- void OnDrawGizmos() {
- if(!bikeSetting.showNormalGizmos || Application.isPlaying)
- return;
- Matrix4x4 rotationMatrix = Matrix4x4.TRS(transform.position,transform.rotation,transform.lossyScale);
- Gizmos.matrix = rotationMatrix;
- Gizmos.color = new Color(1,0,0,0.5f);
- Gizmos.DrawCube(Vector3.zero,new Vector3(0.5f,1.0f,2.5f));
- Gizmos.DrawSphere(bikeSetting.shiftCentre / transform.lossyScale.x,0.2f);
- }
- #pragma warning restore 0414
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement