Skip to content

Instantly share code, notes, and snippets.

@janzeteachesit
Last active February 18, 2017 08:42
Show Gist options
  • Save janzeteachesit/b670713e38f66b12d9c97c669493d692 to your computer and use it in GitHub Desktop.
Save janzeteachesit/b670713e38f66b12d9c97c669493d692 to your computer and use it in GitHub Desktop.
Chapter 1: Tennis_Step09
<!--
As long as it's between the start and end marks then it's a valid comment and won't show up on the page. But people can View Source in their browser and see it!
-->
<canvas id="gameCanvas" width="400" height="300"></canvas><!-- //// -->
/*
Utilising CodePen JavaScript Console (//codepen.io/nullobject/pen/cngzI)
made with love by @nullobject (http://joshbassett.info), 2014.
Stuff from tutorial not needed in CodePen
<!DOCTYPE>, <html>, <head> <body> tags
window.onload = function script
grist for this pen:
https://gist.github.com/janzeteachesit/b670713e38f66b12d9c97c669493d692
*/
// variables to keep track of ball position //// 05
var ballX = 75, ballY = 75; //// 05
var ballSpeedX = 8; //// 06
var ballSpeedY = 8; //// 09
// save the canvas for dimensions, and its 2d context for drawing it //// 05
var canvas, canvasContext; //// 05
canvas = document.getElementById('gameCanvas'); ////
canvasContext = canvas.getContext('2d'); ////
// these next few lines set up our game logic and redner to happen times a second //// 05
var framesPerSecond = 30; //// 05
setInterval(function() { //// 05
moveEverything(); //// 05
drawEverything(); //// 05
}, 1000/framesPerSecond); //// 05
function moveEverything() { //// 06
if(ballX > canvas.width || ballX < 0) { // if ball moves beyond the right or left edges //// 08
ballSpeedX *= -1; // reverse the ball's horizontal direction //// 07
}
ballX += ballSpeedX; // move the ball to the right by a small amount //// 06
if(ballY > canvas.height || ballY < 0) { // if ball moves beyond the top or bottom edges //// 09
ballSpeedY *= -1; // reverse the ball's vertical direction //// 09
}
ballY += ballSpeedY; // move the ball to the right by a small amount //// 06
} //// 06
function drawEverything() { ////
console.log("ballX: " + ballX + " + ballY: " + ballY)
// clear the game view by filling it with black
canvasContext.fillStyle = '#222'; ////
canvasContext.fillRect(0, 0, canvas.width, canvas.height); ////
// draw a white circle
canvasContext.fillStyle = '#fff'; ////
canvasContext.beginPath(); ////
canvasContext.arc(ballX, ballY, 10, 0, Math.PI*2, true); ////
canvasContext.fill(); ////
} ////
<link href="//codepen.io/nullobject/pen/cngzI" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment