Check if two or more objects are side by side
in
Programming Questions
•
3 months ago
I made a little sketch where you have to move to boxes. The sketch should check if the two boxes are side by side or on top of each other. Each box is an object, and the check-function works god with this two objects. But when i want to have three or more boxes it will get complicated. Do you have any suggestions to simplify this?
box box1;
box box2;
int[] xxx= {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
int[] yyy= {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
float[] xpos=new float[10];
float[] ypos=new float[10];
int boxh;
float weite, breite;
int posx;
int posy;
boolean blockaktiv, blockaktiv1;
void setup() {
size(displayWidth, displayHeight);
weite=width/15;
breite=height/20;
boxh=width/13;
for (int i=0;i<=9;i++)
{
ypos[i]=breite;
breite=breite+boxh;
}
for (int i=0;i<=9;i++)
{
xpos[i]=weite;
weite=weite+boxh;
}
box1=new box(color(124, 32, 211), 1, 1, 1, 1);
box2=new box(color(124, 32, 211), 1, 3, 1, 2);
}
void draw() {
background(0);
//x++
box1.display();
box2.display();
//rect(posx,posy,boxh,boxh);
println(width+" "+height);
println(box1.posx+" "+box2.posy);
if (box1.posx==box2.posx-boxh
&&box1.posy==box2.posy)text("BANG!!!!", 10, 10);
if (box2.posx==box1.posx-boxh
&&box1.posy==box2.posy)text("BANG!!!!", 10, 10);
if (box1.posy==box2.posy-boxh
&&box2.posx==box1.posx)text("BANG!!!!", 10, 10);
if (box2.posy==box1.posy-boxh
&&box1.posx==box2.posx)text("BANG!!!!", 10, 10);
}
class box {
color c;
int xx;
int yy;
int[] xa=new int[10];
int[] ya=new int[10];
float xspeed;
boolean aktiv;
float posx, posy;
// The Constructor is defined with arguments.
box(color tempC, int tempXpos, int tempYpos, int tempXa, int tempYa ) {
c = tempC;
xx = tempXpos;
xx = tempYpos;
}
void display() {
stroke(0);
fill(c);
if (mousePressed==false) {
aktiv=false;
}
if (mousePressed==true
&& mouseX>=xpos[xx]
&& mouseX<=xpos[xx]+boxh
&& mouseY>=ypos[yy]
&& mouseY<=ypos[yy]+boxh)
aktiv=true;
if (
mousePressed==true
&& mouseX>=xpos[xx] +boxh
&& mouseX<=xpos[xx] +boxh+boxh
&& mouseY>=ypos[yy]
&& mouseY<=ypos[yy]+boxh+boxh
&& aktiv==true) {
xx=xx+1;
if (xx>=9)xx=9;
if (xx<=0)xx=0;
for (int i=0;i<=9;i++)
{
xa[i]=0;
}
xa[xx]=1;
}
//x--
if (
mousePressed==true
&& mouseX>=xpos[xx] -boxh
&& mouseX<=xpos[xx]
&& mouseY>=ypos[yy]
&& mouseY<=ypos[yy]+boxh+boxh
&& aktiv==true) {
xx=xx-1;
if (xx>=9)xx=9;
if (xx<=0)xx=0;
for (int i=0;i<=9;i++)
{
xa[i]=0;
}
xa[xx]=1;
}
//y++
if (
mousePressed==true
&& mouseX>=xpos[xx]
&& mouseX<=xpos[xx] +boxh
&& mouseY>=ypos[yy] +boxh
&& mouseY<=ypos[yy] +boxh+boxh
&& aktiv==true) {
yy=yy+1;
if (yy>=9)yy=9;
if (yy<=0)yy=0;
for (int i=0;i<=9;i++)
{
ya[i]=0;
}
ya[yy]=1;
}
//y--
if (
mousePressed==true
&& mouseX>=xpos[xx]
&& mouseX<=xpos[xx] +boxh
&& mouseY>=ypos[yy]-boxh
&& mouseY<=ypos[yy]
&& aktiv==true) {
yy=yy-1;
if (yy>=9)yy=9;
if (yy<=0)yy=0;
for (int i=0;i<=9;i++)
{
ya[i]=0;
}
ya[yy]=1;
}
rect(xpos[xx], ypos[yy], boxh, boxh);
posx=xpos[xx];
posy=ypos[yy];
}
}
1