73 lines
1.8 KiB
C#
73 lines
1.8 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class EnemyAI : MonoBehaviour
|
|
{
|
|
public Transform player;
|
|
public float detectRange = 10f;
|
|
public float moveSpeed = 3f;
|
|
public float rotateSpeed = 50f;
|
|
public bool isAttackReady;
|
|
|
|
public Node behaviorTreeRoot;
|
|
|
|
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
|
void Start()
|
|
{
|
|
InitBehaviorTree();
|
|
}
|
|
|
|
// Update is called once per frame
|
|
void Update()
|
|
{
|
|
if (behaviorTreeRoot != null)
|
|
{
|
|
behaviorTreeRoot.Evaluate();
|
|
}
|
|
}
|
|
|
|
void InitBehaviorTree()
|
|
{
|
|
var chaseSequence = new Sequence(new List<Node>
|
|
{
|
|
new TaskNode(CheckCanSeePlayer),
|
|
new TaskNode(ActionMoveToPlayer)
|
|
});
|
|
var rotationScanNode = new TaskNode(ActionRotationScan);
|
|
behaviorTreeRoot = new Selector(new List<Node>
|
|
{
|
|
chaseSequence,
|
|
rotationScanNode
|
|
});
|
|
}
|
|
|
|
private NodeState ActionRotationScan()
|
|
{
|
|
Debug.Log("ActionRotationScan");
|
|
transform.Rotate(Vector3.up, rotateSpeed * Time.deltaTime);
|
|
return NodeState.Running;
|
|
}
|
|
|
|
private NodeState ActionMoveToPlayer()
|
|
{
|
|
Debug.Log($"Moving to Player");
|
|
Vector3 dir = (player.position - transform.position).normalized;
|
|
transform.position += dir * moveSpeed * Time.deltaTime;
|
|
return NodeState.Running;
|
|
}
|
|
|
|
private NodeState CheckCanSeePlayer()
|
|
{
|
|
if (player == null)
|
|
{
|
|
return NodeState.Failure;
|
|
}
|
|
float distance = Vector3.Distance(transform.position,player.position);
|
|
if (distance < detectRange)
|
|
{
|
|
Debug.Log($"Player detected!");
|
|
return NodeState.Success;
|
|
}
|
|
return NodeState.Failure;
|
|
}
|
|
} |