mercredi 27 mai 2015

In Java, generate a random set of x, y coordinates within a rectangle [duplicate]

This question already has an answer here:

The problem is that if my Rectangle position.x or position.y is >=0.0f, then my randomly generated number is always a positive number. Is there a way to generate a truely random set of x, y coordinates within my region?

How I determine a new point within the rectangle ..

// new Rectangle(position, width, height)
Rectangle region = new Rectangle(new Vec3(-5.0f, 0.0f, 0.0f), 1.0f, 1.0f);

// random number between min width and max width
float x = nextFloat(-(region.getWidth() / 2), region.getWidth() / 2);
// random number between min height and max height
float y = nextFloat(-(region.getHeight() / 2), region.getHeight() / 2);

log.info("new X: " + (region.getPosition().x + x));
log.info("new Y: " + (region.getPosition().y + y));

public float nextFloat(float min, float max){

    return min + new Random().nextFloat() * (max - min);
}

Output after 5 executions ..

[12:32:13] INFO - new X: -4.5985336
[12:32:13] INFO - new Y: 0.11210716

[12:32:24] INFO - new X: -4.5284076
[12:32:24] INFO - new Y: 0.38759524

[12:32:39] INFO - new X: -4.901697
[12:32:39] INFO - new Y: 0.42026645

[12:32:55] INFO - new X: -4.5402946
[12:32:55] INFO - new Y: 0.45692778

[12:33:08] INFO - new X: -5.0831842
[12:33:08] INFO - new Y: 0.25894576




Aucun commentaire:

Enregistrer un commentaire