简体   繁体   中英

Unity Rectangle Overlapping

So I got this piece of code that fills the given area of specific size with floor tiles.

while (roomsPlaced < roomCount.maximum)
{
    Vector3 randomPosition = RandomPosition();
    int roomHeight = GetRandomNumber(8, 15);
    int roomWidth = GetRandomNumber(6, 15);

    if (OutOfMap(randomPosition, roomHeight,roomWidth))
    {
        continue;
    }

    if (roomsPlaced > 0) {
        if (Overlaps(new Rect(randomPosition.x, randomPosition.y, roomWidth, roomHeight), roomPositions[roomPositions.Count -1]))
            continue;
    }

    roomPositions.Add(new Rect(randomPosition.x, randomPosition.y, roomWidth, roomHeight));

    for (int x = (int)randomPosition.x; x <= (int)randomPosition.x + roomWidth; x++)
    {
        for (int y = (int)randomPosition.y; y <= (int)randomPosition.y + roomHeight; y++)
        {
            if (x == randomPosition.x || y == randomPosition.y)
                toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)];

            GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;

            instance.transform.SetParent(boardHolder);
        }
    }

    roomsPlaced++;
}

And here is function that should check if current rectangle overlaps the last rectangle on the list.

bool Overlaps(Rect rA, Rect rB)
{
    return (rA.x < rB.x + rB.width && rA.x + rA.width > rB.x && rA.y < rB.y + rB.height && rA.y + rA.height > rB.y);
}

But still I have problem when some of my rooms overlap. What am I doing wrong and what should I do to fix this problem ?

听起来您需要改用Overlaps方法...

Yeeah. I just solved the problem by going through the whole list instead of picking last element on the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM