Tuesday 14 June 2011

Video - Intro to HTML5 Game Dev


In this video, I go into the absolute basics of HTML5 game creation.

The result page is here.

And here is the source I wrote then used in the video:

<html>
<head>
 <script type="text/javascript">
  const FPS = 30;
  var canvas = null;
  var context2D = null;
  
  
  var playerImg = new Image();
  playerImg.src = "http://filevaults.com/media/Slash/553481-smiley.png";
  
  var playerPosX = 0;
  var playerPosY = 0;
  var playerVelX = 0;
  var playerVelY = 0;
  
  
  var keys = new Array();
  window.addEventListener('keydown', keyDown, true);
  window.addEventListener('keyup', keyUp, true);
  function keyDown(evt){
   keys[evt.keyCode] = true;
  }
  function keyUp(evt){
   keys[evt.keyCode] = false;
  }
  
  
  
  window.onload = init;
  
  function init() {
   canvas = document.getElementById('canvas');
   context2D = canvas.getContext('2d');
   
   setInterval(draw, 1000/FPS);
  }
  
  
  function draw() {
   update();
   
   context2D.clearRect(0, 0, canvas.width, canvas.height);
   context2D.drawImage(playerImg, playerPosX, playerPosY);
  }
  
  
  function update() {
   
   if ((37 in keys && keys[37]) || (65 in keys && keys[65])){ //left
     playerVelX -= 2;
    }
    if ((39 in keys && keys[39]) || (68 in keys && keys[68])){ //right
     playerVelX += 2;
    }
    
    playerVelX *= 0.9;
    
    if (playerPosY >= canvas.height - playerImg.height) {
    playerVelY = 0;
    playerPosY = canvas.height - playerImg.height;
    }
    else {
    playerVelY += 2;
    }
   
   playerPosX += playerVelX;
   playerPosY += playerVelY;
  }
  
 </script>
</head>
<body>
 
 <canvas id="canvas" width="500" height="500" style="background-color: #a9a9a9;">
  Browser not compatible with canvas.
  download FireFox 4.
 </canvas>
 
</body>
</html>

4 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Nice tutorial very helpfull as well as the code. Any advice, tutorials or pointers for adding a maze?

    ReplyDelete
  3. BTW, thank you for the very good tutorial.

    ReplyDelete