Moving an object

Hello I need help with an issue and I'm rather new to this whole programming thing. I've been trying to understand how to get my rectangle to move forward and than follow a rectangle path or any type of path really and than return it its starting position. I've been trying to do this with If statements but it just locks up.

code so far

float x = 0;
float y = 100;

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

void draw() {
  background(255);
  fill(0);
  rect(x,y,20,20);

  x = x + 1;

  if (x > 100) {
    x = 100;
    y = y + 1;
  }
  if (y > 200) {
    y = 200;
    x = x + 1;
  }
}

Answers

  • Answer ✓

    Cleaned up your code for you...

    To solve this problem, you must see that the object in motion has four distinct states: one in which it is traveling along each side of the box. As such, there should be an if statement for each and a corresponding change in motion:

    float x = 0;
    float y = 100;
    
    void setup() {
      size(500, 500);
    }
    
    void draw() {
      background(255);
      fill(0);
      rect(x, y, 20, 20);
    
      if(y == 100) //Traveling along the top
        x ++;
      if(y == 200) //Traveling along the bottom
        x --;
      if(x == 100) //Traveling along the right side
        y ++;
      if(x == 0) //Traveling along the left side
        y --;
    }
    

    Now, if you want to make it move along a different path, such as a circle, that would be a bit more complicated... keeping the path axis-aligned makes things easy.

Sign In or Register to comment.