Search Unity

How to make an animation for these scripts?

Discussion in 'Animation' started by NeoWatchowsky, Aug 7, 2014.

  1. NeoWatchowsky

    NeoWatchowsky

    Joined:
    May 20, 2014
    Posts:
    24
    How to make an animation for these scripts? I need Walk, Run, Jump, Backward, strafe, prone. Thank you!

    Code (CSharp):
    1. //HorizontalBob.cs by Azuline Studios© All Rights Reserved
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class HorizontalBob : MonoBehaviour {
    6.     [HideInInspector]
    7.     public GameObject playerObj;
    8.     //variables for horizontal sine bob of camera and weapons
    9.     private float timer = 0.0f;
    10.     [HideInInspector]
    11.     public float bobbingSpeed = 0.0f;
    12.     [HideInInspector]
    13.     public float bobbingAmount = 0.0f;
    14.     [HideInInspector]
    15.     public float translateChange = 0.0f;
    16.     [HideInInspector]
    17.     public float waveslice = 0.0f;
    18.     private float dampVelocity = 0.0f;
    19.     private float totalAxes;
    20.     [HideInInspector]
    21.     public float dampOrg = 0.0f;//Smoothed view postion to be passed to CameraKick script
    22.     private float dampTo = 0.0f;
    23.    
    24.     void Update (){
    25.         //set up external script references
    26.         FPSRigidBodyWalker FPSWalker = playerObj.GetComponent<FPSRigidBodyWalker>();
    27.         CameraKick CameraKickComponent = Camera.main.GetComponent<CameraKick>();
    28.    
    29.         waveslice = 0.0f;
    30.         float horizontal = FPSWalker.inputX;//get input from player movement script
    31.         float vertical = FPSWalker.inputY;
    32.    
    33.         if (Mathf.Abs(horizontal) != 0 || Mathf.Abs(vertical) != 0){//perform bob only when moving
    34.             waveslice = Mathf.Sin(timer);
    35.             timer = timer + bobbingSpeed * Time.deltaTime;
    36.             if (timer > Mathf.PI * 2.0f) {
    37.               timer = timer - (Mathf.PI * 2.0f);
    38.             }
    39.         }else{
    40.             timer = 0.0f;//reset timer when stationary to start bob cycle from neutral position
    41.         }
    42.    
    43.         if (waveslice != 0){
    44.            translateChange = waveslice * bobbingAmount;
    45.            totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
    46.            totalAxes = Mathf.Clamp (totalAxes, 0.0f, 1.0f);
    47.            translateChange = totalAxes * translateChange;
    48.             //set position for smoothing function
    49.             dampTo = translateChange / Time.deltaTime * 0.01f;//divide position by deltaTime for framerate independence
    50.         }else{
    51.             //reset variables to prevent view twitching when falling
    52.             dampTo = 0.0f;
    53.             totalAxes = 0.0f;
    54.             translateChange = 0.0f;
    55.         }
    56.         //use SmoothDamp to smooth position and remove any small glitches in bob amount
    57.         dampOrg = Mathf.SmoothDamp(dampOrg, dampTo, ref dampVelocity, 0.1f, Mathf.Infinity, Time.deltaTime);
    58.         //pass bobbing amount to the camera kick script in the camera object after smoothing
    59.         CameraKickComponent.dampOriginX = dampOrg;
    60.     }
    61. }

    Code (CSharp):
    1. //VerticalBob.cs by Azuline Studios© All Rights Reserved
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class VerticalBob : MonoBehaviour {
    6.     [HideInInspector]
    7.     public GameObject playerObj;
    8.     //Variables for vertical aspect of sine bob of camera and weapons
    9.     //This script also makes camera view roll and pitch with bobbing
    10.     private float timer = 0.0f;
    11.     private float timerRoll = 0.0f;
    12.     [HideInInspector]
    13.     public float bobbingSpeed = 0.0f;
    14.     //Vars for smoothing view position
    15.     private float dampOrg = 0.0f;//Smoothed view postion to be passed to CameraKick script
    16.     private float dampTo = 0.0f;
    17.     private Vector3 tempLocalEulerAngles = new Vector3(0,0,0);
    18.     //These two vars controlled from ironsights script
    19.     //to allow different values for sprinting/walking ect.
    20.     [HideInInspector]
    21.     public float bobbingAmount = 0.0f;
    22.     [HideInInspector]
    23.     public float rollingAmount = 0.0f;
    24.     [HideInInspector]
    25.     public float pitchingAmount = 0.0f;
    26.     private float midpoint = 0.0f;//Vertical position of camera during sine bobbing
    27.     [HideInInspector]
    28.     public float translateChange = 0.0f;
    29.     private float translateChangeRoll = 0.0f;
    30.     private float translateChangePitch = 0.0f;
    31.     private float waveslice = 0.0f;
    32.     private float wavesliceRoll = 0.0f;
    33.     private float dampVelocity = 0.0f;
    34.     private Vector3 dampVelocity2;
    35.     private float totalAxes;
    36.     //Player movement sounds
    37.     public AudioClip[] walkSounds;
    38.     //public AudioClip[] runSounds;
    39.     public AudioClip[] climbSounds;
    40.  
    41.     void Update (){
    42.         //Set up external script references
    43.         FPSRigidBodyWalker FPSWalkerComponent = playerObj.GetComponent<FPSRigidBodyWalker>();
    44.         CameraKick CameraKickComponent = Camera.main.GetComponent<CameraKick>();
    45.    
    46.         waveslice = 0.0f;
    47.         float horizontal = FPSWalkerComponent.inputX;//Get input from player movement script
    48.         float vertical = FPSWalkerComponent.inputY;
    49.         midpoint = FPSWalkerComponent.midPos;//Start bob from view position set in player movement script
    50.    
    51.         if (Mathf.Abs(horizontal) != 0 || Mathf.Abs(vertical) != 0){//Perform bob only when moving
    52.    
    53.             waveslice = Mathf.Sin(timer);
    54.             wavesliceRoll = Mathf.Sin(timerRoll);
    55.                  
    56.             timer = timer + bobbingSpeed * Time.deltaTime;
    57.             timerRoll = timerRoll + (bobbingSpeed / 2.0f) * Time.deltaTime;//Make view roll bob half the speed of view pitch bob
    58.            
    59.             if (timer > Mathf.PI * 2.0f){
    60.                 timer = timer - (Mathf.PI * 2.0f);
    61.                 if(!FPSWalkerComponent.climbing){
    62.                     //Make a short delay before playing footstep sounds to allow landing sound to play
    63.                     if (FPSWalkerComponent.grounded && (FPSWalkerComponent.landStartTime + 0.4f) < Time.time){
    64.                         audio.clip = walkSounds[Random.Range(0, walkSounds.Length)];//Select a random footstep sound from walkSounds array
    65.                         audio.volume = 0.5f;
    66.                         audio.Play();
    67.                     }
    68.                 }else{
    69.                     audio.clip = climbSounds[Random.Range(0, climbSounds.Length)];//Select a random climb sound from climbSounds array
    70.                     audio.volume = 1.0f;
    71.                     audio.Play();
    72.                 }
    73.             }
    74.            
    75.             //Perform bobbing of camera roll
    76.             if (timerRoll > Mathf.PI * 2){
    77.                 timerRoll = (timerRoll - (Mathf.PI * 2));
    78.                 if (!FPSWalkerComponent.grounded){
    79.                     timerRoll = 0;//reset timer when airborne to allow soonest resume of footstep sfx
    80.                 }
    81.             }
    82.          
    83.         }else{
    84.             //reset variables to prevent view twitching when falling
    85.             timer = 0.0f;
    86.             timerRoll = 0.0f;
    87.             tempLocalEulerAngles = new Vector3(0,0,0);//reset camera angles to 0 when stationary
    88.         }
    89.    
    90.         if (waveslice != 0){
    91.             translateChange = waveslice * bobbingAmount;
    92.             translateChangePitch = waveslice * pitchingAmount;
    93.             translateChangeRoll = wavesliceRoll * rollingAmount;
    94.             totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
    95.             totalAxes = Mathf.Clamp (totalAxes, 0.0f, 1.0f);
    96.             //needed for smooth return to neutral view pos
    97.             translateChange = totalAxes * translateChange;
    98.             translateChangePitch = totalAxes * translateChangePitch;
    99.             translateChangeRoll = totalAxes * translateChangeRoll;
    100.             //Set position for smoothing function and add jump value
    101.             //divide position by deltaTime for framerate independence
    102.             dampTo = midpoint + (translateChange / Time.deltaTime * 0.01f);
    103.             //camera roll and pitch bob
    104.             tempLocalEulerAngles = new Vector3(translateChangePitch, 0,translateChangeRoll);
    105.         }else{
    106.             //reset variables to prevent view twitching when falling
    107.             dampTo = midpoint + Mathf.Sin(Time.time * 1.25f) * 0.015f;//add small sine bob for camera idle movement
    108.             totalAxes = 0;
    109.             translateChange = 0;
    110.         }
    111.         //use SmoothDamp to smooth position and remove any small glitches in bob amount
    112.         dampOrg = Mathf.SmoothDamp(dampOrg, dampTo, ref dampVelocity, 0.1f, Mathf.Infinity, Time.deltaTime);
    113.         //Pass bobbing amount and angles to the camera kick script in the camera object after smoothing
    114.         CameraKickComponent.dampOriginY = dampOrg;
    115.         CameraKickComponent.bobAngles = Vector3.SmoothDamp(CameraKickComponent.bobAngles, tempLocalEulerAngles, ref dampVelocity2, 0.1f, Mathf.Infinity, Time.deltaTime);
    116.     }
    117. }

    Code (CSharp):
    1. //FPSPlayer.cs by Azuline Studios© All Rights Reserved
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class FPSPlayer : MonoBehaviour {
    6.      //other objects accessed by this script
    7.     [HideInInspector]
    8.     public GameObject weaponCameraObj;
    9.     [HideInInspector]
    10.     public GameObject weaponObj;
    11.     [HideInInspector]
    12.     public GameObject painFadeObj;
    13.     [HideInInspector]
    14.     public GameObject levelLoadFadeObj;
    15.     [HideInInspector]
    16.     public GameObject healthGuiObj;//this object is instantiated for heath display on hud
    17.     [HideInInspector]
    18.     public GameObject healthGuiObjInstance;
    19.     [HideInInspector]
    20.     public GameObject helpGuiObj;//this object is instantiated for help text display
    21.     [HideInInspector]
    22.     public GameObject helpGuiObjInstance;
    23.     [HideInInspector]
    24.     public GameObject PickUpGuiObj;//this object is instantiated for hand pick up crosshair on hud
    25.     [HideInInspector]
    26.     public GameObject PickUpGuiObjGuiObjInstance;
    27.     [HideInInspector]
    28.     public GameObject CrosshairGuiObj;//this object is instantiated for aiming reticle on hud
    29.     [HideInInspector]
    30.     public GameObject CrosshairGuiObjInstance;
    31.     [HideInInspector]
    32.     public Projector shadow;//to access the player shadow projector
    33.     private AudioSource[]aSources;//access the audio sources attatched to this object as an array for playing player sound effects
    34.    
    35.     //player hit points
    36.     public float hitPoints = 100.0f;
    37.     public float maximumHitPoints = 200.0f;
    38.    
    39.     //Damage feedback
    40.     private float gotHitTimer = -1.0f;
    41.     public Color PainColor = new Color(0.75f, 0f, 0f, 0.5f);//color of pain screen flash can be selected in editor
    42.    
    43.     //crosshair
    44.     public bool crosshairEnabled = true;//enable or disable the aiming reticle
    45.     private bool crosshairVisibleState = true;
    46.     private bool crosshairTextureState = false;
    47.     public Texture2D Reticle;//the texture used for the aiming crosshair
    48.     public Texture2D Hand;//the texture used for the pick up crosshair
    49.     private Color handColor = Color.white;
    50.     private Color reticleColor = Color.white;
    51.     [HideInInspector]
    52.     public LayerMask rayMask = 0;//only layers to include for crosshair raycast in hit detection (for efficiency)
    53.    
    54.     //button and behavior states
    55.     private bool pickUpBtnState = true;
    56.     [HideInInspector]
    57.     public bool restarting = false;//to notify other scripts that level is restarting
    58.    
    59.     //zooming
    60.     private bool zoomBtnState = true;
    61.     private float zoomStopTime = 0.0f;//track time that zoom stopped to delay making aim reticle visible again
    62.     [HideInInspector]
    63.     public bool zoomed = false;
    64.     private float zoomStart = -2.0f;
    65.     private bool zoomStartState = false;
    66.     private float zoomEnd = 0.0f;
    67.     private bool zoomEndState = false;
    68.    
    69.     //sound effects
    70.     public AudioClip painLittle;
    71.     public AudioClip painBig;
    72.     public AudioClip die;
    73.    
    74.     //player controls set in the inspector
    75.     public KeyCode moveForward;
    76.     public KeyCode moveBack;
    77.     public KeyCode strafeLeft;
    78.     public KeyCode strafeRight;
    79.     public KeyCode jump;
    80.     public KeyCode crouch;
    81.     public KeyCode sprint;
    82.     public KeyCode fire;
    83.     public KeyCode zoom;
    84.     public KeyCode reload;
    85.     public KeyCode fireMode;
    86.     public KeyCode holsterWeapon;
    87.     public KeyCode selectNextWeapon;
    88.     public KeyCode selectPreviousWeapon;
    89.     public KeyCode selectWeapon1;
    90.     public KeyCode selectWeapon2;
    91.     public KeyCode selectWeapon3;
    92.     public KeyCode selectWeapon4;
    93.     public KeyCode selectWeapon5;
    94.     public KeyCode selectWeapon6;
    95.     public KeyCode selectWeapon7;
    96.     public KeyCode selectWeapon8;
    97.     public KeyCode selectWeapon9;
    98.     public KeyCode selectWeapon10;
    99.     public KeyCode use;
    100.     public KeyCode moveObject;
    101.     public KeyCode throwObject;
    102.     public KeyCode showHelp;
    103.     public KeyCode restartScene;
    104.     public KeyCode exitGame;
    105.    
    106.     void Start (){  
    107.         //Set time settings to optimal values
    108.         Time.fixedDeltaTime = 0.01f;
    109.         Time.maximumDeltaTime = 0.3333333f;
    110.         //set up physics to allow bullet casings to bounce on thin surfaces
    111.         Physics.minPenetrationForPenalty = 0.001f;
    112.        
    113.         //Physics Layer Management Setup
    114.         //these are the layer numbers and their corresponding uses/names accessed by the FPS prefab
    115.         //    Weapon = 8;
    116.         //    Ragdoll = 9;
    117.         //    WorldCollision = 10;
    118.         //    Player = 11;
    119.         //    Objects = 12;
    120.         //    NPCs = 13;
    121.         //    GUICameraLayer = 14;
    122.         //    WorldGeometry = 15;
    123.         //    BulletMarks = 16;
    124.        
    125.         //player object collisions
    126.         Physics.IgnoreLayerCollision(11, 12);//no collisions between player object and misc objects like bullet casings
    127.         Physics.IgnoreLayerCollision (12, 12);//no collisions between bullet shells
    128.         Physics.IgnoreLayerCollision(11, 9);//no collisions between player and ragdolls
    129.         //weapon object collisions
    130.         Physics.IgnoreLayerCollision(8, 13);//no collisions between weapon and NPCs
    131.         Physics.IgnoreLayerCollision(8, 12);//no collisions between weapon and Objects
    132.         Physics.IgnoreLayerCollision(8, 11);//no collisions between weapon and Player
    133.         Physics.IgnoreLayerCollision(8, 10);//no collisions between weapon and world collision
    134.         Physics.IgnoreLayerCollision(8, 9);//no collisions between weapon and ragdolls
    135.        
    136.  
    137.         //Call FadeAndLoadLevel fucntion with fadeIn argument set to true to tell the function to fade in (not fade out and (re)load level)
    138.         GameObject llf = Instantiate(levelLoadFadeObj) as GameObject;
    139.         llf.GetComponent<LevelLoadFade>().FadeAndLoadLevel(Color.black, 2.0f, true);
    140.        
    141.         //create instance of GUIText to display health amount on hud
    142.         healthGuiObjInstance = Instantiate(healthGuiObj,Vector3.zero,transform.rotation) as GameObject;
    143.         //create instance of GUIText to display help text
    144.         helpGuiObjInstance = Instantiate(helpGuiObj,Vector3.zero,transform.rotation) as GameObject;
    145.         //create instance of GUITexture to display crosshair on hud
    146.         CrosshairGuiObjInstance = Instantiate(CrosshairGuiObj,new Vector3(0.5f,0.5f,0.0f),transform.rotation) as GameObject;
    147.         //set alpha of hand pickup crosshair
    148.         handColor.a = 0.5f;
    149.         //set alpha of aiming reticule and make it 100% transparent if crosshair is disabled
    150.         if(crosshairEnabled){
    151.             reticleColor.a = 0.25f;
    152.         }else{
    153.             //make alpha of aiming reticle zero/transparent
    154.             reticleColor.a = 0.0f;
    155.             //set alpha of aiming reticle at start to prevent it from showing, but allow item pickup hand reticle
    156.             CrosshairGuiObjInstance.GetComponent<GUITexture>().color = reticleColor;
    157.         }
    158.        
    159.         //set reference for main color element of heath GUIText
    160.         HealthText HealthText = healthGuiObjInstance.GetComponent<HealthText>();
    161.         //set reference for shadow background color element of heath GUIText
    162.         //this object is a child of the main health GUIText object, so access it as an array
    163.         HealthText[] HealthText2 = healthGuiObjInstance.GetComponentsInChildren<HealthText>();
    164.        
    165.         //initialize health amounts on GUIText objects
    166.         HealthText.healthGui = hitPoints;
    167.         HealthText2[1].healthGui = hitPoints;
    168.        
    169.     }
    170.    
    171.     void FixedUpdate (){
    172.        
    173.         //set up external script references
    174.         Ironsights IronsightsComponent = GetComponent<Ironsights>();
    175.         FPSRigidBodyWalker FPSWalkerComponent = GetComponent<FPSRigidBodyWalker>();
    176.         PlayerWeapons PlayerWeaponsComponent = weaponObj.GetComponent<PlayerWeapons>();
    177.         WeaponBehavior WeaponBehaviorComponent = PlayerWeaponsComponent.weaponOrder[PlayerWeaponsComponent.childNum].GetComponent<WeaponBehavior>();
    178.        
    179.         //Exit application if escape is pressed
    180.         if (Input.GetKey (exitGame)){
    181.             Application.Quit();
    182.         }
    183.        
    184.         //Restart level if v is pressed
    185.         if (Input.GetKey (restartScene)){
    186.             GameObject llf = Instantiate(levelLoadFadeObj) as GameObject;//Create instance of levelLoadFadeObj
    187.             //call FadeAndLoadLevel function with fadein argument set to false
    188.             //in levelLoadFadeObj to restart level and fade screen out from black on level load
    189.             llf.GetComponent<LevelLoadFade>().FadeAndLoadLevel(Color.black, 2.0f, false);
    190.             //Set parent of shadow projector to main camera's parent because it stops moving after disabling all components on player death or level restart.
    191.             //FPSPlayer will continue moving for a short while due to momentum and makes shadow move away from player.
    192.             shadow.transform.parent = Camera.main.transform.parent;
    193.             //set restarting var to true to be accessed by FPSRigidBodyWalker script to stop rigidbody movement
    194.             restarting = true;
    195.             // Disable all scripts to deactivate player control upon player death
    196.             Component[] coms = transform.parent.transform.gameObject.GetComponentsInChildren<MonoBehaviour>();
    197.             foreach(var b in coms) {
    198.                 MonoBehaviour p = b as MonoBehaviour;
    199.                 if (p){
    200.                     p.enabled = false;
    201.                 }
    202.             }
    203.  
    204.         }
    205.        
    206.         //toggle or hold zooming state by determining if zoom button is pressed or held
    207.         if(Input.GetKey (zoom)){
    208.             if(!zoomStartState){
    209.                 zoomStart = Time.time;//track time that zoom button was pressed
    210.                 zoomStartState = true;//perform these actions only once
    211.                 zoomEndState = false;
    212.                 if(zoomEnd - zoomStart < 0.4f){//if button is tapped, toggle zoom state
    213.                     if(!zoomed){
    214.                         zoomed = true;
    215.                     }else{
    216.                         zoomed = false;  
    217.                     }
    218.                 }
    219.             }
    220.         }else{
    221.             if(!zoomEndState){
    222.                 zoomEnd = Time.time;//track time that zoom button was released
    223.                 zoomEndState = true;
    224.                 zoomStartState = false;
    225.                 if(zoomEnd - zoomStart > 0.4f){//if releasing zoom button after holding it down, stop zooming
    226.                     zoomed = false;  
    227.                 }
    228.             }
    229.         }
    230.        
    231.         //track when player stopped zooming to allow for delay of reticle becoming visible again
    232.         if (zoomed){
    233.             zoomBtnState = false;//only perform this action once per button press
    234.         }else{
    235.             if(!zoomBtnState){
    236.                 zoomStopTime = Time.time;
    237.                 zoomBtnState = true;
    238.             }
    239.         }
    240.        
    241.         //enable and disable crosshair based on various states like reloading and zooming
    242.         if(IronsightsComponent.reloading || zoomed){
    243.             //don't disable reticle if player is using a melee weapon or if player is unarmed
    244.             if(WeaponBehaviorComponent.meleeSwingDelay == 0 && !WeaponBehaviorComponent.unarmed){
    245.                 if(crosshairVisibleState){
    246.                     //disable the GUITexture element of the instantiated crosshair object
    247.                     //and set state so this action will only happen once.
    248.                     CrosshairGuiObjInstance.GetComponent<GUITexture>().enabled = false;
    249.                     crosshairVisibleState = false;
    250.                 }
    251.             }
    252.         }else{
    253.             //Because of the method that is used for non magazine reloads, an additional check is needed here
    254.             //to make the reticle appear after the last bullet reload time has elapsed. Proceed with no check
    255.             //for magazine reloads.
    256.             if((WeaponBehaviorComponent.bulletsPerClip != WeaponBehaviorComponent.bulletsToReload
    257.                 && WeaponBehaviorComponent.reloadLastStartTime + WeaponBehaviorComponent.reloadLastTime < Time.time)
    258.             || WeaponBehaviorComponent.bulletsPerClip == WeaponBehaviorComponent.bulletsToReload){
    259.                 //allow a delay before enabling crosshair again to let the gun return to neutral position
    260.                 //by checking the zoomStopTime value
    261.                 if(!crosshairVisibleState && (zoomStopTime + 0.2f < Time.time)){
    262.                     CrosshairGuiObjInstance.GetComponent<GUITexture>().enabled = true;
    263.                     crosshairVisibleState = true;
    264.                 }
    265.             }
    266.         }
    267.                
    268.         //Pick up items      
    269.         RaycastHit hit;
    270.         if(!IronsightsComponent.reloading//no item pickup when reloading
    271.         && !WeaponBehaviorComponent.lastReload//no item pickup when when reloading last round in non magazine reload
    272.         && !PlayerWeaponsComponent.switching//no item pickup when switching weapons
    273.         && !FPSWalkerComponent.canRun//no item pickup when sprinting
    274.             //there is a small delay between the end of canRun and the start of sprintSwitching (in PlayerWeapons script),
    275.             //so track actual time that sprinting stopped to avoid the small time gap where the pickup hand shows briefly
    276.         && ((FPSWalkerComponent.sprintStopTime + 0.4f) < Time.time)){
    277.             //raycast a line from the main camera's origin using a point extended forward from camera position/origin as a target to get the direction of the raycast
    278.             if (Physics.Raycast(Camera.main.transform.position, ((Camera.main.transform.position + Camera.main.transform.forward * 5.0f) - Camera.main.transform.position).normalized, out hit, 2.0f, rayMask)) {
    279.                 if(hit.collider.gameObject.tag == "PickUp"){//if the object hit by the raycast is a pickup item and has the "Pickup" tag
    280.                    
    281.                     if (pickUpBtnState && Input.GetKey(use)){
    282.                         //run the PickUpItem function in the pickup object's script
    283.                         hit.collider.SendMessageUpwards("PickUpItem", SendMessageOptions.DontRequireReceiver);
    284.                         pickUpBtnState = false;
    285.                     }
    286.                    
    287.                     if(!crosshairTextureState){
    288.                         UpdateReticle(false);//show hand pickup crosshair if raycast hits a pickup item
    289.                     }
    290.                 }else{
    291.                     if(crosshairTextureState){
    292.                         UpdateReticle(true);//show aiming reticle crosshair if item is not a pickup item
    293.                     }
    294.                 }
    295.             }else{
    296.                 if(crosshairTextureState){
    297.                     UpdateReticle(true);//show aiming reticle crosshair if raycast hits nothing
    298.                 }
    299.             }
    300.         }else{
    301.             if(crosshairTextureState){
    302.                 UpdateReticle(true);//show aiming reticle crosshair if reloading, switching weapons, or sprinting
    303.             }
    304.         }
    305.        
    306.         //only register one press of E key to make player have to press button again to pickup items instead of holding E
    307.         if (Input.GetKey(use)){
    308.             pickUpBtnState = false;
    309.         }else{
    310.             pickUpBtnState = true;  
    311.         }
    312.    
    313.     }
    314.    
    315.     //set reticle type based on the boolean value passed to this function
    316.     void UpdateReticle( bool reticleType ){
    317.         if(!reticleType){
    318.             CrosshairGuiObjInstance.GetComponent<GUITexture>().texture = Hand;
    319.             CrosshairGuiObjInstance.GetComponent<GUITexture>().color = handColor;
    320.             crosshairTextureState = true;
    321.         }else{
    322.             CrosshairGuiObjInstance.GetComponent<GUITexture>().texture = Reticle;
    323.             CrosshairGuiObjInstance.GetComponent<GUITexture>().color = reticleColor;
    324.             crosshairTextureState = false;  
    325.         }
    326.     }
    327.    
    328.     //add hitpoints to player health
    329.     public void HealPlayer( float healAmt  ){
    330.            
    331.         if (hitPoints <= 0.0f){//Don't add health if player is dead
    332.             return;
    333.         }
    334.        
    335.         //Update health GUIText
    336.         HealthText HealthText = healthGuiObjInstance.GetComponent<HealthText>();
    337.         HealthText[] HealthText2 = healthGuiObjInstance.GetComponentsInChildren<HealthText>();
    338.        
    339.         //Apply healing
    340.         if(hitPoints + healAmt > maximumHitPoints){
    341.             hitPoints = maximumHitPoints;
    342.         }else{
    343.             hitPoints += healAmt;
    344.         }
    345.            
    346.         //set health hud value to hitpoints remaining
    347.         HealthText.healthGui = Mathf.Round(hitPoints);
    348.         HealthText2[1].healthGui = Mathf.Round(hitPoints);
    349.            
    350.         //change color of hud health element based on hitpoints remaining
    351.         if (hitPoints <= 25.0f){
    352.             HealthText.guiText.material.color = Color.red;
    353.         }else if (hitPoints <= 40.0f){
    354.                 HealthText.guiText.material.color = Color.yellow;  
    355.         }else{
    356.             HealthText.guiText.material.color = HealthText.textColor;  
    357.         }
    358.  
    359.     }
    360.    
    361.     //remove hitpoints from player health
    362.     public void ApplyDamage ( float damage  ){
    363.            
    364.         if (hitPoints <= 0.0f){//Don't apply damage if player is dead
    365.             return;
    366.         }
    367.        
    368.         //Update health GUIText
    369.         HealthText HealthText = healthGuiObjInstance.GetComponent<HealthText>();
    370.         HealthText[] HealthText2 = healthGuiObjInstance.GetComponentsInChildren<HealthText>();
    371.  
    372.         Quaternion painKickRotation;//Set up rotation for pain view kicks
    373.         int painKickUpAmt = 0;
    374.         int painKickSideAmt = 0;
    375.    
    376.         hitPoints -= damage;//Apply damage
    377.            
    378.         //set health hud value to hitpoints remaining
    379.         HealthText.healthGui = Mathf.Round(hitPoints);
    380.         HealthText2[1].healthGui = Mathf.Round(hitPoints);
    381.            
    382.         //change color of hud health element based on hitpoints remaining
    383.         if (hitPoints <= 25.0f){
    384.             HealthText.guiText.material.color = Color.red;
    385.         }else if (hitPoints <= 40.0f){
    386.                 HealthText.guiText.material.color = Color.yellow;  
    387.         }else{
    388.             HealthText.guiText.material.color = HealthText.textColor;  
    389.         }
    390.        
    391.         GameObject pf = Instantiate(painFadeObj) as GameObject;//Create instance of painFadeObj
    392.         pf.GetComponent<PainFade>().FadeIn(PainColor, 0.75f);//Call FadeIn function in painFadeObj to fade screen red when damage taken
    393.            
    394.         //Play pain sound when getting hit
    395.         if (Time.time > gotHitTimer && painBig && painLittle) {
    396.             // Play a big pain sound
    397.             if (hitPoints < 40 || damage > 30) {
    398.                 AudioSource.PlayClipAtPoint(painBig, Camera.main.transform.position);
    399.                 gotHitTimer = Time.time + Random.Range(.5f, .75f);
    400.             } else {
    401.                 //Play a small pain sound
    402.                 AudioSource.PlayClipAtPoint(painLittle, Camera.main.transform.position);
    403.                 gotHitTimer = Time.time + Random.Range(.5f, .75f);
    404.             }
    405.         }
    406.        
    407.         painKickUpAmt = Random.Range(100, -100);//Choose a random view kick up amount
    408.         if(painKickUpAmt < 50 && painKickUpAmt > 0){painKickUpAmt = 50;}//Maintain some randomness of the values, but don't make it too small
    409.         if(painKickUpAmt < 0 && painKickUpAmt > -50){painKickUpAmt = -50;}
    410.        
    411.         painKickSideAmt = Random.Range(100, -100);//Choose a random view kick side amount
    412.         if(painKickSideAmt < 50 && painKickSideAmt > 0){painKickSideAmt = 50;}
    413.         if(painKickSideAmt < 0 && painKickSideAmt > -50){painKickSideAmt = -50;}
    414.        
    415.         //create a rotation quaternion with random pain kick values
    416.         painKickRotation = Quaternion.Euler(Camera.main.transform.localRotation.eulerAngles - new Vector3(painKickUpAmt, painKickSideAmt, 0));
    417.        
    418.         //smooth current camera angles to pain kick angles using Slerp
    419.         Camera.main.transform.localRotation = Quaternion.Slerp(Camera.main.transform.localRotation, painKickRotation, 0.016f );
    420.    
    421.         //Call Die function if player is dead
    422.         if (hitPoints <= 0.0f){
    423.             Die();
    424.         }
    425.     }
    426.    
    427.     void Die (){
    428.         AudioSource.PlayClipAtPoint(die, Camera.main.transform.position);
    429.            
    430.         GameObject llf = Instantiate(levelLoadFadeObj) as GameObject;//Create instance of levelLoadFadeObj
    431.         //call FadeAndLoadLevel function with fadein argument set to false
    432.         //in levelLoadFadeObj to restart level and fade screen out from black on level load
    433.         llf.GetComponent<LevelLoadFade>().FadeAndLoadLevel(Color.black, 2.0f, false);
    434.        
    435.         //Set parent of shadow projector to main camera's parent because it stops moving after disabling all components on player death or level restart.
    436.         //FPSPlayer will continue moving for a short while due to momentum and makes shadow move away from player.
    437.         shadow.transform.parent = Camera.main.transform.parent;
    438.        
    439.         // Disable all scripts in prefab object to deactivate player control upon player death
    440.         Component[] coms = transform.parent.transform.gameObject.GetComponentsInChildren<MonoBehaviour>();
    441.         foreach(var b in coms) {
    442.             MonoBehaviour p = b as MonoBehaviour;
    443.             if (p){
    444.                 p.enabled = false;
    445.             }
    446.         }
    447.        
    448.  
    449.        
    450.     }
    451.  
    452. }

    Code (CSharp):
    1. //FPSRigidBodyWalker.cs by Azuline Studios© All Rights Reserved
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class FPSRigidBodyWalker : MonoBehaviour {
    6.    
    7.     //objects accessed by this script
    8.     [HideInInspector]
    9.     public GameObject weaponObj;
    10.     [HideInInspector]
    11.     public GameObject CameraObj;
    12.    
    13.     //track player input
    14.     [HideInInspector]
    15.     public float inputXSmoothed = 0.0f;//binary inputs smoothed using lerps
    16.     [HideInInspector]
    17.     public float inputYSmoothed = 0.0f;
    18.     [HideInInspector]
    19.     public int inputX = 0;//1 = button pressed 0 = button released
    20.     [HideInInspector]
    21.     public int inputY = 0;
    22.        
    23.     //player movement speed amounts
    24.     public float runSpeed = 9.0f;
    25.     public float walkSpeed = 4.0f;
    26.     public float jumpSpeed = 3.0f;
    27.     private float limitStrafeSpeed = 0.0f;
    28.     public float backwardSpeedPercentage = 0.6f;//percentage to decrease movement speed while moving backwards
    29.     public float crouchSpeedPercentage = 0.55f;//percentage to decrease movement speed while crouching
    30.     private float crouchSpeedAmt = 1.0f;
    31.     public float strafeSpeedPercentage = 0.8f;//percentage to decrease movement speed while strafing directly left or right
    32.     private float speedAmtY = 1.0f;//current player speed per axis which is applied to rigidbody velocity vector
    33.     private float speedAmtX = 1.0f;
    34.     [HideInInspector]
    35.     public bool zoomSpeed = false;//to control speed of movement while zoomed, handled by Ironsights script and true when zooming
    36.     public float zoomSpeedPercentage = 0.6f;//percentage to decrease movement speed while zooming
    37.     private float zoomSpeedAmt = 1.0f;
    38.     private float speed = 6.0f;//combined axis speed of player movement
    39.        
    40.     //rigidbody physics settings
    41.     public int gravity = 15;//additional gravity that is manually applied to the player rigidbody
    42.     public int slopeLimit = 40;//the maximum allowed ground surface/normal angle that the player is allowed to climb
    43.     private int maxVelocityChange = 5;//maximum rate that player velocity can change
    44.     private Transform myTransform;
    45.     private Vector3 moveDirection = Vector3.zero;//movement velocity vector, modified by other speed factors like walk, zoom, and crouch states
    46.     [HideInInspector]
    47.     public bool grounded = false;//true when capsule cast hits ground surface
    48.     private bool rayTooSteep = false;//true when ray from capsule origin hits surface/normal angle greater than slopeLimit, compared with capsuleTooSteep
    49.     private bool capsuleTooSteep = false;//true when capsule cast hits surface/normal angle greater than slopeLimit, compared with rayTooSteep
    50.     [HideInInspector]
    51.     public Vector3 velocity = Vector3.zero;//total movement velocity vector
    52.     private CapsuleCollider capsule;
    53.     [HideInInspector]
    54.     public Transform initialParent;//store original parent for use when unparenting player rigidbody from moving platforms
    55.     private bool parentState = false;//only set parent once to prevent rapid parenting and de-parenting that breaks functionality
    56.        
    57.     //falling
    58.     [HideInInspector]
    59.     public float airTime = 0.0f;//total time that player is airborn
    60.     private bool airTimeState = false;
    61.     public float fallingDamageThreshold = 5.5f;//Units that player can fall before taking damage
    62.     private float fallStartLevel;//the y coordinate that the player lost grounding and started to fall
    63.     [HideInInspector]
    64.     public float fallingDistance;//total distance that player has fallen
    65.     private bool falling = false;//true when player is losing altitude
    66.        
    67.     //climbing (ladders or other climbable surfaces)
    68.     [HideInInspector]
    69.     public bool climbing = false;//true when playing is in contact with ladder trigger
    70.     public float climbSpeed = 4.0f;//speed that player moves upward when climbing
    71.     [HideInInspector]
    72.     public float climbSpeedAmt = 4.0f;//actual rate that player is climbing
    73.    
    74.     //jumping
    75.     public float antiBunnyHopFactor = 0.35f;//to limit the time between player jumps
    76.     [HideInInspector]
    77.     public bool jumping = false;//true when player is jumping
    78.     private float jumpTimer = 0.0f;//track the time player began jump
    79.     private bool jumpfxstate = true;
    80.     private bool jumpBtn = true;//to control jump button behavior
    81.     [HideInInspector]
    82.     public float landStartTime = 0.0f;//time that player landed from jump
    83.        
    84.     //sprinting
    85.     [HideInInspector]
    86.     public bool canRun = true;//true when player is allowed to sprint
    87.     [HideInInspector]
    88.     public bool sprintActive = false;//true when sprint button is ready
    89.     private bool sprintBtnState = false;
    90.     [HideInInspector]
    91.     public bool cancelSprint = false;//true when sprint is canceled by other player input
    92.     [HideInInspector]
    93.     public float sprintStopTime = 0.0f;//track when sprinting stopped for control of item pickup time in FPSPlayer script
    94.     private bool sprintStopState = true;
    95.    
    96.     //crouching  
    97.     [HideInInspector]
    98.     public float midPos = 0.9f;//camera vertical position
    99.     [HideInInspector]
    100.     public bool crouched = false;//true when player is crouching
    101.     private bool crouchState = false;
    102.     private bool crouchHit = false;//true when object above player prevents standing up from crouch
    103.        
    104.     //sound effeects
    105.     public AudioClip landfx;//audiosource attatched to this game object with landing sound effect
    106.     public AudioClip jumpfx;//audiosource attatched to this game object with jumping sound effect
    107.     public LayerMask clipMask;//mask for reducing the amount of objects that ray and capsule casts have to check
    108.    
    109.     void Start (){
    110.         myTransform = transform;//define transform for efficiency
    111.         initialParent = myTransform.parent;//track parent of rigidbody on level load
    112.         //clamp movement modifier percentages
    113.         backwardSpeedPercentage = Mathf.Clamp01(backwardSpeedPercentage);
    114.         crouchSpeedPercentage = Mathf.Clamp01(crouchSpeedPercentage);
    115.         strafeSpeedPercentage = Mathf.Clamp01(strafeSpeedPercentage);
    116.         zoomSpeedPercentage = Mathf.Clamp01(zoomSpeedPercentage);
    117.     }
    118.    
    119.     void Awake (){
    120.         //Initialize rigidbody
    121.         rigidbody.freezeRotation = true;
    122.         rigidbody.useGravity = true;
    123.         capsule = GetComponent<CapsuleCollider>();
    124.     }
    125.     void FixedUpdate (){
    126.         RaycastHit hit;
    127.         //set up external script references
    128.         SmoothMouseLook SmoothMouseLookComponent = CameraObj.GetComponent<SmoothMouseLook>();
    129.         FPSPlayer FPSPlayerComponent = GetComponent<FPSPlayer>();
    130.            
    131.         //set the vertical bounds of the capsule used to detect player collisions
    132.         Vector3 p1 = myTransform.position;//bottom of player capsule
    133.         Vector3 p2 = p1 + Vector3.up * capsule.height/2;//top of player capsule
    134.        
    135.         //track rigidbody velocity
    136.         velocity = rigidbody.velocity;
    137.            
    138.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    139.         //Player Input
    140.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    141.    
    142.         //track movement buttons and set input vars
    143.         //Input.Axis is not used here to have have more control over button states and to avoid glitches
    144.         //such as pressing opposite movement buttons simultaneously causing player to move very slow in one direction
    145.         if (Input.GetKey (FPSPlayerComponent.moveForward)){inputY = 1;}
    146.         if (Input.GetKey (FPSPlayerComponent.moveBack)){inputY = -1;}
    147.         if (!Input.GetKey (FPSPlayerComponent.moveBack) && !Input.GetKey (FPSPlayerComponent.moveForward)){inputY = 0;}
    148.         if (Input.GetKey (FPSPlayerComponent.moveBack) && Input.GetKey (FPSPlayerComponent.moveForward)){inputY = 0;}
    149.         if (Input.GetKey (FPSPlayerComponent.strafeLeft)){inputX = -1;}
    150.         if (Input.GetKey (FPSPlayerComponent.strafeRight)){inputX = 1;}
    151.         if (!Input.GetKey (FPSPlayerComponent.strafeLeft) && !Input.GetKey (FPSPlayerComponent.strafeRight)){inputX = 0;}
    152.         if (Input.GetKey (FPSPlayerComponent.strafeLeft) && Input.GetKey (FPSPlayerComponent.strafeRight)){inputX = 0;}
    153.        
    154.         //Smooth our movement states using Mathf.Lerp
    155.         inputXSmoothed = Mathf.Lerp(inputXSmoothed,inputX,Time.deltaTime * 6.0f);
    156.         inputYSmoothed = Mathf.Lerp(inputYSmoothed,inputY,Time.deltaTime * 6.0f);
    157.            
    158.         //This is the start of the large block that performs all movement actions while grounded  
    159.         if (grounded) {
    160.                
    161.             /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    162.             //Landing
    163.             /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    164.            
    165.             //reset airTimeState var so that airTime will only be set once when player looses grounding
    166.             airTimeState = true;
    167.            
    168.             if (falling){//reset falling state and perform actions if player has landed from a fall
    169.                
    170.                 fallingDistance = 0;
    171.                 landStartTime = Time.time;//track the time when player landed
    172.                    falling = false;
    173.                
    174.                 if((fallStartLevel - myTransform.position.y)>2.0f){
    175.                     //play landing sound effect when falling and not landing from jump
    176.                     if(!jumping){
    177.                         //play landing sound
    178.                         AudioSource.PlayClipAtPoint(landfx, Camera.main.transform.position);
    179.                         //make camera jump when landing for better feeling of player weight  
    180.                         if (Camera.main.animation.IsPlaying("CameraLand")){
    181.                             //rewind animation if already playing to allow overlapping playback
    182.                             Camera.main.animation.Rewind("CameraLand");
    183.                         }
    184.                         Camera.main.animation.CrossFade("CameraLand", 0.35f,PlayMode.StopAll);
    185.                     }
    186.                 }
    187.                
    188.                 //track the distance of the fall and apply damage if over falling threshold
    189.                 if (myTransform.position.y < fallStartLevel - fallingDamageThreshold){
    190.                     CalculateFallingDamage(fallStartLevel - myTransform.position.y);
    191.                 }
    192.             }
    193.                
    194.             /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    195.             //Crouch Mode Handling
    196.             /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    197.                
    198.             //set crouched variable that other scripts will access to check for crouching
    199.             if(Input.GetKey (FPSPlayerComponent.crouch)){
    200.                 if(!crouchState){
    201.                     if(!crouched){
    202.                         crouched = true;
    203.                         sprintActive = false;//cancel sprint if crouch button is pressed
    204.                     }else{
    205.                         if(!Physics.CapsuleCast (p1, p2, capsule.radius * 0.9f, transform.up, out hit, 0.4f, clipMask.value)){
    206.                             crouched = false;
    207.                         }
    208.                     }
    209.                     crouchState = true;
    210.                 }
    211.             }else{
    212.                 crouchState = false;
    213.                 if(sprintActive || climbing){
    214.                     crouched = false;//cancel crouch if sprint button is pressed
    215.                 }
    216.             }
    217.             //cancel crouch if jump button is pressed
    218.             if(Input.GetKey (FPSPlayerComponent.jump) && crouched && !Physics.CapsuleCast (p1, p2, capsule.radius * 0.9f, transform.up, out hit, 0.4f, clipMask.value)){
    219.                 crouched = false;
    220.                 landStartTime = Time.time;//set land time to time jump is pressed to prevent uncrouching and then also jumping
    221.             }
    222.                
    223.             /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    224.             //Sprinting
    225.             /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    226.            
    227.             //set sprintActive based on sprint button input
    228.             if(Input.GetKey (FPSPlayerComponent.sprint)){
    229.                 if(sprintBtnState){
    230.                     if(!sprintActive && !crouchHit){//only allow sprint to start or cancel crouch if player is not under obstacle
    231.                         sprintActive = true;
    232.                     }else{
    233.                         sprintActive = false;//pressing sprint button again while sprinting stops sprint
    234.                     }
    235.                     sprintBtnState = false;
    236.                 }
    237.             }else{
    238.                 sprintBtnState = true;
    239.                 if(!canRun){
    240.                     sprintActive = false;
    241.                 }
    242.             }
    243.            
    244.             //cancel a sprint in certain situations
    245.             if((sprintActive && Input.GetKey (FPSPlayerComponent.fire))
    246.             ||(sprintActive && Input.GetKey (FPSPlayerComponent.reload))
    247.             ||(sprintActive && Input.GetKey (FPSPlayerComponent.zoom))//cancel sprint if zoom button is pressed
    248.             ||(FPSPlayerComponent.zoomed && Input.GetKey (FPSPlayerComponent.fire))
    249.             ||climbing){
    250.                 cancelSprint = true;
    251.             }
    252.            
    253.             //reset cancelSprint var so it has to pressed again to sprint
    254.             if(!sprintActive && cancelSprint){
    255.                 if(!Input.GetKey (FPSPlayerComponent.zoom)){
    256.                     cancelSprint = false;
    257.                 }
    258.             }
    259.        
    260.             //determine if player can run
    261.             if(inputY != 0.0f
    262.             && sprintActive
    263.             && !crouched
    264.             && (!cancelSprint || (cancelSprint && FPSPlayerComponent.zoomed))
    265.             && grounded){
    266.                  canRun = true;
    267.                 FPSPlayerComponent.zoomed = false;//cancel zooming when sprinting
    268.                 sprintStopState = true;
    269.             }else{
    270.                 if(sprintStopState){
    271.                     sprintStopTime = Time.time;
    272.                     sprintStopState = false;
    273.                 }
    274.                  canRun = false;
    275.             }  
    276.                
    277.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    278.         //Player Movement Speeds
    279.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    280.    
    281.             //check that player can run and set speed
    282.             if(canRun){
    283.                 if(speed < runSpeed){
    284.                     speed += 12 * Time.deltaTime;//gradually accelerate to run speed
    285.                 }
    286.             }else{
    287.                 if(speed > walkSpeed){
    288.                     speed -= 16 * Time.deltaTime;//gradually decelerate to walk speed
    289.                 }
    290.             }
    291.                    
    292.             //check if player is zooming and set speed
    293.             if(zoomSpeed){
    294.                 if(zoomSpeedAmt > zoomSpeedPercentage){
    295.                     zoomSpeedAmt -= Time.deltaTime;//gradually decrease variable to zooming limit value
    296.                 }
    297.             }else{
    298.                 if(zoomSpeedAmt < 1.0f){
    299.                     zoomSpeedAmt += Time.deltaTime;//gradually increase variable to neutral
    300.                 }
    301.             }
    302.            
    303.             //check that player can crouch and set speed
    304.             //also check midpos because player can still be under obstacle when crouch button is released
    305.             if(crouched || midPos < 0.9f){
    306.                 if(crouchSpeedAmt > crouchSpeedPercentage){
    307.                     crouchSpeedAmt -= Time.deltaTime;//gradually decrease variable to crouch limit value
    308.                 }
    309.             }else{
    310.                 if(crouchSpeedAmt < 1.0f){
    311.                     crouchSpeedAmt += Time.deltaTime;//gradually increase variable to neutral
    312.                 }
    313.             }
    314.            
    315.             //limit move speed if backpedaling
    316.             if (inputY >= 0){
    317.                 if(speedAmtY < 1.0f){
    318.                     speedAmtY += Time.deltaTime;//gradually increase variable to neutral
    319.                 }
    320.             }else{
    321.                 if(speedAmtY > backwardSpeedPercentage){
    322.                     speedAmtY -= Time.deltaTime;//gradually decrease variable to backpedal limit value
    323.                 }
    324.             }
    325.            
    326.             //allow limiting of move speed if strafing directly sideways and not diagonally
    327.             if (inputX == 0 || inputY != 0){
    328.                 if(speedAmtX < 1.0f){
    329.                     speedAmtX += Time.deltaTime;//gradually increase variable to neutral
    330.                 }
    331.             }else{
    332.                 if(speedAmtX > strafeSpeedPercentage){
    333.                     speedAmtX -= Time.deltaTime;//gradually decrease variable to strafe limit value
    334.                 }
    335.             }
    336.                
    337.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    338.         //Jumping
    339.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    340.        
    341.             if(jumping){
    342.                 //play landing sound effect after landing from jump and reset jumpfxstate
    343.                 if(jumpTimer + 0.25f < Time.time){
    344.                         //play landing sound
    345.                         AudioSource.PlayClipAtPoint(landfx, Camera.main.transform.position);
    346.                        
    347.                         if (Camera.main.animation.IsPlaying("CameraLand")){
    348.                             //rewind animation if already playing to allow overlapping playback
    349.                             Camera.main.animation.Rewind("CameraLand");
    350.                         }
    351.                         Camera.main.animation.CrossFade("CameraLand", 0.35f,PlayMode.StopAll);
    352.                        
    353.                         jumpfxstate = true;
    354.                 }
    355.                 //reset jumping var (this check must be before jumping var is set to true below)
    356.                 jumping = false;
    357.                 //allow a small amount of time for capsule to become un-grounded before setting
    358.                 //jump button state to false to prevent continuous jumping if jump button is held.
    359.                 if(jumpTimer + 0.25f < Time.time){
    360.                     jumpBtn = false;
    361.                 }
    362.             }
    363.            
    364.             //determine if player is jumping and set jumping variable
    365.             if (Input.GetKey (FPSPlayerComponent.jump)
    366.             && !FPSPlayerComponent.zoomed
    367.             && jumpBtn//check that jump button is not being held
    368.             && !crouched
    369.             && landStartTime+antiBunnyHopFactor < Time.time//check for bunnyhop delay before jumping
    370.             && !rayTooSteep){//do not jump if ground normal is greater than slopeLimit
    371.                
    372.                 if(!jumping){
    373.                     jumping = true;
    374.                     //track the time we began to jump
    375.                     jumpTimer = Time.time;
    376.                 }
    377.                 //apply the jump velocity to the player rigidbody
    378.                 rigidbody.velocity = new Vector3(velocity.x, Mathf.Sqrt(2 * jumpSpeed * gravity), velocity.z);
    379.             }
    380.            
    381.             //set jumpBtn to false to prevent continuous jumping while holding jump button.
    382.             if (!Input.GetKey (FPSPlayerComponent.jump) && landStartTime+antiBunnyHopFactor<Time.time){
    383.                 jumpBtn = true;
    384.             }
    385.                    
    386.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    387.         //Crouching
    388.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    389.             if(Time.timeSinceLevelLoad > 0.5f){          
    390.                 //crouch
    391.                 if(crouched){
    392.                         if(midPos > 0.45f){midPos -= 5 * Time.deltaTime;}//decrease camera height to crouch height
    393.                         if(capsule.height > 1.25f){capsule.height -= 5 * Time.deltaTime;}//decrease capsule height to crouch height
    394.                 }else{
    395.                     if(!Input.GetKey (FPSPlayerComponent.jump)){
    396.                         if(midPos < 0.9f){midPos += 2.25f * Time.deltaTime;}//increase camera height to standing height
    397.                          if(capsule.height < 2.0f){capsule.height += 2.25f * Time.deltaTime;}//increase camera height to standing height
    398.                     }
    399.                 }  
    400.             }
    401.            
    402.         }else{//Player is airborn////////////////////////////////////////////////////////////////////////////////////////////////////////////
    403.            
    404.             //keep track of the time that player lost grounding for air manipulation and moving gun while jumping
    405.             if(airTimeState){
    406.                 airTime = Time.time;
    407.                 airTimeState = false;
    408.             }
    409.                
    410.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    411.         //Falling
    412.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    413.            
    414.             //subtract height we began falling from current position to get falling distance
    415.             fallingDistance = fallStartLevel - myTransform.position.y;
    416.        
    417.             if (!falling){
    418.                 falling = true;          
    419.                 //start tracking altitude (y position) for fall check
    420.                 fallStartLevel = myTransform.position.y;
    421.                
    422.                 //check jumpfxstate var to play jumping sound only once
    423.                 if(jumping && jumpfxstate){
    424.                     //play jumping sound
    425.                     AudioSource.PlayClipAtPoint(jumpfx, Camera.main.transform.position);
    426.                     jumpfxstate = false;
    427.                 }      
    428.             }  
    429.         }
    430.            
    431.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    432.         //Climbing
    433.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    434.        
    435.         //make player climb up ladders or other surfaces
    436.         if(climbing){//climbing var is managed by a ladder script attatched to a trigger that is placed near a ladder
    437.             if(inputY > 0){//only climb if player is moving forward
    438.                 //make player climb up or down based on the pitch of the main camera (check mouselook script pitch)
    439.                 climbSpeedAmt = 1 + (climbSpeed * (SmoothMouseLookComponent.rotationY / 48));
    440.                 climbSpeedAmt = Mathf.Clamp(climbSpeedAmt, -climbSpeed, climbSpeed);//limit vertical speed to climb speed
    441.                 //apply climbing velocity to the player's rigidbody
    442.                 rigidbody.velocity = new Vector3(velocity.x, climbSpeedAmt, velocity.z);
    443.             }else{
    444.                 //if not moving forward, do not add extra upward velocity, but allow the player to move off the ladder
    445.                 rigidbody.velocity = new Vector3(velocity.x, 0, velocity.z);
    446.             }
    447.         }
    448.            
    449.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    450.         //Player Ground Check
    451.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    452.    
    453.         //cast capsule shape down to see if player is about to hit anything or is resting on the ground
    454.         if (Physics.CapsuleCast (p1, p2, capsule.radius * 0.9f, -transform.up, out hit, 0.75f, clipMask.value) || climbing){
    455.             grounded = true;
    456.         }else{
    457.             grounded = false;
    458.         }
    459.        
    460.         //check that angle of the normal directly below the capsule center point is less than the movement slope limit
    461.         if (Physics.Raycast(myTransform.position, -transform.up, out hit, 2.6f, clipMask.value)) {
    462.             if(Vector3.Angle ( hit.normal, Vector3.up ) > slopeLimit){
    463.                 rayTooSteep = true;  
    464.             }else{
    465.                 rayTooSteep = false;  
    466.             }
    467.         }
    468.            
    469.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    470.         //Player Velocity
    471.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    472.        
    473.         //limit speed if strafing diagonally
    474.         limitStrafeSpeed = (inputX != 0.0f && inputY != 0.0f)? .7071f : 1.0f;
    475.        
    476.         //align localEulerAngles and eulerAngles y values with cameras' to make player walk in the direction the camera is facing
    477.         Vector3 tempLocalEulerAngles = new Vector3(0,CameraObj.transform.localEulerAngles.y,0);//store angles in temporary vector for C#
    478.         myTransform.localEulerAngles = tempLocalEulerAngles;//apply angles from temporary vector to player object
    479.         Vector3 tempEulerAngles = new Vector3(0, CameraObj.transform.eulerAngles.y,0);//store angles in temporary vector for C#
    480.         myTransform.eulerAngles = tempEulerAngles;//apply angles from temporary vector to player object
    481.        
    482.         //apply velocity to player rigidbody and allow a small amount of air manipulation
    483.         //to allow jumping up on obstacles when jumping from stationary position with no forward velocity
    484.         if((grounded || climbing || ((airTime + 0.3f) > Time.time)) && FPSPlayerComponent.hitPoints > 0 && !FPSPlayerComponent.restarting){
    485.             //Check both capsule center point and capsule base slope angles to determine if the slope is too high to climb.
    486.             //If so, bypass player control and apply some extra downward velocity to help capsule return to more level ground.
    487.             if(!capsuleTooSteep || (capsuleTooSteep && !rayTooSteep)){
    488.                 // We are grounded, so recalculate movedirection directly from axes  
    489.                 moveDirection = new Vector3(inputXSmoothed*limitStrafeSpeed, 0.0f, inputYSmoothed*limitStrafeSpeed);
    490.                 //realign moveDirection vector to world space
    491.                 moveDirection = myTransform.TransformDirection(moveDirection);
    492.                 //apply speed limits to moveDirection vector
    493.                 moveDirection = moveDirection * speed * speedAmtX * speedAmtY * crouchSpeedAmt * zoomSpeedAmt;
    494.        
    495.                 //apply a force that attempts to reach target velocity
    496.                 Vector3 velocityChange = moveDirection - velocity;
    497.                 //limit max speed
    498.                 velocityChange.x = Mathf.Clamp(velocityChange.x, -maxVelocityChange, maxVelocityChange);
    499.                 velocityChange.z = Mathf.Clamp(velocityChange.z, -maxVelocityChange, maxVelocityChange);
    500.        
    501.                 //apply ladder climbing speed to velocityChange vector and set y velocity to zero if not climbing ladder
    502.                 if(climbing && inputY > 0){
    503.                     velocityChange.y = climbSpeedAmt;
    504.                 }else{
    505.                     velocityChange.y = 0;
    506.                 }
    507.                
    508.                 //finally, add movement velocity to player rigidbody velocity
    509.                 rigidbody.AddForce(velocityChange, ForceMode.VelocityChange);
    510.                
    511.             }else{
    512.                 //If slope is too high below both the center and base contact point of capsule, apply some downward velocity to help
    513.                 //the capsule fall to more level ground. Check the slope angle at two points on the collider to prevent it from
    514.                 //getting stuck when player control is bypassed and to have more control over the slope angle limit.
    515.                 rigidbody.AddForce(new Vector3 (0, -2, 0), ForceMode.VelocityChange);
    516.             }
    517.         }else{
    518.             //if player is dead or restarting level set velocity to zero to prevent rigidbody from moving when camera is stopped
    519.             if(FPSPlayerComponent.hitPoints <= 0 || FPSPlayerComponent.restarting){  
    520.                 rigidbody.velocity = Vector3.zero;  
    521.             }
    522.         }
    523.        
    524.         if(!climbing){
    525.             //apply gravity manually for more tuning control except when climbing a ladder to avoid unwanted downward movement
    526.             rigidbody.AddForce(new Vector3 (0, -gravity * rigidbody.mass, 0));
    527.             rigidbody.useGravity = true;
    528.         }else{
    529.             rigidbody.useGravity = false;
    530.         }
    531.        
    532.     }
    533.    
    534.     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    535.     //Rigidbody Collisions
    536.     /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    537.    
    538.     void TrackCollision ( Collision col  ){
    539.         //define a height of about a fourth of the capsule height to check for collisions with platforms
    540.         float minimumHeight = (capsule.bounds.min.y + capsule.radius);
    541.         //check the collision points within our predefined height range
    542.         foreach(ContactPoint c in col.contacts){
    543.             if (c.point.y < minimumHeight) {
    544.                 //check that we want to collide with this object (check for "PhysicsObject" tag) and that it's surface is not too steep
    545.                 if(!parentState && col.gameObject.tag == "PhysicsObject" && Vector3.Angle ( c.normal, Vector3.up ) < 70){
    546.                     //set player object parent to platform transform to inherit it's movement in addition to player movement
    547.                     myTransform.parent = col.transform;
    548.                     parentState = true;//only set parent once to prevent rapid parenting and de-parenting that breaks functionality
    549.                 }
    550.                 //check that angle of the surface that the capsule base is touching is less than the movement slope limit
    551.                 if(Vector3.Angle ( c.normal, Vector3.up ) > slopeLimit){
    552.                     capsuleTooSteep = true;  
    553.                 }else{
    554.                     capsuleTooSteep = false;  
    555.                 }
    556.             }
    557.         }
    558.        
    559.     }
    560.    
    561.     void OnCollisionExit ( Collision col  ){
    562.         //unparent if we are no longer standing on our parent
    563.         myTransform.parent = initialParent;
    564.         //return parentState to false so we may check for collisions again
    565.         parentState = false;
    566.         capsuleTooSteep = false;  
    567.     }
    568.    
    569.     void OnCollisionStay ( Collision col  ){
    570.        TrackCollision (col);
    571.     }
    572.    
    573.     void OnCollisionEnter ( Collision col  ){
    574.        TrackCollision (col);
    575.     }
    576.    
    577.     void CalculateFallingDamage ( float fallDistance  ){
    578.         GetComponent<FPSPlayer>().ApplyDamage(fallDistance * 2);  
    579.     }
    580. }