Hi,
I am making a tile-based game. I ready find a path between two tiles, and store that into an array. But I have trouble moving an object based on path. Here is my code, which doesn’t seem to work.
Basically, I loop through pathlist array to obtain positions. A while loop is used to move from point A to point B. The “gamestate” and “ismoving” variables are used to prevent a section of code from executing.
//main loop
function Update() {
if (gamestate==1)
{
//examine unit list, select current unit
Somefunction();
}
if (gamestate==2)
{
//check if current unit belongs to player or AI. wait for user input. find path, store path in pathlist array.
Someotherfunction();
}
if (gamestate==3)
{
//move unit
if (ismoving == false) //global variable, already declared.
{
ismoving = true;
for (var i:int = pathlist.length-2;i>=0;i--) //pathlist is an array, which stores the result from A*. pathlist[0] is the ending tile, pathlist[pathlist.length-1] is the starting tile
{
var lerpt:float = 0; //for Vector3.Lerp() function
var startlocation:Vector3 = Vector3(pathlist[i+1].xvalue,0,pathlist[i+1].yvalue);
var endlocation:Vector3 = Vector3(pathlist[i].xvalue,0,pathlist[i].yvalue);
var locator:Vector3 = Vector3(pathlist[i+1].xvalue,0,pathlist[i+1].yvalue);
while (lerpt != 1)
{
lerpt += 1*Time.deltaTime;
if (lerpt >= 1)
{
lerpt = 1;
}
locator = Vector3.Lerp(startlocation,endlocation,lerpt);
unit.transform.position.x = locator.x; //the object to be moved
unit.transform.position.y = locator.y;
unit.transform.position.z = locator.z;
}
}
ismoving = false;
gamestate = 4;
}
}
}