Advertisement
Guest User

Untitled

a guest
Feb 19th, 2018
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 30.38 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Security.Principal;
  4. using UnityEngine;
  5. using UnityEngine.Tilemaps;
  6.  
  7. namespace Gamekit2D
  8. {
  9.     [RequireComponent(typeof(CharacterController2D))]
  10.     [RequireComponent(typeof(Animator))]
  11.     public class PlayerCharacter : MonoBehaviour
  12.     {
  13.         static protected PlayerCharacter s_PlayerInstance;
  14.         static public PlayerCharacter PlayerInstance { get { return s_PlayerInstance; } }
  15.  
  16.         public InventoryController inventoryController
  17.         {
  18.             get { return m_InventoryController; }
  19.         }
  20.  
  21.         public SpriteRenderer spriteRenderer;
  22.         public Damageable damageable;
  23.         public Damager meleeDamager;
  24.         public Transform facingLeftBulletSpawnPoint;
  25.         public Transform facingRightBulletSpawnPoint;
  26.         public BulletPool bulletPool;
  27.         public Transform cameraFollowTarget;
  28.  
  29.         public float maxSpeed = 10f;
  30.         public float groundAcceleration = 100f;
  31.         public float groundDeceleration = 100f;
  32.         [Range(0f, 1f)] public float pushingSpeedProportion;
  33.  
  34.         [Range(0f, 1f)] public float airborneAccelProportion;
  35.         [Range(0f, 1f)] public float airborneDecelProportion;
  36.         public float gravity = 50f;
  37.         public float jumpSpeed = 20f;
  38.         public float jumpAbortSpeedReduction = 100f;
  39.  
  40.         [Range(k_MinHurtJumpAngle, k_MaxHurtJumpAngle)] public float hurtJumpAngle = 45f;
  41.         public float hurtJumpSpeed = 5f;
  42.         public float flickeringDuration = 0.1f;
  43.  
  44.         public float meleeAttackDashSpeed = 5f;
  45.         public bool dashWhileAirborne = false;
  46.  
  47.         public RandomAudioPlayer footstepAudioPlayer;
  48.         public RandomAudioPlayer landingAudioPlayer;
  49.         public RandomAudioPlayer hurtAudioPlayer;
  50.         public RandomAudioPlayer meleeAttackAudioPlayer;
  51.         public RandomAudioPlayer rangedAttackAudioPlayer;
  52.  
  53.         public float shotsPerSecond = 1f;
  54.         public float bulletSpeed = 5f;
  55.         public float holdingGunTimeoutDuration = 10f;
  56.         public bool rightBulletSpawnPointAnimated = true;
  57.  
  58.         public float cameraHorizontalFacingOffset;
  59.         public float cameraHorizontalSpeedOffset;
  60.         public float cameraVerticalInputOffset;
  61.         public float maxHorizontalDeltaDampTime;
  62.         public float maxVerticalDeltaDampTime;
  63.         public float verticalCameraOffsetDelay;
  64.  
  65.         public bool spriteOriginallyFacesLeft;
  66.  
  67.         protected CharacterController2D m_CharacterController2D;
  68.         protected Animator m_Animator;
  69.         protected CapsuleCollider2D m_Capsule;
  70.         protected Transform m_Transform;
  71.         protected Vector2 m_MoveVector;
  72.         protected List<Pushable> m_CurrentPushables = new List<Pushable>(4);
  73.         protected Pushable m_CurrentPushable;
  74.         protected float m_TanHurtJumpAngle;
  75.         protected WaitForSeconds m_FlickeringWait;
  76.         protected Coroutine m_FlickerCoroutine;
  77.         protected Transform m_CurrentBulletSpawnPoint;
  78.         protected float m_ShotSpawnGap;
  79.         protected WaitForSeconds m_ShotSpawnWait;
  80.         protected Coroutine m_ShootingCoroutine;
  81.         protected float m_NextShotTime;
  82.         protected bool m_IsFiring;
  83.         protected float m_ShotTimer;
  84.         protected float m_HoldingGunTimeRemaining;
  85.         protected TileBase m_CurrentSurface;
  86.         protected float m_CamFollowHorizontalSpeed;
  87.         protected float m_CamFollowVerticalSpeed;
  88.         protected float m_VerticalCameraOffsetTimer;
  89.         protected InventoryController m_InventoryController;
  90.  
  91.         protected Checkpoint m_LastCheckpoint = null;
  92.         protected Vector2 m_StartingPosition = Vector2.zero;
  93.         protected bool m_StartingFacingLeft = false;
  94.  
  95.         protected bool m_InPause = false;
  96.  
  97.         protected readonly int m_HashHorizontalSpeedPara = Animator.StringToHash("HorizontalSpeed");
  98.         protected readonly int m_HashVerticalSpeedPara = Animator.StringToHash("VerticalSpeed");
  99.         protected readonly int m_HashGroundedPara = Animator.StringToHash("Grounded");
  100.         protected readonly int m_HashCrouchingPara = Animator.StringToHash("Crouching");
  101.         protected readonly int m_HashPushingPara = Animator.StringToHash("Pushing");
  102.         protected readonly int m_HashTimeoutPara = Animator.StringToHash("Timeout");
  103.         protected readonly int m_HashRespawnPara = Animator.StringToHash("Respawn");
  104.         protected readonly int m_HashDeadPara = Animator.StringToHash("Dead");
  105.         protected readonly int m_HashHurtPara = Animator.StringToHash("Hurt");
  106.         protected readonly int m_HashForcedRespawnPara = Animator.StringToHash("ForcedRespawn");
  107.         protected readonly int m_HashMeleeAttackPara = Animator.StringToHash("MeleeAttack");
  108.         protected readonly int m_HashHoldingGunPara = Animator.StringToHash("HoldingGun");
  109.  
  110.         protected const float k_MinHurtJumpAngle = 0.001f;
  111.         protected const float k_MaxHurtJumpAngle = 89.999f;
  112.         protected const float k_GroundedStickingVelocityMultiplier = 3f;    // This is to help the character stick to vertically moving platforms.
  113.  
  114.         //used in non alloc version of physic function
  115.         protected ContactPoint2D[] m_ContactsBuffer = new ContactPoint2D[16];
  116.  
  117.         // MonoBehaviour Messages - called by Unity internally.
  118.         void Awake()
  119.         {
  120.             s_PlayerInstance = this;
  121.  
  122.             m_CharacterController2D = GetComponent<CharacterController2D>();
  123.             m_Animator = GetComponent<Animator>();
  124.             m_Capsule = GetComponent<CapsuleCollider2D>();
  125.             m_Transform = transform;
  126.             m_InventoryController = GetComponent<InventoryController>();
  127.  
  128.             m_CurrentBulletSpawnPoint = spriteOriginallyFacesLeft ? facingLeftBulletSpawnPoint : facingRightBulletSpawnPoint;
  129.         }
  130.  
  131.         void Start()
  132.         {
  133.             hurtJumpAngle = Mathf.Clamp(hurtJumpAngle, k_MinHurtJumpAngle, k_MaxHurtJumpAngle);
  134.             m_TanHurtJumpAngle = Mathf.Tan(Mathf.Deg2Rad * hurtJumpAngle);
  135.             m_FlickeringWait = new WaitForSeconds(flickeringDuration);
  136.  
  137.             meleeDamager.DisableDamage();
  138.  
  139.             m_ShotSpawnGap = 1f / shotsPerSecond;
  140.             m_NextShotTime = Time.time;
  141.             m_ShotSpawnWait = new WaitForSeconds(m_ShotSpawnGap);
  142.  
  143.             if (!Mathf.Approximately(maxHorizontalDeltaDampTime, 0f))
  144.             {
  145.                 float maxHorizontalDelta = maxSpeed * cameraHorizontalSpeedOffset + cameraHorizontalFacingOffset;
  146.                 m_CamFollowHorizontalSpeed = maxHorizontalDelta / maxHorizontalDeltaDampTime;
  147.             }
  148.  
  149.             if (!Mathf.Approximately(maxVerticalDeltaDampTime, 0f))
  150.             {
  151.                 float maxVerticalDelta = cameraVerticalInputOffset;
  152.                 m_CamFollowVerticalSpeed = maxVerticalDelta / maxVerticalDeltaDampTime;
  153.             }
  154.  
  155.             SceneLinkedSMB<PlayerCharacter>.Initialise(m_Animator, this);
  156.  
  157.             m_StartingPosition = transform.position;
  158.             m_StartingFacingLeft = GetFacing() < 0.0f;
  159.         }
  160.  
  161.         void OnTriggerEnter2D(Collider2D other)
  162.         {
  163.             Pushable pushable = other.GetComponent<Pushable>();
  164.             if (pushable != null)
  165.             {
  166.                 m_CurrentPushables.Add(pushable);
  167.             }
  168.         }
  169.  
  170.         void OnTriggerExit2D(Collider2D other)
  171.         {
  172.             Pushable pushable = other.GetComponent<Pushable>();
  173.             if (pushable != null)
  174.             {
  175.                 if (m_CurrentPushables.Contains(pushable))
  176.                     m_CurrentPushables.Remove(pushable);
  177.             }
  178.         }
  179.  
  180.         void Update()
  181.         {
  182.             if (PlayerInput.Instance.Pause.Down)
  183.             {
  184.                 if (!m_InPause)
  185.                 {
  186.                     if (ScreenFader.IsFading)
  187.                         return;
  188.  
  189.                     PlayerInput.Instance.ReleaseControl(false);
  190.                     PlayerInput.Instance.Pause.GainControl();
  191.                     m_InPause = true;
  192.                     Time.timeScale = 0;
  193.                     UnityEngine.SceneManagement.SceneManager.LoadSceneAsync("UIMenus", UnityEngine.SceneManagement.LoadSceneMode.Additive);
  194.                 }
  195.                 else
  196.                 {
  197.                     Unpause();
  198.                 }
  199.             }
  200.         }
  201.  
  202.         void FixedUpdate()
  203.         {
  204.             m_CharacterController2D.Move(m_MoveVector * Time.deltaTime);
  205.             m_Animator.SetFloat(m_HashHorizontalSpeedPara, m_MoveVector.x);
  206.             m_Animator.SetFloat(m_HashVerticalSpeedPara, m_MoveVector.y);
  207.             UpdateBulletSpawnPointPositions();
  208.             UpdateCameraFollowTargetPosition();
  209.         }
  210.  
  211.         public void Unpause()
  212.         {
  213.             //if the timescale is already > 0, we
  214.             if (Time.timeScale > 0)
  215.                 return;
  216.  
  217.             StartCoroutine(UnpauseCoroutine());
  218.         }
  219.  
  220.         protected IEnumerator UnpauseCoroutine()
  221.         {
  222.             Time.timeScale = 1;
  223.             UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync("UIMenus");
  224.             PlayerInput.Instance.GainControl();
  225.             //we have to wait for a fixed update so the pause button state change, otherwise we can get in case were the update
  226.             //of this script happen BEFORE the input is updated, leading to setting the game in pause once again
  227.             yield return new WaitForFixedUpdate();
  228.             yield return new WaitForEndOfFrame();
  229.             m_InPause = false;
  230.         }
  231.  
  232.         // Protected functions.
  233.         protected void UpdateBulletSpawnPointPositions()
  234.         {
  235.             if (rightBulletSpawnPointAnimated)
  236.             {
  237.                 Vector2 leftPosition = facingRightBulletSpawnPoint.localPosition;
  238.                 leftPosition.x *= -1f;
  239.                 facingLeftBulletSpawnPoint.localPosition = leftPosition;
  240.             }
  241.             else
  242.             {
  243.                 Vector2 rightPosition = facingLeftBulletSpawnPoint.localPosition;
  244.                 rightPosition.x *= -1f;
  245.                 facingRightBulletSpawnPoint.localPosition = rightPosition;
  246.             }
  247.         }
  248.  
  249.         protected void UpdateCameraFollowTargetPosition()
  250.         {
  251.             float newLocalPosX;
  252.             float newLocalPosY = 0f;
  253.  
  254.             float desiredLocalPosX = (spriteOriginallyFacesLeft ^ spriteRenderer.flipX ? -1f : 1f) * cameraHorizontalFacingOffset;
  255.             desiredLocalPosX += m_MoveVector.x * cameraHorizontalSpeedOffset;
  256.             if (Mathf.Approximately(m_CamFollowHorizontalSpeed, 0f))
  257.                 newLocalPosX = desiredLocalPosX;
  258.             else
  259.                 newLocalPosX = Mathf.Lerp(cameraFollowTarget.localPosition.x, desiredLocalPosX, m_CamFollowHorizontalSpeed * Time.deltaTime);
  260.  
  261.             bool moveVertically = false;
  262.             if (!Mathf.Approximately(PlayerInput.Instance.Vertical.Value, 0f))
  263.             {
  264.                 m_VerticalCameraOffsetTimer += Time.deltaTime;
  265.  
  266.                 if (m_VerticalCameraOffsetTimer >= verticalCameraOffsetDelay)
  267.                     moveVertically = true;
  268.             }
  269.             else
  270.             {
  271.                 moveVertically = true;
  272.                 m_VerticalCameraOffsetTimer = 0f;
  273.             }
  274.  
  275.             if (moveVertically)
  276.             {
  277.                 float desiredLocalPosY = PlayerInput.Instance.Vertical.Value * cameraVerticalInputOffset;
  278.                 if (Mathf.Approximately(m_CamFollowVerticalSpeed, 0f))
  279.                     newLocalPosY = desiredLocalPosY;
  280.                 else
  281.                     newLocalPosY = Mathf.MoveTowards(cameraFollowTarget.localPosition.y, desiredLocalPosY, m_CamFollowVerticalSpeed * Time.deltaTime);
  282.             }
  283.  
  284.             cameraFollowTarget.localPosition = new Vector2(newLocalPosX, newLocalPosY);
  285.         }
  286.  
  287.         protected IEnumerator Flicker()
  288.         {
  289.             float timer = 0f;
  290.  
  291.             while (timer < damageable.invulnerabilityDuration)
  292.             {
  293.                 spriteRenderer.enabled = !spriteRenderer.enabled;
  294.                 yield return m_FlickeringWait;
  295.                 timer += flickeringDuration;
  296.             }
  297.  
  298.             spriteRenderer.enabled = true;
  299.         }
  300.  
  301.         protected IEnumerator Shoot()
  302.         {
  303.             while (PlayerInput.Instance.RangedAttack.Held)
  304.             {
  305.                 if (Time.time >= m_NextShotTime)
  306.                 {
  307.                     SpawnBullet();
  308.                     m_NextShotTime = Time.time + m_ShotSpawnGap;
  309.                 }
  310.                 yield return null;
  311.             }
  312.         }
  313.  
  314.         protected void SpawnBullet()
  315.         {
  316.             //we check if there is a wall between the player and the bullet spawn position, if there is, we don't spawn a bullet
  317.             //otherwise, the player can "shoot throught wall" because the arm extend to the other side of the wall
  318.             Vector2 testPosition = transform.position;
  319.             testPosition.y = m_CurrentBulletSpawnPoint.position.y;
  320.             Vector2 direction = (Vector2)m_CurrentBulletSpawnPoint.position - testPosition;
  321.             float distance = direction.magnitude;
  322.             direction.Normalize();
  323.  
  324.             RaycastHit2D[] results = new RaycastHit2D[12];
  325.             if (Physics2D.Raycast(testPosition, direction, m_CharacterController2D.ContactFilter, results, distance) > 0)
  326.                 return;
  327.  
  328.             BulletObject bullet = bulletPool.Pop(m_CurrentBulletSpawnPoint.position);
  329.             bool facingLeft = m_CurrentBulletSpawnPoint == facingLeftBulletSpawnPoint;
  330.             bullet.rigidbody2D.velocity = new Vector2(facingLeft ? -bulletSpeed : bulletSpeed, 0f);
  331.             bullet.spriteRenderer.flipX = facingLeft ^ bullet.bullet.spriteOriginallyFacesLeft;
  332.  
  333.             rangedAttackAudioPlayer.PlayRandomSound();
  334.         }
  335.  
  336.         // Public functions - called mostly by StateMachineBehaviours in the character's Animator Controller but also by Events.
  337.         public void SetMoveVector(Vector2 newMoveVector)
  338.         {
  339.             m_MoveVector = newMoveVector;
  340.         }
  341.  
  342.         public void SetHorizontalMovement(float newHorizontalMovement)
  343.         {
  344.             m_MoveVector.x = newHorizontalMovement;
  345.         }
  346.  
  347.         public void SetVerticalMovement(float newVerticalMovement)
  348.         {
  349.             m_MoveVector.y = newVerticalMovement;
  350.         }
  351.  
  352.         public void IncrementMovement(Vector2 additionalMovement)
  353.         {
  354.             m_MoveVector += additionalMovement;
  355.         }
  356.  
  357.         public void IncrementHorizontalMovement(float additionalHorizontalMovement)
  358.         {
  359.             m_MoveVector.x += additionalHorizontalMovement;
  360.         }
  361.  
  362.         public void IncrementVerticalMovement(float additionalVerticalMovement)
  363.         {
  364.             m_MoveVector.y += additionalVerticalMovement;
  365.         }
  366.  
  367.         public void GroundedVerticalMovement()
  368.         {
  369.             m_MoveVector.y -= gravity * Time.deltaTime;
  370.  
  371.             if (m_MoveVector.y < -gravity * Time.deltaTime * k_GroundedStickingVelocityMultiplier)
  372.             {
  373.                 m_MoveVector.y = -gravity * Time.deltaTime * k_GroundedStickingVelocityMultiplier;
  374.             }
  375.         }
  376.  
  377.         public Vector2 GetMoveVector()
  378.         {
  379.             return m_MoveVector;
  380.         }
  381.  
  382.         public bool IsFalling()
  383.         {
  384.             return m_MoveVector.y < 0f && !m_Animator.GetBool(m_HashGroundedPara);
  385.         }
  386.  
  387.         public void UpdateFacing()
  388.         {
  389.             bool faceLeft = PlayerInput.Instance.Horizontal.Value < 0f;
  390.             bool faceRight = PlayerInput.Instance.Horizontal.Value > 0f;
  391.  
  392.             if (faceLeft)
  393.             {
  394.                 spriteRenderer.flipX = !spriteOriginallyFacesLeft;
  395.                 m_CurrentBulletSpawnPoint = facingLeftBulletSpawnPoint;
  396.             }
  397.             else if (faceRight)
  398.             {
  399.                 spriteRenderer.flipX = spriteOriginallyFacesLeft;
  400.                 m_CurrentBulletSpawnPoint = facingRightBulletSpawnPoint;
  401.             }
  402.         }
  403.  
  404.         public void UpdateFacing(bool faceLeft)
  405.         {
  406.             if (faceLeft)
  407.             {
  408.                 spriteRenderer.flipX = !spriteOriginallyFacesLeft;
  409.                 m_CurrentBulletSpawnPoint = facingLeftBulletSpawnPoint;
  410.             }
  411.             else
  412.             {
  413.                 spriteRenderer.flipX = spriteOriginallyFacesLeft;
  414.                 m_CurrentBulletSpawnPoint = facingRightBulletSpawnPoint;
  415.             }
  416.         }
  417.  
  418.         public float GetFacing()
  419.         {
  420.             return spriteRenderer.flipX != spriteOriginallyFacesLeft ? -1f : 1f;
  421.         }
  422.  
  423.         public void GroundedHorizontalMovement(bool useInput, float speedScale = 1f)
  424.         {
  425.             float desiredSpeed = useInput ? PlayerInput.Instance.Horizontal.Value * maxSpeed * speedScale : 0f;
  426.             float acceleration = useInput && PlayerInput.Instance.Horizontal.ReceivingInput ? groundAcceleration : groundDeceleration;
  427.             m_MoveVector.x = Mathf.MoveTowards(m_MoveVector.x, desiredSpeed, acceleration * Time.deltaTime);
  428.         }
  429.  
  430.         public void CheckForCrouching()
  431.         {
  432.             m_Animator.SetBool(m_HashCrouchingPara, PlayerInput.Instance.Vertical.Value < 0f);
  433.         }
  434.  
  435.         public bool CheckForGrounded()
  436.         {
  437.             bool wasGrounded = m_Animator.GetBool(m_HashGroundedPara);
  438.             bool grounded = m_CharacterController2D.IsGrounded;
  439.  
  440.             if (grounded)
  441.             {
  442.                 FindCurrentSurface();
  443.  
  444.                 if (!wasGrounded && m_MoveVector.y < -1.0f)
  445.                 {//only play the landing sound if falling "fast" enough (avoid small bump playing the landing sound)
  446.                     landingAudioPlayer.PlayRandomSound(m_CurrentSurface);
  447.                 }
  448.             }
  449.             else
  450.                 m_CurrentSurface = null;
  451.  
  452.             m_Animator.SetBool(m_HashGroundedPara, grounded);
  453.  
  454.             return grounded;
  455.         }
  456.  
  457.         public void FindCurrentSurface()
  458.         {
  459.             Collider2D groundCollider = m_CharacterController2D.GroundColliders[0];
  460.  
  461.             if (groundCollider == null)
  462.                 groundCollider = m_CharacterController2D.GroundColliders[1];
  463.  
  464.             if (groundCollider == null)
  465.                 return;
  466.  
  467.             TileBase b = PhysicsHelper.FindTileForOverride(groundCollider, transform.position, Vector2.down);
  468.             if (b != null)
  469.             {
  470.                 m_CurrentSurface = b;
  471.             }
  472.         }
  473.  
  474.         public void CheckForPushing()
  475.         {
  476.             bool pushableOnCorrectSide = false;
  477.             Pushable previousPushable = m_CurrentPushable;
  478.  
  479.             m_CurrentPushable = null;
  480.  
  481.             if (m_CurrentPushables.Count > 0)
  482.             {
  483.                 bool movingRight = PlayerInput.Instance.Horizontal.Value > float.Epsilon;
  484.                 bool movingLeft = PlayerInput.Instance.Horizontal.Value < -float.Epsilon;
  485.  
  486.                 for (int i = 0; i < m_CurrentPushables.Count; i++)
  487.                 {
  488.                     float pushablePosX = m_CurrentPushables[i].pushablePosition.position.x;
  489.                     float playerPosX = m_Transform.position.x;
  490.                     if (pushablePosX < playerPosX && movingLeft || pushablePosX > playerPosX && movingRight)
  491.                     {
  492.                         pushableOnCorrectSide = true;
  493.                         m_CurrentPushable = m_CurrentPushables[i];
  494.                         break;
  495.                     }
  496.                 }
  497.  
  498.                 if (pushableOnCorrectSide)
  499.                 {
  500.                     Vector2 moveToPosition = movingRight ? m_CurrentPushable.playerPushingRightPosition.position : m_CurrentPushable.playerPushingLeftPosition.position;
  501.                     moveToPosition.y = m_CharacterController2D.Rigidbody2D.position.y;
  502.                     m_CharacterController2D.Teleport(moveToPosition);
  503.                 }
  504.             }
  505.  
  506.             if(previousPushable != null && m_CurrentPushable != previousPushable)
  507.             {//we changed pushable (or don't have one anymore), stop the old one sound
  508.                 previousPushable.EndPushing();
  509.             }
  510.  
  511.             m_Animator.SetBool(m_HashPushingPara, pushableOnCorrectSide);
  512.         }
  513.  
  514.         public void MovePushable()
  515.         {
  516.             //we don't push ungrounded pushable, avoid pushing floating pushable or falling pushable.
  517.             if (m_CurrentPushable && m_CurrentPushable.Grounded)
  518.                 m_CurrentPushable.Move(m_MoveVector * Time.deltaTime);
  519.         }
  520.  
  521.         public void StartPushing()
  522.         {
  523.             if (m_CurrentPushable)
  524.                 m_CurrentPushable.StartPushing();
  525.         }
  526.  
  527.         public void StopPushing()
  528.         {
  529.             if(m_CurrentPushable)
  530.                 m_CurrentPushable.EndPushing();
  531.         }
  532.  
  533.         public void UpdateJump()
  534.         {
  535.             if (!PlayerInput.Instance.Jump.Held && m_MoveVector.y > 0.0f)
  536.             {
  537.                 m_MoveVector.y -= jumpAbortSpeedReduction * Time.deltaTime;
  538.             }
  539.         }
  540.  
  541.         public void AirborneHorizontalMovement()
  542.         {
  543.             float desiredSpeed = PlayerInput.Instance.Horizontal.Value * maxSpeed;
  544.  
  545.             float acceleration;
  546.  
  547.             if (PlayerInput.Instance.Horizontal.ReceivingInput)
  548.                 acceleration = groundAcceleration * airborneAccelProportion;
  549.             else
  550.                 acceleration = groundDeceleration * airborneDecelProportion;
  551.  
  552.             m_MoveVector.x = Mathf.MoveTowards(m_MoveVector.x, desiredSpeed, acceleration * Time.deltaTime);
  553.         }
  554.  
  555.         public void AirborneVerticalMovement()
  556.         {
  557.             if (Mathf.Approximately(m_MoveVector.y, 0f) || m_CharacterController2D.IsCeilinged && m_MoveVector.y > 0f)
  558.             {
  559.                 m_MoveVector.y = 0f;
  560.             }
  561.             m_MoveVector.y -= gravity * Time.deltaTime;
  562.         }
  563.  
  564.         public bool CheckForJumpInput()
  565.         {
  566.             return PlayerInput.Instance.Jump.Down;
  567.         }
  568.  
  569.         public bool CheckForFallInput()
  570.         {
  571.             return PlayerInput.Instance.Vertical.Value < -float.Epsilon && PlayerInput.Instance.Jump.Down;
  572.         }
  573.  
  574.         public bool MakePlatformFallthrough()
  575.         {
  576.             int colliderCount = 0;
  577.             int fallthroughColliderCount = 0;
  578.        
  579.             for (int i = 0; i < m_CharacterController2D.GroundColliders.Length; i++)
  580.             {
  581.                 Collider2D col = m_CharacterController2D.GroundColliders[i];
  582.                 if(col == null)
  583.                     continue;
  584.  
  585.                 colliderCount++;
  586.  
  587.                 if (PhysicsHelper.ColliderHasPlatformEffector (col))
  588.                     fallthroughColliderCount++;
  589.             }
  590.  
  591.             if (fallthroughColliderCount == colliderCount)
  592.             {
  593.                 for (int i = 0; i < m_CharacterController2D.GroundColliders.Length; i++)
  594.                 {
  595.                     Collider2D col = m_CharacterController2D.GroundColliders[i];
  596.                     if (col == null)
  597.                         continue;
  598.  
  599.                     PlatformEffector2D effector;
  600.                     PhysicsHelper.TryGetPlatformEffector (col, out effector);
  601.                     FallthroughReseter reseter = effector.gameObject.AddComponent<FallthroughReseter>();
  602.                     reseter.StartFall(effector);
  603.                     //set invincible for half a second when falling through a platform, as it will make the player "standup"
  604.                     StartCoroutine(FallThroughtInvincibility());
  605.                 }
  606.             }
  607.  
  608.             return fallthroughColliderCount == colliderCount;
  609.         }
  610.  
  611.         IEnumerator FallThroughtInvincibility()
  612.         {
  613.             damageable.EnableInvulnerability(true);
  614.             yield return new WaitForSeconds(0.5f);
  615.             damageable.DisableInvulnerability();
  616.         }
  617.  
  618.         public bool CheckForHoldingGun()
  619.         {
  620.             bool holdingGun = false;
  621.  
  622.             if (PlayerInput.Instance.RangedAttack.Held)
  623.             {
  624.                 holdingGun = true;
  625.                 m_Animator.SetBool(m_HashHoldingGunPara, true);
  626.                 m_HoldingGunTimeRemaining = holdingGunTimeoutDuration;
  627.             }
  628.             else
  629.             {
  630.                 m_HoldingGunTimeRemaining -= Time.deltaTime;
  631.  
  632.                 if (m_HoldingGunTimeRemaining <= 0f)
  633.                 {
  634.                     m_Animator.SetBool(m_HashHoldingGunPara, false);
  635.                 }
  636.             }
  637.  
  638.             return holdingGun;
  639.         }
  640.  
  641.         public void CheckAndFireGun()
  642.         {
  643.             if (PlayerInput.Instance.RangedAttack.Held && m_Animator.GetBool(m_HashHoldingGunPara))
  644.             {
  645.                 if (m_ShootingCoroutine == null)
  646.                     m_ShootingCoroutine = StartCoroutine(Shoot());
  647.             }
  648.  
  649.             if ((PlayerInput.Instance.RangedAttack.Up || !m_Animator.GetBool(m_HashHoldingGunPara)) && m_ShootingCoroutine != null)
  650.             {
  651.                 StopCoroutine(m_ShootingCoroutine);
  652.                 m_ShootingCoroutine = null;
  653.             }
  654.         }
  655.  
  656.         public void ForceNotHoldingGun()
  657.         {
  658.             m_Animator.SetBool(m_HashHoldingGunPara, false);
  659.         }
  660.  
  661.         public void EnableInvulnerability()
  662.         {
  663.             damageable.EnableInvulnerability();
  664.         }
  665.  
  666.         public void DisableInvulnerability()
  667.         {
  668.             damageable.DisableInvulnerability();
  669.         }
  670.  
  671.         public Vector2 GetHurtDirection()
  672.         {
  673.             Vector2 damageDirection = damageable.GetDamageDirection();
  674.  
  675.             if (damageDirection.y < 0f)
  676.                 return new Vector2(Mathf.Sign(damageDirection.x), 0f);
  677.  
  678.             float y = Mathf.Abs(damageDirection.x) * m_TanHurtJumpAngle;
  679.  
  680.             return new Vector2(damageDirection.x, y).normalized;
  681.         }
  682.  
  683.         public void OnHurt(Damager damager, Damageable damageable)
  684.         {
  685.             //if the player don't have control, we shouldn't be able to be hurt as this wouldn't be fair
  686.             if (!PlayerInput.Instance.HaveControl)
  687.                 return;
  688.  
  689.             UpdateFacing(damageable.GetDamageDirection().x > 0f);
  690.             damageable.EnableInvulnerability();
  691.  
  692.             m_Animator.SetTrigger(m_HashHurtPara);
  693.  
  694.             //we only force respawn if helath > 0, otherwise both forceRespawn & Death trigger are set in the animator, messing with each other.
  695.             if(damageable.CurrentHealth > 0 && damager.forceRespawn)
  696.                 m_Animator.SetTrigger(m_HashForcedRespawnPara);
  697.  
  698.             m_Animator.SetBool(m_HashGroundedPara, false);
  699.             hurtAudioPlayer.PlayRandomSound();
  700.  
  701.             //if the health is < 0, mean die callback will take care of respawn
  702.             if(damager.forceRespawn && damageable.CurrentHealth > 0)
  703.             {
  704.                 StartCoroutine(DieRespawnCoroutine(false, true));
  705.             }
  706.         }
  707.  
  708.         public void OnDie()
  709.         {
  710.             m_Animator.SetTrigger(m_HashDeadPara);
  711.  
  712.             StartCoroutine(DieRespawnCoroutine(true, false));
  713.         }
  714.  
  715.         IEnumerator DieRespawnCoroutine(bool resetHealth, bool useCheckPoint)
  716.         {
  717.             PlayerInput.Instance.ReleaseControl(true);
  718.             yield return new WaitForSeconds(1.0f); //wait one second before respawing
  719.             yield return StartCoroutine(ScreenFader.FadeSceneOut(useCheckPoint ? ScreenFader.FadeType.Black : ScreenFader.FadeType.GameOver));
  720.             if(!useCheckPoint)
  721.                 yield return new WaitForSeconds (2f);
  722.             Respawn(resetHealth, useCheckPoint);
  723.             yield return new WaitForEndOfFrame();
  724.             yield return StartCoroutine(ScreenFader.FadeSceneIn());
  725.             PlayerInput.Instance.GainControl();
  726.         }
  727.  
  728.         public void StartFlickering()
  729.         {
  730.             m_FlickerCoroutine = StartCoroutine(Flicker());
  731.         }
  732.  
  733.         public void StopFlickering()
  734.         {
  735.             StopCoroutine(m_FlickerCoroutine);
  736.             spriteRenderer.enabled = true;
  737.         }
  738.  
  739.         public bool CheckForMeleeAttackInput()
  740.         {
  741.             return PlayerInput.Instance.MeleeAttack.Down;
  742.         }
  743.  
  744.         public void MeleeAttack()
  745.         {
  746.             m_Animator.SetTrigger(m_HashMeleeAttackPara);
  747.         }
  748.  
  749.         public void EnableMeleeAttack()
  750.         {
  751.             meleeDamager.EnableDamage();
  752.             meleeDamager.disableDamageAfterHit = true;
  753.             meleeAttackAudioPlayer.PlayRandomSound();
  754.         }
  755.  
  756.         public void DisableMeleeAttack()
  757.         {
  758.             meleeDamager.DisableDamage();
  759.         }
  760.  
  761.         public void TeleportToColliderBottom()
  762.         {
  763.             Vector2 colliderBottom = m_CharacterController2D.Rigidbody2D.position + m_Capsule.offset + Vector2.down * m_Capsule.size.y * 0.5f;
  764.             m_CharacterController2D.Teleport(colliderBottom);
  765.         }
  766.  
  767.         public void PlayFootstep()
  768.         {
  769.             footstepAudioPlayer.PlayRandomSound(m_CurrentSurface);
  770.             var footstepPosition = transform.position;
  771.             footstepPosition.z -= 1;
  772.             VFXController.Instance.Trigger("DustPuff", footstepPosition, 0, false, null, m_CurrentSurface);
  773.         }
  774.  
  775.         public void Respawn(bool resetHealth, bool useCheckpoint)
  776.         {
  777.             if (resetHealth)
  778.                 damageable.SetHealth(damageable.startingHealth);
  779.  
  780.             //we reset the hurt trigger, as we don't want the player to go back to hurt animation once respawned
  781.             m_Animator.ResetTrigger(m_HashHurtPara);
  782.             if (m_FlickerCoroutine != null)
  783.             {//we stop flcikering for the same reason
  784.                 StopFlickering();
  785.             }
  786.  
  787.             m_Animator.SetTrigger(m_HashRespawnPara);
  788.  
  789.             if (useCheckpoint && m_LastCheckpoint != null)
  790.             {
  791.                 UpdateFacing(m_LastCheckpoint.respawnFacingLeft);
  792.                 GameObjectTeleporter.Teleport(gameObject, m_LastCheckpoint.transform.position);
  793.             }
  794.             else
  795.             {
  796.                 UpdateFacing(m_StartingFacingLeft);
  797.                 GameObjectTeleporter.Teleport(gameObject, m_StartingPosition);
  798.             }
  799.         }
  800.  
  801.         public void SetChekpoint(Checkpoint checkpoint)
  802.         {
  803.             m_LastCheckpoint = checkpoint;
  804.         }
  805.  
  806.         //This is called by the inventory controller on key grab, so it can update the Key UI.
  807.         public void KeyInventoryEvent()
  808.         {
  809.             if (KeyUI.Instance != null) KeyUI.Instance.ChangeKeyUI(m_InventoryController);
  810.         }
  811.     }
  812. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement