Bouncing off all edges of a screen §
int xPos = 400;
int yPos = 200;
int xVelocity = -3;
int yVelocity = -3;
void setup() {
size(500, 500);
}
void draw() {
// caleb b
// bouncing off all edges of a screen
background(190, 190, 0);
rect(xPos, yPos, 20, 20);
xPos += xVelocity;
yPos += yVelocity;
// Check if the square has reached (or gone past) the left edge
// This translates to checking that the square's x-position is
// equal to (or less than) 0
if (xPos <= 0) {
// Switch the sign of the velocity to change directions
xVelocity = -xVelocity;
}
// Check if the square has reached (or gone past) the right edge
// i.e. check if it's xPosition is >= the screen width (which is 500)
if (xPos >= 480) {
// Switch the sign of the velocity to change directions
xVelocity = -xVelocity;
}
// Do the same but for Y velocity
if (yPos <= 0) {
yVelocity = -yVelocity;
}
if (yPos >= 480) {
yVelocity = -yVelocity;
}
}
Bouncing Ball §
int xPos = 400;
int yPos = 200;
int xVelocity = -3;
int yVelocity = -3;
void setup() {
size(500, 500);
frameRate(60);
}
void draw() {
// caleb b
// bouncing ball
background(190, 190, 0);
ellipse(xPos, yPos, 20, 20);
xPos += xVelocity;
yPos += yVelocity;
// Check if the square has reached (or gone past) the left edge
// This translates to checking that the square's x-position is
// equal to (or less than) 0
if (xPos <= 10) {
// Switch the sign of the velocity to change directions
xVelocity = -xVelocity;
}
// Check if the square has reached (or gone past) the right edge
// i.e. check if it's xPosition is >= the screen width (which is 500)
if (xPos >= 490) {
// Switch the sign of the velocity to change directions
xVelocity = -xVelocity;
}
// Do the same for Y velocity
if (yPos <= 10) {
yVelocity = -yVelocity;
}
if (yPos >= 490) {
yVelocity = -yVelocity;
}
}