Hi,
I have Gameobjectst and made prefabs out of them. But i have a problem moving them with “lerp”. I think it has something to do with “instantinating” . I used nearly the same functionality in another script and there it works.
I want to spawn “Instances” of my prefab Objects. One Instance every x seconds.
The “Spawn” function is working fine. The problem ist the “move” function. The Objects are spawning at the correct position, but “lerp” move them instantly some units away. I figured out that this is because “beginningTime” is always set to zero after the function “move” started. But i have no idea why this is happening all the time.
Here an example how my Code looks like:
// GameMaster Class, here i manage the whole game:
#pragma strict
var crebse : GameObject;
var actualInsect : GameObject;
var spawnTimer : float;
var firstTime : float;
var randomNum : int;
public static var insectsArray = new Array();
function Start ()
{
spawnTimer = 0.0;
crabs = GameObject.FindGameObjectWithTag("Crabs_Prefab");
firstTime = Time.time;
}
function Update () {
spawnInsects ();
moveInsects ();
}
function spawnInsects ()
{
var secondTime = Time.time;
// Spawn all 3 Seconds an Insect
if( secondTime - firstTime > 3.0)
{
firstTime = Time.time;
crabs.GetComponent(WaterInsects_Script).Spawn();
}
}
function moveInsects ()
{
// go through all created instances and move them
for (var i: int = 0; i < insectsArray .length; i++)
{
actualInsect = insectsArray[i];
var Insectnumber = i;
actualInsect.GetComponent(WaterInsects_Script).Move();
}
}
//The Script "WaterInsects_Script" that is attached to the "Prefab Objects":
#pragma strict
private var spawnInsect : GameObject;
var movementSpeed : float;
var distCovered : float;
var fracJourney : float;
var timeAtSpawn : float;
var journeyLength : float;
function Start ()
{
}
function Update () {
}
function Spawn ()
{
var newWaterAnimal = this.transform.gameObject;
journeyLength = Vector2.Distance(Vector2 (0, 2), Vector2 (5, 5));
spawnInsect = Instantiate (newWaterAnimal, Vector2 (0, 2), Quaternion.identity ) as GameObject ;
GameMaster_Class.InsectsArray.push(spawnInsect);
// The is variable is set when an object spawns
timeAtSpawn = Time.time;
}
function Move ()
{
// calculate the actual moved way
distCovered = (Time.time -timeAtSpawn)* movementSpeed;
// calculate the actual percentage of the moved way
fracJourney = distCovered / journeyLength;
// move the object with lerp
gameObject.transform.position = Vector3.Lerp(Vector2 (0, 2), Vector2 (5, 5), fracJourney);
}
Im Sorry that this is a little bit messy, i copied some parts out and changed some names.