Make a Ball bounce off all Four Walls
// Declare CONSTANT_VARIABLES
var BALL_SIZE = 20;
var BALL_SPEED = 2; // Declare Variable for Ball Speed
// Declare operatorVariables
var ballDirectionX = "right";
var ballDirectionY = "down";
var ballPositionX = 40;
var ballPositionY = 200;
draw = function(){ // Begin Draw Loop
background(0); // Clear the screen Black
// Draw the Ball
ellipse(ballPositionX, ballPositionY, BALL_SIZE, BALL_SIZE);
/** If it hits the Right side of Screen */
if(ballPositionX > 399 - BALL_SIZE / 2){
ballDirectionX = "left"; // Reverse Direction
}
/** If it hits the Left side of Screen */
if(ballPositionX < BALL_SIZE / 2){
ballDirectionX = "right"; // Forward Direction
}
/** The Bottom of the Screen */
if(ballPositionY > 399 - BALL_SIZE / 2){
ballDirectionY = "up";
}
/** The Top of Screen */
if(ballPositionY < BALL_SIZE / 2){
ballDirectionY = "down";
}
// Add BALL_SPEED to Ball Position X
if(ballDirectionX === "right"){
ballPositionX += BALL_SPEED;
}else{ // Don't need "if left". Only 2 possiblities ;)
ballPositionX -= BALL_SPEED;
}
// Add BALL_SPEED to Ball Position Y
if(ballDirectionY === "down"){
ballPositionY += BALL_SPEED;
}else{ ballPositionY -= BALL_SPEED; }
}; // End Draw Loop
We also need to create these actions as Functions
draw = function(){ // Begin Draw Loop
background(0); // Clear the screen Black
// Draw the Ball
ellipse(ballPositionX, ballPositionY, BALL_SIZE, BALL_SIZE);
/** Call the Ball Update Function **/
updateBall();
}; // End Draw Loop
Lets also make the Paddle a Function
// Declare GAME_CONSTANTS These never change.
var PADDLE_WIDTH = 60;
var PADDLE_HEIGHT = 20;
var PADDLE_TOP = 360;
// Declare gameOperators These will be updated.
var paddleLeft;
/** Declare Update & Draw Functions outside Draw Loop */
var updatePaddle = function(){
paddleLeft = mouseX - PADDLE_WIDTH / 2;
};
var drawPaddle = function(){
rect(paddleLeft, PADDLE_TOP, PADDLE_WIDTH, PADDLE_HEIGHT);
};
draw = function(){ // Begin Draw Loop
background(0);
/** Call Update & Draw Functions inside Draw Loop */
updatePaddle();
drawPaddle();
}; // End Draw Loop
/* Tutorials in plain English by Dillinger © 2013
All code is owned by its respective author
and made available under an MIT license:
http://opensource.org/licenses/mit-license.php */
Letʻs add some Variables
/** Declare PADDLE_CONSTANTS */
var PADDLE_WIDTH = 60;
var PADDLE_HEIGHT = 20;
var PADDLE_TOP = 360;
/** Declare BALL_CONSTANTS */
var BALL_SIZE = 20;
var BALL_SPEED = 4; // Declare Variable for Ball Speed
/** Declare paddleOperators */
var paddleLeft;
/** Declare ballOperators */
var ballDirectionX = "right";
var ballDirectionY = "down";
var ballPositionX = 40;
var ballPositionY = 200;