1

I am creating an atari breakout game in processing and I'm trying to figure out the collision detection that allows the ball to bounce off the controller. The commented out lines (along with the hitController function) is supposed to be the method for this and the program runs fine without the commented lines but with them, it causes a NullPointerException. Any suggestions?

class Ball {
  float rad = 15;
  float xpos, ypos;
  float xspeed = 2.8;
  float yspeed = 2.2;
  float xdir = 1;
  float ydir = 1;
  Controller controller;

  Ball(){
    noStroke();
    ellipseMode(RADIUS);
    xpos = width/2;
    ypos = height/2;

  }

  void move(){
    xpos = xpos + (xspeed * xdir);
    ypos = ypos + (yspeed * ydir);

    if(xpos > width - rad || xpos < rad){
      xdir *= -1;
    }
    if(ypos > height - rad || ypos < rad){
      ydir *= -1;
    }
    //boolean hit = hitController(xpos, ypos, rad, controller.getY());
    //if(hit){
      //xdir *= -1;
      //ydir *= -1;
    //}
  }

   void display(){
    ellipse(xpos, ypos, rad, rad);
    }

    boolean hitController(float cx, float cy, float rad, float ry){
      float testX = cx;
      float testY = cy;
      if(cy < ry){
        testY = ry;
      }
      float distX = cx - testX;
      float distY = cy - testY;
      float distance = sqrt((distX * distX)+(distY * distY));

      if(distance <= rad){
        return true;
      } else {
        return false;
      }
    }

  }

edit: I have included the controller class below as well.

class Controller {
  int cwidth;
  int cheight;
  color c;
  float x, y;

  Controller() {
    cwidth = 155;
    cheight = 15;
    c = color(50,10,10,150);
    x = 0;
    y = 0;
  }

  void setLocation(int x, int y) {
    this.x = x;
    this.y = y;
  }


  void display() {
    x = constrain(mouseX, 70, 640 );
    y = constrain(mouseY, 480, 480);

    rectMode(CENTER);
    fill(c);
    rect(x, y, cwidth, cheight);

  }

  float getX() {
    return x;
  }

  float getY() {
    return y;
  } 
}
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • 1
    Could you provide the entire program so it's easier to test? Because you haven't provided any controller class which may be causing the problem – MorganS42 Nov 30 '19 at 00:15
  • 3
    Where do you instantiate `controller`? Even though you declared it as a global variable, you must instantiate it (probably in the `setup()` method). – laancelot Nov 30 '19 at 00:19
  • Please provide a [mcve]. The problem is quite possibly traceable to code which you have neglected to include. – John Coleman Nov 30 '19 at 01:33
  • Please read the answers to the question that I've linked as a duplicate of this one. Understanding why *this* specific example fails isn't nearly as important as learning how to diagnose similar problems in the future. – Jon Skeet Nov 30 '19 at 09:54

0 Answers0