I’ve been using this following code that a professor of mine wrote a while ago. And it worked pretty well until today. The way it works is that the objects with this script move towards another object (set by the user, it could be an empty game object or anything). However, when using this script today, it moves the destination object that the objects with the script are supposed to be moving towards up on the Y-axis against my will. Then the destination sinks down as though it has a rigidbody (it doesn’t). I have the objects that are supposed to move instatiating every 10 seconds in increments of 5. Anyways, is there a better script or a way to fix this?
Here’s the code:
var waypoints : Transform [];
var speed = 6; // dependant on object mass. might need to increase if mass > 1
var closeDistance = 1; // can set how close is close
var goback = false; // go back to the first location if true (looping like)
var flag : Transform; // use to visualize next destination
//
private var index = 0;
private var destiny : Transform;
private var vspeed = 0.0;
private var controller : CharacterController;
function
Start()
{
controller = GetComponent(CharacterController);
destiny = null;
if (waypoints.Length > 0)
{
destiny = waypoints[0];
destiny.position.y = transform.position.y;
transform.LookAt(destiny);
if (flag) flag.position = destiny.position;
Debug.Log("Destiny " + destiny.position);
}
if (destiny == null)
{
Debug.Log("NO WAYPOINTS SET");
}
vspeed = speed; // set it to the main speed
}
function
GetNextLocation()
{
if (destiny && CloseEnough())
{
if (index >= waypoints.Length)
{
if (goback)
{
index = 0;
vspeed = speed;
}
else {
vspeed = 0; // we stop moving
return;
}
}
destiny = waypoints[index++];
if (flag) flag.position = destiny.position;
}
if (destiny) {
transform.LookAt(destiny);
//Debug.Log ("Look At " + destiny.position);
}
}
function
CloseEnough()
{
var sqrLen = (destiny.position - transform.position).sqrMagnitude;
if( sqrLen < closeDistance*closeDistance )
{
return true;
}
return false;
}
function Update () {
GetNextLocation();
controller.SimpleMove(transform.TransformDirection(Vector3.forward) * vspeed);
}
function
LateUpdate()
{
if (destiny)
destiny.position.y = transform.position.y;
}
@script RequireComponent(CharacterController)