using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBehavior : MonoBehaviour {
[SerializeField] Transform playerPosition;
[SerializeField] float speedMovement;
[SerializeField] float stopDistance;
[SerializeField] float waitDuration;
Transform enemyAIPosition;
State state;
enum State
{
Chase,
MoveAround,
}
void Start()
{
enemyAIPosition = this.transform;
CheckUpdateState();
}
void LateUpdate()
{
flipCharacter();
if (state == State.Chase)
{
Chasing();
}
}
void Chasing()
{
Vector3 destinationToPlayer = new Vector3((playerPosition.localPosition.x - enemyAIPosition.localPosition.x), enemyAIPosition.localPosition.y , 0);
destinationToPlayer = Vector3.Normalize(destinationToPlayer);
enemyAIPosition.localPosition += destinationToPlayer * speedMovement * Time.deltaTime;
CheckUpdateState();
}
void CheckUpdateState()
{
if(Vector3.Distance(playerPosition.localPosition, enemyAIPosition.localPosition) > stopDistance)
{
ChangeState(State.Chase);
}
else if(Vector3.Distance(playerPosition.localPosition, enemyAIPosition.localPosition) <= stopDistance)
{
ChangeState(State.MoveAround);
}
}
IEnumerator MoveAroundPlayer()
{
yield return new WaitForSeconds(waitDuration);
Shooting();
Vector3 checkPosition;
if(playerPosition.localPosition.x > enemyAIPosition.localPosition.x)
{
checkPosition = playerPosition.localPosition + new Vector3(stopDistance, 0, 0);
}
else
{
checkPosition = playerPosition.localPosition + new Vector3(-stopDistance, 0, 0);
}
while(Vector3.Distance(checkPosition,enemyAIPosition.localPosition) > 0.2)
{
CheckUpdateState();
Vector3 directToDestination = checkPosition - enemyAIPosition.localPosition;
directToDestination = Vector3.Normalize(directToDestination);
enemyAIPosition.localPosition += directToDestination * speedMovement * Time.deltaTime;
if(state != State.MoveAround)
{
yield break;
}
yield return null;
}
}
void flipCharacter()
{
if(playerPosition.localPosition.x > enemyAIPosition.localPosition.x)
{
this.transform.localScale = new Vector3(1, 1, 1);
}
else
{
this.transform.localScale = new Vector3(1, 1, -1);
}
}
void Shooting()
{
print("Shooting");
}
void ChangeState(State newState)
{
if(state != newState)
{
state = newState;
if (Vector3.Distance(enemyAIPosition.localPosition, playerPosition.localPosition) <= stopDistance)
{
StartCoroutine(MoveAroundPlayer());
}
}
}
}
This script for making enemy AI movement
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.