- Home /
What logic should i implement in this 2D game?
Hello everyone, I would like to ask about a game i am making,it is a about a 2D game where the player goes from up to down, and there are obstacles being generated randomly while the background(which is the movable object) moves up. My question is: what logic should i implement in regard for obstacle generation?My current implementation (which is wrong) is creating a queue holding the objects and then comparing the position of the item on peek of the queue with the distance of the player and then creating a new object,but this implementation keeps generating objects non-stop and this ruin the game,So how should i think about that. Till now this is my code regarding the obstacles: using System.Collections; using System.Collections.Generic; using UnityEngine;
public class ObstacleManager : MonoBehaviour {
public float scrollSpeed;
public int numberOfObjects;
public float recycleOffset;
public Transform prefab;
public Vector3 minSize, maxSize, minGap, maxGap;
public float minY, maxY;
private static Vector3 startPos;
private Vector3 nextPosition;
private Queue<Transform> objectQueue;
// Use this for initialization
void Start () {
GameEventManager.GameStart += GameStart;
GameEventManager.GameOver += GameOver;
objectQueue = new Queue<Transform>(numberOfObjects);
enabled = false;
}
// Update is called once per frame
void Update ()
{
// if (objectQueue.Count > 0 && prefab != null) {
//// Debug.Log("1: "+objectQueue.Peek().localPosition.y + recycleOffset);
//// Debug.Log("2: "+-(PlayerController.distanceTraveled));
//// Debug.Log(objectQueue.Peek().localPosition.y + recycleOffset < -(PlayerController.distanceTraveled));
// if(objectQueue.Peek().localPosition.y + recycleOffset < -(PlayerController.distanceTraveled)){
// Recycle();
//// Debug.Log(prefab.position);
// }
// }
}
public void ObsctaclesMovement (float speed)
{
float newPos = Mathf.Repeat(Time.time * speed,10);
transform.position = startPos + Vector3.up * newPos;
}
private void GameStart () {
nextPosition = startPos;
for (int i = 0; i < numberOfObjects; i++) {
objectQueue.Enqueue((Transform)Instantiate(
prefab, new Vector3(prefab.position.x, 0f, 0f), Quaternion.identity));
}
for(int i = 0; i < numberOfObjects; i++){
Recycle();
}
enabled = true;
}
private void GameOver () {
enabled = false;
}
private void Recycle () {
Vector3 position = nextPosition;
Vector3 scale = new Vector3(
Random.Range(0.5f, 6.5f),
Random.Range(-1.5f, -16f),
0f);
position.x = scale.x;
position.y = scale.y;
Transform o = objectQueue.Dequeue();
o.localPosition = position;
objectQueue.Enqueue(o);
nextPosition = new Vector3(
Random.Range(0.5f, 6.5f),
Random.Range(-1.5f, -16f) ,
0f);
// Debug.Log("nex position: "+nextPosition);
}
}
Answer by greencheese122 · May 17, 2018 at 10:27 AM
Use a coroutine
public Ienumerator spawn(){
While(true){
//Do Staff where
Yield return new WaitForSeconds(prof seconds);
}
}
And Then call it in start fiction with StartCoroutine(spawn());