Quantcast
Channel: Questions in topic: "random spawn"
Viewing all articles
Browse latest Browse all 125

How to Detect if a Collider is in the Area, Move Away, Rinse and Repeat?

$
0
0
Hello, everyone. In my 2D game, since I couldn't figure out how to prevent them from originally spawning on top of each other, a few random platforms are generated within a certain area by an empty gameobject. Once they spawn in, I want them to detect if there are other platforms within a certain distance using Physics2D.OverlapCircleAll(transform.position, radius);. The platforms have edge colliders. If they detect one or more other platforms within the circle, they will teleport a random position, rinse and repeat. However, instead of doing what I meant to happen, they just teleport all over the screen or don't do anything after spawning in, regardless to whether they're touching another platform or not. I don't understand why. Here is the code attached to the platform prefab: using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformCfg : MonoBehaviour { bool canStayHere = true; float height = 2; float radius = 2; float width = 2; Collider2D[] colliders; // Use this for initialization void Start () { } // Update is called once per frame void Update() { CheckForPlatforms(); if (!canStayHere) { Displace(); } } void CheckForPlatforms() { colliders = Physics2D.OverlapCircleAll(transform.position, radius); if (colliders.Length >= 1) { canStayHere = false; Array.Clear(colliders, 0, colliders.Length); } else canStayHere = true; } void Displace() { float randX = UnityEngine.Random.Range(transform.position.x - width, transform.position.x + width); float randY = UnityEngine.Random.Range(transform.position.y - height, transform.position.y + height); transform.position = new Vector2(randX, randY); } } If anyone can tell me why this happens and how to fix this, I would be thankful. If you have a better solution to prevent the platforms from spawning too close to each other, please tell me! Thank you.

Viewing all articles
Browse latest Browse all 125

Trending Articles