random walk position generation still generates duplicates even though there is a duplicate checker

54 Views Asked by At

As the title says, I created a random walk position generator for our dungeon crawler game. But everytime i generate a room, there is still a duplicate position generated even though there is a duplicate checker (located at posGenerator() while loop). Sometimes it generates good (no duplicate positions) and sometimes it generates duplicates.

Any ideas and opinions are welcomed. Thanks!

Vector2 position logs (duplicate generation)

Vector2 position logs (no duplicate generation)

posGenerator()

public void posGenerator() {
        Vector2 currentPosition = transform.position;
        positionList.Add(currentPosition);
        for(int i = 0; i < roomCount; i++){
            int currentDirection = RandomNumberGenerator();
            currentPosition = directionalPosition(currentPosition, currentDirection);
            while(positionList.Contains(currentPosition)){  // keep generating position until a new position is generated
                currentPosition = generateNewPosition(positionList[i], currentDirection);
            }
            positionList.Add(currentPosition);
            if(i+1 == roomCount){
                for(int j=1;j<positionList.Count;j++){
                    Debug.Log("Position " + j + ": " + positionList[j]);
                    directionList.Add(generateDirectionList(positionList[j-1], positionList[j]));
                }
            }
        }
    }

generateNewPosition()

public Vector2 generateNewPosition(Vector2 position, int direction) {
        int[] excludeDirections;

        switch (direction) {
            case 1: excludeDirections = new int[] { 2, 3, 4 }; break;
            case 2: excludeDirections = new int[] { 1, 3, 4 }; break;
            case 3: excludeDirections = new int[] { 1, 2, 4 }; break;
            default: excludeDirections = new int[] { 1, 2, 3 }; break;
        }

        int randomIndex = Random.Range(0, excludeDirections.Length);
        int newPosition = excludeDirections[randomIndex];
        return directionalPosition(position, newPosition);
    }

I tried changing the structure of while loop, tried using if else and refactoring my code. Still doesnt work. I expect no duplicate positions

1

There are 1 best solutions below

2
Frenchy On

I am not expert in unity, but it seems your error comes from this line:

    Vector2 currentPosition = transform.position;
    positionList.Add(currentPosition);

at each time you enter in this method, you add currentPosition to the list...but following your program, currentPosition is already in the list...so you add a duplicate.(except the first time you enter, the list is empty) so just add to the list only if the list is empty...