Simple Collision Detection
in
Programming Questions
•
1 year ago
For now, what i want to do is have the controllable square turn red when it touches another square. Eventually i will have the screen clear until the mouse is pressed. Please give any help on setting up the collision detection. Here is my code so far:
Rectangle rect1;
Rectangle rect2;
Rectangle rect3;
Rectangle rect4;
void setup() {
size(200,200);
rect1 = new Rectangle(color(255,0,0),0,random(200),random(2,5));
rect2 = new Rectangle(color(0,0,255),0,random(200),random(2,5));
rect3 = new Rectangle(color(0,255,0),0,random(200),random(2,5));
rect4 = new Rectangle(color(255,0,255),0,random(200),random(2,5));
}
void draw() {
background(255);
rect1.drive();
rect1.display();
rect2.drive();
rect2.display();
rect3.drive();
rect3.display();
rect4.drive();
rect4.display();
fill(0);
rect(mouseX,mouseY,10,10);
}
class Rectangle {
color c;
float xpos;
float ypos;
float xspeed;
Rectangle(color tempC, float tempXpos, float tempYpos, float tempXspeed) {
c = tempC;
xpos = tempXpos;
ypos = tempYpos;
xspeed = tempXspeed;
}
void display() {
stroke(0);
fill(c);
rectMode(CENTER);
rect(xpos,ypos,30,30);
}
void drive() {
xpos = xpos + xspeed;
if (xpos > width) {
xpos = 0;
ypos = random(200);
xspeed = random(2,5);
}
}
}
1