Skip to content

Instantly share code, notes, and snippets.

View CodeDraken's full-sized avatar

CodeDraken

View GitHub Profile
// some default values
const defaultConfig = {
width: 500,
height: 500,
gravity: 0.25,
friction: 0.98
}
// classes are functions that create objects
;(function () {
// global variables that will be loaded/initialized later
let canvas, ctx, gravity, ball, friction
// runs once at the beginning
// loads any data and kickstarts the loop
function init () {
// *load data here*
// our canvas variables
canvas = document.getElementById('gameCanvas')
// bottom bound / floor
if (ball.y + ball.radius >= canvas.height) {
// reverse direction and lose energy from bouncing
ball.velY *= -ball.bounce
// reset position
ball.y = canvas.height - ball.radius
// slow down the ball's X velocity with friction
ball.velX *= friction
}
// top bound / ceiling
function update () {
// queue the next update
window.requestAnimationFrame(update)
// logic goes here
// bottom bound / floor
if (ball.y + ball.radius >= canvas.height) {
ball.velY = -ball.velY
ball.y = canvas.height - ball.radius
// the main piece of the loop
// runs everything
function update () {
// queue the next update
window.requestAnimationFrame(update)
// logic goes here
// add gravity
ball.velY += gravity
// the main piece of the loop
// runs everything
function update () {
// queue the next update
window.requestAnimationFrame(update)
// logic goes here
// draw after logic/calculations
draw()
// draws stuff to the screen
// allows us to separate calculations and drawing
function draw () {
// clear the canvas and redraw everything
ctx.clearRect(0, 0, canvas.width, canvas.height)
// draw the ball (only object in this scene)
ctx.beginPath()
ctx.fillStyle = 'red'
ctx.arc(
// global variables that will be loaded/initialized later
let canvas, ctx, gravity, ball, friction
function init () {
// our canvas variables
// ...
// set the canvas size
// ...
// world/scene settings
// ...
(function () {
// global variables that will be loaded/initialized later
let canvas, ctx, gravity, ball, friction
// runs once at the beginning
// loads any data and kickstarts the loop
function init () {
// load data here
canvas = document.getElementById('gameCanvas')
ctx = canvas.getContext('2d')
// global variables that will be loaded/initialized later
let canvas, ctx, gravity, ball, friction
// runs once at the beginning
// loads any data and kickstarts the loop
function init () {
// load and initialize data here
// ...
// begin update loop