- Home /
How to Spawn an Extra Platform for the Player to Jump On If There Are None Within the Player's Field of View?
Hello, everyone. I am making a 2D game where the player is a ball that must jump upwards on platforms, a bit like doodle jump. However, when I spawn platforms randomly (within a certain area, so that they keep going up), sometimes a platform won't appear within the player's field of view. This could happen at the start of the game or after landing on another platform. I tried to avoid this by making an empty game object in the middle of the screen search the player's field of view for 2D colliders every time the player lands, and if it returns less than 3 colliders (the ball and the platform that it is currently on), a "backup platform" will be spawned within the player's field of view. Spawning the platform works perfectly, but for some reason, the game spawns a platform every time the player lands, regardless of how many platforms are within the field of view. I have no idea why this happens, so if someone knows what I'm doing wrong, I would be thankful for your help. Here the code attached to the platform detector:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformDetectorCfg : MonoBehaviour {
float height = 2.5f; // half the height of the area i want it to search
float previousSize = 5;
float previousX = 10; // a starting number so that it can be changed when the player spawns
float previousY = 10; // a starting number so that it can be changed when the player spawns
float width = 2.81f; // half the width of the area i want it to search
public GameObject platform;
// Use this for initialization
void Start () {
//DetectPlatforms();
}
// Update is called once per frame
void Update () {
if (previousX != transform.position.x || previousY != transform.position.y)
{
DetectPlatforms();
previousX = transform.position.x;
previousY = transform.position.y;
}
if (Camera.main.orthographicSize != previousSize)
{
height *= 1.036f;
width *= 1.355872f;
previousSize = Camera.main.orthographicSize;
}
}
void DetectPlatforms()
{
Collider2D[] colliders = Physics2D.OverlapBoxAll(transform.position, new Vector2(width, height), 0);//Quaternion.identity);
if (colliders.Length < 3)
{
float randX = Random.Range(transform.position.x - width, transform.position.x + width);
float randY = Random.Range(transform.position.y - height, transform.position.y + height);
Instantiate(platform, new Vector2(randX, randY), Quaternion.identity);
}
}
}
Thank you.
run the code, set a break point where the instantiation happens and read out what collider is missing as it looks like it's all less than 3 even though you think it should be 3