0
\$\begingroup\$

I created a random direction in x and y-axis at where to move, then my problem is when I tried to randomize it sometimes I get the same value at the same time on both x and y-axis. How do I not let this happen, I only want one axis to have a value, not both?


ERROR

enter image description here


HOW I WANT IT TO HAPPEN

enter image description here


CODE

public Vector2 randomDirection;

void Awake()
{
}

void Update()
{
    randomDirection = new Vector2(Random.Range(-1, 2), Random.Range(-1, 2));
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

There are lots of ways to skin this cat.

You could decide your axis first, then decide the direction along that axis:

public static Vector2 GetRandomCardinalDirection() {
    Vector2 direction = Vector2.zero;
    int componentIndex = Random.Range(0, 2);
    direction[componentIndex] = Mathf.Sign(Random.value);
}

You could use a switch statement to pick one of your four possible values:

public static Vector2 GetRandomCardinalDirection() {
    int direction = Random.Range(0, 4);
    switch(direction) {
        case 0: return Vector2.up;
        case 1: return Vector2.right;
        case 2: return Vector2.down;
        default: return Vector2.left;
    }
}

You could store the 4 values in an array, and use your random value as an index:

static readonly Vector2[] _cardinalDirections = new Vector2[] {
    Vector2.up, Vector2.right, Vector2.down, Vector2.left
};

public static Vector2 GetRandomCardinalDirection() {
    return _cardinalDirections[Random.Range(0, 4)];
}

You could do some bit tricks to decode a direction from an integer 0-3:

public static Vector2 GetRandomCardinalDirection() {
    // Make a random number 0-3 (that's 00, 01, 10, or 11 in binary)
    int dieRoll = Random.Range(0, 4);
    // Take just "the ones bit" and use it as our axis (0 = x, 1 = y)
    int axis = dieRoll & 1;
    // Take "the twos bit" (value 0 or 2) and subtract 1 to get -1 or +1
    int sign = (dieRoll & 2) - 1;

    // Initialize a vector2 with zeroes (0, 0)
    Vector2 direction = Vector2.zero;
    // Set our chosen axis, x or y, to have our desired -1/+1 value
    direction[axis] = sign;
    // Send that vector back to our caller.
    return direction;
}

...etc.

\$\endgroup\$
2
  • \$\begingroup\$ Your 4th answer code solved my problem! May I know what it does? \$\endgroup\$
    – Saidus
    May 4, 2020 at 5:59
  • 1
    \$\begingroup\$ @Saidus I've elaborated on the code above, breaking it into steps and adding comments. \$\endgroup\$
    – DMGregory
    May 4, 2020 at 14:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .