Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- public class EnemyAI : MonoBehaviour {
- // Debugging
- public bool loggingEnabled = false;
- // A.I.
- public string playerTag = "Player";
- private GameObject player;
- // Stats
- public float acceleration = 10;
- public float jumpForce = 200;
- public float maxSpeed = 10;
- public float damage = 1;
- // Physics
- private Vector2 moveDir = Vector2.zero;
- // By doing this, isGrounded becomes read-only outside of this script
- [HideInInspector] public bool isGrounded { get; private set; }
- // Initialization
- void Start ()
- {
- isGrounded = false;
- player = GameObject.FindWithTag ("Player");
- }
- void FixedUpdate ()
- {
- moveDir = Vector2.zero;
- // Get player position in local space
- Vector2 playerPos = transform.InverseTransformPoint (player.transform.position);
- // Determine what direction to go in
- if (playerPos.x > 0.5f)
- moveDir.x += acceleration;
- else if (playerPos.x < -0.5f)
- moveDir.x -= acceleration;
- if (playerPos.y > 0.2f && isGrounded)
- moveDir.y += jumpForce;
- rigidbody2D.AddForce (moveDir);
- Vector2 velocity = rigidbody2D.velocity;
- velocity.x = Mathf.Clamp (velocity.x, -maxSpeed, maxSpeed);
- rigidbody2D.velocity = velocity;
- if (loggingEnabled)
- Debug.Log (isGrounded + " " + playerPos + " | " + transform.position + " | " + moveDir);
- }
- void OnTriggerStay2D (Collider2D other)
- {
- if (other.tag == "Ground" && isGrounded == false)
- isGrounded = true;
- else if (other.tag == "Player")
- other.GetComponent<HealthLogic> ().Damage (damage);
- }
- void OnTriggerExit2D (Collider2D other)
- {
- if (other.tag == "Ground")
- isGrounded = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement