Collision detection with circle and square test

Hi, I am struggling with learning how to use colission detection in processing, and i would really appreciate some help, I have tried everything in my power to figure it out, but I just can’t do it. For a project in my class, I need to use this exact method to create a game and make it have a game over, however I am just testing it by doing a simple circle and square colission detection. The problem is im not sure how to detect corners, any help? P.S I apologize for the way my code is, I have been just testing stuff non stop.

float x,y;
final int RECT_SIZE = 50;
final int DIAM = 35;
boolean hit=false;
void setup(){
  size(500,500);
  noStroke();
  x = random(0,width-RECT_SIZE);
  y = random(0,height-RECT_SIZE);
}
void draw(){
  background(#A1A2A1);
  //rectangle
  fill(#A21085);
  rect(x,y,RECT_SIZE,RECT_SIZE);
   pointOverlap(mouseX,mouseY,x,y,RECT_SIZE,RECT_SIZE);
  //circle is green when it is NOT on the rectangle
  fill(#00FF00);
  if(hit){

    fill(#FF0000);
  }
  ellipse(mouseX,mouseY,DIAM,DIAM);
  
  // work on this
  //hit = rectOverlap(x1,y1,x2,y2,size1,size2);
}
//and this
boolean pointOverlap(float x1,float y1, float x2, float y2, float size1, float size2){
  boolean test = false;
  if(x1+size1/2>=x2&&y1+size1/2==y2){
  test=true;
  print(test);
  }
  return test;  
}
//and this
boolean rectOverlap(float x1,float y1, float x2, float y2, float size1,float size2){
  boolean test = false;
  
  
  return test;
}
//this makes the square move when you click the mouse
void mousePressed(){
  x = random(0,width-RECT_SIZE);
  y = random(0,height-RECT_SIZE);
}
1 Like
3 Likes

Had some similar problems. Not sure if this is helpful but…
Now firstly: you don’t need an extra variable test i think, if the function is of boolean type you can just write it like

boolean pointOverlap(float x1,float y1, float x2, float y2, float size1, float size2){
  if(x1+size1/2>=x2&&y1+size1/2==y2){
  print(test);
  return true;
  }
  else {
  return false;
  }  
}

Then you can use it this way

  if(pointOverlap) {
  ...//executes when pointOverlap returns true
  }

Sorry if you knew that already:)
What is the problem with detecting corners? Think of it this way: You want the circle to notice when it hits a square.
I guess one could compare each coordinate of each square with the ones of the circle but i guess thats too much at least for my laptop. Another possibility is to check whether the circle is inside the square. Look at GoToLoops link its good

1 Like

Are you allowed to use code libraries, or is the goal in your class to understand your own implementation of collision?

1 Like

By the way here is a nice explanation (for rects that aren’t rotated lower answer):

thanks guys, i figured it out