game development using html 5

129
http://osama-oransa.blogspot.com/ March, 2012 HTML 5 Game Development Osama Oransa Hewlett Packard

Upload: osaora

Post on 15-Jan-2015

212 views

Category:

Software


0 download

DESCRIPTION

For more details visit my blog: http://osama-oransa.blogspot.com/

TRANSCRIPT

Page 1: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML 5 GameDevelopment

Osama OransaHewlett Packard

Page 2: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

This is Me!

Page 3: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 4: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML5 Logo

Page 5: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 6: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Development Concepts

• Animations

• Interactions

• Controls

• Boundaries

• Entry Points

• Physics

• AI rules.

Page 7: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Animations

• The animation of any character is based on drawing thisshape many times with different shapes.

• So a cycle of clean and re-draw the shape with timeslicing is the basic of animations.

Page 8: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• You don’t have to create a multiple images, you can use1 image that have all of your frames and display only 1frame at a time.

Page 9: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Sprite Class

• Create object and specify the size of the single frame(width x height)

• Define draw function that draw the specified frame.

• You can either change the frame according to the objectactions or auto-change it.

• This depends on your game object behavior.– drawImage(Image Object, source X, source Y, source Width, sou

rce Height, destination X (X position), destination Y (Y position),Destination width, Destination height)

Page 10: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Interactions

• 2 Types: Dynamics and Collisions.

• Graphics interact with each others through collisiondetection, so once you detect the user character hascollision with enemy or wall or a box,…etc.. we can dothe subsequent needed reaction.

• Collision detections varies from:– Boundaries calculations

– Color detections

Page 11: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Collision Detection

• Calculating the boundaries of each character using itsaxis and width/height

• Advanced collision detection take into consideration thefilled parts only.

• Example:– No Collision

– Collision

Page 12: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Detect collision using the color of the objectboundaries.

• Mostly used in edge detections for the boundaries.

1. X<=10

2. Color==brown

Page 13: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Controls

• Controls varies from Keyboard, Mouse, Joystick, Touch,…etc.

• The most important is to be able to detect controls andrespond to them.

• Also controls have lifetime and could be changed withdifferent game screens.

• Some controls are valid only under certain conditions– Pick something only if exist

– Jump only if the space allow that.

Page 14: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Controls mainly focus on the following:

– Control/Change Direction

– Control/Change Speed

– Control/Change Action

• Sometimes user object is continuously moving so youare only directing the movement, sometimes it is idle andwait your direction and speed etc.

• Controls are mainly affected by boundaries.

Page 15: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Boundaries

• Each game scene this is known as the world , this worldmust have a boundaries where the user object can moveonly inside this.

• The boundaries could be physical like the walls or virtuallike end of your world.

Page 16: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Entry Points

• Usually games have start point either from menu or abutton to start the game from the beginning.

• But most of the games have multiple entry points likeload saved game, where the user can go to this savedscene directly.

• The needs here is to design the game code to enablestarting the game smoothly from different points.

• Your entry point need to have some abstraction toenable this smoothly.

Page 17: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Physics

• Physics engines are very important in gamedevelopment to simulate the animations and interactionbetween the object.

• Make things simulate what happen in the real world.

• Example:

– http://labs.skookum.com/demos/barcampclt_physics

• Example of JS Physics engine: Box2DJS

– Box2DJS is a JavaScript port of Box2D Physics Engine.

– URL : http://box2d-js.sourceforge.net/

Page 18: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

AI

• Most of interactive games need some level of AI tocontrol the enemies or play on behalf of the opponent.

• It varies from simple if/switch cases to complex AIengine rules.

• It could be predictive or non-predictive.

• The more ability to predict future movements the bettergaming quality you will have.

Page 19: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Summary

• Animations

• Interactions

• Controls

• Boundaries

• Entry Points

• Physics

• AI rules.

Page 20: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 21: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML 5 Game Components

• HTML 5 Canvas

• Drawing Functions

• Gradient Colors

• Pattern Fill

• Drawing Text

• 2D Context

• HTML 5 Web Storage

• HTML 5 Audio/Video

Page 22: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML 5

• HTML 5 improves interoperability and reducesdevelopment costs by making precise rules on how tohandle all HTML elements, and how to recover fromerrors.

• Some of the new features in HTML 5 are functions forembedding audio, video, graphics, client-side datastorage, and interactive documents.

• To test browser support:– http://www.html5test.com/

Page 23: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML 5 Canvas

• Uses JavaScript to draw graphics on a web page.

• A canvas is a rectangular area, and you control everypixel of it.

• The canvas element has several methods for drawingpaths, boxes, circles, characters, and adding images.

<canvas id="myCanvas" width="200" height="100"></canvas>

Page 24: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Example

