How do I make the ball behave like this: when you click, it moves horizontally until it bounces...

How do I make the ball behave like this: when you click, it moves horizontally until it bounces off a wall, and then it automatically starts moving as before? This is the code:

int xPosition, yPosition;
int xAdder = 3;
int yAdder = 7;
int r, g, b;
boolean rIncreasing = true;

void setup() {

  size(displayWidth/2, displayHeight); 
  xPosition = 200;
}

void draw() {

  background(255, 0, 255);

  fill(r, g, b);

  ellipse(xPosition, yPosition, 100, 100);

  xPosition = xPosition + xAdder;
  yPosition = yPosition + yAdder;

  if (xPosition > displayWidth/2) {
    xAdder = -3;
  }
  if (yPosition > displayHeight) {
   yAdder = -7; 
  }

  if (xPosition < 0) {

    xAdder = 3;
  }

  if (yPosition < 0) {

    yAdder = 7;
  }

  if (rIncreasing) {
    r = r + 1;
  } 
  else {
    r = r - 1;
  }

  if (r > 255) {
    rIncreasing = false;
  } 
  else if (r < 0) {
    rIncreasing = true;
  }
}

Answers

  • edited October 2013

    Hey, this is a solution :

    int x, y, dx;
    int width;
    boolean state;//true = moving ; false = not moving
    
    void setup() {
      state = false;
      width = displayWidth/2;
      background(0);
      size(displayWidth/2, displayHeight);
      x = 300; 
      y = 100;
      dx =2; 
    }
    
    void draw(){
      background(0);
      ellipse(x, y, 10, 10);
      if(mousePressed)
        state = true;
      //Correction of horizontal movement
      if(state){
        x +=dx;
        if(x>=width || x <=0){
          dx = -dx;
          if(x>=width)
            x = width-1;
          if(x<=0)
            x = 1;
        }
      }
    }
    

    Hope i helped.

  • Ok, seriously, didn't we answer this the last time you posted it?

    forum.processing.org/two/discussion/comment/870

  • No, this is slightly different

Sign In or Register to comment.