Loading...
Logo
Processing Forum

Hey all,

Just wondering if anyone can guide with my code I've sort of got it working but it's not perfect I'm trying to make it so the smaller Square is detected as soon as any part of it enters the area of the bigger one but I have no clue how to do that.
any ideas? 

thanks so much,

Harrison
code

Copy code
  1. float blockX = random(500);
  2. float blockY = random(500);


  3. void setup(){
  4.   
  5.   size(500,500);
  6.   smooth();
  7.   noStroke();
  8. }
  9. void draw()
  10. {
  11.   
  12.   collide();
  13.   background(200);
  14.   fill(0);
  15.   rect(mouseX,mouseY,20,20);
  16.   fill(0,0,255);
  17.   rect(blockX,blockY,5,5);
  18.   
  19. }

  20. void collide(){
  21.   
  22.   if(((mouseX + 10  >=  blockX)&&(mouseX <= blockX )&&(mouseY + 10 >= blockY)&&(mouseY <= blockY))
  23.   ||((mouseX - 10  >=  blockX)&&(mouseX <= blockX )&&(mouseY - 10 >= blockY)&&(mouseY <= blockY))){
  24.   
  25.   blockX = random(500);
  26.   blockY = random(500);
  27.   }
  28.   
  29.   
  30. }

Replies(2)

First off you might want to look at using rectMode(CENTER), then the dragged rectangle will appear at the centre of the mouse location rather than the corner.  As for the collision detection, assuming you're using rectMode(CENTER) on all rectangles then the x/y coordinates represent the centres of the rectangles and you need to determine when an edge of one rectangle crosses the edge of another.  You were actually on the right track with mouseX + 10....  So:

Copy code
  1. // where 'rect1' is at the mouse location and rect2 is the target
  2. if(mouseX + rect1HalfSide > blockX - rect2HalfSide
  3.   && mouseX - rect1HalfSide < blockX + rect2HalfSide
  4.   && mouseY + rect1HalfSide > blockY - rect2HalfSide
  5.   && mouseY - rect1HalfSide < blockY + rect2HalfSide
  6.   ) {
  7.       //do stuff...
  8. }

Notice that separating things out onto lines makes it a bit more readable and there's no || (OR) being used...

Ah, that's a neat little function rectMODE thanks! I like this format too 

Thank you!