Reputation: 117
I am trying to achieve an endless runner that Instantiates tiled (modular) models randomly onto one another as you run along.
Here is the code attached to the model, when it triggers with "Player", it instantiates a new model randomly from an array. However, I want it to spawn in at exactly -90x from the previous model so that they tile. At the moment, it instantiates into world space at -90, 0 , 0
.
function OnTriggerEnter (hit : Collider) {
//obstacles spawn
if(hit.gameObject.tag == "Player") {
var toSpawn : GameObject = obstacles[Random.Range(0,obstacles.Length)];
var spawnPosition = new Vector3 (-90,0,0);
var Spawn = Instantiate (toSpawn, spawnPosition), Quaternion.identity;
}
}
Upvotes: 1
Views: 883
Reputation: 1029
You could keep a count of how many tiles have already been placed, and use it as a multiplier.
private int tileCount = 1;
and in your OnTriggerEnter() method:
var offset = new Vector3 (-90 * tileCount,0,0);
tileCount++;
Upvotes: 4
Reputation: 8193
you need to cache the old tile then or find it somehow
GameObject lastSpawn;
function OnTriggerEnter (hit : Collider)
{
//obstacles spawn
if(hit.gameObject.tag == "Player")
{
var toSpawn : GameObject = obstacles[Random.Range(0,obstacles.Length)];
var offset = new Vector3 (-90,0,0);
var spawn = Instantiate (toSpawn, lastSpawn.transform.position + offset), Quaternion.identity) as GameObject;
lastTile = spawn;
}
}
now this one will allow for variable tile sizes (not tested):
GameObject lastSpawn;
function OnTriggerEnter (hit : Collider)
{
//obstacles spawn
if(hit.gameObject.tag == "Player")
{
var toSpawn : GameObject = obstacles[Random.Range(0,obstacles.Length)];
var offset = lastSpawn.GetComponent<MeshRenderer>().bounds.extents + gameObject.GetComponent<MeshRenderer>().bounds.extents;
offset.y = 0f;
var spawn = Instantiate (toSpawn, lastSpawn.transform.position + offset), Quaternion.identity) as GameObject;
lastTile = spawn;
}
}
Upvotes: 1