Hi there! First question on the forums!
Im currently making a game in which waves of enemies are sent to the player.
My most recent enemy has a more complex AI script then all of my other enemies, which work completely fine when instantiated.
my Reaper enemy has 3 behaviors: chase, aim, charge.
When placed in the scene the 3 behaviors act normally, however when I instantiate Reapers, then seem to be stuck on the chase behavior
Any Help would be greatly appreciated! <3
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReaperMovement : MonoBehaviour
{
[Header("references")]
public GameObject target;
public Rigidbody2D rb;
private Vector3 CursorPosition;
[Header("Variables")]
public float maxSpeed;
public float accelerationSpeed;
public float Damage;
public float ChargeForce;
//Aiming flicker
private Color DefaultColour;
public SpriteRenderer sprite;
private void Start()
{
target = GameObject.FindGameObjectWithTag("Player");
DefaultColour = sprite.GetComponent<SpriteRenderer>().color;
StartCoroutine(Think());
}
private void Update()
{
}
//Deal damage to player
private void OnCollisionEnter2D(Collision2D collider)
{
if (collider.gameObject.CompareTag("Player") && collider.gameObject.name == "Player")
{
//Debug.Log(collider.transform.name);
Health enemy = collider.transform.GetComponent<Health>();
if (enemy != null)
{
enemy.TakeDamage(Damage);
}
}
}
public enum AIState { Chasing, Aiming, Charging};
public AIState aIState = AIState.Chasing;
IEnumerator Think()
{
while (true)
{
switch (aIState)
{
case AIState.Chasing:
Vector3 direction = target.transform.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
float distanceToPlayer = Vector3.Distance(target.transform.position, transform.position);
if (distanceToPlayer > 0.01f)
{
rb.AddForce(transform.up * accelerationSpeed, ForceMode2D.Force);
}
if (distanceToPlayer <= 6f)
{
aIState = AIState.Aiming;
Debug.Log("IN RANGE");
}
break;
case AIState.Aiming:
int i = 5;
while (i > 0)
{
sprite.color = new Color(1f, 1f, 1f, 1f);
yield return new WaitForSeconds(0.1f);
sprite.color = DefaultColour;
yield return new WaitForSeconds(0.1f);
direction = target.transform.position - transform.position;
angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle - 90, Vector3.forward);
i--;
yield return new WaitForSeconds(0.25f);
}
aIState = AIState.Charging;
break;
case AIState.Charging:
rb.AddForce(transform.up * ChargeForce, ForceMode2D.Force);
yield return new WaitForSeconds(0.75f);
aIState = AIState.Chasing;
break;
default:
break;
}
yield return new WaitForSeconds(0.3f);
}
}
}