Page 25: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

Page 26: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Drawing Functions

• Use JS to draw on it:

<script type="text/javascript">var c=document.getElementById("myCanvas");var cxt=c.getContext("2d");cxt.fillStyle=“red";cxt.fillRect(0,0,150,75);

</script>

Page 27: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Some draw functions:cxt.moveTo(10,10);

cxt.lineTo(150,50);

cxt.lineTo(10,50);

cxt.stroke();

cxt.fillStyle="#FF0000";

cxt.beginPath();

cxt.arc(70,18,15,0,Math.PI*2,true);

cxt.closePath();

cxt.fill();

Page 28: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Gradient Colors

var grd=cxt.createLinearGradient(0,0,175,50);

grd.addColorStop(0,"#FF0000");

grd.addColorStop(1,"#00FF00");

cxt.fillStyle=grd;

cxt.fillRect(0,0,175,50);

var img=new Image()

img.src="img_flwr.png"

cxt.drawImage(img,0,0);

Page 29: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Pattern Fill

• Instead of repeat drawing we can apply a pattern usingan image, so you can get the same results with a littleefforts:

var pattern = context.createPattern(backgroundImg,"repeat");

context.rect(0, 25, screenWidth, canvas.height);

context.fillStyle = pattern;

context.fill();

• Possible Parameter Values:repeat, repeat-x, repeat-y, no-repeat.

Page 30: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Drawing Text

context.save();

context.font = "bold 16px sans-serif";

context.textAlign = "left";

context.textBaseline = "top";

context.fillStyle = "red";

context.fillText(“My Game”, 150, 5);

context.restore();

Page 31: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

2D Context

• Best practice to work with context is to push current 2Dcontext status into stack , modify its properties, finishyour work then pop the old status back from the stack.

context.save();

var pattern = context.createPattern(woodImg, "repeat");

context.rect(0, 350, 600, 100);

context.fillStyle = pattern;

context.fill();

context.restore();

context.rect(50, 150, 600, 100);

Page 32: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML 5 Web Storage

• Two new methods for storing data on the client:1. localStorage: stores data with no time limit.2. sessionStorage: stores data for one session.

• Earlier, this was done with cookies.– Cookies are not suitable for large amounts of data,

because they are passed on by EVERY request to theserver, making it very slow and in-effective.

• In HTML5, the data is NOT passed on by every serverrequest, but used ONLY when asked for.

Page 33: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

The localStorage Method

• It is possible to store large amounts of data withoutaffecting the website's performance.

• A website can only access data stored by itself.

• HTML5 uses JavaScript to store and access the data.

• Stores the data with no time limit.

• The data will be available the next day, week, or year.

Page 34: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Example

<script type="text/javascript">localStorage.lastname=“Oransa";document.write(localStorage.lastname);

</script><script type="text/javascript">if (localStorage.pagecount){

localStorage.pagecount=Number(localStorage.pagecount) +1;}else {

localStorage.pagecount=1;}document.write("Visits "+ localStorage.pagecount);</script>

Page 35: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

The sessionStorage Method

• Stores the data for one session.• The data is deleted when the user closes the browser

window.<script type="text/javascript">

sessionStorage.lastname=“Oransa";document.write(sessionStorage.lastname);

</script><script type="text/javascript">

if (sessionStorage.pagecount){sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;

}else {sessionStorage.pagecount=1;

}document.write("Visits "+sessionStorage.pagecount);

</script>

Page 36: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Example

• Methods:– localStorage.setItem('level', level);

– level = parseInt(localStorage.getItem('level',0));

• We used 0 here as default value if no value alreadystored.

• The getter will return null if the value not exist and nodefault value and this is very useful.

• Also you can remove the save item by calling:– removeItem(‘level’);

Page 37: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML 5 Audio

• You can create audio files for your game to reflectuser interactions.

• Using JS code:boom = new Audio("boom.wav");

boom.play();

• Using HTML 5 tag:

<audio src="Phonics Song 2.wav" controls="controls"autoplay="autoplay">Your browser don't support the video element.

</audio>

Page 38: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

HTML 5 Video

• Today, most videos are shown through a plugin (likeflash).

• HTML5 specifies a standard way to include video, withthe video element.<video src=“myMovie.ogg" controls="controls">

Your browser don’t support the video element.

</video>

• Insert content between the <video> and </video> tagsfor browsers that do not support the video element.

Page 39: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Summary

• HTML 5 Canvas

• Drawing Functions

• Gradient Colors

• Pattern Fill

• Drawing Text

• 2D Context

• HTML 5 Web Storage

• HTML 5 Audio/Video

Page 40: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 41: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Balloon Game

Page 42: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Developing A Game Step by Step

• Writing HTML

• Game Status

• Load Resources (Images/Sounds)

• Control Methods

• Game Data

• Game Loop

• Buttons (Start/Load/Save)

Page 43: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Writing HTML<head>

<title>Balloon Game</title>

<script src="js/data.js" ></script>

<script src="js/game.js" ></script>

</head>

<body onload="init();">

<div id="container" style="border:1px solid; cursor:none; width:400px; height:300px;">

<canvas id="canvas" width="400" height="300" ></canvas><div align="center">

<br>

<img id="save" style="cursor:pointer;" src="images/save.png" onclick="saveGame();"/>

<img id="start" style="cursor:pointer;" src="images/start.png" onclick="toggleGameplay();"/>

<img id="load" style="cursor:pointer;" src="images/load.png" onclick="loadGame();"/>

<br>

</div>

</div>

</body>

Page 44: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game VariablesgameloopId=0;gameRunning = false;speed=1;horizontalSpeed = speed;verticalSpeed = -speed;screenWidth=400;screenHeight=300level=0;lives=15;state=0;currentLevel=null;context=null;x=100; xx=100;y=200;

Page 45: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Define Resources//Create game imagesballonImg= new Image();ballonRightImg= new Image();boomImg=new Image();backgroundImg = new Image();pinLeftImg = new Image();pinRightImg = new Image();pinTopImg = new Image();pinButtomImg = new Image();loadImages();//Create and load game soundsboom = new Audio(“audio/boom.wav");

Page 46: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Load Images//load all images for game

function loadImages() {

ballonImg.src = "images/balloon.png";

ballonRightImg.src = "images/balloon2.png";

backgroundImg.src = "images/back.png";

pinLeftImg.src = "images/pin2.png";

pinRightImg.src = "images/pin.png";

pinTopImg.src = "images/pin-red.png";

pinButtomImg.src = "images/pin-red2.png";

boomImg.src = "images/boom.png";

}

Page 47: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Status

• We have 3 different Game Status:

– 0=Playing

– 1=Died (Exploded)

– 2=Game Over

• In each status the game will behave differently:

– 0=Draw the user object

– 1=Draw the explosion (+boom sound) and wait restartof the current level.

– 2=Draw “Game Over” and wait restart of the game.

Page 48: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Statechart

Page 49: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Mouse Control

function mouseMove(event){if(event.pageX>x){ //or clientX

horizontalSpeed=speed;}else{

horizontalSpeed=-speed;}if(event.pageY>y){ //or clientY

verticalSpeed=speed;}else{

verticalSpeed=-speed;}

}

Page 50: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Keyboard Controlfunction doKeyDown(event){

switch (event.keyCode) {case 38: /* Up arrow was pressed */

verticalSpeed=-speed;break;

case 40: /* Down arrow was pressed */verticalSpeed=speed;break;

case 37: /* Left arrow was pressed */horizontalSpeed=-speed;break;

case 39: /* Right arrow was pressed */horizontalSpeed=speed;break;

}}

Page 51: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Touch Control

• Touch events– Three basic touch events are outlined in the spec and implemented

widely across mobile devices:

– touchstart: a finger is placed on a DOM element.

– touchmove: a finger is dragged along a DOM element.

– touchend: a finger is removed from a DOM element.

• Each touch event includes three lists of touches:– touches: a list of all fingers currently on the screen.

– targetTouches: a list of fingers on the current DOM element.

– changedTouches: a list of fingers involved in the current event. Forexample, in a touchend event, this will be the finger that was removed.

• URL:– https://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html

Page 52: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• These lists consist of objects that contain touchinformation: identifier: a number that uniquely identifiesthe current finger in the touch session.

• target: the DOM element that was the target of theaction.

• client/page/screen coordinates: where on the screenthe action happened.

• radius coordinates and rotationAngle: describe theellipse that approximates finger shape.

Page 53: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Example

• This snippet lets you drag a DOM element around usingsingle-finger touch:

var obj = document.getElementById('id');

obj.addEventListener('touchmove', function(event) {

// If there's exactly one finger inside this element

if (event.targetTouches.length == 1) {

var touch = event.targetTouches[0];

// Place element where the finger is

obj.style.left = touch.pageX + 'px'; obj.style.top = touch.pageY + 'px';

}

}, false);

Page 54: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Gamepad Control

• Gamepad specification defines a low-level interface thatrepresents gamepad devices.

• 3 Interfaces defined:

– Gamepad, Navigator and GamepadEvent

• URL:

– https://dvcs.w3.org/hg/gamepad/raw-file/default/gamepad.html

Page 55: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Initialize the Gamefunction init(){

context = document.getElementById('canvas').getContext('2d');screenWidth = document.getElementById('canvas').width;screenHeight = document.getElementById('canvas').height;document.getElementById('canvas').onmousemove=mouseMove;window.addEventListener('keydown',doKeyDown,true);//load level 0state=0;level=0;lives=15;loadLevelData();

}

Page 56: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game DatalevelsDetails= new Array()levelsStartPoint= new Array();levelsPinLeftDetails= new Array();levelsPinRightDetails= new Array();levelsPinTopDetails= new Array();levelsPinButtomDetails= new Array();////////////// level 0levelsDetails[0]= new Array(

10,180,340,80,10,95,120,90,10,38,40,65,50,38,320,40,300,20,50,20,230,78,40,105,315,78,40,80,270,120,60,38 );levelsStartPoint[0]= new Array( 250,200 );levelsPinLeftDetails[0]= new Array( 5,165,5,190,5,215 );levelsPinRightDetails[0]= new Array( 100,150,100,125,340,40,322,220,322,190 );levelsPinTopDetails[0]= new Array( 50,95,70,95,90,95,225,78,245,78 );levelsPinButtomDetails[0]= new Array( 150,228,170,228 );///////////// Level 1levelsDetails[1]= new Array( 290,20,60,280,40,20,60,210,90,140,220,90);levelsStartPoint[1]= new Array( 300,240 );levelsPinLeftDetails[1]= new Array( 35,165,35,190 );levelsPinRightDetails[1]= new Array( 320,140,320,115,320,90 );levelsPinTopDetails[1]= new Array( 130,140,150,140,170,140,190,140,210,140 );levelsPinButtomDetails[1]= new Array( 250,198 );

Page 57: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Load Level Datafunction loadLevelData(){

details =levelsDetails[level];startPoint =levelsStartPoint[level];pinLeftDetails =levelsPinLeftDetails[level];pinRightDetails =levelsPinRightDetails[level];pinTopDetails =levelsPinTopDetails[level];pinButtomDetails =levelsPinButtomDetails[level];if(startPoint[0]!=-1) {

x=startPoint[0];}else{

x=xx;}y=startPoint[1];drawLevel();

}

Page 58: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

Level 3

Level 2

Level1

Page 59: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Draw Levelsfunction drawLevel(){

context.clearRect(0, 0, screenWidth, screenHeight);var pattern = context.createPattern(backgroundImg, "repeat");context.rect(0, 25, screenWidth, canvas.height);context.fillStyle = pattern;context.fill();//draw level detailsfor (var l = 0; l < details.length; l=l+4) {

context.fillRect(details[l],details[l+1],details[l+2],details[l+3]);}if(pinRightDetails[0]!=-1){

for (var l = 0; l < pinRightDetails.length; l=l+2) {context.drawImage(pinRightImg, pinRightDetails[l],pinRightDetails[l+1]);

}}

Page 60: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.if(pinLeftDetails[0]!=-1){

for (var l = 0; l < pinLeftDetails.length; l=l+2) {context.drawImage(pinLeftImg,

pinLeftDetails[l],pinLeftDetails[l+1]);}

}if(pinButtomDetails[0]!=-1){

for (var l = 0; l < pinButtomDetails.length; l=l+2) {context.drawImage(pinButtomImg,

pinButtomDetails[l],pinButtomDetails[l+1]);}

}context.fillText("Ballon Game", 20, 5);currentLevel=context.getImageData(0, 0, screenWidth, screenHeight);

}

Page 61: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Loop

• It do the following 2 tasks:– Draw the background again.– Draw the new animations.

• In our game we will only move the user object , if thereare other objects that need to be moved , then we musthandle them here.function gameLoop(){

if(state==0){context.putImageData(currentLevel, 0, 0);moveUser();

}}

Page 62: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Static Background

Page 63: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Flow

init()

loadLevelData()

drawLevel()

Click start

Level Image

Draw Level ImageDraw Movement

Game Loop

Load resourcesDefine variablesDefine controls

Load Game

Page 64: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

MoveUser Methodfunction moveUser(){

collision=false;//Move the user in the current direction……… Logic of movements…..//detect collision!if(collision==true){

//Draw the boomcontext.drawImage(boomImg, x, y);lives--;boom.play();state=1;gameRunning=false;clearInterval(gameloopId);if(lives==0){

gameOver();}

}else{//Draw the userif(horizontalSpeed>0) context.drawImage(ballonImg, x, y);else context.drawImage(ballonRightImg, x, y);if(y<10) {

if(level<10) level++;else level=0;xx=x;loadLevelData();

}}drawGameStatistics();

}

Logic of Movement& Collision detection

Draw the collisionOr the balloon.

Detect Game OverDetect Next Level

Draw Game statistics

Page 65: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

function drawGameStatistics(){

var curLevel=level+1;

context.save();

context.font = "bold 16px sans-serif";

context.textAlign = "left";

context.textBaseline = "top";

context.fillStyle = "red";

context.fillText("Level "+curLevel+" - Lives "+lives, 150, 5);

context.restore();

}

Page 66: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

function gameOver(){state=2;context.save();context.font = "bold 16px sans-serif";context.textAlign = "left";context.textBaseline = "top";context.fillStyle = "rgba(0, 0, 200, 0.5)";context.fillRect(90,70,230,125);context.fillStyle = "yellow";context.fillText("Game Over", 160, 125);context.restore();

}

Page 67: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

User Movementsif(horizontalSpeed>0){

if(x<screenWidth-30){imagedata = context.getImageData(x+35, y, 1, 35)data=imagedata.datavar point1=data[0]+data[1]+data[2];var point2=data[68]+data[69]+data[70];var point3=data[136]+data[137]+data[138];if(point1!=255 && point2!=255 && point3!=255 && point1!=765 && point2!=765

&& point3!=765) {x+= horizontalSpeed;if(point1!=0 || point2!=0 || point3!=0) {

collision=true;}

}}

}else{…. Same logic but in opposite direction …

}

Page 68: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.if(verticalSpeed>0){

if(y<screenHeight){imagedata = context.getImageData(x, y+44, 35, 1)data=imagedata.data//add check for the bricksvar point1=data[0]+data[1]+data[2];var point2=data[136]+data[137]+data[138];if(point1!=255 && point2!=255 && point1!=765 && point2!=765) {

y+= verticalSpeed;if(point1!=0 || point2!=0) {

collision=true;}

}}

}else{

….. Same logic but in opposite direction…..}

Page 69: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Logging

• In Java Script coding is some how difficult introubleshooting issues.

• There are different ways to do that:

– Use FireBug (FF plugin)

– User Web Console and log messages using

• console.log("here x=“+x);

– Use alert(‘the message here’);

– Use JS code: (either replace or append) :document.getElementById('log').innerHTML="Log="+point1+" "+point2+" "+point3;

Page 70: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Start/Pause Gamefunction toggleGameplay(){

gameRunning = !gameRunning;if(gameRunning){

clearInterval(gameloopId);if(state==1){

state=0;loadLevelData();

}else if(state==2){state=0;level=0;lives=15;loadLevelData();

}gameloopId = setInterval(gameLoop, 40);

}else{clearInterval(gameloopId);

}}

Page 71: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Save Game

function saveGame(){

localStorage.setItem('level', level);

localStorage.setItem('lives', lives);

localStorage.setItem('xx', xx);

alert("Game Saved!");

}

Page 72: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Load Gamefunction loadGame(){

gameRunning=false;//check if a game is already savedif(localStorage.getItem('level')==null){

alert("No Game Saved");return;

}state=1;level = parseInt(localStorage.getItem('level',0));lives = Number(localStorage.getItem('lives',15));xx = parseInt(localStorage.getItem('xx',150));loadLevelData();toggleGameplay();

}

Page 73: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

We’re done!

• So we have made the following so far:

– HTML : just canvas and few buttons.

– DATA file : to draw different level

– CODE : to handle the drawing, animations , controls,sound effects and game logic.

Page 74: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Demo

• Game Files Structure

• Check Game Code

• Game Demo

Page 75: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Summary

• Writing HTML

• Game Status

• Load Resources (Images/Sounds)

• Control Methods

• Game Data

• Game Loop

• Buttons (Start/Load/Save)

Page 76: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Think of a Game

• Now let’s think of a game and see how we can do it..

Page 77: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 78: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Advanced Game Development Topics

1. Using Physics Engine– Save Balls Game

– World Creation

– Objects Creation

– Physics & Renders

– World Step

– Joints

– Impulses & Forces

2. Using AI Engine– Tic Tac Toe Game

– Game Components

– AI Engine/Rules

Page 79: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

1) Using Physics Engine

• Box2D is an open source 2D physics engine with astrong community, numerous ports, and has been testedand deployed in many games (such as Rolando andAngry Birds).

• HTML5 games are an exciting new platform, and withmodern JavaScript engines and hardware acceleratedgraphics, browsers are now capable of running moredemanding gaming experiences complete with physicsemulations.

Page 80: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Demo

• To understand physics engine functionality:

– http://www.binarytides.com/blog/getting-started-with-box2d-in-javascript/

– http://box2d-js.sourceforge.net/

– http://www.interactivepulp.com/pulpcore/physics/

Page 81: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Example 1Save The Balls

Page 82: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Writing HTML

• Add the usual canvas

<canvas id="mainCanvas" width="480" height="400px">

• Import JS files in the same order described in the APIs orexist in our demo.

• You may remove the un-used features from these imports butyou still need to keep the order.<script ……

<script src='js/box2d/collision/shapes/b2Shape.js'></script>

<script src='js/box2d/collision/shapes/b2ShapeDef.js'></script>

<script src='js/box2d/collision/shapes/b2BoxDef.js'></script>

<script …..

Page 83: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Initialization

window.onload = function(){

init(); // Initialize the world

step(); // Update the world

}

Page 84: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

World Creation

• Create world by dimensions : min & max

• Create world gravity.worldAABB = new b2AABB();

worldAABB.minVertex.Set(-50, -50);

worldAABB.maxVertex.Set(700, 500);

gravity = new b2Vec2(0, 300);

doSleep = true; //false will be slower

world = new b2World(worldAABB, gravity, doSleep);

Page 85: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Every object in Box2d has the following parts :

– Fixture:

• Defines properties like friction , restitution , density

– Shape (2d geometrical shape):

• Can be circle or polygon (set of vertices).

– Body:

• Defines the point where the object is and what isits type – dynamic , static or kinetic

Page 86: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Objects Creation

• Create ground by creating box/object definition and bodydefinition:

var groundSd = new b2BoxDef();

groundSd.extents.Set(600, 50); //dimension

groundSd.restitution = 0.0;

var groundBd = new b2BodyDef();

groundBd.AddShape(groundSd);

groundBd.position.Set(300, 400); // center

return world.CreateBody(groundBd);

Page 87: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Create User Cursor:

cursorSd = new b2BoxDef();

cursorSd.extents.Set(30, 0);

cursorSd.restitution = 0.5;

cursorBd = new b2BodyDef();

cursorBd.AddShape(cursorSd);

cursorBd.position.Set(user_x+30, 200);

return world.CreateBody(cursorBd);

Page 88: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Create Balls:function createNewCircle(x, y){

var circleSd = new b2CircleDef();

circleSd.density = 1.0;

circleSd.radius = 13;

circleSd.restitution = 0.6;

circleSd.friction = 0.1;

var circleBd = new b2BodyDef();

circleBd.AddShape(circleSd);

circleBd.position.Set(x, y);

return world.CreateBody(circleBd);

}

Page 89: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Physics & Renders

• The render is totally different than physics object..

• The physics control the behavior while render controlhow we need to shape this.

• Example:

function drawCursor(){

context.drawImage(blockImg , user_x, 200,60, 20);

}

Page 90: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

function drawGround(){

context.save();

var pattern = context.createPattern(woodImg, "repeat");

context.rect(0, 350, 600, 100);

context.fillStyle = pattern;

context.fill();

for(var i=140;i<340;i=i+20){

context.drawImage(pinButtomImg , i,330);

}

context.restore();

}

Page 91: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.function drawCircle(circle){

if(circle.m_position.x>150 && circle.m_position.x<350 && circle.m_position.y>=330){

context.drawImage(boomImg,circle.m_position.x, circle.m_position.y-13, 25,25);

boom.play();

return true;

}

context.save();

context.translate(circle.m_position.x , circle.m_position.y );

context.rotate(1);

context.translate(-(circle.m_position.x), -(circle.m_position.y));

context.fillStyle = pattern;

context.beginPath();

context.arc(circle.m_position.x , circle.m_position.y , 13, 0, Math.PI * 2, true);

context.closePath();

context.fill();

context.restore();

return false;

}

Page 92: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Loopfunction step(){

random=Math.random();

if(sc_total>0 && random>0.43 && random<0.47){

var circle = createNewCircle(random*400, random*200);

bodies.push(circle);

sc_total--;

}

world.Step(1.0/60, 1);

drawWorld();

drawGameStatistics();

if(sc_total>0) {

loopId=setTimeout('step()', 10);

}else{

gameOver();

}

}

Page 93: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

World Step

• The world.Step method takes 3 parameters – timestep ,velocity iterations , position iterations

• The timestep indicates , how much time the world shouldmove ahead by , say 1 second or 0.1 second.

//fps = 60 , time steps

var fps = 60;

var timeStep = 1.0/fps;

world.Step(timeStep , 8 , 3);

Page 94: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Draw World

function drawWorld(){

context.clearRect(0, 0, width, height); // clear the canvas

drawGround();

cursor.SetCenterPosition(new b2Vec2(user_x+30,200),0);

drawCursor();

for(var i=0; i<bodies.size(); i++){

if(drawCircle(bodies[i])==true){

world.DestroyBody(bodies[i]);

removeByElement(bodies,bodies[i]);

score++;

}

}

}

Page 95: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Joints

• Bind two bodies.

• Box2D features six different joint types:– Distance, Gear, Mouse, Prismatic, Pulley and Revolute joint.

• For example, let's look at the definition of a Revolutejoint:

