Unity 3D
function PickNextWaypoint (currentWaypoint :
AutoWayPoint) {
// We want to find the waypoint where the
character
has to turn the least
// The direction in which we are walking
var forward =
transform.TransformDirection(Vector3.forward);
// The closer two vectors, the larger the dot
product will be.
var best = currentWaypoint;
var bestDot = -10.0;
for (var cur : AutoWayPoint in
currentWaypoint.connected) {
var direction =
Vector3.Normalize(cur.transform.position -
transform.position);
var dot = Vector3.Dot(direction,
forward);
if (dot > bestDot && cur !=
currentWaypoint)
{
bestDot = dot;
best = cur;
}
}
return best;
}
function AttackPlayer () {
var lastVisiblePlayerPosition = target.position;
while (true) {
if (CanSeeTarget ()) {
// Target is dead - stop hunting
if (target == null)
return;
// Target is too far away - give up
var distance =
Vector3.Distance(transform.position, target.position);
if (distance > shootRange * 3)
return;
lastVisiblePlayerPosition =
target.position;
if (distance >
dontComeCloserRange)
MoveTowards
(lastVisiblePlayerPosition);
else
RotateTowards(lastVisiblePlayerPosition);
var forward =
transform.TransformDirection(Vector3.forward);
var targetDirection =
lastVisiblePlayerPosition - transform.position;
targetDirection.y = 0;
var angle =
Vector3.Angle(targetDirection, forward);
// Start shooting if close and play is in sight
if (distance < shootRange &&
angle <
shootAngle)
yield
StartCoroutine("Shoot");
} else {
yield
StartCoroutine("SearchPlayer",
lastVisiblePlayerPosition);
// Player not visible anymore - stop attacking
if (!CanSeeTarget ())
return;
}
yield;
}
}