# Array and dist();

I did 2 Arrays of floats to make X and Y positions for a collision system that uses dist(); but I dont know how to put the arrays information on it.
The function must work for 15 ellipses that are not implementated but first I need to set the array numbers on the dist(); so I dont have to repeat the code for every single ellipse.

``````float yp[] = {60.0, 130.0, 250.0, 420.0, 1245.0, 985.0, 655.0, 228.0, 179.0, 568.0, 1174.0, 445.0, 792.0, 1066.0, 750.0};
float xp[] = {908.0, 198.0, 248.0, 273.0, 206.0, 180.0, 269.0, 108.0, 991.0, 224.0, 257.0, 576.0, 204.0, 371.0};

void obstacles(){

**if(dist(x+=xSpeed, y+=xSpeed, xp[], yp[]) < Rad)**
//That is where I need help, how I can implementate all the array on the xp[] and yp[] place?
{
if(xSpeed >0){
xSpeed = -1;
}
else if(xSpeed < 0){
xSpeed = 1;
}
if(ySpeed > 0){
ySpeed = -1;
}
else if(ySpeed < 0){
ySpeed = 1;
}

}
}
``````
1 Like

Look at `array` in the reference

Displaying both arrays

To display it use a `for` loop - see reference

``````
for(int i.....) {

ellipse(xp[i], yp [i], 7,7);

}
``````

the distance part

For the distance part use another `for` loop with i and inside it a for loop with j that starts at i+1

``````for(int i=0; i.....................
for(int j=i+1; j.....................
``````

Chrisir

1 Like

Chrisir is right.

something like

`````` //update the ellipses
for(int i = 0; i < xp.length; i++) {
xp[i] += xSpeed;
yp[i] += ySpeed;
}
//handle collisions
for(int i = 0; i < xp.length; i++) {
for(int j = 0; j < xp.length; j++) {
if(i != j) {
float dx = xp[i] - xp[j];
float dy = yp[i] - yp[j];
float dist = Math.sqrt(dx * dx + dy * dy);

xSpeed = -xSpeed;
ySpeed = -ySpeed;
}
}
}
}
``````

but this is much nicer

``````class MyEllipse
{
PVector pos, vel;
public MyEllipse(float x, float y, float radius) {
pos = new PVector(x, y);
vel = new PVector(random(5), random(5));
}

public void update() {
}

public void present() {
}
}

MyEllipse[] myEllipses;
void setup() {
size(640, 480, P2D);
noStroke();

//amount of coordinates so i dropped the extra y coordinate
myEllipses = new MyEllipse[] {
new MyEllipse(60, 908, 32),
new MyEllipse(120, 198, 32),
new MyEllipse(250, 248, 32),
new MyEllipse(420, 273, 32),
new MyEllipse(1245, 206, 32),
new MyEllipse(985, 180, 32),
new MyEllipse(655, 269, 32),
new MyEllipse(228, 108, 32),
new MyEllipse(179, 991, 32),
new MyEllipse(568, 224, 32),
new MyEllipse(1174, 257, 32),
new MyEllipse(445, 576, 32),
new MyEllipse(792, 204, 32),
new MyEllipse(1066, 371, 32)
};
}

void draw() {
background(0);
for(int i = 0; i < myEllipses.length; i++) {
MyEllipse me1 = myEllipses[i];
for(int j = 0; j < myEllipses.length; j++) {
if(i != j) {
MyEllipse me2 = myEllipses[j];

if(me1.pos.dist(me2.pos) < 32) {
me1.vel.mult(-1);
}
}
}
}

for(int i = 0; i < myEllipses.length; i++) {
MyEllipse me = myEllipses[i];

me.update();
me.present();
}
}
``````
2 Likes