I'm trying to make a Pong clone, but the ball bounces off the wall anyways even if there's no pad

right rpad = new right(); ball b = new ball(); int pos; int ballY,ballX; void setup() { size(800,600); } void draw() { background(0,0,0); rpad.display(pos); b.move(ballY); if ((ballY<pos+40) && (ballY>pos-40)) { b.bounce(); } class ball { int x = width/2; int y = height/2; int velx = 4; int vely = 4; int locy; void move(int locy) { locy = y; x+=velx; y+=vely; fill(255); ellipse(x,y,15,15); if (y>600 || y<0) { vely=vely*-1; } if (x<10) { velx*=-1; } } void bounce() { if (x > 790) { velx*=-1; } } } class right { int x = 790; int y = 300; void display(int posY) { rectMode(mouseY); rect(x,mouseY+40,x+10,mouseY-40); posY = mouseY; } } }

Tagged:

Answers

  • Answer ✓
    RightPaddle rpad = new RightPaddle();
    Ball b = new Ball();
    
    //int pos;
    
    // int ballY, ballX;
    
    void setup() {
      size(800, 600);
    }
    
    void draw() {
      background(0, 0, 0);
    
      rpad.display();
      b.move(); 
    
      if ((b.y<mouseY+40) && (b.y>mouseY-40)) {
        b.bounce();
      } else {
        if (b.x > 790) {
          exit();
        }
      }
    }
    
    // ==========================================================
    
    class Ball {
    
      int x = width/2;
      int y = height/2;
      int velx = 4;
      int vely = 4;
      //int locy;
    
      void move() {
        // locy = y;
        x+=velx;
        y+=vely;
    
        fill(255);
        ellipse(x, y, 15, 15);
    
        if (y>600 || y<0) {
          vely=vely*-1;
        }
        if (x<10) { 
          velx*=-1;
        }
      }  
    
      void bounce() {
        if (x > 790) {
          velx=-abs(velx);
        }
      }
    }
    
    // ==========================================================
    
    class RightPaddle {
    
      int x = 790;  
      // int y = 300;
    
      void display() {
        rectMode(mouseY);   
        rect(x, mouseY+40, x+10, mouseY-40);
        // posY = mouseY;
      }
    }
    //
    
  • no clear understanding of classes and objects here

    do the tutorial on objects please

    Best, Chrisir ;-)

  • edited May 2017

    Basically, you need an if statement saying that if the ball touches the wall, it stops. I'm not sure on the code for this, but here's basically what you need:

    if (ballTouchesPaddle) {
      velx = velx * -1;
    }
    else if (ballCenterPosition == width - 15) {
      velx = 0; //you will need a reset here
    }
    

    That code WILL NOT COMPILE. I feel, however, that it will give you a good representation of what you need. The first conditional can be created by saing basically if the ball's center x is 15 less than the paddle's center x and the ball's center y is within 40 of the paddle's center y, they are touching. The second one seems self-explanatory. I'm pretty sure it's your int x in your Ball class.

Sign In or Register to comment.