Game levels are unexpectedly generating on top of each other

Game levels are unexpectedly generating on top of each other

Content Index :

Game levels are unexpectedly generating on top of each other
Tag : chash , By : DonMac
Date : November 26 2020, 12:01 PM

Hope that helps So I came up with the following solution:
(Limit - if a room is already spawned it is still possible that it might get surrounded by other spawning rooms so its doors get blocked)
#if UNITY_EDITOR // exclude this from a build
using Unity.Editor;

public enum DoorType
    Top = 0x01,
    Right = 0x02,
    Bottom = 0x04,
    Left = 0x08

public class EnumFlagsAttribute : PropertyAttribute
    public EnumFlagsAttribute() { }

#if UNITY_EDITOR // exclude this from a build
public class EnumFlagsAttributeDrawer : PropertyDrawer
    public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
        _property.intValue = EditorGUI.MaskField(_position, _label, _property.intValue, _property.enumNames);
public class RoomTemplates : MonoBehaviour
    public RoomSpawner[] bottomRooms;
    public RoomSpawner[] topRooms;
    public RoomSpawner[] leftRooms;
    public RoomSpawner[] rightRooms;


    public RoomSpawner closedRoomTop;
    public RoomSpawner closedRoomRight;
    public RoomSpawner closedRoomBottom;
    public RoomSpawner closedRoomLeft;


    public List<GameObject> rooms;
public class RoomSpawner : MonoBehaviour
    [EnumFlags] public DoorType openingDirections;

    // Keep track of already used positions
    private static List<Vector2Int> occupiedPositions = new List<Vector2Int>();

    // store own room position
    private Vector2Int roomFieldPosition;

    private RoomTemplates templates;
    private bool spawned = false;

    private void Start()
        templates = FindObjectOfType<RoomTemplates>();

        roomFieldPosition = new Vector2Int(Mathf.RoundToInt(transform.localPosition.x), Mathf.RoundToInt(transform.localPosition.z));


        Invoke("Spawn", 0.5f);

    private static DoorType GetPossibleDirections(Vector2Int position)
        DoorType output = 0;

        if (!occupiedPositions.Contains(new Vector2Int(position.x, position.y + 1))) output |= DoorType.Top;
        if (!occupiedPositions.Contains(new Vector2Int(position.x, position.y - 1))) output |= DoorType.Bottom;

        if (!occupiedPositions.Contains(new Vector2Int(position.x + 1, position.y))) output |= DoorType.Right;
        if (!occupiedPositions.Contains(new Vector2Int(position.x - 1, position.y))) output |= DoorType.Left;

        return output;

    private void SpawnRoom(DoorType type)
        Vector2Int nextPosition;
        RoomSpawner[] templateArray;
        RoomSpawner closedRoom;

        switch (type)
            case DoorType.Top:
                nextPosition = new Vector2Int(roomFieldPosition.x, roomFieldPosition.y + 1);
                templateArray = templates.topRooms;
                closedRoom = templates.closedRoomTop;

            case DoorType.Right:
                nextPosition = new Vector2Int(roomFieldPosition.x + 1, roomFieldPosition.y);
                templateArray = templates.rightRooms;
                closedRoom = templates.closedRoomRight;

            case DoorType.Bottom:
                nextPosition = new Vector2Int(roomFieldPosition.x, roomFieldPosition.y - 1);
                templateArray = templates.bottomRooms;
                closedRoom = templates.closedRoomBottom;

            case DoorType.Left:
                nextPosition = new Vector2Int(roomFieldPosition.x - 1, roomFieldPosition.y);
                templateArray = templates.leftRooms;
                closedRoom = templates.closedRoomLeft;


        if (occupiedPositions.Contains(nextPosition)) return;

        var directions = GetPossibleDirections(nextPosition);

        var prefabs = new List<RoomSpawner>();
        foreach (var doorType in (DoorType[])Enum.GetValues(typeof(DoorType)))
            if (!directions.HasFlag(doorType)) continue;

            prefabs.AddRange(templateArray.Where(r => r.openingDirections.HasFlag(doorType)));

        if (prefabs.Count == 0)

        // Need to spawn a room with a BOTTOM door.
        var rand = Random.Range(0, prefabs.Count);
        Instantiate(prefabs[rand], new Vector3(nextPosition.x, 0, nextPosition.y), Quaternion.identity);

    private void Spawn()
        if (spawned) return;

        if (openingDirections.HasFlag(DoorType.Top)) SpawnRoom(DoorType.Top);
        if (openingDirections.HasFlag(DoorType.Bottom)) SpawnRoom(DoorType.Bottom);

        if (openingDirections.HasFlag(DoorType.Right)) SpawnRoom(DoorType.Right);
        if (openingDirections.HasFlag(DoorType.Left)) SpawnRoom(DoorType.Left);

        spawned = true;

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Game with no levels possible?

Tag : iphone , By : DotNetWise
Date : March 29 2020, 07:55 AM
seems to work fine Actually I allways prefered non liner games.
Most RTS games suffer from this illness ( you build up a nice base and than the stage is over and you start from scratch again ).

Doing a toast causes the game to close unexpectedly

Tag : android , By : dbarbot
Date : March 29 2020, 07:55 AM
wish helps you Toasts must be called on the UI thread.
Assuming Game.context holds a reference to the calling Activity, change your code to something like this:
((Activity) Game.context).runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(Game.context, "10Seconds", Toast.LENGTH_SHORT).show();                   

how to implement multiple(for different game levels) leaderboard in android libgdx game?

Tag : android , By : JoeCh
Date : March 29 2020, 07:55 AM
hop of those help? To send score to multiple leaderboard there is a need to create all those multiple leaderboard and just send score to particular one.
To call all leaderboard at once on single button click use this
startActivityForResult( Games.Leaderboards.getAllLeaderboardsIntent( gameHelper.getApiClient()), 1 ); 

Trying to add new levels to my Breakout game

Tag : chash , By : Per
Date : March 29 2020, 07:55 AM
Hope that helps Fixed the problem now, by putting the else if-statement inside "if (lives > 0)"

Images as game levels

Tag : java , By : Nate Bedortha
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • C# XDocument Element/Elements returns null
  • Autofac keyed service with IEnumerable relationship type
  • Installing EntityFramework via NuGet manager
  • Always Check if there is Internet Connection Xamarin forms
  • WCF OneWay service slows down when aspNetCompatibilityEnabled is set to false
  • Can we use JsonRequestBehavior.AllowGet with [HttpPost] attribute?
  • How to customize the Setup wizard with custom forms in Visual Studio setup project
  • C# ASP.NET - Use method from another class to create labels
  • C# List IList or IEnumerable as argument
  • Parsing File with C# And Replace method
  • Losing special unicode characters in encryption (C#)
  • Getting stored procedure returned value instead of row affected
  • How can I construct HTML using NameValuePair in android?
  • Loading a pop up page in ASP.net through a js file
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com