Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.AI;
- [RequireComponent(typeof(NavMeshAgent))]
- public class Enemy : LivingEntity {
- public enum state { idle, chase, attack};
- private state currentState;
- private NavMeshAgent pathFinder;
- private Transform target;
- private float attackThreshhold = .5f;
- private float timeBetweenAttacks = 1;
- private float attackTimer;
- private float myCollisionRadius;
- private float targetCollisionRadius;
- // Start is called before the first frame update
- protected override void Start() {
- base.Start();
- currentState = state.chase;
- pathFinder = GetComponent<NavMeshAgent>();
- target = GameObject.FindGameObjectWithTag("Player").transform;
- myCollisionRadius = GetComponent<CapsuleCollider>().radius;
- targetCollisionRadius = GetComponent<CapsuleCollider>().radius;
- StartCoroutine(updatePath());
- }
- // Update is called once per frame
- void Update() {
- if(Time.time > attackTimer)
- {
- float sqrDistanceToTarget = (target.position - transform.position).sqrMagnitude;
- if (sqrDistanceToTarget < Mathf.Pow(attackThreshhold + myCollisionRadius + targetCollisionRadius, 2)) {
- attackTimer = Time.time + timeBetweenAttacks;
- StartCoroutine(attack());
- }
- }
- }
- IEnumerator attack() {
- currentState = state.attack;
- pathFinder.enabled = false;
- Vector3 origin = transform.position;
- Vector3 attackPos = target.position;
- float percent = 0;
- float attackSpeed = 3;
- while(percent <= 1) {
- percent += Time.deltaTime * attackSpeed;
- float interpolation = (-Mathf.Pow(percent, 2) + percent) * 4;
- transform.position = Vector3.Lerp(origin, attackPos, interpolation);
- yield return null;
- }
- currentState = state.chase;
- pathFinder.enabled = true;
- }
- IEnumerator updatePath() {
- float refreshRate = .25f;
- while(target != null) {
- if(currentState == state.chase) {
- Vector3 dirToTarget = (target.position - transform.position).normalized;
- Vector3 targetPosition = target.position - dirToTarget * (myCollisionRadius + targetCollisionRadius/2);
- if (!dead) pathFinder.SetDestination(targetPosition);
- yield return new WaitForSeconds(refreshRate);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement