Detecting if SquareA is colliding with SquareB
in
Programming Questions
•
6 months ago
Hello everyone!
I started learning Processing two days ago and I'm experimenting quite a bit. So far, I'm loving it. I've been trying to make a little program where the user can control a square (SquareA) and when he collides with SquareB, the screen goes all red.
I managed to program a very primitive form of collision, but it only takes in account SquareB's corner (I'm comparing the coordinates of both squares to generate a big, red rect() that would cover the whole screen.
I think the logic is kind of there, but I would need to find a way to take in account all the points in both squares and compare them. I don't know how to do this yet and there's where I would need some help. My idea, for the moment, is to find a way to calculate the squares areas to know which coordinates they're occupying and then comparing them. But this seems kind of complicated, I'm sure there's another way that I don't know yet.
Any pointers for syntax and those kind of things will be appreciated too.
Here's a screenshot, for visual reference.
Here's the code.
- void setup(){
- size(500,500);
- frameRate(60);
- background(255);
- smooth();
- }
- //Positions
- int posX = 250;
- int posY = 250;
- int posEx = 200;
- int posEy = 100;
- //Function to call "SquareB"
- void enemy() {
- fill(255,8,8);
- rect(posEx,posEy,50,50);
- }
- //Moving SquareA
- void keyPressed() {
- background(255);
- print("PosX:"); println(posX);
- print("PosY:"); println(posY);
- print("PosEx:"); println(posEx);
- print("PosEy:"); println(posEy);
- println("------------");
- if (key ==CODED){
- if (keyCode==DOWN)
- posY = posY+10;
- else if (keyCode==LEFT)
- posX = posX-10;
- else if (keyCode==RIGHT)
- posX = posX+10;
- else if (keyCode==UP)
- posY = posY-10;
- }
- }
- //Here is where my problem is, I think
- void draw(){
- noStroke();
- fill(2);
- rect(posX,posY,20,20);
- enemy();
- if ((posX==posEx) && (posY==posEy)){
- fill(255,8,8);
- rect(0,0,5000,1000);
- }}
1