Advertisement
summitgames

Motorbike scoller controller

Aug 16th, 2015
2,724
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.83 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class Motorcycle_Controller : MonoBehaviour
  5. {
  6.     //if this is activated the controlls will be got from touches else it'll be keyboard or joystick buttons
  7.     public bool forMobile = false;
  8.    
  9.     //used for mobile to detect which button was touched
  10.     public GUITexture throttleTexture;
  11.     public GUITexture brakeTexture;
  12.     public GUITexture leftTexture;
  13.     public GUITexture rightTexture;
  14.    
  15.     //used to determine when player is crashed
  16.     public static bool crash = false;
  17.     public static bool crashed = false;
  18.    
  19.     //used to enable/disable motorcycle controlling
  20.     public static bool isControllable = true;
  21.    
  22.     //used to count scores
  23.     public static int score = 0;
  24.    
  25.     public bool is2D = false;
  26.     public bool usingAccelerometer = false;
  27.    
  28.     //used to change motorcycle characteristics
  29.     public Rigidbody body;
  30.     public Transform frontFork;
  31.     public Transform frontWheel;
  32.     public Transform rearFork;
  33.     public Transform rearWheel;
  34.    
  35.     public float speed = 60.0f;
  36.     public float groundedWeightFactor = 20.0f;
  37.     public float inAirRotationSpeed = 10.0f;
  38.     public float wheelieStrength = 15.0f;
  39.    
  40.     //used to attach biker's bones to motorcycle positions so the biker will follow the motorcycle
  41.     public Transform hips;
  42.     public Transform leftHand;
  43.     public Transform rightHand;
  44.     public Transform leftFoot;
  45.     public Transform rightFoot;
  46.    
  47.     public Transform hipsPosition; 
  48.     public Transform leftFootPosition; 
  49.     public Transform leftHandPosition; 
  50.     public Transform rightFootPosition;
  51.     public Transform rightHandPosition;
  52.     //-------------------------------------------
  53.    
  54.     //used to start/stop dirt particles
  55.     public ParticleSystem dirt;
  56.    
  57.     //used for showing score particles when flips are done
  58.     public ParticleSystem backflipParticle;
  59.     public ParticleSystem frontflipParticle;   
  60.    
  61.     //used to show scores
  62.     public GUIText scoreText;
  63.     public Color scoreTextColor;
  64.    
  65.     //used to determine if motorcycle is grounded or in air
  66.     private RaycastHit hit;
  67.     private bool onGround = false;     
  68.     private bool inAir = false;    
  69.    
  70.     //used to manipulate engine sound pitch
  71.     private AudioSource audioSource;
  72.     private float pitch;
  73.    
  74.     //used to allign biker to motorcycle
  75.     private Vector3 tempPosition;
  76.     private float smooth = 0.0f;
  77.    
  78.     //used to determine when flip is done
  79.     private bool flip = false;             
  80.    
  81.     //used for knowing input   
  82.     private bool accelerate = false;
  83.     private bool brake = false;
  84.     private bool left = false;
  85.     private bool right = false;
  86.     private bool leftORright = false;          
  87.    
  88.    
  89.     //start function is called once when game starts
  90.     void Start ()
  91.     {
  92.         Input.multiTouchEnabled = true;
  93.         //reset static variables
  94.         crash = false;
  95.         crashed = false;
  96.         isControllable = true;
  97.         score = 0;
  98.        
  99.         tempPosition = hipsPosition.position;
  100.        
  101.         //change score text color
  102.         scoreText.material.color = scoreTextColor;     
  103.        
  104.         //adding motorcycle body as a follow target for camera
  105.         if(is2D)
  106. //if there is activated is2D checkbox on motorcycle, than you need to assign "CameraFollow2D.cs" script to camera
  107.             Camera.main.GetComponent<CameraFollow2D>().target = body.transform;
  108.         else
  109.             Camera.main.GetComponent<SmoothFollow>().target = body.transform;      
  110.        
  111.         //ignoring collision between motorcycle wheels and body
  112.         Physics.IgnoreCollision (frontWheel.GetComponent<Collider>(), body.GetComponent<Collider>());
  113.         Physics.IgnoreCollision (rearWheel.GetComponent<Collider>(), body.GetComponent<Collider>());
  114.        
  115.         //ignoring collision between motorcycle and ragdoll
  116.         Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Motorcycle"), LayerMask.NameToLayer ("Ragdoll"),true);
  117.        
  118.         //ignoring collision between motorcycle colliders
  119.         Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Motorcycle"), LayerMask.NameToLayer ("Motorcycle"),true);
  120.        
  121.         //used to manipulate engine sound pitch
  122.         audioSource = body.GetComponent<AudioSource>();    
  123.        
  124.         //setting rear wheel max angular rotation speed
  125.         rearWheel.GetComponent<Rigidbody> ().maxAngularVelocity = speed;               
  126.     }
  127.    
  128.        
  129.    
  130. //  Update is called once per frame
  131.     void Update()
  132.     {
  133.         if(isControllable)
  134.         {
  135.             if(forMobile)
  136.             {
  137.                 var touches = Input.touches;
  138.                
  139.                 accelerate = false;
  140.                 brake = false;
  141.                 left = false;
  142.                 right = false;
  143.                 leftORright = false;                           
  144.                
  145.                
  146.                 //use accelerometer for rotatin motorcycle left and right
  147.                 if(usingAccelerometer)
  148.                 {
  149.                     if(Screen.orientation == ScreenOrientation.LandscapeLeft || Screen.orientation == ScreenOrientation.LandscapeRight)
  150.                     {
  151.                         if(Input.acceleration.x > 0.07f)
  152.                             left = true;
  153.                         else if(Input.acceleration.x < -0.07f)
  154.                             right = true;
  155.                            
  156.                         if(left || right) //left or right button is touched
  157.                         leftORright = true;
  158.                     }
  159.                 }
  160.                
  161.                 //detect which mobile buttons are pressed and make decisions accordingly
  162.                 foreach (var touch in touches)
  163.                 {                      
  164.                     if(touch.phase != TouchPhase.Canceled && touch.phase != TouchPhase.Ended)
  165.                     {                                                                                          
  166.                         if(throttleTexture.HitTest (touch.position)) //if touch position is inside throttle texture
  167.                             accelerate = true;
  168.                        
  169.                         if(brakeTexture.HitTest (touch.position)) //if touch position is inside brake texture
  170.                             brake = true;
  171.                        
  172.                         if(leftTexture.HitTest (touch.position)) //left button is touched
  173.                             left = true;                       
  174.                        
  175.                         if(rightTexture.HitTest (touch.position)) //right button is touched
  176.                             right = true;                      
  177.                        
  178.                         if(left || right) //left or right button is touched
  179.                             leftORright = true;                    
  180.                     }
  181.                    
  182.                 }
  183.                
  184.                 if(Input.touchCount == 0)
  185.                 {
  186.                    
  187.                 }
  188.             }
  189.             else
  190.             {
  191.                 //detect which keys are pressed. keys relevant to "Horizontal" and "Vertical" keywords are set in: Edit -> Project Settings -> Input
  192.                 if(Input.GetAxisRaw("Horizontal") != 0)
  193.                     leftORright = true;
  194.                 else
  195.                     leftORright = false;
  196.                
  197.                 if(Input.GetAxisRaw("Horizontal") > 0)
  198.                     right = true;
  199.                 else
  200.                     right = false;
  201.                
  202.                 if(Input.GetAxisRaw("Horizontal") < 0)
  203.                     left = true;
  204.                 else
  205.                     left = false;
  206.                
  207.                 if(Input.GetAxisRaw("Vertical") > 0 || Input.GetKey (KeyCode.Joystick1Button2))
  208.                     accelerate = true;
  209.                 else
  210.                     accelerate = false;            
  211.                
  212.                 if(Input.GetAxisRaw("Vertical") < 0 || Input.GetKey (KeyCode.Joystick1Button1))
  213.                     brake = true;
  214.                 else
  215.                     brake = false;             
  216.                 //----------------------------------
  217.             }
  218.        
  219.                    
  220.             if(body.rotation.eulerAngles.z > 210 && body.rotation.eulerAngles.z < 220)                 
  221.                         flip = true;                                                                                       
  222.                        
  223.             if(body.rotation.eulerAngles.z > 320 && flip) //backflip is done
  224.             {
  225.                 flip = false;              
  226.                 backflipParticle.Emit(1);
  227.                 score += 100;
  228.                 scoreText.text = "SCORE : " + score;
  229.             }
  230.            
  231.             if(body.rotation.eulerAngles.z < 30 && flip) //frontflip is done
  232.             {                                                          
  233.                 flip = false;
  234.                 frontflipParticle.Emit(1);
  235.                 score += 150;  
  236.                 scoreText.text = "SCORE : " + score;                   
  237.             }
  238.            
  239.             //if any horizontal key (determined in edit -> project settings -> input)  is pressed or if "formobile" is activated, left or right buttons are touched or accelerometer is used
  240.             if(leftORright)
  241.             {
  242.                 if(right)//right horizontal key is pressed or if "formobile" is activated, right button is touched or using accelerometer
  243.                     tempPosition = Vector3.Lerp (tempPosition, hipsPosition.position + new Vector3(0.1f,0.1f,0f), smooth); //aligning bikers hips position to motorcycle to illustrate stand effect
  244.                
  245.                 if(left)//left horizontal key is pressed or left button is touched on mobile or using accelerometer
  246.                     tempPosition = Vector3.Lerp (tempPosition, hipsPosition.position - new Vector3(0.1f,-0.05f,0f), smooth); //illustrating back lean
  247.             }
  248.             else tempPosition = Vector3.Lerp (tempPosition, hipsPosition.position, smooth); //used to smoothly follow biker's hips to motorcycle           
  249.            
  250.             //changing engine sound pitch depending rear wheel rotational speed
  251.             if(accelerate)
  252.             {
  253.                 pitch = rearWheel.GetComponent<Rigidbody>().angularVelocity.sqrMagnitude / speed;
  254.                 pitch *= Time.deltaTime * 2;
  255.                 pitch = Mathf.Clamp (pitch + 1, 0.5f,1.8f);        
  256.             }
  257.             else
  258.                 pitch = Mathf.Clamp (pitch - Time.deltaTime * 2, 0.5f, 1.8f);                                                              
  259.         }      
  260.         else if(!crashed) tempPosition = Vector3.Lerp (tempPosition, hipsPosition.position, smooth); //used to smoothly follow biker's hips to motorcycle
  261.        
  262.         if(crash && !crashed) //if player just crashed
  263.             {                                          
  264.                 if(is2D)//if there is activated is2D checkbox on motorcycle, than you need to assign "CameraFollow2D.cs" script to camera
  265.                 Camera.main.GetComponent<CameraFollow2D>().target = hips; //make camera to follow biker's hips
  266.                 else
  267.                 Camera.main.GetComponent<SmoothFollow>().target = hips; //make camera to follow biker's hips
  268.                
  269.                 //make bones not kinematic, so biker detaches from motorcycle
  270.                 hips.GetComponent<Rigidbody>().isKinematic = false;
  271.                 leftHand.GetComponent<Rigidbody>().isKinematic = false;
  272.                 rightHand.GetComponent<Rigidbody>().isKinematic = false;
  273.                 leftFoot.GetComponent<Rigidbody>().isKinematic = false;
  274.                 rightFoot.GetComponent<Rigidbody>().isKinematic = false;
  275.                
  276.                 //add velocity to biker depending motorcycle speed
  277.                 hips.GetComponent<Rigidbody>().velocity  = body.GetComponent<Rigidbody>().velocity * 5;
  278.                 hips.GetComponent<Rigidbody>().angularVelocity  = body.GetComponent<Rigidbody>().angularVelocity * 5;
  279.            
  280.                 //turn on collision between ragdoll and motorcycle
  281.                 Physics.IgnoreLayerCollision(LayerMask.NameToLayer("Motorcycle"), LayerMask.NameToLayer ("Ragdoll"),false);
  282.                                
  283.                 if(!is2D) //disable all physics constraints if 2D isn't activated for motorcycle in inspector menu, so physics calculation will occur on all axis
  284.                 {
  285.                     hips.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
  286.                     body.constraints = RigidbodyConstraints.None;
  287.                     frontFork.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
  288.                     frontWheel.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
  289.                     rearFork.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;
  290.                     rearWheel.GetComponent<Rigidbody>().constraints = RigidbodyConstraints.None;                           
  291.                 }
  292.                
  293.                 isControllable = false;
  294.                 crashed = true;
  295.             }
  296.             else if(!crashed) //if we aren't crashed, aligning biker's bones to motorcycle positions, so biker will follow to motorcycle
  297.             {                          
  298.                 hips.position = tempPosition;
  299.                 hips.rotation = hipsPosition.rotation;     
  300.                 leftHand.position = leftHandPosition.position;
  301.                 rightHand.position = rightHandPosition.position;
  302.                 leftFoot.position = leftFootPosition.position;
  303.                 rightFoot.position = rightFootPosition.position;           
  304.             }
  305.        
  306.         //manipulating engine sound pitch
  307.         pitch = Mathf.Clamp (pitch - Time.deltaTime * 2, 0.5f, 1.8f);
  308.         audioSource.pitch = pitch;
  309.        
  310.         //if player is crashed and "R" is pressed or touch is detected on mobile, than restart current level
  311.         if((Input.GetKeyDown (KeyCode.R) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)) && crashed)
  312.         Application.LoadLevel (Application.loadedLevel);
  313.     }
  314.    
  315.    
  316.    
  317.     //physics are calculated in FixedUpdate function
  318.     void FixedUpdate ()
  319.     {          
  320.         if(isControllable){
  321.             smooth = Mathf.Clamp (Time.deltaTime * body.velocity.sqrMagnitude * 2, 0.3f, 1);
  322.            
  323.             if (accelerate)
  324.             {
  325.                 rearWheel.GetComponent<Rigidbody>().freezeRotation = false; //allow rotation to rear wheel
  326.                 rearWheel.GetComponent<Rigidbody>().AddTorque (new Vector3 (0, 0, -speed * Time.deltaTime),ForceMode.Impulse);  //add rotational speed to rear wheel
  327.                
  328.                 if(onGround)//if motorcycle is standing on object tagged as "Ground"
  329.                 {          
  330.                     if(!dirt.isPlaying)
  331.                     dirt.Play (); //play dirt particle
  332.                    
  333.                     dirt.transform.position = rearWheel.position; //allign dirt to rear wheel
  334.                    
  335.                 } else dirt.Stop ();
  336.                
  337.             } else dirt.Stop ();
  338.            
  339.             if(brake)
  340.                 rearWheel.GetComponent<Rigidbody>().freezeRotation = true; //disable rotation for rear wheel if player is braking                              
  341.             else           
  342.                 rearWheel.GetComponent<Rigidbody>().freezeRotation = false; //enable rotation for rear wheel if player isn't braking
  343.                
  344.             if (left) { //left horizontal key (determined in edit -> project settings -> input) is pressed or left button is touched on mobile if "formobile" is activated
  345.                 if (!inAir) { //rotate left the motorcycle body
  346.                     body.AddTorque (new Vector3 (0, 0, (forMobile ? Mathf.Abs(Input.acceleration.x) : 1) * groundedWeightFactor * 100 * Time.deltaTime));
  347.                     body.AddForceAtPosition (body.transform.up * Mathf.Abs(Input.acceleration.x) * wheelieStrength * body.velocity.sqrMagnitude/100,
  348.                         new Vector3 (frontWheel.position.x, frontWheel.position.y - 0.5f, body.transform.position.z));//add wheelie effect
  349.                 } else {
  350.                     body.AddTorque (new Vector3 (0, 0, (forMobile ? Mathf.Abs(Input.acceleration.x) : 1) * inAirRotationSpeed * 100 * Time.deltaTime));    
  351.                 }
  352.    
  353.             } else if (right) { //right horizontal key is pressed or right button is touched on mobile
  354.                 if (!inAir) { //rotate right the motorcycle body
  355.                     body.AddTorque (new Vector3 (0, 0, (forMobile ? Mathf.Abs(Input.acceleration.x) : 1) * -groundedWeightFactor * 100 * Time.deltaTime));             
  356.                 } else {
  357.                     body.AddTorque (new Vector3 (0, 0, (forMobile ? Mathf.Abs(Input.acceleration.x) : 1) * -inAirRotationSpeed * 100 * Time.deltaTime));  
  358.                 }
  359.    
  360.             }
  361.                    
  362.             if(Physics.Raycast(rearWheel.position, -body.transform.up, out hit, rearWheel.GetComponent<Collider>().bounds.extents.y + 0.2f)) // cast ray to know if motorcycle is in air or grounded   
  363.             {
  364.                 if(hit.collider.tag == "Ground") //if motorcycle is standig on object taged as "Ground"
  365.                     onGround = true;
  366.                 else
  367.                     onGround = false;
  368.                
  369.                 inAir = false;                                 
  370.             }
  371.             else
  372.             {
  373.                 onGround = false;
  374.                 inAir = true;
  375.             }
  376.            
  377.         }
  378.         else dirt.Stop ();
  379.     }
  380. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement