Example of bouncing ball

var gameScreen = document.getElementById("gameScreen");
var context = gameScreen.getContext("2d");

context.fillStyle = "#FFFFFF";
context.font = "8px Sans-Serif";
context.fillText("Pong!", 10, 10);

var ball = {
	x : 50,
	y : 50,
	width : 5,
	height : 5,
	x_direction : 1,
	y_direction : 1
};

var previousBall = ball;

var boundary = {
	x1: 20,
	x2: 200,
	y1: 20,
	y2: 120	
};

context.fillStyle = "#FF00FF";
context.strokeStyle = "#FF00FF";

context.strokeRect(boundary.x1, boundary.y1, boundary.x2 - boundary.x1, boundary.y2 - boundary.y1);

var timer = setInterval(updateGameScreen, 10);


function updateGameScreen() {
	context.clearRect(previousBall.x, previousBall.y, previousBall.width, previousBall.height);
	previousBall = ball;
	
	if (ball.x_direction === 1) {
		ball.x += 2;
		
		if (ball.x_direction === 1 && ball.x > boundary.x2 - 10) {
			ball.x_direction = -1;
		}
	}
	
	if (ball.x_direction === -1){
		ball.x -= 2;
		
		if (ball.x_direction === -1 && ball.x < boundary.x1 + 10) {
			ball.x_direction = 1;
		}
	}
	
	
	if (ball.y_direction === 1) {
		ball.y++;
		
		if (ball.y_direction === 1 && ball.y > boundary.y2 - 7) {
			ball.y_direction = -1;
		}
	}
	
	if (ball.y_direction === -1){
		ball.y--;
		
		if (ball.y_direction === -1 && ball.y < boundary.y1 + 7) {
			ball.y_direction = 1;
		}
	}
	
	context.fillRect(ball.x, ball.y, ball.width, ball.height);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s