var joint = new b2RevoluteJointDef();

joint .body1=circle1;

joint .body2=circle2;

joint.collideConnected =true;

world.CreateJoint(joint);

Page 96: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Impulses

• Box2D allows you to add force and impulses to bodies.

• Adding an impulse is like hitting a body with a hard bat.Adding force over time is like pushing on a body.

• Both force and impulse require a vector, specifically ab2Vec2, for direction and magnitude.

• The following code is an easy way to create an impulse:var degrees=70;

var power=100;

body.ApplyImpulse(new b2Vec2(Math.cos(degrees * (Math.PI / 180)) *power, Math.sin(degrees * (Math.PI / 180)) * power),body.GetWorldCenter());

Page 97: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Animate Object

//animate the fan

context.drawImage(fanImg,fanframe*64,0,64,64,60,300,64,64);

fanCounter++;

if(fanCounter==10){

fanframe++;

fanCounter=0;

if(fanframe>=3) { fanframe=0;}

}

Page 98: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cursor Control

• This line of code set the next position based on usermovements:

cursor.SetCenterPosition(

new b2Vec2(user_x+30,200) , 0);

Page 99: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Fan Effects

• It poll the balls by applying “Force”.

– ApplyImpulse : immediately change momentum.

• Think being hit by a bat.

– ApplyForce : change momentum over time.

• Think pushing something.

• So far balls move towards the pins.

if(circle.m_position.x>70 && circle.m_position.y>=320){

circle.ApplyForce(new b2Vec2(1000,1000),newb2Vec2(100,100));

}

Page 100: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Rotating The Ball

pattern = context.createPattern(ballImg, "repeat");

context.save();

context.translate(circle.m_position.x , circle.m_position.y );

context.rotate(1);

context.translate(-(circle.m_position.x), -(circle.m_position.y));

context.fillStyle = pattern;

context.beginPath();

context.arc(circle.m_position.x , circle.m_position.y , 13, 0, Math.PI * 2,true);

context.closePath();

context.fill();

context.restore();

Page 101: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Example 2Angry Ball

• Example for : Collision , Contact, Destruction , Impulseand Pattern.

• Modification of original post by Seth Ladd in his blog.

Page 102: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Add User Control

• Add keyboard control : Space Bar / Enter

Page 103: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

2) Using AI Engine

• We will build a simple AI engine to build one of thefamous games “Tic Tac Toe”.

Page 104: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Components

• Game initialization

• Game Control

• Game Render / Loop

• AI engine.

Page 105: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game initialization

window.addEventListener('keydown',doKeyDown,true);

box=new Array();

box[0]=new Array(); box[1]=new Array(); box[2]=new Array();

box[0][0]=0;box[0][1]=0;box[0][2]=0;

box[1][0]=0;box[1][1]=0;box[1][2]=0;

box[2][0]=0;box[2][1]=0;box[2][2]=0;

levelOfAI=1;

state=0;

counter=0;

gameLoop();

Page 106: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Control

case 32: /* Space bar is pressed */

case 13: /* Enter is pressed */

if(state==0 && playerTurn==true){

var n=x-70;var s=y-75;

n=n/70;s=s/55;

if(box[n][s]==emptyValue) {

box[n][s]=lossValue;

playerTurn=false;

counter++;

gameLoop();

}

}

break;

emptyValue =0lossValue =1winValue =2

Page 107: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Game Render/Loopif(playerTurn==false){

play();

playerTurn=true;

}

for(var l=0;l<3;l++){

for(var i=0;i<3;i++){

if(box[i][l]==winValue){

context.drawImage(XImg,70+ 70*i, 65+55*l);

}else if(box[i][l]==lossValue){

context.drawImage(OImg,70+ 70*i, 65+55*l);

}

}

}

var t=check();

