move one rect with another. usin collide functions/

edited March 2014 in Using Processing

hi. I want move a rect with anothe rect but I only can move the rect in this way please show my code.. and well I want move the second rect depens of the position of the mover rect

float x=100.0;
float y=100.0;
float w=80;
float h=30;

float x1=150;
float y1=150;
float w1=80;
float h1=30;

void setup(){
  rectMode(CENTER);
  size(500,500);
}

void draw(){
  background(0);
  x=mouseX;
  y=mouseY;
  rect(x,y,w,h);
  rect(x1,y1,w1,h1);
  if (collision(x,y,w,h,x1,y1,w1,h1)==true){
    println("collide");
    fill(255,0,0);
 x1=mouseX+80;
 y1=mouseY;
  } else {
    println("nocollide");
    fill(255);
  }
}

boolean collision(float x_1, float y_1, float width_1, float height_1,
                  float x_2, float y_2, float width_2, float height_2){
  return !(x_1 > x_2+width_2 || x_1+width_1 < x_2 || y_1 > y_2+height_2 || y_1+height_1 < y_2);
}
Tagged:

Answers

  • Answer ✓

    Note: you call fill() after having drawn the rect(), it isn't doing what you expect (the fill will be used on the next draw() call).

    A good way to do what you want is to learn to use classes. There are tons of examples of rectangle colliding in the forum and in the examples shipped with Processing.

Sign In or Register to comment.