Jony Jony - 1 month ago 9
Java Question

Generate a random position between 2 corners points

If we have two objects of

which represents 2 corners of a rectangle, a region:

Vector2 corner1 = new Vector2(-5, -5);
Vector2 corner2 = new Vector2(5, 5);

How can you generate a random position between these two vectors (any where in the rectangle it creates)?

What I thought to do is, the the distance from
and the same for
, and do a random value from that range.

But what if the first vector is
5, 5
and second vector is
-5, -5
? I will have to add a negative distance, am I right?

Whats the most efficient way to do this?

Answer Source

Here is some example code I'll explain what it does. First you need to find distance between x1 and x2 and distance between y1 and y2 get a random value between the total distance then subtract half of that distance so if we had total distance 10 we would get a random number (0 - 10) subtract 5 and we get the range -5 to 5.

    int x1 = 5;
    int x2 = -5;
    int y1 = 5;
    int y2 = -5;

    Random rand = new Random();

    int distanceX = Math.abs(x1 - x2);
    int distanceY = Math.abs(y1 - y2);

    int randX = rand.nextInt(distanceX) - (distanceX/2);
    int randY = rand.nextInt(distanceY) - (distanceY/2);

    System.out.println(randX + " " + randY);

You would just need to use the Vector 2 so

distanceX = Math.abs(corner1.x - corner2.x);

etc... you might need to change ints to floats depending on what Vector2 contains.

float randX = ((rand.nextFloat()*distanceX) - (distanceX/2));