Advertisement
Guest User

EnemyAI.cs

a guest
Aug 22nd, 2014
463
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class EnemyAI : MonoBehaviour {
  5.  
  6.     // Debugging
  7.     public bool loggingEnabled = false;
  8.  
  9.     // A.I.
  10.     public string playerTag = "Player";
  11.  
  12.     private GameObject player;
  13.  
  14.     // Stats
  15.     public float acceleration = 10;
  16.     public float jumpForce = 200;
  17.     public float maxSpeed = 10;
  18.  
  19.     public float damage = 1;
  20.  
  21.     // Physics
  22.     private Vector2 moveDir = Vector2.zero;
  23.     // By doing this, isGrounded becomes read-only outside of this script
  24.     [HideInInspector] public bool isGrounded { get; private set; }
  25.  
  26.     // Initialization
  27.     void Start ()
  28.     {
  29.         isGrounded = false;
  30.  
  31.         player = GameObject.FindWithTag ("Player");
  32.     }
  33.  
  34.     void FixedUpdate ()
  35.     {
  36.         moveDir = Vector2.zero;
  37.  
  38.         // Get player position in local space
  39.         Vector2 playerPos = transform.InverseTransformPoint (player.transform.position);
  40.  
  41.         // Determine what direction to go in
  42.         if (playerPos.x > 0.5f)
  43.             moveDir.x += acceleration;
  44.         else if (playerPos.x < -0.5f)
  45.             moveDir.x -= acceleration;
  46.  
  47.         if (playerPos.y > 0.2f && isGrounded)
  48.             moveDir.y += jumpForce;
  49.  
  50.         rigidbody2D.AddForce (moveDir);
  51.  
  52.         Vector2 velocity = rigidbody2D.velocity;
  53.         velocity.x = Mathf.Clamp (velocity.x, -maxSpeed, maxSpeed);
  54.         rigidbody2D.velocity = velocity;
  55.  
  56.         if (loggingEnabled)
  57.             Debug.Log (isGrounded + " " + playerPos + " | " + transform.position + " | " + moveDir);
  58.     }
  59.  
  60.     void OnTriggerStay2D (Collider2D other)
  61.     {
  62.         if (other.tag == "Ground" && isGrounded == false)
  63.             isGrounded = true;
  64.         else if (other.tag == "Player")
  65.             other.GetComponent<HealthLogic> ().Damage (damage);
  66.     }
  67.  
  68.     void OnTriggerExit2D (Collider2D other)
  69.     {
  70.         if (other.tag == "Ground")
  71.             isGrounded = false;
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement