Advertisement
Guest User

Text

a guest
Sep 25th, 2014
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.22 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement