Hello , im using the Hashgrid object from the processing utils library.
The way for iterating over the elements of the hashgrid is a bit different than traditional iteration with "for" , it is in the folliwing way:
for (Iterator i=hashGrid.iterator(); i.hasNext()
{
Dot d_1 = (Dot)i.next();
}
My question is: how can i access to the i variable as a number?
If i need to calculate the distance between 2 points in my hash grid i need to make a nested iteration and make the traditional " if ( i != j){ }"
in order that the code doesnt calculate the distance with itself, but this doesnt work in this new way of iterating, as a consecuence of this i and J are never going to be the same, so that means that its going to calculate the distance between itself and my collisions are not going to work. Any idea of how to solve this?
thanks
here is the code:
Code:
import org.gicentre.processing.utils.*;
HashGrid hashGrid;
static final float RADIUS = 50; // Search radius for hash grid
void setup()
{
size(800,400);
smooth();
noFill();
hashGrid = new HashGrid(width,height,RADIUS);
for (int i=0; i< 2; i++)
{
hashGrid.add(new Dot(random(width),random(height)));
}
}
void draw()
{
background(255);
stroke(0);
strokeWeight(2);
for (Iterator i=hashGrid.iterator(); i.hasNext();)
{
Dot d = (Dot)i.next();
d.mueve();
point(d.getLocation().x, d.getLocation().y);
}
Set dotsNearMouse = hashGrid.get(new PVector(mouseX,mouseY));
if (mousePressed)
{
hashGrid.removeAll(dotsNearMouse);
}
else
{
strokeWeight(6);
stroke(120,20,20,200);
for (Iterator i=dotsNearMouse.iterator(); i.hasNext();)
{
Dot d = (Dot)i.next();
//print(d.getLocation().x);
point(d.getLocation().x,d.getLocation().y);
}
}
hashGrid.updateAll(); // se requiere esto cuando hay movimiento para refrescar los objetos en el hashgrid
}
class Dot implements Locatable
{
private PVector d;
float dista;
Dot(float x, float y)
{
d = new PVector(x,y);
}
void mueve(){
d.x = d.x + (random(20) - 10) * 0.1 ;
d.y = d.y + (random(20) - 10) * 0.1 ;
//colision begins here
for (Iterator i=hashGrid.iterator(); i.hasNext();)
{
Dot d_1 = (Dot)i.next();
for (Iterator j=hashGrid.iterator(); j.hasNext();)
{
Dot d_2 = (Dot)j.next();
//print(" " + i);
//here is the problem because im not using a real iterator variable , i and j are never going to be the same numbers
//and as a result of this problem this is goint to calculate the distance between a point with sphere.
if ( i != j){
dista = dist(d_1.getLocation().x , d_1.getLocation().y, d_2.getLocation().x , d_2.getLocation().y);
if( dista < 1 ) {
print(" " + dista);
}
}
}
}
}
PVector getLocation()
{
return d;
}
}