- Home /
Question by
sacredwolf000 · Dec 07, 2013 at 03:20 AM ·
javascriptarraypathfinding
array out of range in simple pathinder javascript
Hi I am a college student taking a scripting class for game design and finals are coming near. In my script the player capsule moves through each five pathodes goes back the other way but then it does not repeat itself. And that's wear the error comes in, at line js.32 it says that the array is out of range. is there something that I am missing and how can I fix it? This the first scripting class I have ever taken so I am very much a beginner here.
#pragma strict
var pathNodes = new Transform[5];
var currentNode : Transform;
var nodeIndex : int = 0;
var distanceToTarget : float = 25;
var pos : Vector3 = Vector3.zero;
var controller : CharacterController;
var nextNode : int = 1;
var speed : int = 4;
var nodeDistance : int = 1;
function Start ()
{
controller = transform.GetComponent(CharacterController);
currentNode = pathNodes[nodeIndex];
pos = currentNode.position;
pos.y = transform.position.y;
transform.LookAt(pos);
}
function PathUpdate ()
{
nodeIndex += nextNode;
if(nextNode == 0)
{
nextNode = 1;
}
else if(nodeIndex == pathNodes.length - 1)
{
nextNode = -1;
}
currentNode = pathNodes[nodeIndex];
pos = currentNode.position;
pos.y = transform.position.y;
transform.LookAt(pathNodes[nodeIndex]);
}
function Update ()
{
transform.LookAt(pos);
controller.Move(transform.forward * Time.deltaTime * speed);
distanceToTarget = Vector3.Distance(transform.position, currentNode.position);
print(distanceToTarget);
if(distanceToTarget <= nodeDistance)
{
PathUpdate();
}
}
Comment
Answer by robertbu · Dec 07, 2013 at 03:26 AM
I see one problem right here:
else if(nodeIndex == pathNodes.length - 1)
{
nextNode = -1;
}
currentNode = pathNodes[nodeIndex];
If you are at the end of your list, then you set nextNode to -1. Then on the next line you use -1 as an index into an array. Using -1 to index into an array will cause your error.
Untested, but I think you want this:
function PathUpdate ()
{
nodeIndex += nextNode;
if(nodeIndex == pathNodes.length)
{
nextNode = 0;
}
currentNode = pathNodes[nodeIndex];
pos = currentNode.position;
pos.y = transform.position.y;
transform.LookAt(pathNodes[nodeIndex]);
}