Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class EnemyMovementController : MonoBehaviour {
  5.  
  6. public float enemySpeed;
  7.  
  8. Animator enemyAnimator;
  9.  
  10. // Direction enemy is facing
  11. public GameObject enemyGraphic;
  12. bool canFlip = true;
  13. bool facingRight = false;
  14. float flipTime = 5f;
  15. float nextFlipChance = 0f;
  16.  
  17. // When enemy is attacking
  18. public float chargeTime;
  19. float startChargeTime;
  20. bool charging;
  21. Rigidbody2D enemyRB;
  22.  
  23. // Use this for initialization
  24. void Start() {
  25. enemyAnimator = GetComponentInChildren<Animator>();
  26. enemyRB = GetComponent<Rigidbody2D>();
  27. }
  28.  
  29. // Update is called once per frame
  30. void Update() {
  31. if (Time.time > nextFlipChance)
  32. {
  33. if (Random.Range(0, 10) >= 5) flipFacing();
  34. nextFlipChance = Time.time + flipTime;
  35. }
  36. }
  37.  
  38. void OnTriggerEnter2D(Collider2D other)
  39. {
  40. if (other.tag == "Player")
  41. {
  42. if (facingRight && other.transform.position.x < transform.position.x)
  43. {
  44. flipFacing();
  45.  
  46. }
  47. else if (!facingRight && other.transform.position.x > transform.position.x)
  48. {
  49. flipFacing();
  50. }
  51. canFlip = false;
  52. charging = true;
  53. startChargeTime = Time.time + chargeTime;
  54.  
  55. }
  56. }
  57.  
  58. void OnTriggerStay2D(Collider2D other)
  59. {
  60. if(other.tag == "Player")
  61. {
  62. if(startChargeTime < Time.time)
  63. {
  64. if (!facingRight) enemyRB.AddForce(new Vector2(-1, 0) * enemySpeed);
  65. else enemyRB.AddForce(new Vector2(1, 0) * enemySpeed);
  66. enemyAnimator.SetBool("isCharging", charging);
  67. }
  68. }
  69. }
  70.  
  71. void OnTriggerExit2D(Collider2D other)
  72. {
  73. if (other.tag == "Player")
  74. {
  75. canFlip = true;
  76. charging = false;
  77. enemyRB.velocity = new Vector2(0f, 0f);
  78. enemyAnimator.SetBool("isCharging", charging);
  79. }
  80. }
  81.  
  82.  
  83. void flipFacing()
  84. {
  85. if (!canFlip) return;
  86. float facingX = enemyGraphic.transform.localScale.x;
  87. facingX *= -1f;
  88. facingRight = !facingRight;
  89.  
  90. }
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement