Search This Blog

Thursday, September 6, 2012

HTML 5 gaming

Few people around me were working with HTML 5. After seeing those cool stuffs it was irresistible to start working in it. Canvas element is the most attractive part of HTML5 according to me. Using it we can develop very cool stuffs like animations and games!
I decided to develop a game. I was playing Road Fighter ( classic nes game, which makes me nostalgic whenever i play it now ) yesterday night. So i thought of developing a similar game.
Games require lot of intelligent coding. I was introduced to game development basics by a colleague. So i don't use while(1) for looping infinitely anymore.
I started of with a simple gameloop for which i set an interval of 1000/60 . Which means the loop runs again and again after 1000/60 milliseconds. (ie)  1/60th of a second. This gives us 60 frames per second speed in which our game runs.
Inside the game loop i called functions to drawlines and then clear the canvas.
By drawing lines vertically and moving it down for every loop i had a road movement like effect.
Next i placed mycar at the bottom of the canvas.
Used jquery to capture key press and moved the car left and right based on keys i press.
Finally made another car to come in opposite direction.
Still lot of things left to be complete, but before moving any further i thought of refactoring my code.
At this point i came across requestAnimFrame function which gives smooth animations in html5.
It took some time to figure out how to use the Animation frame. It works like this, our gameloop has to be given as a callback function to the requestAnimFrame event of windows. Inside the function which gets called when we request a animation frame, we setInterval of 60fps and call our gameloop after getting a new animation frame each time. I don't know how exactly it speeds up my animation/game. But i will research and tell you soon.
Stay in touch. See you in next blog.

No comments:

Post a Comment