SebastianLawe

Untitled

Feb 13th, 2015
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 15.78 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Diagnostics;
  4. using System;
  5. using System.Collections.Generic;
  6. using Assets.Scripts;
  7.  
  8. public class PlayerController : RPCNetworkObject {
  9.     #region Constructors
  10.     public int _health = 100;
  11.     public int _mana = 100;
  12.     public float _force;
  13.     public float _jump;
  14.     public float _speedCap;
  15.     private bool _shiftEnded = true;
  16.     private bool _walkingBackwards = false;
  17.     private int _moveButtonPushCount = 0;
  18.     public Animator[] _animators;
  19.     public SpriteEvents _events;
  20.     public bool _useAI = false;
  21.     public bool _activateInputChange = false;
  22.     public string _faction;
  23.     public bool _modifyOpponentHealth;
  24.     public int _healthModifier;
  25.     public bool _freeForAll = false;
  26.     private bool _running = false;
  27.     private Vector3 _firstPos = new Vector3();
  28.     Stopwatch _deathTimer = new Stopwatch();
  29.     Stopwatch _vaultTimer = Stopwatch.StartNew();
  30.     public bool _claimedCamera;
  31.     private bool _checkedPos = false;
  32.     public bool AbilityActive;
  33.     public int Damage;
  34.     public bool canReceiveInput;
  35.     public bool damagePerformed;
  36.     public bool isBlocking;
  37.     public ArmableObject _leftHand;
  38.     public ArmableObject _rightHand;
  39.     private PlayerController _lastAntagoniser;
  40.     public GameObject _focalPoint;
  41.     public Stopwatch _syncTimer = Stopwatch.StartNew();
  42.     private Vector3 _lastPos = new Vector3();
  43.     public AudioSource[] _playerAttackSounds;
  44.     public List<Weapon> _weaponInventory;
  45.     private WeildingSystem _inventorySystemLeft;
  46.     private WeildingSystem _inventorySystemRight;
  47.     private WeaponPairingSystem _weaponPairingSystem;
  48.     #endregion Constructors
  49.  
  50.     // Use this for initialization
  51.     void Start() {
  52.         base.Start();
  53.         networkView.RPC("SetPosition", PhotonTargets.All, transform.position);
  54.         InitializePlayer();
  55.         // Check and see if this is a free for all server.
  56.         if (_freeForAll) {
  57.             // Create a randomly generated _faction. Nobody is a friend here.
  58.             _faction = DateTime.Now.Ticks.ToString() + UnityEngine.Random.Range(0, 999);
  59.         }
  60.         // Enable or disable the camera manager for this game object, depending on if its a human or AI.
  61.         GetComponent<CameraManager>().enabled = !_useAI;
  62.         _inventorySystemLeft = new WeildingSystem(_leftHand);
  63.         _inventorySystemRight = new WeildingSystem(_rightHand);
  64.         _weaponPairingSystem = new WeaponPairingSystem(_inventorySystemLeft, _inventorySystemRight, _animators);
  65.     }
  66.  
  67.     void Update() {
  68.         CheckForWeaponSwap();
  69.     }
  70.  
  71.     private void CheckForWeaponSwap() {
  72.  
  73.     }
  74.  
  75.     // Update is called once per frame
  76.     void FixedUpdate() {
  77.         GetComponent<Rigidbody>().maxAngularVelocity = 0.5f;
  78.         // Check if somebody else owns this game object.
  79.         if (!photonView.isMine) {
  80.             // Ease into the newest position.
  81.             transform.position = Vector3.Lerp(transform.position, _lastPos, 0.3f);
  82.         }
  83.         // Check to see if we've tracked our first position.
  84.         if (!_checkedPos) {
  85.             // Track initial position.
  86.             TrackInitialPos();
  87.         }
  88.         // Check to see player is below the map.
  89.         CheckIfPlayerBelowMap();
  90.         // Check to see if the player is dead.
  91.         if (_health <= 0) {
  92.             DeathOperations();
  93.         } else {
  94.             // Check to see if we can receive input.
  95.             if (canReceiveInput) {
  96.                 CheckForEditorChanges();
  97.                 if (_events == null) {
  98.                     InitializePlayer();
  99.                 }
  100.                 base.Update();
  101.                 // Get our vertical value.
  102.                 float vertical = _events != null ? _events.Vertical : 0;
  103.                 // Get our horizontal value.
  104.                 float horizontal = _events != null ? _events.Horizontal : 0;
  105.                 // Get our jump value.
  106.                 float jump = _events != null ? _events.JumpValue : 0;
  107.                 // Trigger nessecary animation.
  108.                 TriggerAnimations(vertical, horizontal);
  109.                 // Check to see if we don't use AI.
  110.                 if (!_useAI) {
  111.                     // Manage player rotation.
  112.                     ManagePlayerRotation(vertical, horizontal);
  113.                 }
  114.                 // Check if player is ours.
  115.                 if (photonView.isMine) {
  116.                     // Regulate player motion.
  117.                     RegulateMotion(horizontal, vertical, jump);
  118.                 }
  119.             }
  120.         }
  121.         AdjustPlayerCam();
  122.     }
  123.  
  124.     #region Methods
  125.     private void TriggerAnimations(float vertical, float horizontal) {
  126.         // Go through all our _animators and set appropriate values.
  127.         for (int i = 0; i < _animators.Length; i++) {
  128.             Animator animator = _animators[i];
  129.             if (animator != null) {
  130.                 animator.SetBool("Fly", true);
  131.                 photonView.RPC("SetFloat", PhotonTargets.All, "Altitude", transform.position.y, i);
  132.                 photonView.RPC("SetFloat", PhotonTargets.All, "Speed", Mathf.Abs(Mathf.Abs(horizontal) > Mathf.Abs(vertical) ? horizontal * _force : vertical * _force), i);
  133.             }
  134.         }
  135.     }
  136.  
  137.     private void CheckForEditorChanges() {
  138.         // Check to see if somebody wants to invoke changes in the editor.
  139.         if (_activateInputChange) {
  140.             InitializePlayer();
  141.             // The change has been done, untrigger the boolean.
  142.             _activateInputChange = false;
  143.         }
  144.     }
  145.  
  146.     private void DeathOperations() {
  147.         // Check to see if our respawn counter hasn't started yet.
  148.         if (!_deathTimer.IsRunning) {
  149.             // Start the respawn counter.
  150.             _deathTimer.Start();
  151.         }
  152.         // Go through all _animators listed on this script.
  153.         foreach (Animator animator in _animators) {
  154.             // Disable the _animators.
  155.             animator.enabled = false;
  156.         }
  157.         // Freeze the player so they can no longer move.
  158.         GetComponent<Rigidbody>().freezeRotation = false;
  159.         // Destroy our _events so that the play can no longer interact with this script.
  160.         _events = null;
  161.         // Check to see if this server allows respawning.
  162.         if (FindObjectOfType<ServerManager>()._canRespawn) {
  163.             // Check if its time to respawn.
  164.             CheckRespawn();
  165.         } else {
  166.             ReleaseCamera();
  167.         }
  168.     }
  169.  
  170.     private void TrackInitialPos() {
  171.         // Get our first position and store it in memory.
  172.         _lastPos = _firstPos = transform.position;
  173.         // Mark that we've collected our first position.
  174.         _checkedPos = true;
  175.     }
  176.  
  177.     private void CheckIfPlayerBelowMap() {
  178.         // Check to see if we've fallen below the map.
  179.         if (transform.position.y < -2) {
  180.             // Kill the player.
  181.             _health = 0;
  182.             // Turn the character upside down.
  183.             transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(180, 90, 0), 0.03f);
  184.         }
  185.     }
  186.  
  187.     private void ReleaseCamera() {
  188.         // Check to see if the main camera has been claimed by this player.
  189.         if (_claimedCamera) {
  190.             // Unclaim camera.
  191.             Camera.main.GetComponent<CameraClaim>().Claimed = false;
  192.             // Set the camera to follow the person who killed this player.
  193.             Camera.main.GetComponent<CameraFollow>().player = _lastAntagoniser._focalPoint;
  194.         }
  195.         // Destory this script.
  196.         Destroy(this);
  197.     }
  198.  
  199.     private void ManagePlayerRotation(float vertical, float horizontal) {
  200.         // Do a null check on our _events.
  201.         if (_events != null) {
  202.             // Check to see if we have input.
  203.             if (_events.InputActive) {
  204.                 // Rotate the character according to the corresponding vertical and horizontal values.
  205.                 Vector3 rotation = GetRelativeRotation(Camera.main.transform.rotation.eulerAngles, vertical, horizontal, 1f, 1f);
  206.                 // Set the character rotation.
  207.                 if (photonView.isMine) {
  208.                     SetRotation(Quaternion.Euler(0, rotation.y, 0));
  209.                 }
  210.             }
  211.         }
  212.     }
  213.  
  214.     private void CheckRespawn() {
  215.         // Check to see if its time to respawn the human player.
  216.         if (!_useAI && _deathTimer.ElapsedMilliseconds >= 5000) {
  217.             // Check to make sure this is our human controlled player.
  218.             if (photonView.isMine) {
  219.                 // Check to see if this player ever claimed the main camera.
  220.                 if (_claimedCamera) {
  221.                     // Unclaim the main camera.
  222.                     Camera.main.GetComponent<CameraClaim>().Claimed = false;
  223.                 }
  224.                 // Disable the ability to rotate the character.
  225.                 GetComponent<CameraManager>().enabled = false;
  226.                 // Respawn.
  227.                 FindObjectOfType<ServerManager>().SpawnPlayer(_faction);
  228.             }
  229.             // Check to see if its time to dispose of the characters dead body.
  230.             if (_deathTimer.ElapsedMilliseconds >= 5000) {
  231.                 // Destroy the dead body.
  232.                 if (photonView.isMine) {
  233.                     PhotonNetwork.Destroy(gameObject);
  234.                 }
  235.             }
  236.         }
  237.             // Check to see if its time to respawn the AI player.
  238.         else if (_useAI && _deathTimer.ElapsedMilliseconds >= 5000) {
  239.             // Make sure this is our AI player.
  240.             if (photonView.isMine) {
  241.                 // Respawn.
  242.                 FindObjectOfType<ServerManager>().SpawnAI(_faction);
  243.                 if (photonView.isMine) {
  244.                     PhotonNetwork.Destroy(gameObject);
  245.                 }
  246.             }
  247.         }
  248.     }
  249.  
  250.     private void InitializePlayer() {
  251.         // Send an RPC command which sets the PlayerController event type across connected clients.
  252.         photonView.RPC("SetMasterInput", PhotonTargets.All, new object[0]);
  253.         // Send an RPC command that initializes the _events the PlayerController reacts to.
  254.         photonView.RPC("InitializeEvents", PhotonTargets.All, new object[0]);
  255.     }
  256.  
  257.     private void RegulateMotion(float horizontal, float vertical, float jump) {
  258.         // Add relative force via RPC.
  259.         photonView.RPC("AddRelativeForce", PhotonTargets.All, 0f, 0f, Mathf.Abs(Mathf.Abs(horizontal) > Mathf.Abs(vertical)
  260.             ? horizontal * _force : vertical * _force));
  261.         // Add force via RPC.
  262.         photonView.RPC("AddForce", PhotonTargets.All, 0f, jump, 0f);
  263.         if (vertical == 0) {
  264.             GetComponent<Collider>().material.dynamicFriction = 1;
  265.         } else {
  266.             GetComponent<Collider>().material.dynamicFriction = 0;
  267.         }
  268.         _moveButtonPushCount = 0;
  269.         // Resist movement for faster deceleration.
  270.         ResistForce(_speedCap, 0.2f);
  271.     }
  272.  
  273.     private Vector3 GetRelativeRotation(Vector3 rotation, float vertical, float horizontal, float xTolerance, float yTolerance) {
  274.         if (vertical >= xTolerance && horizontal >= yTolerance) {
  275.             rotation += new Vector3(0, 45, 0);
  276.         } else if (vertical >= xTolerance && horizontal <= -yTolerance) {
  277.             rotation += new Vector3(0, 315, 0);
  278.         } else if (vertical <= -xTolerance && horizontal >= yTolerance) {
  279.             rotation += new Vector3(0, 135, 0);
  280.         } else if (vertical <= -xTolerance && horizontal <= -yTolerance) {
  281.             rotation += new Vector3(0, 225, 0);
  282.         } else if (vertical <= -xTolerance && horizontal == 0f) {
  283.             rotation += new Vector3(0, 180, 0);
  284.         } else if (vertical == 0f && horizontal <= -yTolerance) {
  285.             rotation += new Vector3(0, 270, 0);
  286.         } else if (vertical == 0f && horizontal >= yTolerance) {
  287.             rotation += new Vector3(0, 90, 0);
  288.         }
  289.         return rotation;
  290.     }
  291.  
  292.     [RPC]
  293.     public void SetRotation(Quaternion rotation) {
  294.         transform.rotation = rotation;
  295.     }
  296.     [RPC]
  297.     public void SetPosition(Vector3 position) {
  298.         _lastPos = position;
  299.     }
  300.  
  301.     void AdjustPlayerCam() {
  302.         if (photonView.isMine) {
  303.             if (_syncTimer.ElapsedMilliseconds >= 100) {
  304.                 networkView.RPC("SetPosition", PhotonTargets.All, transform.position);
  305.                 _syncTimer.Reset();
  306.                 _syncTimer.Start();
  307.             }
  308.             if (!_useAI)
  309.                 if (!canReceiveInput && Camera.main.fieldOfView < 80) {
  310.                     Camera.main.fieldOfView++;
  311.                 } else if (_animators[0].GetBool("Run") && Camera.main.fieldOfView < 70 && !_modifyOpponentHealth) {
  312.                     Camera.main.fieldOfView++;
  313.                 } else if (_modifyOpponentHealth && Camera.main.fieldOfView < 40) {
  314.                     Camera.main.fieldOfView--;
  315.                 } else if (Camera.main.fieldOfView > 60 && !_animators[0].GetBool("Run")) {
  316.                     Camera.main.fieldOfView--;
  317.                 }
  318.         }
  319.     }
  320.  
  321.     [RPC]
  322.     private void SetFloat(string identifier, float value, int index) {
  323.         _animators[index].SetFloat(identifier, value);
  324.     }
  325.  
  326.     [RPC]
  327.     private void SetMasterInput() {
  328.         if (_events != null) {
  329.             DestroyImmediate(_events);
  330.         }
  331.         if (_useAI) {
  332.             _events = gameObject.AddComponent<AIEvents>();
  333.             (_events as AIEvents).CanRun = true;
  334.         } else {
  335.             _events = gameObject.AddComponent<PlayerEvents>();
  336.         }
  337.     }
  338.  
  339.     [RPC]
  340.     private void InitializeEvents() {
  341.         _events.Run += delegate {
  342.             foreach (Animator animator in _animators) {
  343.                 animator.SetBool("Run", true);
  344.             }
  345.             if (!_running) {
  346.                 if (_shiftEnded) {
  347.                     _force *= 4;
  348.                     _speedCap *= 4;
  349.                     GetComponent<Rigidbody>().drag *= 3;
  350.                     GetComponent<Rigidbody>().angularDrag *= 3;
  351.                     _shiftEnded = false;
  352.                     _running = true;
  353.                 }
  354.             }
  355.         };
  356.         _events.StopRun += delegate {
  357.             foreach (Animator animator in _animators) {
  358.                 animator.SetBool("Run", false);
  359.             }
  360.             if (_running) {
  361.                 _force /= 4;
  362.                 _speedCap /= 4;
  363.                 GetComponent<Rigidbody>().drag /= 3;
  364.                 GetComponent<Rigidbody>().angularDrag /= 3;
  365.                 _shiftEnded = true;
  366.                 _running = false;
  367.             }
  368.         };
  369.         _events.Attack += delegate {
  370.             foreach (Animator animator in _animators) {
  371.                 animator.SetTrigger("Attack");
  372.             }
  373.         };
  374.         _events.Defend += delegate {
  375.             foreach (Animator animator in _animators) {
  376.                 if (!AbilityActive) {
  377.                     AbilityActive = true;
  378.                     animator.GetComponent<Interaction>().MagicDeflect();
  379.                 }
  380.             }
  381.         };
  382.  
  383.         _events.Jump += delegate {
  384.             foreach (Animator animator in _animators) {
  385.                 animator.SetTrigger("Jump");
  386.             }
  387.         };
  388.     }
  389.  
  390.     public bool ResistForce(float limit, float counterForce) {
  391.         Vector3 velocity = transform.GetComponent<Rigidbody>().velocity;
  392.         if (Mathf.Abs(velocity.x) > 0 && Mathf.Abs(velocity.x) > limit) {
  393.             AddForce(velocity.x * counterForce * -1f, 0f, 0f);
  394.         }
  395.         if (Mathf.Abs(velocity.y) > 0 && Mathf.Abs(velocity.y) > limit) {
  396.             AddForce(0f, velocity.y * counterForce * -1f, 0f);
  397.         }
  398.         if (Mathf.Abs(velocity.z) > 0 && Mathf.Abs(velocity.z) > limit) {
  399.             AddForce(0f, 0f, velocity.z * counterForce * -1f);
  400.         }
  401.         return Mathf.Max(Mathf.Abs(velocity.x), Mathf.Abs(velocity.y), Mathf.Abs(velocity.x)) < limit;
  402.     }
  403.  
  404.     void OnCollisionEnter(Collision collision) {
  405.         //if (collision._gameObject.layer == 12) {
  406.         //  Vault(false);
  407.         //}
  408.         PerformDamage(collision);
  409.     }
  410.  
  411.     void OnCollisionStay(Collision collision) {
  412.         //if (collision._gameObject.layer != 12) {
  413.         //  Vault(false);
  414.         //}
  415.         PerformDamage(collision);
  416.     }
  417.  
  418.     void OnCollisionLeave(Collision collision) {
  419.         if (collision.gameObject.layer != 12) {
  420.             Vault(false);
  421.         }
  422.         if (collision.gameObject.GetComponent<PlayerController>() != null) {
  423.             photonView.RPC("ResetDamage", PhotonTargets.All, new object[0]);
  424.         }
  425.     }
  426.     void OnGUI() {
  427.         if (_claimedCamera) {
  428.             GUI.Label(new Rect(0, 0, 200, 200), "Health: " + _health.ToString());
  429.             GUI.Label(new Rect(0, 20, 200, 200), "Mana: " + _mana.ToString());
  430.         }
  431.     }
  432.  
  433.     [RPC]
  434.     private void ResetDamage() {
  435.         foreach (Animator animator in _animators) {
  436.             animator.GetComponent<Interaction>().Reset();
  437.         }
  438.     }
  439.     [RPC]
  440.     public void Vault(bool value) {
  441.         if (_vaultTimer.ElapsedMilliseconds >= 2000) {
  442.             if (_running) {
  443.                 foreach (Animator animator in _animators) {
  444.                     animator.SetTrigger("Vault");
  445.                     _vaultTimer.Reset();
  446.                     _vaultTimer.Start();
  447.                 }
  448.             }
  449.         }
  450.     }
  451.  
  452.     private void PerformDamage(Collision collision) {
  453.         PlayerController controller = collision.gameObject.GetComponent<PlayerController>();
  454.         Projectile projectile = collision.gameObject.GetComponent<Projectile>();
  455.         _lastAntagoniser = controller;
  456.         if (projectile != null) {
  457.             _lastAntagoniser = projectile._master;
  458.         }
  459.         if (controller != null) {
  460.             if (controller._faction != _faction) {
  461.                 if (_modifyOpponentHealth) {
  462.                     if (!controller._modifyOpponentHealth) {
  463.                         if (photonView.isMine) {
  464.                             if (!damagePerformed) {
  465.                                 controller.photonView.RPC("ModifyHealth", PhotonTargets.All, Damage);
  466.                                 damagePerformed = true;
  467.                                 _mana += 20;
  468.                             }
  469.                         }
  470.                     } else {
  471.                         photonView.RPC("AddRelativeForce", PhotonTargets.All, 0f, 0f, -50f);
  472.                         Instantiate(Resources.Load("AirDeformer"), ((transform.position + controller.transform.position) / 2f), Quaternion.identity);
  473.                     }
  474.                 }
  475.             }
  476.         }
  477.         if (projectile != null) {
  478.             if (projectile._master != null) {
  479.                 if (projectile._master._faction != _faction) {
  480.                     photonView.RPC("ModifyHealth", PhotonTargets.All, projectile._damage);
  481.                 }
  482.             }
  483.         }
  484.     }
  485.  
  486.     [RPC]
  487.     private void ModifyHealth(int modifer) {
  488.         if (modifer < 0) {
  489.             foreach (Animator animator in _animators) {
  490.                 animator.SetTrigger("Injured");
  491.                 animator.GetComponent<Interaction>().Reset();
  492.             }
  493.             _health += modifer;
  494.         }
  495.     }
  496.  
  497.     internal void Jump() {
  498.         photonView.RPC("AddForce", PhotonTargets.All, 0f, 200f, 0f);
  499.     }
  500.     #endregion Methods
  501. }
Advertisement
Add Comment
Please, Sign In to add comment