Protected: 2 – How to Build a 2D Platform Game With the Canvas Element and Javascript

This content is password protected. To view it please enter your password below:

Advertisements

1 – How to Build a 2D Platform Game With the Canvas Element and Javascript

I decided I wanted to learn more about the new canvas element in html5 and gain a better understanding of how it worked with javascript to create animation and interactions that appear to be on level with flash. I believe the best way to learn something is to dig in and program something. So, without further introduction, lets begin building a 2d platform game with the canvas element and javascript.

The Goal:
  • I would like our end result to be a basic, re-usable platform game engine based off the html5 canvas element.

What you will need:

  • An up to date browser that supports html5
  • A text editor

Inside this tutorial:

To get started open up a new html document and add our canvas element inside the body tag:

<canvas id=”canvas” width=”500″ height=”600″ style=”border:dashed”>
Your Browser Does not offer support for the canvas tag, please update.
</canvas>

This will place a 500×600 cavas on your doc with a dashed border. Like an iframe, The content in the cavas tag will only be displayed if the browser viewing it does not support the canvas tag.

Next we are going to open up the script tag and define a useful function for shorthand and our character object constructor.

Useful shorthand:

//Useful shorthand function//
function $(id){return document.getElementById(id);}

This shorthand function is simply going to take out some of the code we need to write in order to get elements by ID. By using this function we can save time by writing –$(‘canvas’)– Instead of writing –document.getElementById(‘canvas’)–

Character object constructor:

//char object constructor
function char(){
//Set base characteristics for this character
this.x = 20;
this.y = 500;
this.width = 50;
this.height = 75;
this.speed = 5;
this.color = ‘#0f0’;

//Initiate this character
this.init();
}//Close char constructor

Our char constructor is setting some basic attributes about our character that would ideally be set with optional parameters. But that is outside the scope of this tutorial, for now we will just get it down on paper and worry about the finer details at a later time. Lets take a look at what we just set.

this.x is setting the horizontal position of our char, and this.y the vertical. this.height and width should be fairly self explanatory, as should this.color. this.speed is setting an integer by wich we will increment and decrement our char position, the higher the number, the faster he goes. The last thing we do is call this.init() method, which we will define now.

char init method:

char.prototype.init = function(){
this.draw();
}//Close char.init();

Currently all our init() method does is call this chars draw method. It could be removed by calling the draw method directly from our char constructor. However by leaving it in we are providing our future selves with a place to perform pre-loading changes to our character. For example, if the level loaded is sticky and our character wouldn’t be able to move as fast as he normally would we could  set an IF statement to adjust the speed accordingly. Something like: –if(environment == sticky){this.speed -= 2}– and then we would never have to think about it again.

char draw method:

char.prototype.draw = function() {
//get canvas and context information
var canvas = $(‘canvas’);
var ctx = canvas.getContext(‘2d’);

//clear stage
ctx.fillStyle = “#FFF”;
ctx.fillRect(0,0,canvas.width,canvas.height);

//Draw new position
ctx.fillStyle = this.color;
ctx.fillRect(this.x,this.y,this.width,this.height);
}

Our char.draw() method is where we start to get into the complicated functions of the canvas element. So lets dissect this method and explain what we are doing.

First we get the canvas element by id (did you notice our shorthand function?) and store it the variable ‘canvas’. Next we are getting the 2 dimensional context of the canvas, so that the canvas knows we are only working in 2d, and store it in variable ‘ctx’ (short for context). var ctx is the object we are gong to call all of our drawing functions on.

Next we clear the stage of pre-existing drawings. Simply put we are setting any drawing to be filled with white (ctx.fillStyle = “#FFF”;) and then drawing a box over the entire canvas(ctx.fillRect(0,0,canvas.width,canvas.height);). If we did not do this, when our character moved his old position would still be on the canvas and the new would be drawn over it, leaving a nice trail showing where we went. (That is rather important, I urge you to take out these two lines after we get the char moving and see what I mean.)

Finally we draw our character with the parameters set in the char object constructor. first setting the fillstyle to this.color (ctx.fillStyle = this.color;) and then drawing him at the proper x and y location with the proper width and height (ctx.fillRect(this.x,this.y,this.width,this.height);).

At this point we are ready to create an instance of a char object and see it drawn on the canvas.All we need to do is call the object creator:

var p1 = new char();

If you have been following along you may now load up our page in your browser and should now be able to see a green rectangle in the bottom left corner of your canvas.

– – Consider cutting post here – –

Lets add some interaction! first thing we are going to need are some var for intervals and a listener for a key press:

//set the “Frame Rate” for which our character will step.
var stepRate = 25;

//set Directional variables that will hold the movment intervals
var mu = false;// mu = Movement Up
var md = false;// md = Movement down
var ml = false;// ml = Movement Left
var mr = false;// mr = Movement Right

document.onkeydown = function(e){// start listening for keydown events

//Set keycode/charcode to var
if(navigator.appName == “Netscape”){var key = e.keyCode;}
else{var key = (event.charCode)? event.charCode : event.keyCode;}

if(key == 38){// if up is pressed
if(mu == false){// if not moving up
mu = setInterval(function(){p1.moveup()}, stepRate);// Set upward movement
}
return false;
}
if(key == 40){// if down is pressed
if(!md){// if not moving down
md = setInterval(function(){p1.movedown()}, stepRate);// Set downward movement
}
return false;
}
if(key == 37){// if left is pressed
if(!ml){// if not moving left
ml = setInterval(function(){p1.moveleft()}, stepRate);// set left movement
}
return false;
}
if(key== 39){// if right is pressed
if(!mr){// if not moving right
mr = setInterval(function(){p1.moveright()}, stepRate);// set right movement
}
return false;
}
}//close document.onkeydown

Now that is a longer bit of code, lets go through it.

The first thing we are setting (var steprate = 25) is the step rate, or frame rate. This number represents how many milliseconds are going by before the frame refreshes. since our interaction is going to be very simple right now, the frame is only going to refresh when the character is walking. Eventually (when we add gravity) we will need to change that but for this tutorial it will work just fine.

Next we have a group of variable that will hold our intervals followed by our document.onkeydown function.

This function simply gets the keyCode or charCode, depending on the browser, and if it matches one of the defined key codes ( in this case the arrow keys ) it checks to see if our character is moving in that direction ( if(!mu) )  and if not, sets an interval that calls our chars move methods at the step rate. It also returns the default action false if the key pressed matched so that the screen doesn’t scroll up and down.

Next we need to add our chars move methods. Semantically you would want to add these under the other char methods.

our char move methods:

char.prototype.moveup = function(){
// new Y position
this.y -= this.speed;
//Check and account for boundary
if(this.y <= 0 ){this.y += this.speed*2;}
this.draw()
}
char.prototype.movedown = function(){
//new Y position
this.y += this.speed;
//check and account for boundary
if(this.y+this.height >= $(‘canvas’).height){this.y -= this.speed*2;}
this.draw();
}
char.prototype.moveleft = function(){
//new X position
this.x -= this.speed;
//check and account for boundary
if(this.x <= 0 ){this.x += this.speed*2;}
this.draw();
}
char.prototype.moveright = function(){
//new X position
this.x += this.speed;
//check and account for boundary
if(this.x+this.width >= $(‘canvas’).width){this.x -= this.speed*2;}
this.draw();
}

For each move method the first thing we are doing to calculating the new x and y position respectively. We do this by adding or subtracting the chars set speed to the position. ( this.x += this.speed; ) After that we check to see if the new position is going to put our char outside of the canvas, if it does we add or subtract this.speed x 2 in order to keep him inside of the boundary.

Now we have our correct new position calculated and all that we need to do is draw our character at this position, simply done by once again calling our already defined draw method.

At this point if you load up our page you will get that green box that will move when you press the arrow keys. The problem is that when the key is released our box continues on in that direction. We will fix that with a key up event listener:

document.onkeyup = function(e){// start listening for keyup events

//Set keycode/charcode to var
if(navigator.appName == “Netscape”){var key = e.keyCode;}
else{var key = (event.charCode)? event.charCode : event.keyCode;}

if(key == 38){// if up is released
clearInterval(mu);// clear the movement
mu = false;// set holder to false
}
if(key == 40){// if down is released
clearInterval(md);// clear the movement
md = false;// set holder to false
}
if(key == 37){// if left is released
clearInterval(ml);// clear the movement
ml = false;// set holder to false
}
if(key == 39){// if right is released
clearInterval(mr);// clear the movement
mr = false;// set holder to false
}
}//close document.onkeyup

Upon examination this bit of script is pretty straight forward. Just like our key down it gets the keyCode or CharCode for the browser and tests to see if it matches one of our directional keys. If it does it simply clears the interval and sets the variable holding the interval to false. Simple as that.

We now have a green box that we can move around with our arrow keys. We have defined an char object constructor and several methods of our char object so that in the future we will be able to add more than the one player.


here

test


Polyphasic sleep schedule – day 14

So this day marks two weeks.

only one more week to go.

I had decided to sleep the night leading into day 14. just to sleep. It wasn’t to bad and i wound up waking up earlier and more alert then i have in a very long time.  so even if after the end of this 3 weeks, i decided to go back to a monophasic sleep cycle. these three weeks have been wonderful in teaching me about sleep.

Looking back on the history of the past 2 weeks, I realize that i have not followed the uberman schedule verbatim. I have been doing this whimsical sleep when i want, be awake when i want. Slowly some rough guidelines are forming in my head that keep me awake and alert.  but they have not been a set schedule. just out lines. what I have began to realize is:1:

1. stick as close to the schedule as you can, because the more time you on the schedule the less time you spend sleeping.

2. missing naps is a pain, IF you don’t pre-compensate for the missed sleep. for example if you have work and cant take 1 or 2 naps during that time, add 20 mins per nap you will miss on top of the regular 20 mins (optional:  an extra 20 mins for playing it safe ) such as if you are going to miss two naps sleep 1 to 2 hours and you will be set for that time. (This is just a rough estimation, and id like to look into it more, but its kind of the guideline I’ve ran by.)

3. DO NOT SLEEP LONGER THEN 7-8 HOURS AT A TIME!! running over this especially when pretty close to on schedule is the best way to mess your mind up. you wake up disoriented and groggy.

4. there is a maximum amount of time before you should sleep again. I am not sure what it is, but Judging by the uberman its seems 20 mins sleep = 4 hours awake is about average, and thats what i set my pre-compensation rule to. so lets check it against an 8 hour (monophasic sleep schedule )

8 hours sleep = 24 TMS (twenty minuet sections)

lol, by that logic thats 96 hours you can stay awake.

obviously, not exactly right, and I beleive thats because during a 90 min sleep phase you pass through several cycles REM only being one of them. and Im not allowing the time in other cycles to be acounted for.

so my 20 min rule gets deteriorated over time.

more on that latter.

those are the 4 basic rules I’ve ran my sleeping by. as of right now, the max time awake rule is mostly played by feel depending on how tiered i am, or how close I’m sticking to schedule. no real problems during that time.

the benefits of this “whimsical” sleep schedule is that its more flexible then the uberman. but you still get the time awake at night if you so choose. there is also no right or wrong way to do it since thats what its about is being more moveable around your schedule.

Im curious to hammer out a schedule that is not a mathematical as any of the ones I’ve read about so far. one that appears lop sided when looked at. kind of like the everyman schedule. but again, not as clean cut. a schedule built around a work schedule or some thing like that. We will see.

Im quite curious as to what you think about this whimsical schedule. Let me know.

 

Im skipping the daily summary today since i slept last night. just assume everything is normal. 😛


Polyphasic sleep schedule – day 13

As far as i can remember day 13 was pretty unremarkable. I did skip my 9AM nap, which had some negative effects latter on in the day. but other then that It we pretty unremarkable. so this post may be a short one, sorry if that bothers you.

This last week i realized i missed some thing about a monophasic sleep schedule. That is the time i spent laying next to my wife every night. Since, normally, we are asleep, i would not have thought that this would have been a conscious realization but i have been missing the time spent at her side at night.

DAILY SUMMARY, SUNDAY, DAY 13

  • Health: Normal
  • Energy Level: Normal
  • Daily Functioning: Skipped nap made it hard to stay awake in church.
  • Social performance: Normal-ish, today seemed a little tense.
  • brief day overview: As stated, today was a little tense and im still slightly on edge. Which is another reason this post is short,  I dont really have the patients for it today.
  • Schedule Adherence: 5/6 naps so 86% -and 90% accurate sleeping times.  Over all :  88%

Sorry again for the short post.



Polyphasic sleep schedule – day 12

Allright, day twelve.

as explained in my late day 11 post day 12 didn’t start out very well.

I was tired. No getting around that. I began the 6 nap period, mostly asleep, remaining that way until the sun was up. (I think it was around 6 or 7) Waking up from a full nights sleep confirmed my suspicion; Im much more groggy when I get more then ive been allowing myself to get. Over sleeping, like that, is worse then skipping naps, by far. I spent the next few hours groggy and in and out of conciseness.

After I finally got my fee under me, I didn’t get aback on schedule till my 5PM nap, which happend to be the first nap I’ve taken in a location other then my bed. I was at my in laws house, they got home today after a 3 week mission to the Philippines, and, after explaining everything to them, I took shelter in a lazy boy in the basement were I spent a lovely 20 minuets.

Recently I have not been sure if I fall asleep during my naps or not. Ill just be laying there and my alarm with go off. Logically my mind says i havent gone to sleep, but then i cant remember thinking about anything for quite some time. Its fairly confusing.

 

DAILY SUMMARY, SATURDAY, DAY 12

  • Health: After becoming solidly conscious this morning, Heath was fine.
  • Energy Level: Same here, after the morning fog wore off, i was great.
  • Daily Functioning: Functioned fine, even shoveled a drive way.
  • Social performance: I dont feel like i talk to alot of people, so it was nice today to have my in laws come home and give me some one “new” to socialize with.
  • brief day overview: A fairly nice day, enjoyed being with my family.
  • Schedule Adherence: Allright, time to see how much I messed up….    only 2/6 naps in this cycle, owch.  33% for that.  as for being awake and asleep when im suposed to: 45% so the grand total:  .. .. .. .. .. (drum roll).. .. .. .. ..  39% schedule Adherence.    Owch.



Polyphasic sleep schedule – day 11

My apologies, again, for not posting this on time.  And just to clarify this post is for friday, day 11, and should have been posted last night at 1AM. Last night i had my little brother and sister over for the night and i was playing with them, thats why i didn’t post.

I also Skipped 3 out of 6 naps. at around 8 everything was going well, I had stayed on schedule and it was looking like it was going to be another, more or less, on track day.  Then the Cafe I filled in at the weekend called and asked if i would come down. I believe that when an opportunity to make money come along you take it, so accordingly, I took it.

Lucky for me I had extended my 5AM nap so staying up during the day while working at the cafe was not to hard even though i worked thorough my 9AM and 1PM naps. I was up and i was doing stuff and i was very surprised at how little fatigue i felt. I was expecting to be dragging my feet by 3 (when i get off) but i was still awake and active. I walked up the hill debating wether to take a nap as soon as i got home or to wait until 5 and just be on schedule again. The decision was made for me by my teething infant son, he had been grumpy all day and it was break time for mom. so I waited until 5 with no real problems. That nap went well. down and up within 20 mins.

so i was on schedule again, until 9. My 9 PM nap became the third nap that i skipped on day 11, which means collectively by 1AM i had slept 1 hour in a 24 hour period. On a normal monophaisc sleep schedule thats tough, but not to bad, but on this schedule it wasn’t quite enough, and i was pretty exhausted by my 1AM nap. I was pretty worried that i wouldn’t wake up, but i had a plan.

I caffeinated my self 15 before nap time and forced myself to stay up. Just before 1 I set a spicy cup of noodle out to hydrate on my bedside table. Now these spicy cup noodles are one of my favorite things in the world and i would rather go blind then let one go to waste. Now i was sure to wake up when my alarm went off, and i would be waking up to some thing amazing right on my bedside table. It worked and i woke up and had a lovely “breakfast” in bed. I put on an episode of Futurama while i ate and that was my mistake. After i finished eating i sat down to finish the episode and promptly fell back asleep. 😦

and thats why this post is late.

Ive started day 12 off very poorly indeed. but ill leave that for tonights post at 1AM.

DAILY SUMMARY, FRIDAY, DAY 11

  • Health: A normal day in regards to health.
  • Energy Level: As I said surprisingly well during the day for skipping my naps.
  • Daily Functioning: Same thing. very, and surprisingly well until about midnight.
  • Social performance: Normal again! i was pretty social and everything went well.
  • brief day overview: Im going to skip this section since i gave a pretty thorough description above. (now im wondering how many people actually take the time to read it all)
  • Schedule Adherence: 50% accuracy on taking my naps, terrible, i know. As far as sleeping when i was not supposed to the only place out of place was 5AM so i get a pretty good score on that so…… 90%. and for the grand total:  70% again! (but a very different kind of 70% from yesterday)

Day 12 % is gonna be pretty low, I can tell you that right now.