Bouncing off the wall

edited March 2017 in Questions about Code

I would like to ask you for help with bouncing off the wall.I would like that ball bounce exactly off the wall(not bounce off other parts of screen).

PImage wall1; int wall1X,wall1Y,wall1W,wall1H; int x; float y; boolean collision; void setup() { size(900,300); frameRate(30); background(255);
wall1=loadImage("wall.png"); wall1X=90; wall1Y=10; wall1W=10; wall1H=100; x=width/2+200; y=random(100,200); }

void draw() { background(255); fill(0); ellipse(x,y,25,25); image(wall1,wall1X,wall1Y,wall1W,wall1H); x-=5;

if(wall1Y<11) { collision=true;
} if(collision)

{ wall1Y+=5; }

if(wall1Y>200) {

collision=false;

} if(collision==false) { wall1Y-=5; } }

Tagged:

Answers

  • Please edit your post, select your code and hit ctrl+o to format your code. Make sure there is an empty line above and below your code

    Kf

  • ok, main idea here is to have a variable that you add to the position of wall (and another for ball); now on reflection you change that directional var.

    PImage wall1; 
    int wall1X, wall1Y, wall1W, wall1H; 
    int x; 
    float y;
    float xAdd = -5;
    float wall1Y_ADD = 5;  
    boolean collision; 
    void setup() { 
      size(900, 300); 
      frameRate(30); 
      background(255);
      wall1=loadImage("wall.png"); 
      wall1X=90; 
      wall1Y=10; 
      wall1W=10; 
      wall1H=100; 
      x=width/2+200; 
      y=random(100, 200);
    }
    
    void draw() { 
      background(255); 
      fill(0); 
      ellipse(x, y, 25, 25); 
      text("wall1", wall1X, wall1Y, wall1W, wall1H);
    
      // ball 
      x+=xAdd;
    
      // WALL / PADDLE 
      if (wall1Y<11) { 
        wall1Y_ADD = abs(wall1Y_ADD);
      } 
      if (wall1Y>height-30) {
        wall1Y_ADD = -1 * abs(wall1Y_ADD);
      } 
    
      wall1Y += wall1Y_ADD;
    
      // interact ball and paddle 
      if (x<=wall1X+5 &&
        x>wall1X-15 &&
        y>wall1Y && 
        y<wall1Y + wall1H)
      {
        background(255, 0, 0);//RED
        xAdd *= -1;
      }
      //
    }
    
Sign In or Register to comment.