Find closest object to mouse position in a collection
A program that sets random positions for 30 circles, and highlights in red the one closest to the mouse cursor.
Processing / Java
ArrayList<PVector> points = new ArrayList<PVector>();
void setup() {
size(640, 480);
for(int i=0; i<30; i++) {
points.add(new PVector(random(width), random(height)));
}
}
void draw() {
background(255);
float mind = Float.MAX_VALUE;
PVector found = null;
for(PVector p : points) {
float d = p.dist(new PVector(mouseX, mouseY));
if(d < mind) {
found = p;
mind = d;
}
}
for(PVector p : points) {
fill(p == found ? #FF0000 : 255);
ellipse(p.x, p.y, 20, 20);
}
}
OPENRNDR / Kotlin
fun main() = application {
program {
val points = List(30) { drawer.bounds.center + drawer.bounds.center * Random.vector2() }
extend {
drawer.clear(ColorRGBa.WHITE)
val closest = points.minByOrNull { (mouse.position - it).squaredLength }
points.forEach {
drawer.fill = if (it == closest) ColorRGBa.RED else ColorRGBa.WHITE
drawer.circle(it, 20.0)
}
}
}
}
I did not include three imports
in the Kotlin program as they are handled automatically by the IDE.
My favorite part here is finding the closest Vector2 to the mouse position which goes from 9 lines of code to just 1. One thing that would make that line more readable though is if Vector2
implemented a method called .squaredDistance
so you could write it.squaredDistance(mouse.position)
I also struggled a bit in figuring out the best way to generate the random points because I couldn’t find a simple method to generate random values between (0.0, 0.0) and (width, height).
This is another way of doing it
val points = List(30) {
Vector2.uniform(Vector2.ZERO, drawer.bounds.position(1.0, 1.0))
}
which gives you 30 points, each one sampled randomly using a uniform distribution between the point (0.0, 0.0) and the point (640.0, 480.0), which happens to be the default size of the window. drawer.bounds
is the Rectangle that defines the visible area and .position(1.0, 1.0)
refers to the bottom right corner of that area.
Share your questions and comments below | Find other OPENRNDR & Processing posts