- Home /
2D infinate runner generation
I am in the middle of creating a 2D infinite runner game for a mobile device. I am stuck on the generation part. I have this so far but it doesn't work at all. The left, right, rightobj and leftobj are colliders
using UnityEngine;
using System.Collections;
public class Generator : MonoBehaviour {
public GameObject[] platforms;
public Transform left;
public Transform right;
public GameObject rightobj;
public GameObject leftobj;
public Transform player;
// Use this for initialization
void Start ()
{
rightobj.SetActive (true);
}
// Update is called once per frame
void Update ()
{
Platforms ();
}
void Platforms()
{
rightobj.SetActive (true);
float rightPos = right.transform.position.x;
float leftPos = left.transform.position.x;
float playerPos = player.transform.position.x;
int num = Random.Range (0, platforms.Length);
if (rightPos - playerPos > 5.0f && (rightPos % 7 < 0.1 || rightPos % 7 > 6.9))
{
Instantiate (platforms[num], new Vector3(rightPos,0.85f,0.0f), Quaternion.identity);
print ("generating platforms");
}
else
{
rightobj.SetActive (false);
print ("not 5");
}
if (Mathf.Abs(leftPos - playerPos) > 2.0f)
{
Destroy(platforms[num]);
print ("DESTROY THEM!!!!");
}
}
}
When I run the script This happens.
Looks like the code is doing what you told it to, but you haven't provided a way to know the size of the platform game object that will be placed. $$anonymous$$aybe if I knew what was in the platforms array it would make more sense.
It does look like there's a problem here:
You define left and right as transforms
public Transform left;
public Transform right;
And then try to access them like gameobjects
float rightPos = right.transform.position.x;
float leftPos = left.transform.position.x;
Not sure if that would break everything or not. Otherwise most of your problems are here, I am sure:
if (rightPos - playerPos > 5.0f && (rightPos % 7 < 0.1 || rightPos % 7 > 6.9))
I would suggest to simplify your logic into multiple if statements ins$$anonymous$$d of this compound one with 3 comparison operators.
Thanks, I wanted to generate the prefabs like an actual infinite runner game, e.g. the platforms are generating next to each other and not like this
Your answer
Follow this Question
Related Questions
2D Tile Map Question 0 Answers
2D Character Controller Double Jump? 1 Answer
New Game Object not being created 1 Answer
Generating 2D collisions for maze 0 Answers