I have a GameObject which for now is just a cube. What I am trying to do is to get the cube to follow a path that I create in real time by clicking in the game world.
I have an array set up which, once instantiated, each waypoint is added to but the cube will not register the added waypoints and instead gets stuck in a point in space which is unrelated to any of the instantiated waypoints.
I’m sure it’s something very simple which I have overlooked. I have tried searching for similar problems but without much luck.
The code:
#pragma strict
import System.Collections.Generic;
//var waypointList = new List.< Transform>();
var waypoint : Transform[];
var speed : float = 20;
var currentWaypoint : int = 0;
var insWP : GameObject;
var wpCookie : GameObject;
var ray : Ray;
var hit : RaycastHit;
var hoverWP : Vector3;
var loop : boolean = true;
function Update(){
if (Input.GetButtonDown ("Fire1")) {
// Construct a ray from the current mouse coordinates
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit))
{
hoverWP = Vector3(hit.point.x, hit.point.y + 10, hit.point.z);
Instantiate (insWP, hoverWP, transform.rotation);
Instantiate (wpCookie, hit.point, Quaternion.identity);
addToArray( insWP );
Debug.Log(waypoint.length);
}
}
if(currentWaypoint < waypoint.length)
{
//var target : Vector3 = waypoint[currentWaypoint].position;
var moveDirection : Vector3 = waypoint[currentWaypoint].transform.position - transform.position;
var velocity = rigidbody.velocity;
if(moveDirection.magnitude < 1)
{
currentWaypoint++;
}
else
{
velocity = moveDirection.normalized * speed;
}
rigidbody.velocity = velocity;
}
else
{
if(loop)
{
currentWaypoint = 0;
}
else
{
velocity = Vector3.zero;
}
}
}
function addToArray ( obj : GameObject)
{
waypoint += [obj.transform];
}