# Help understanding code

Hi
The code below works but I don’t understand why to check boundaries I check boxSize/2 - ballSize instead of just boxSize-ballSize. I’m clearly not understanding something here. Can anyone explain it to me please?

``````PVector location;
PVector velocity;
float boxSize = 100;
int ballSize = 5;

void setup(){
background(0);
size(600,600, P3D);
location = new PVector(0,0,0);
velocity = new PVector(3,2,1);
}

void draw(){
background(0);
noFill();
pushMatrix();
translate(width/2,height/2,0);
box(boxSize);

translate(location.x, location.y, location.z);

//println(location.x, location.y, location.z);

if ((location.x > boxSize/2 - ballSize || location.x < -boxSize/2 + ballSize)) {
velocity.x = velocity.x * -1;
}
if ((location.y > boxSize/2 -  ballSize|| location.y <-boxSize/2 + ballSize)) {
velocity.y = velocity.y * -1;
}
if (location.z > boxSize/2 -  ballSize || location.z < -boxSize/2 + ballSize) {
velocity.z = velocity.z * -1;
}

stroke(255);
strokeWeight(5);
sphere(ballSize);
popMatrix();
}
``````
1 Like
• the box has the size `boxSize`, half of it is `boxSize/2`

• The ball starts at 0,0 (where we add width/2 and height/2 to)

But that’s why we check for boxSize/2 : the box center is at 0,0 and boxSize/2 is the length of the distance from the center to each side of the box (in x and y and z direction).

The box sides are located at `+boxSize/2` and at `-boxSize/2` from the center (to each direction)

Chrisir

Remark

everything looks better with `lights()` and RED:

Now you can make a single player Pong game

``````
PVector location;
PVector velocity;
float boxSize = 350;
int ballSize = 14;

void setup() {
size(600, 600, P3D);
//frameRate(8);
background(0);
location = new PVector(random(3), random(0.4, 3), random(0.4, 3));
velocity = new PVector(random(0.4, 3), random(0.4, 2), random(0.4, 1));
}

void draw() {
background(0);
lights();

// ---------------------------------------------

pushMatrix();
translate(width/2, height/2, 0);
noFill();
stroke(255);
strokeWeight(5);
box(boxSize);
popMatrix();

// ---------------------------------------------

pushMatrix();
translate(width/2, height/2, 0);
translate(location.x, location.y, location.z);
bounce();
noStroke();
fill(255, 0, 0); // RED
sphere(ballSize);
popMatrix();
}

// ---------------------------------------------

void bounce() {

//println(location.x, location.y, location.z);

if ((location.x > boxSize/2 - ballSize || location.x < -boxSize/2 + ballSize)) {
velocity.x = velocity.x * -1;
}
if ((location.y > boxSize/2 -  ballSize|| location.y < -boxSize/2 + ballSize)) {
velocity.y = velocity.y * -1;
}
if (location.z > boxSize/2 -  ballSize || location.z < -boxSize/2 + ballSize) {
velocity.z = velocity.z * -1;
}
}
//
``````
1 Like

Thank you so much - I hadn’t realized that Box was drawn from the center (should have read the reference !!!) . Many thanks.

1 Like

Remark

everything looks better with `lights()`