if(t==lossValue) {

playerScore++;

display("You Win");

…..

Page 108: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Our AI Engine

• 2 Levels : Easy (0) and Hard (1)

• Some if conditions to decide the best movement of theprocessor.

function play (){

//try to win the game

if(tryToWin()) return;

//try to prevent him from win

if(tryToPreventLoss()) return;

//try to play in the center

if(tryToCenteralize()) return;

}

Page 109: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Using Frameworks

• Example of ready frameworks to use:

– Impact :• Impact is a JavaScript Game Engine that allows you to

develop stunning HTML5 Games for desktop andmobile browsers.

• http://impactjs.com/

– EaselJS:• A javascript library for working with

the html5 canvas element

• http://easeljs.com/

Page 110: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Advantages:

– Easy , documentation, do not write from scratch.

– Tutorials, samples, out of box functionality.

• Disadvantages:

– Difficult to troubleshoot abnormal behavior.

– Tight coupling with the framework.

Page 111: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Summary

1. Using Physics Engine– Save Balls Game

– World Creation

– Objects Creation

– Physics & Renders

– World Step

– Joints

– Impulses & Forces

2. Using AI Engine– Tic Tac Toe Game

– Game Components

– AI Engine/Rules

Page 112: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 113: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Packaging The Game

• 2 Methods:

– Platform specific tools

– Generic Tools

Page 114: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Packaging Our Game

Page 115: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Platform Specific

• Example for Android:

• Create WebView in main.xml instead of TextView.

• Create WebView in your main class.

• Load your page:

webView.loadUrl(file:///android_asset/www/index.html);

• Put your html in the folder:

– /assets/www/index.html

– Put your images, CS and JS in correspondingfolders relative to this parent folder.

• In this video you can see detailed steps:

– http://www.youtube.com/watch?v=uVqp1zcMfbE

Page 116: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Generic

• MoSync

– The MoSync SDK is licensed under GPL2. Thatmeans you are free to use it in anyway you want ifyou give away whatever you create with it for free.

– Create new project HTML 5

– Add your HTML, JS, images and CSS.

– Define application icon.

– Package for the platform you want.

– Test on emulator and mobile.

Page 117: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• PhoneGap

– Package your games into an iPhone or Android App,ready to be distributed in the App Stores.

• appMobi

– Easily integrate and distribute your games into nativeiPhone and Android Apps.

– You don't even need a Mac or XCode to get yourgame into the iPhone App Store.

Page 118: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 119: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

What’s Next?

• 3D Games using WebGL

• Mouse Lock

Page 120: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

3D Games using WebGL

• WebGL is a cross-platform, royalty-free web standard fora low-level 3D graphics API based on OpenGL ES 2.0,exposed through the HTML5 Canvas element.

• Close to OpenGL ES 2.0 specification.• WebGL brings plugin-free 3D to the web, implemented

right into the browser.• Major browser vendors Apple (Safari), Google (Chrome),

Mozilla (Firefox), and Opera (Opera) are members of theWebGL Working Group.

• URL: http://www.khronos.org/webgl/

Page 121: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Based on OpenGL ES 2.0

– Matches DirectX 9 in capabilities

• No GL extension or plugins.

• No proprietary plugins or APIs

• Cross-browser (not IE)

• Full hardware acceleration

• A lot of tutorials available online:

– http://learningwebgl.com/blog/

Page 122: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Mouse Lock

• The Mouse Lock API provides for input methods ofapplications based on the movement of the mouse, notjust the absolute position of a cursor.

• A popular example is that of first person movementcontrols in three dimensional graphics applications suchas games.

– Mandatory for FPS, useful for action games

– http://chromestory.com/2011/10/developer-news-mouse-lock-api/

Page 123: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• Movement of the mouse is interpreted for rotation of theview-port, there is no limit to how far movement can go,and no mouse cursor is displayed.

function mouseClick(e) {

// Request that mouse be locked.

document.lockMouse(x);

// x is the object to get the lock for (send the movement toit.)

Page 124: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

More Information

• http://dev.w3.org/html5/spec/Overview.html

• http://dev.w3.org/html5/2dcontext/

• http://diveintohtml5.info/index.html

• http://dev.w3.org/html5/webstorage/

• http://www.casualgirlgamer.com/articles/entry/28/The-Best-30-HTML-5-games/

• http://dev.opera.com/articles/view/creating-pseudo-3d-games-with-html-5-can-1/

• http://blog.sethladd.com/2011/08/box2d-orientation-for-javascript.html

Page 125: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• http://michalbe.blogspot.com/2010/09/simple-game-with-html5-canvas-part-1.html

• http://jacebook.co.uk/blog/2010/09/11/html5-writing-a-game/

• http://html5games.com/2010/11/html5-game-dev-tutorials

• http://www.html5rocks.com/en/mobile/touch/

• https://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html

• http://msdn.microsoft.com/en-us/hh563503

• http://blog.sethladd.com/

• http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#text-styles

Page 126: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Cont.

• http://impactjs.com/

• http://easeljs.com/

• http://www.khronos.org/webgl/

• http://learningwebgl.com/blog/

• http://chromestory.com/2011/10/developer-news-mouse-lock-api/

• Animated Gifs from: http://animated-gifs.org

Page 127: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Covered Topics

• Game Development Concepts

• HTML 5 Game Components

• Developing A Game Step by Step

• Advanced Game Development Topics

• Packaging The Game

• What's next?

Page 128: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

New Game Conference

The Conference for HTML5 Game Developers.

Brought by Bocoup and Google.

“The future of gaming is in your browser.”

Prepare your Game for 2012

Page 129: Game Development Using HTML 5

http://osama-oransa.blogspot.com/ March, 2012

Thanks