Question by
Blast73 · Apr 25, 2016 at 05:29 AM ·
instantiateinstantiate prefab
Instantiated prefabs all stacking on top of each other
I'm trying to spawn obstacles for a 2D endless runner where the background moves and the player is still. I'm running into an issue where all of the obstacles I'm spawning are stacking so that every new one that is spawned immediately teleports to the very first one that was spawned. The issue is either in the spawning script or the movement script for the object but I can't figure it out. Here are the two scripts.
obstacle movement:
public class obstacleBehavior : MonoBehaviour {
public float obstacleSpeed;
private Vector2 startPosition;
void Start (){
startPosition = transform.position;
}
void Update (){
float newPosition = Time.time * obstacleSpeed;
transform.position = startPosition + Vector2.left * newPosition;
}
}
Spawner:
public class obstacleSpawner : MonoBehaviour {
public Transform obstacle1;
public GameObject spawner;
private float timer1 = 2f;
void Start () {
Instantiate (obstacle1, spawner.transform.position, transform.rotation);
}
void Update () {
timer1 -= Time.deltaTime;
if (timer1 < 0) {
Instantiate (obstacle1, spawner.transform.localPosition, transform.rotation);
Debug.Log (timer1);
timer1 = 2f;
}
}
}
Comment
Best Answer
Answer by Blast73 · Apr 25, 2016 at 06:15 AM
The problem was in the movement of the obstacle, since I was adjusting the transform it was adjusting the transform for all of them. I added a rigidbody and just added force, which is relative to each.