Thank you!
I am having a problem accessing paddle.x.
In my main program I create a paddle and then I create a ball, passing to it the paddle.
I can access paddle.x fine in the main program and in my Ball constructor. But when I try to access it elsewhere in my Ball class it throws null pointer exception.
Here is my current code:
Ball ball;
Paddle paddle;
void setup() {
size(640, 480);
paddle = new Paddle();
ball = new Ball(paddle);
// println(paddle.x); prints paddle.x
}
void draw() {
background(0);
paddle.draw();
paddle.move();
paddle.checkBoundaries();
ball.draw();
ball.move();
}
class Paddle {
public float x;
public final float y = 440;
float speedX;
public Paddle() {
x = 0;
}
public void move() {
x = mouseX;
}
public void draw() {
fill(255);
rect(x, y, 100, 20);
}
public void checkBoundaries(){
if(x < 0){
x = 0;
}
if(x > (width - 100)){
x = width - 100;
}
}
}
class Ball {
float xPos =0;
float yPos = 0;
float xSpeed = 2.8;
float ySpeed = 2.2;
int xDirection = 1;
int yDirection = 1;
int rad = 16;
final float speed = 5;
Paddle paddle;
public Ball(Paddle paddle){
paddle = paddle;
// set starting position of the ball, start in center of screen
xPos = width / 2;
yPos = height / 2;
// println(paddle.x); prints paddle.x
}
public void move() {
// update the ball's position
xPos += (xSpeed * xDirection);
yPos += (ySpeed * yDirection);
// println(paddle.x); throws null pointer exception
}
public void draw() {
ellipse(xPos, yPos, rad, rad);
checkBoundaries();
}
public void checkBoundaries() {
//// check collision between ball and paddle, 100 = paddle length
//if(xPos > paddle.x){
////if(xPos > paddle.x && xPos < (paddle.x + 100) && (yPos + 20) >= paddle.y) {
// xSpeed = abs(xSpeed) * -1;
// ySpeed = abs(ySpeed) * -1;
//}
println(paddle.x);
if(xPos > width - rad) {
xSpeed = abs(xSpeed) * -1;
}
if(xPos < rad) {
xSpeed = abs(xSpeed);
}
if(yPos > height - rad) {
ySpeed = abs(ySpeed) * -1;
}
// check lower screen boundary
//if(yPos < rad) {
// ySpeed = abs(ySpeed);
//}
}
public void checkCollision() {
}
}
Paddle and Ball are included together above.
So I am confused about passing objects in processing. I had to use globals to make this work. Instead - as above - what I really want to do is have the ball know about the paddle. But after passing to the constructor when I try to access paddle.x I get null pointer.
Note: I am using all public and no getter/setters for simplicities sake.