- Home /
 
Basic Enemy Javascript
Super new at scripting. Trying to get my enemy to follow pathnodes until my player comes within range. Made this script. The enemy only moves in a straight line, not towards the path nodes. The nodes are in the correct places in the inspector.
pragma strict
var pathNodes = new Transform[5]; var startPosition : Transform; var currentNode : Transform; var nextNode : int = 1; var nodeIndex : int = 0; var distanceToTarget : float = 0; var nodePosition : Vector3 = Vector3.zero; var controller : CharacterController; var playerDis : float = 0; var squirrel : boolean = false; var nodeDistance : float = .25; var playerPosition : Vector3 = Vector3.zero; var player : GameObject; var guarding : boolean;
function Start () {
controller = transform.GetComponent(CharacterController);
currentNode = pathNodes[nodeIndex]; nodePosition = currentNode.position; nodePosition.y = transform.position.y; transform.LookAt(nodePosition);
}
function Update () {
//detecting player playerDis = Vector3.Distance(transform.position, player.transform.position); if(playerDis <= 5) { guarding = false; squirrel = true;
 ProjectSquirrel();
 
 
               } else { squirrel = false; PathFinding(); } }
//custom functions
//node path updating function PathUpdate() { nodeIndex += nextNode; if(nodeIndex == 0) { nextNode = 1; } else if(nodeIndex == pathNodes.Length - 1) { nextNode = -1; } currentNode = pathNodes[nodeIndex];
 currentNode = pathNodes[nodeIndex];
 nodePosition = currentNode.position;
 nodePosition.y = transform.position.y;
 transform.LookAt(nodePosition);
 guarding = true;
 print("Gaurd duty");
 
               }
//searchinganddestroying
function ProjectSquirrel() { playerPosition = GameObject.FindGameObjectWithTag("Player").transform.position; playerPosition.y = transform.position.y; transform.LookAt(playerPosition); controller.Move(transform.forward Time.deltaTime 20); print("You're gonna die"); }
function PathFinding() { //changing path to nodes distanceToTarget = Vector3.Distance(transform.position, currentNode.position); if(distanceToTarget <= nodeDistance) { PathUpdate(); } controller.Move(transform.forward Time.deltaTime 20); print("Patrolling"); }
Your answer
 
             Follow this Question
Related Questions
A* optimization and path help 0 Answers
A* Pathfinding AIFollow in JavaScript? 0 Answers
AI Pathfinding Script 4 Answers
Follow up to AI Pathfinding Question 0 Answers
array of boxes 2 Answers