- Home /
Question by
CJWILLIAMS3D · Jun 15, 2016 at 06:16 AM ·
aienemiestargetting
AI Target Finding Optimization
I currently have AI that determines who is closest between the two players in COOP, but having 6+ enemies on screen brings the game to an absolute crawl suddenly.
I've tried multiple ways to optimize and slow this process down, and it is running through an Invoke Repeating.
function findTarget () {
// Distance and Quaternion Rotation math
var distance = Mathf.Infinity;
var position = transform.position;
// Transforms the enemy toward the ground should they be lifted.
if (!isGrounded) {
transform.position += Vector3.down * 8 * Time.deltaTime;
}
// Finding nearest player
for (var _player : GameObject in _players) {
var difference = _player.transform.position - position;
var currentDistance = difference.sqrMagnitude;
if (currentDistance < distance) {
nearestPlayer = _player;
distance = currentDistance;
target = nearestPlayer.transform;
Debug.Log ("Nearest " + nearestPlayer);
Debug.Log ("Target is " + target);
// The enemy now has a target
var distance2 = Vector3.Distance(aiTransform.position, target.position);
var dy : float = target.position.y - aiTransform.position.y;
var dx : float = target.position.x - aiTransform.position.x;
var angle : float = Mathf.Atan2(dy, dx);
if (distance2<=range && distance2>stop) {
// The enemy is rotating constantly toward target
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation (target.position - transform.position), rotationSpeed * Time.deltaTime);
var time = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.transform.position, moveSpeed * Time.deltaTime);
enemyAnim.SetBool ("chasing", true);
}
}
}
}
Comment
Your answer
Follow this Question
Related Questions
Enemy frozen in place by light? 2 Answers
2D top-down shooter AI 0 Answers
Different enemy types script design 1 Answer
Controlling when enemies walk on top of each other. 0 Answers
How to Respawn Ai Enemies After Destroy Gameobject?? 4 Answers