HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Plan to make a small game - got a hang of canvas and made a cube fly around

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
aroundgotmadehangmakeflyplangamesmallcube

Problem

I'm planning to make a small game for learning purposes. So far, I've got the hang of the canvas element and using the context to draw things on it, as well as object notation and classes in JavaScript.

But before moving on to making the rest of the game, I'd like you to please take a look at my code and see if there's something I should have done differently. Anything, such as that shouldn't be called or anything as simple as that. Any tips and suggestions are happily accepted!

Here is a link to the jsbin: http://jsbin.com/hozazeki/1

If that one throws an error or doesn't work, try this: http://jsbin.com/hozazeki/1/edit

P.S: I refer to the red cube as goat. Placeholder graphics, 'ya know?

```
//Creating requestAnimationFrame to avoid crashing the browser
var requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| fallbackRequestAnimationFrame;

function fallbackRequestAnimationFrame(func) {
setTimeout(func, 0); // Emulate a requestAnimationFrame if none is available
}

//Game object - doesn't have to be a class
game = {

state: "stopped", //initial state of the game
W: 800, //canvas size vars
H: 600,

//Function called by the html page - initializes the game
init: function(){

//get canvas context object
var canvas = document.getElementById("canvas");
this.context = canvas.getContext("2d");

//create goat
this.goat = new Goat();

//start game
this.start(this.context);
},

//Function called to start the game - triggers the game loop
start: function(canvas){

//change the game state
this.state = "running";

//variables used for deltaTime
this.previousTime = new Date().getTime();

//trigger game loop
requestAnimationFrame

Solution

Interesting,

-
http://jsperf.com/path-rect-vs-fillrect/7 will tell you that fillRect is faster than what you use in clearCanvas.

-
window.onload

-
(deltaTime / 1000)

-
game.previousTime += deltaTime;

-
in update, you really update the data(model), your function name should reflect that

Other than that, I like your style. I would advise you to read up on IIFE's, as they can help you avoid writing this. all the time. Your code is fine now, but at some point this. might get annoying.

Context

StackExchange Code Review Q#46560, answer score: 5

Revisions (0)

No revisions yet.