- Home /
How Do I Create Random Platforms in a 2d Game?
I was trying to figure on how to create them but nothing seems to be working. I have a Platform prefab and I want this to be randomly created.
This is the code I was trying. But this is not working. nothing happens.
I appreciate any kind of help.
using UnityEngine;
using System.Collections.Generic;
public class PlatformManager : MonoBehaviour {
public Transform prefab;
public int numberOfObjects;
public float recycleOffset;
public Vector3 startPosition;
public Vector3 minSize, maxSize, minGap, maxGap;
public float minY, maxY;
private Vector3 nextPosition;
private Queue<Transform> objectQueue;
void Start () {
objectQueue = new Queue<Transform>(numberOfObjects);
for(int i = 0; i < numberOfObjects; i++){
objectQueue.Enqueue((Transform)Instantiate(prefab));
}
nextPosition = startPosition;
for(int i = 0; i < numberOfObjects; i++){
Recycle();
}
}
void Update () {
if(objectQueue.Peek().localPosition.x + recycleOffset < PlayerScript.distanceTraveled){
Recycle();
}
}
private void Recycle () {
Vector3 scale = new Vector3(
Random.Range(minSize.x, maxSize.x),
Random.Range(minSize.y, maxSize.y),
Random.Range(minSize.z, maxSize.z));
Vector3 position = nextPosition;
position.x += scale.x * 0.5f;
position.y += scale.y * 0.5f;
Transform o = objectQueue.Dequeue();
o.localScale = scale;
o.localPosition = position;
objectQueue.Enqueue(o);
nextPosition += new Vector3(
Random.Range(minGap.x, maxGap.x) + scale.x,
Random.Range(minGap.y, maxGap.y),
Random.Range(minGap.z, maxGap.z));
if(nextPosition.y < minY){
nextPosition.y = minY + maxGap.y;
}
else if(nextPosition.y > maxY){
nextPosition.y = maxY - maxGap.y;
}
}
}
the problem I face here is that the platform move ahead of the camera...
Otherwise just change it to: position.x += (scale.x 0.5) Random.Range(1, scale.x); and do this also for the y axis except you will need to change the .x to .y. Rule 40 and 41 or of that doesn't work try these at rule 50 etc.
Possible Issuer 1
if(objectQueue.Peek().localPosition.x + recycleOffset < PlayerScript.distanceTraveled)
Your objects are recycled as the Player $$anonymous$$oves a certain distance, which either means the distance is incorrect or the player is outpacing the camera. Can you provide your PlayerScript?
Possible Issue 2
You aren't providing enough platforms, and your platforms are being recycled too early.
Possible Issuer 3
Your recycleOffset is too large causing all the platforms to move too far ahead, out pacing the camera.
Your answer
Follow this Question
Related Questions
How to clip game objects to a rectangular area? 0 Answers
Jumping from a floor to another floor (2D) 2 Answers
Accelerating speed 2 Answers
Character doesn't jump repeatedly 1 Answer
2d Beat Em Up Jump Functionality 0 Answers