SlideShare una empresa de Scribd logo
1 de 129
Descargar para leer sin conexión
http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Game
Development
Osama Oransa
Hewlett Packard
http://osama-oransa.blogspot.com/ March, 2012
This is Me!
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?
http://osama-oransa.blogspot.com/ March, 2012
HTML5 Logo
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?
http://osama-oransa.blogspot.com/ March, 2012
Game Development Concepts
• Animations
• Interactions
• Controls
• Boundaries
• Entry Points
• Physics
• AI rules.
http://osama-oransa.blogspot.com/ March, 2012
Animations
• The animation of any character is based on drawing this
shape many times with different shapes.
• So a cycle of clean and re-draw the shape with time
slicing is the basic of animations.
http://osama-oransa.blogspot.com/ March, 2012
Cont.
• You don’t have to create a multiple images, you can use
1 image that have all of your frames and display only 1
frame at a time.
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 object
actions 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)
http://osama-oransa.blogspot.com/ March, 2012
Interactions
• 2 Types: Dynamics and Collisions.
• Graphics interact with each others through collision
detection, so once you detect the user character has
collision with enemy or wall or a box,…etc.. we can do
the subsequent needed reaction.
• Collision detections varies from:
– Boundaries calculations
– Color detections
http://osama-oransa.blogspot.com/ March, 2012
Collision Detection
• Calculating the boundaries of each character using its
axis and width/height
• Advanced collision detection take into consideration the
filled parts only.
• Example:
– No Collision
– Collision
http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Detect collision using the color of the object
boundaries.
• Mostly used in edge detections for the boundaries.
1. X<=10
2. Color==brown
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 and
respond to them.
• Also controls have lifetime and could be changed with
different game screens.
• Some controls are valid only under certain conditions
– Pick something only if exist
– Jump only if the space allow that.
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 you
are only directing the movement, sometimes it is idle and
wait your direction and speed etc.
• Controls are mainly affected by boundaries.
http://osama-oransa.blogspot.com/ March, 2012
Boundaries
• Each game scene this is known as the world , this world
must have a boundaries where the user object can move
only inside this.
• The boundaries could be physical like the walls or virtual
like end of your world.
http://osama-oransa.blogspot.com/ March, 2012
Entry Points
• Usually games have start point either from menu or a
button to start the game from the beginning.
• But most of the games have multiple entry points like
load saved game, where the user can go to this saved
scene directly.
• The needs here is to design the game code to enable
starting the game smoothly from different points.
• Your entry point need to have some abstraction to
enable this smoothly.
http://osama-oransa.blogspot.com/ March, 2012
Physics
• Physics engines are very important in game
development to simulate the animations and interaction
between 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/
http://osama-oransa.blogspot.com/ March, 2012
AI
• Most of interactive games need some level of AI to
control the enemies or play on behalf of the opponent.
• It varies from simple if/switch cases to complex AI
engine rules.
• It could be predictive or non-predictive.
• The more ability to predict future movements the better
gaming quality you will have.
http://osama-oransa.blogspot.com/ March, 2012
Summary
• Animations
• Interactions
• Controls
• Boundaries
• Entry Points
• Physics
• AI rules.
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?
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
http://osama-oransa.blogspot.com/ March, 2012
HTML 5
• HTML 5 improves interoperability and reduces
development costs by making precise rules on how to
handle all HTML elements, and how to recover from
errors.
• Some of the new features in HTML 5 are functions for
embedding audio, video, graphics, client-side data
storage, and interactive documents.
• To test browser support:
– http://www.html5test.com/
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 every
pixel of it.
• The canvas element has several methods for drawing
paths, boxes, circles, characters, and adding images.
<canvas id="myCanvas" width="200" height="100">
</canvas>
http://osama-oransa.blogspot.com/ March, 2012
Example
http://osama-oransa.blogspot.com/ March, 2012
Cont.
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>
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();
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);
http://osama-oransa.blogspot.com/ March, 2012
Pattern Fill
• Instead of repeat drawing we can apply a pattern using
an image, so you can get the same results with a little
efforts:
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.
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();
http://osama-oransa.blogspot.com/ March, 2012
2D Context
• Best practice to work with context is to push current 2D
context status into stack , modify its properties, finish
your 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);
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 the
server, making it very slow and in-effective.
• In HTML5, the data is NOT passed on by every server
request, but used ONLY when asked for.
http://osama-oransa.blogspot.com/ March, 2012
The localStorage Method
• It is possible to store large amounts of data without
affecting 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.
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>
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>
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 already
stored.
• The getter will return null if the value not exist and no
default value and this is very useful.
• Also you can remove the save item by calling:
– removeItem(‘level’);
http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Audio
• You can create audio files for your game to reflect
user 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>
http://osama-oransa.blogspot.com/ March, 2012
HTML 5 Video
• Today, most videos are shown through a plugin (like
flash).
• HTML5 specifies a standard way to include video, with
the video element.
<video src=“myMovie.ogg" controls="controls">
Your browser don’t support the video element.
</video>
• Insert content between the <video> and </video> tags
for browsers that do not support the video element.
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
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?
http://osama-oransa.blogspot.com/ March, 2012
Balloon Game
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)
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>
http://osama-oransa.blogspot.com/ March, 2012
Game Variables
gameloopId=0;
gameRunning = false;
speed=1;
horizontalSpeed = speed;
verticalSpeed = -speed;
screenWidth=400;
screenHeight=300
level=0;
lives=15;
state=0;
currentLevel=null;
context=null;
x=100; xx=100;
y=200;
http://osama-oransa.blogspot.com/ March, 2012
Define Resources
//Create game images
ballonImg= 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 sounds
boom = new Audio(“audio/boom.wav");
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";
}
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 restart
of the current level.
– 2=Draw “Game Over” and wait restart of the game.
http://osama-oransa.blogspot.com/ March, 2012
Statechart
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;
}
}
http://osama-oransa.blogspot.com/ March, 2012
Keyboard Control
function 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;
}
}
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. For
example, in a touchend event, this will be the finger that was removed.
• URL:
– https://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
http://osama-oransa.blogspot.com/ March, 2012
Cont.
• These lists consist of objects that contain touch
information: identifier: a number that uniquely identifies
the current finger in the touch session.
• target: the DOM element that was the target of the
action.
• client/page/screen coordinates: where on the screen
the action happened.
• radius coordinates and rotationAngle: describe the
ellipse that approximates finger shape.
http://osama-oransa.blogspot.com/ March, 2012
Example
• This snippet lets you drag a DOM element around using
single-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);
http://osama-oransa.blogspot.com/ March, 2012
Gamepad Control
• Gamepad specification defines a low-level interface that
represents gamepad devices.
• 3 Interfaces defined:
– Gamepad, Navigator and GamepadEvent
• URL:
– https://dvcs.w3.org/hg/gamepad/raw-
file/default/gamepad.html
http://osama-oransa.blogspot.com/ March, 2012
Initialize the Game
function 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 0
state=0;
level=0;
lives=15;
loadLevelData();
}
http://osama-oransa.blogspot.com/ March, 2012
Game Data
levelsDetails= new Array()
levelsStartPoint= new Array();
levelsPinLeftDetails= new Array();
levelsPinRightDetails= new Array();
levelsPinTopDetails= new Array();
levelsPinButtomDetails= new Array();
////////////// level 0
levelsDetails[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 1
levelsDetails[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 );
http://osama-oransa.blogspot.com/ March, 2012
Load Level Data
function 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();
}
http://osama-oransa.blogspot.com/ March, 2012
Cont.
Level 3
Level 2
Level1
http://osama-oransa.blogspot.com/ March, 2012
Draw Levels
function 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 details
for (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]);
}
}
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);
}
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 there
are other objects that need to be moved , then we must
handle them here.
function gameLoop(){
if(state==0){
context.putImageData(currentLevel, 0, 0);
moveUser();
}
}
http://osama-oransa.blogspot.com/ March, 2012
Static Background
http://osama-oransa.blogspot.com/ March, 2012
Game Flow
init()
loadLevelData()
drawLevel()
Click start
Level Image
Draw Level Image
Draw Movement
Game Loop
Load resources
Define variables
Define controls
Load Game
http://osama-oransa.blogspot.com/ March, 2012
MoveUser Method
function moveUser(){
collision=false;
//Move the user in the current direction
……… Logic of movements…..
//detect collision!
if(collision==true){
//Draw the boom
context.drawImage(boomImg, x, y);
lives--;
boom.play();
state=1;
gameRunning=false;
clearInterval(gameloopId);
if(lives==0){
gameOver();
}
}else{
//Draw the user
if(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 collision
Or the balloon.
Detect Game Over
Detect Next Level
Draw Game statistics
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();
}
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();
}
http://osama-oransa.blogspot.com/ March, 2012
User Movements
if(horizontalSpeed>0){
if(x<screenWidth-30){
imagedata = context.getImageData(x+35, y, 1, 35)
data=imagedata.data
var 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 …
}
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 bricks
var 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…..
}
http://osama-oransa.blogspot.com/ March, 2012
Logging
• In Java Script coding is some how difficult in
troubleshooting 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="+point
1+" "+point2+" "+point3;
http://osama-oransa.blogspot.com/ March, 2012
Start/Pause Game
function 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);
}
}
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!");
}
http://osama-oransa.blogspot.com/ March, 2012
Load Game
function loadGame(){
gameRunning=false;
//check if a game is already saved
if(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();
}
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.
http://osama-oransa.blogspot.com/ March, 2012
Demo
• Game Files Structure
• Check Game Code
• Game Demo
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)
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..
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?
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
http://osama-oransa.blogspot.com/ March, 2012
1) Using Physics Engine
• Box2D is an open source 2D physics engine with a
strong community, numerous ports, and has been tested
and deployed in many games (such as Rolando and
Angry Birds).
• HTML5 games are an exciting new platform, and with
modern JavaScript engines and hardware accelerated
graphics, browsers are now capable of running more
demanding gaming experiences complete with physics
emulations.
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/
http://osama-oransa.blogspot.com/ March, 2012
Example 1
Save The Balls
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 or
exist in our demo.
• You may remove the un-used features from these imports but
you 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 …..
http://osama-oransa.blogspot.com/ March, 2012
Initialization
window.onload = function(){
init(); // Initialize the world
step(); // Update the world
}
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);
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 is
its type – dynamic , static or kinetic
http://osama-oransa.blogspot.com/ March, 2012
Objects Creation
• Create ground by creating box/object definition and body
definition:
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);
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);
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);
}
http://osama-oransa.blogspot.com/ March, 2012
Physics & Renders
• The render is totally different than physics object..
• The physics control the behavior while render control
how we need to shape this.
• Example:
function drawCursor(){
context.drawImage(blockImg , user_x, 200,60, 20);
}
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();
}
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;
}
http://osama-oransa.blogspot.com/ March, 2012
Game Loop
function 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();
}
}
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 should
move 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);
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++;
}
}
}
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 Revolute
joint:
var joint = new b2RevoluteJointDef();
joint .body1=circle1;
joint .body2=circle2;
joint.collideConnected =true;
world.CreateJoint(joint);
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 a
b2Vec2, 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());
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;}
}
http://osama-oransa.blogspot.com/ March, 2012
Cursor Control
• This line of code set the next position based on user
movements:
cursor.SetCenterPosition(
new b2Vec2(user_x+30,200) , 0);
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),new
b2Vec2(100,100));
}
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();
http://osama-oransa.blogspot.com/ March, 2012
Example 2
Angry Ball
• Example for : Collision , Contact, Destruction , Impulse
and Pattern.
• Modification of original post by Seth Ladd in his blog.
http://osama-oransa.blogspot.com/ March, 2012
Add User Control
• Add keyboard control : Space Bar / Enter
http://osama-oransa.blogspot.com/ March, 2012
2) Using AI Engine
• We will build a simple AI engine to build one of the
famous games “Tic Tac Toe”.
http://osama-oransa.blogspot.com/ March, 2012
Game Components
• Game initialization
• Game Control
• Game Render / Loop
• AI engine.
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();
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 =0
lossValue =1
winValue =2
http://osama-oransa.blogspot.com/ March, 2012
Game Render/Loop
if(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");
…..
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 the
processor.
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;
}
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 and
mobile browsers.
• http://impactjs.com/
– EaselJS:
• A javascript library for working with
the html5 canvas element
• http://easeljs.com/
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.
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
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?
http://osama-oransa.blogspot.com/ March, 2012
Packaging The Game
• 2 Methods:
– Platform specific tools
– Generic Tools
http://osama-oransa.blogspot.com/ March, 2012
Packaging Our Game
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 corresponding
folders relative to this parent folder.
• In this video you can see detailed steps:
– http://www.youtube.com/watch?v=uVqp1zcMfbE
http://osama-oransa.blogspot.com/ March, 2012
Generic
• MoSync
– The MoSync SDK is licensed under GPL2. That
means you are free to use it in anyway you want if
you 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.
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 native
iPhone and Android Apps.
– You don't even need a Mac or XCode to get your
game into the iPhone App Store.
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?
http://osama-oransa.blogspot.com/ March, 2012
What’s Next?
• 3D Games using WebGL
• Mouse Lock
http://osama-oransa.blogspot.com/ March, 2012
3D Games using WebGL
• WebGL is a cross-platform, royalty-free web standard for
a 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 the
WebGL Working Group.
• URL: http://www.khronos.org/webgl/
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/
http://osama-oransa.blogspot.com/ March, 2012
Mouse Lock
• The Mouse Lock API provides for input methods of
applications based on the movement of the mouse, not
just the absolute position of a cursor.
• A popular example is that of first person movement
controls in three dimensional graphics applications such
as games.
– Mandatory for FPS, useful for action games
– http://chromestory.com/2011/10/developer-news-mouse-
lock-api/
http://osama-oransa.blogspot.com/ March, 2012
Cont.
• Movement of the mouse is interpreted for rotation of the
view-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 to
it.)
…
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
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
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
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?
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
http://osama-oransa.blogspot.com/ March, 2012
Thanks 

Más contenido relacionado

La actualidad más candente

[jqconatx] Adaptive Images for Responsive Web Design
[jqconatx] Adaptive Images for Responsive Web Design[jqconatx] Adaptive Images for Responsive Web Design
[jqconatx] Adaptive Images for Responsive Web DesignChristopher Schmitt
 
Building an HTML5 Video Player
Building an HTML5 Video PlayerBuilding an HTML5 Video Player
Building an HTML5 Video PlayerJim Jeffers
 
Web Development for UX Designers
Web Development for UX DesignersWeb Development for UX Designers
Web Development for UX DesignersAshlimarie
 
High Performance Web Design
High Performance Web DesignHigh Performance Web Design
High Performance Web DesignKoji Ishimoto
 
Accessibility - A feature you can build
Accessibility - A feature you can buildAccessibility - A feature you can build
Accessibility - A feature you can buildMonika Piotrowicz
 
Real World Web components
Real World Web componentsReal World Web components
Real World Web componentsJarrod Overson
 
Even faster web sites presentation 3
Even faster web sites presentation 3Even faster web sites presentation 3
Even faster web sites presentation 3Felipe Lavín
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?Remy Sharp
 
スマートフォンサイトの作成術 - 大川洋一
スマートフォンサイトの作成術 - 大川洋一スマートフォンサイトの作成術 - 大川洋一
スマートフォンサイトの作成術 - 大川洋一okyawa
 
CSS pattern libraries
CSS pattern librariesCSS pattern libraries
CSS pattern librariesRuss Weakley
 
Even faster web sites
Even faster web sitesEven faster web sites
Even faster web sitesFelipe Lavín
 
The Art of AngularJS in 2015
The Art of AngularJS in 2015The Art of AngularJS in 2015
The Art of AngularJS in 2015Matt Raible
 
JavaScript For People Who Don't Code
JavaScript For People Who Don't CodeJavaScript For People Who Don't Code
JavaScript For People Who Don't CodeChristopher Schmitt
 
Killing the Angle Bracket
Killing the Angle BracketKilling the Angle Bracket
Killing the Angle Bracketjnewmanux
 

La actualidad más candente (20)

HTML5 Essentials
HTML5 EssentialsHTML5 Essentials
HTML5 Essentials
 
[jqconatx] Adaptive Images for Responsive Web Design
[jqconatx] Adaptive Images for Responsive Web Design[jqconatx] Adaptive Images for Responsive Web Design
[jqconatx] Adaptive Images for Responsive Web Design
 
HTML5 JS APIs
HTML5 JS APIsHTML5 JS APIs
HTML5 JS APIs
 
Building an HTML5 Video Player
Building an HTML5 Video PlayerBuilding an HTML5 Video Player
Building an HTML5 Video Player
 
Web Development for UX Designers
Web Development for UX DesignersWeb Development for UX Designers
Web Development for UX Designers
 
Jquery tutorial
Jquery tutorialJquery tutorial
Jquery tutorial
 
Taking your Web App for a walk
Taking your Web App for a walkTaking your Web App for a walk
Taking your Web App for a walk
 
High Performance Web Design
High Performance Web DesignHigh Performance Web Design
High Performance Web Design
 
ActiveDOM
ActiveDOMActiveDOM
ActiveDOM
 
Accessibility - A feature you can build
Accessibility - A feature you can buildAccessibility - A feature you can build
Accessibility - A feature you can build
 
Real World Web components
Real World Web componentsReal World Web components
Real World Web components
 
Please dont touch-3.6-jsday
Please dont touch-3.6-jsdayPlease dont touch-3.6-jsday
Please dont touch-3.6-jsday
 
Even faster web sites presentation 3
Even faster web sites presentation 3Even faster web sites presentation 3
Even faster web sites presentation 3
 
HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?
 
スマートフォンサイトの作成術 - 大川洋一
スマートフォンサイトの作成術 - 大川洋一スマートフォンサイトの作成術 - 大川洋一
スマートフォンサイトの作成術 - 大川洋一
 
CSS pattern libraries
CSS pattern librariesCSS pattern libraries
CSS pattern libraries
 
Even faster web sites
Even faster web sitesEven faster web sites
Even faster web sites
 
The Art of AngularJS in 2015
The Art of AngularJS in 2015The Art of AngularJS in 2015
The Art of AngularJS in 2015
 
JavaScript For People Who Don't Code
JavaScript For People Who Don't CodeJavaScript For People Who Don't Code
JavaScript For People Who Don't Code
 
Killing the Angle Bracket
Killing the Angle BracketKilling the Angle Bracket
Killing the Angle Bracket
 

Destacado

The Future of the Web: HTML5
The Future of the Web: HTML5The Future of the Web: HTML5
The Future of the Web: HTML5Derek Bender
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuningosa_ora
 
Computer virus
Computer virusComputer virus
Computer viruskiran_a_c
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsosa_ora
 
Html5 with SharePoint 2010
Html5 with SharePoint 2010Html5 with SharePoint 2010
Html5 with SharePoint 2010Hemant Joshi
 
HTML 5 Step By Step - Ebook
HTML 5 Step By Step - EbookHTML 5 Step By Step - Ebook
HTML 5 Step By Step - EbookScottperrone
 
virus programming using batch file
virus programming using batch filevirus programming using batch file
virus programming using batch fileAris Suryadi
 
Hello world program
Hello world programHello world program
Hello world programSpy Seat
 
Html 4 01 Weekend Crash Course (2000) 0764547461
Html 4 01 Weekend Crash Course (2000)  0764547461Html 4 01 Weekend Crash Course (2000)  0764547461
Html 4 01 Weekend Crash Course (2000) 0764547461bhuvanann
 
Batch file programming
Batch file programmingBatch file programming
Batch file programmingswapnil kapate
 
jQTouch – Mobile Web Apps with HTML, CSS and JavaScript
jQTouch – Mobile Web Apps with HTML, CSS and JavaScriptjQTouch – Mobile Web Apps with HTML, CSS and JavaScript
jQTouch – Mobile Web Apps with HTML, CSS and JavaScriptPhilipp Bosch
 
Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008dion
 
HTML5 & Friends
HTML5 & FriendsHTML5 & Friends
HTML5 & FriendsRemy Sharp
 
Html 5 in a big nutshell
Html 5 in a big nutshellHtml 5 in a big nutshell
Html 5 in a big nutshellLennart Schoors
 
What is strategic fit
What is strategic fitWhat is strategic fit
What is strategic fitAnu Vanu
 

Destacado (20)

Up to Speed on HTML 5 and CSS 3
Up to Speed on HTML 5 and CSS 3Up to Speed on HTML 5 and CSS 3
Up to Speed on HTML 5 and CSS 3
 
The Future of the Web: HTML5
The Future of the Web: HTML5The Future of the Web: HTML5
The Future of the Web: HTML5
 
Profiler Guided Java Performance Tuning
Profiler Guided Java Performance TuningProfiler Guided Java Performance Tuning
Profiler Guided Java Performance Tuning
 
Computer virus
Computer virusComputer virus
Computer virus
 
JPA 2.1 performance tuning tips
JPA 2.1 performance tuning tipsJPA 2.1 performance tuning tips
JPA 2.1 performance tuning tips
 
Html5 with SharePoint 2010
Html5 with SharePoint 2010Html5 with SharePoint 2010
Html5 with SharePoint 2010
 
Security
SecuritySecurity
Security
 
Zeus
ZeusZeus
Zeus
 
HTML 5 Step By Step - Ebook
HTML 5 Step By Step - EbookHTML 5 Step By Step - Ebook
HTML 5 Step By Step - Ebook
 
virus programming using batch file
virus programming using batch filevirus programming using batch file
virus programming using batch file
 
Hello world program
Hello world programHello world program
Hello world program
 
Html 4 01 Weekend Crash Course (2000) 0764547461
Html 4 01 Weekend Crash Course (2000)  0764547461Html 4 01 Weekend Crash Course (2000)  0764547461
Html 4 01 Weekend Crash Course (2000) 0764547461
 
Jsf2 html5-jazoon
Jsf2 html5-jazoonJsf2 html5-jazoon
Jsf2 html5-jazoon
 
Batch file programming
Batch file programmingBatch file programming
Batch file programming
 
HTML 5 & CSS 3
HTML 5 & CSS 3HTML 5 & CSS 3
HTML 5 & CSS 3
 
jQTouch – Mobile Web Apps with HTML, CSS and JavaScript
jQTouch – Mobile Web Apps with HTML, CSS and JavaScriptjQTouch – Mobile Web Apps with HTML, CSS and JavaScript
jQTouch – Mobile Web Apps with HTML, CSS and JavaScript
 
Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008Gears and HTML 5 @media Ajax London 2008
Gears and HTML 5 @media Ajax London 2008
 
HTML5 & Friends
HTML5 & FriendsHTML5 & Friends
HTML5 & Friends
 
Html 5 in a big nutshell
Html 5 in a big nutshellHtml 5 in a big nutshell
Html 5 in a big nutshell
 
What is strategic fit
What is strategic fitWhat is strategic fit
What is strategic fit
 

Similar a Game Development Using HTML 5

Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016
Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016
Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016Bart Read
 
Nsc 2013 06-17 - random rants on 2013
Nsc 2013 06-17 - random rants on 2013Nsc 2013 06-17 - random rants on 2013
Nsc 2013 06-17 - random rants on 2013Mikael Svenson
 
Web Components
Web ComponentsWeb Components
Web ComponentsFITC
 
Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...Peter Gfader
 
Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015Karman Interactive
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the BrowserFITC
 
jQuery Conference 2012 keynote
jQuery Conference 2012 keynotejQuery Conference 2012 keynote
jQuery Conference 2012 keynotedmethvin
 
[Pinto] Is my SharePoint Development team properly enlighted?
[Pinto] Is my SharePoint Development team properly enlighted?[Pinto] Is my SharePoint Development team properly enlighted?
[Pinto] Is my SharePoint Development team properly enlighted?European Collaboration Summit
 
Hangman for the Masses Showcase of Web Tech
Hangman for the Masses Showcase of Web TechHangman for the Masses Showcase of Web Tech
Hangman for the Masses Showcase of Web TechOlmo F. Maldonado
 
Drawing the Line with Browser Compatibility
Drawing the Line with Browser CompatibilityDrawing the Line with Browser Compatibility
Drawing the Line with Browser Compatibilityjsmith92
 
How to build a SaaS solution in 60 days
How to build a SaaS solution in 60 daysHow to build a SaaS solution in 60 days
How to build a SaaS solution in 60 daysBrett McLain
 
Html5 shubelal
Html5 shubelalHtml5 shubelal
Html5 shubelalShub
 
Training presentation.pptx
Training presentation.pptxTraining presentation.pptx
Training presentation.pptxNishchaiyaBayla1
 
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomBrowser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomAlex Blom
 
5 Common Mistakes You are Making on your Website
 5 Common Mistakes You are Making on your Website 5 Common Mistakes You are Making on your Website
5 Common Mistakes You are Making on your WebsiteAcquia
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSNaga Harish M
 
Html5 - the new kid on the block
Html5 - the new kid on the blockHtml5 - the new kid on the block
Html5 - the new kid on the blockMarian Borca
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScriptkoppenolski
 

Similar a Game Development Using HTML 5 (20)

Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016
Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016
Client Side Performance for Back End Developers - Camb Expert Talks, Nov 2016
 
Nsc 2013 06-17 - random rants on 2013
Nsc 2013 06-17 - random rants on 2013Nsc 2013 06-17 - random rants on 2013
Nsc 2013 06-17 - random rants on 2013
 
Html5
Html5Html5
Html5
 
Web Components
Web ComponentsWeb Components
Web Components
 
State of the Web
State of the WebState of the Web
State of the Web
 
Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...Silverlight vs HTML5 - Lessons learned from the real world...
Silverlight vs HTML5 - Lessons learned from the real world...
 
Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015Ottawa unity user_group_feb13_2015
Ottawa unity user_group_feb13_2015
 
Improving Game Performance in the Browser
Improving Game Performance in the BrowserImproving Game Performance in the Browser
Improving Game Performance in the Browser
 
jQuery Conference 2012 keynote
jQuery Conference 2012 keynotejQuery Conference 2012 keynote
jQuery Conference 2012 keynote
 
[Pinto] Is my SharePoint Development team properly enlighted?
[Pinto] Is my SharePoint Development team properly enlighted?[Pinto] Is my SharePoint Development team properly enlighted?
[Pinto] Is my SharePoint Development team properly enlighted?
 
Hangman for the Masses Showcase of Web Tech
Hangman for the Masses Showcase of Web TechHangman for the Masses Showcase of Web Tech
Hangman for the Masses Showcase of Web Tech
 
Drawing the Line with Browser Compatibility
Drawing the Line with Browser CompatibilityDrawing the Line with Browser Compatibility
Drawing the Line with Browser Compatibility
 
How to build a SaaS solution in 60 days
How to build a SaaS solution in 60 daysHow to build a SaaS solution in 60 days
How to build a SaaS solution in 60 days
 
Html5 shubelal
Html5 shubelalHtml5 shubelal
Html5 shubelal
 
Training presentation.pptx
Training presentation.pptxTraining presentation.pptx
Training presentation.pptx
 
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex BlomBrowser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
Browser Internals for JS Devs: WebU Toronto 2016 by Alex Blom
 
5 Common Mistakes You are Making on your Website
 5 Common Mistakes You are Making on your Website 5 Common Mistakes You are Making on your Website
5 Common Mistakes You are Making on your Website
 
About Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JSAbout Best friends - HTML, CSS and JS
About Best friends - HTML, CSS and JS
 
Html5 - the new kid on the block
Html5 - the new kid on the blockHtml5 - the new kid on the block
Html5 - the new kid on the block
 
Intro JavaScript
Intro JavaScriptIntro JavaScript
Intro JavaScript
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburgmasabamasaba
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...masabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 

Último (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 

Game Development Using HTML 5

  • 1. http://osama-oransa.blogspot.com/ March, 2012 HTML 5 Game Development Osama Oransa Hewlett Packard
  • 3. 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?
  • 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?
  • 6. http://osama-oransa.blogspot.com/ March, 2012 Game Development Concepts • Animations • Interactions • Controls • Boundaries • Entry Points • Physics • AI rules.
  • 7. http://osama-oransa.blogspot.com/ March, 2012 Animations • The animation of any character is based on drawing this shape many times with different shapes. • So a cycle of clean and re-draw the shape with time slicing is the basic of animations.
  • 8. http://osama-oransa.blogspot.com/ March, 2012 Cont. • You don’t have to create a multiple images, you can use 1 image that have all of your frames and display only 1 frame at a time.
  • 9. 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 object actions 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)
  • 10. http://osama-oransa.blogspot.com/ March, 2012 Interactions • 2 Types: Dynamics and Collisions. • Graphics interact with each others through collision detection, so once you detect the user character has collision with enemy or wall or a box,…etc.. we can do the subsequent needed reaction. • Collision detections varies from: – Boundaries calculations – Color detections
  • 11. http://osama-oransa.blogspot.com/ March, 2012 Collision Detection • Calculating the boundaries of each character using its axis and width/height • Advanced collision detection take into consideration the filled parts only. • Example: – No Collision – Collision
  • 12. http://osama-oransa.blogspot.com/ March, 2012 Cont. • Detect collision using the color of the object boundaries. • Mostly used in edge detections for the boundaries. 1. X<=10 2. Color==brown
  • 13. 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 and respond to them. • Also controls have lifetime and could be changed with different game screens. • Some controls are valid only under certain conditions – Pick something only if exist – Jump only if the space allow that.
  • 14. 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 you are only directing the movement, sometimes it is idle and wait your direction and speed etc. • Controls are mainly affected by boundaries.
  • 15. http://osama-oransa.blogspot.com/ March, 2012 Boundaries • Each game scene this is known as the world , this world must have a boundaries where the user object can move only inside this. • The boundaries could be physical like the walls or virtual like end of your world.
  • 16. http://osama-oransa.blogspot.com/ March, 2012 Entry Points • Usually games have start point either from menu or a button to start the game from the beginning. • But most of the games have multiple entry points like load saved game, where the user can go to this saved scene directly. • The needs here is to design the game code to enable starting the game smoothly from different points. • Your entry point need to have some abstraction to enable this smoothly.
  • 17. http://osama-oransa.blogspot.com/ March, 2012 Physics • Physics engines are very important in game development to simulate the animations and interaction between 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/
  • 18. http://osama-oransa.blogspot.com/ March, 2012 AI • Most of interactive games need some level of AI to control the enemies or play on behalf of the opponent. • It varies from simple if/switch cases to complex AI engine rules. • It could be predictive or non-predictive. • The more ability to predict future movements the better gaming quality you will have.
  • 19. http://osama-oransa.blogspot.com/ March, 2012 Summary • Animations • Interactions • Controls • Boundaries • Entry Points • Physics • AI rules.
  • 20. 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?
  • 21. 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
  • 22. http://osama-oransa.blogspot.com/ March, 2012 HTML 5 • HTML 5 improves interoperability and reduces development costs by making precise rules on how to handle all HTML elements, and how to recover from errors. • Some of the new features in HTML 5 are functions for embedding audio, video, graphics, client-side data storage, and interactive documents. • To test browser support: – http://www.html5test.com/
  • 23. 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 every pixel of it. • The canvas element has several methods for drawing paths, boxes, circles, characters, and adding images. <canvas id="myCanvas" width="200" height="100"> </canvas>
  • 26. 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>
  • 27. 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();
  • 28. 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);
  • 29. http://osama-oransa.blogspot.com/ March, 2012 Pattern Fill • Instead of repeat drawing we can apply a pattern using an image, so you can get the same results with a little efforts: 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.
  • 30. 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();
  • 31. http://osama-oransa.blogspot.com/ March, 2012 2D Context • Best practice to work with context is to push current 2D context status into stack , modify its properties, finish your 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);
  • 32. 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 the server, making it very slow and in-effective. • In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for.
  • 33. http://osama-oransa.blogspot.com/ March, 2012 The localStorage Method • It is possible to store large amounts of data without affecting 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.
  • 34. 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>
  • 35. 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>
  • 36. 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 already stored. • The getter will return null if the value not exist and no default value and this is very useful. • Also you can remove the save item by calling: – removeItem(‘level’);
  • 37. http://osama-oransa.blogspot.com/ March, 2012 HTML 5 Audio • You can create audio files for your game to reflect user 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>
  • 38. http://osama-oransa.blogspot.com/ March, 2012 HTML 5 Video • Today, most videos are shown through a plugin (like flash). • HTML5 specifies a standard way to include video, with the video element. <video src=“myMovie.ogg" controls="controls"> Your browser don’t support the video element. </video> • Insert content between the <video> and </video> tags for browsers that do not support the video element.
  • 39. 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
  • 40. 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?
  • 42. 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)
  • 43. 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>
  • 44. http://osama-oransa.blogspot.com/ March, 2012 Game Variables gameloopId=0; gameRunning = false; speed=1; horizontalSpeed = speed; verticalSpeed = -speed; screenWidth=400; screenHeight=300 level=0; lives=15; state=0; currentLevel=null; context=null; x=100; xx=100; y=200;
  • 45. http://osama-oransa.blogspot.com/ March, 2012 Define Resources //Create game images ballonImg= 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 sounds boom = new Audio(“audio/boom.wav");
  • 46. 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"; }
  • 47. 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 restart of the current level. – 2=Draw “Game Over” and wait restart of the game.
  • 49. 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; } }
  • 50. http://osama-oransa.blogspot.com/ March, 2012 Keyboard Control function 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; } }
  • 51. 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. For example, in a touchend event, this will be the finger that was removed. • URL: – https://dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
  • 52. http://osama-oransa.blogspot.com/ March, 2012 Cont. • These lists consist of objects that contain touch information: identifier: a number that uniquely identifies the current finger in the touch session. • target: the DOM element that was the target of the action. • client/page/screen coordinates: where on the screen the action happened. • radius coordinates and rotationAngle: describe the ellipse that approximates finger shape.
  • 53. http://osama-oransa.blogspot.com/ March, 2012 Example • This snippet lets you drag a DOM element around using single-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);
  • 54. http://osama-oransa.blogspot.com/ March, 2012 Gamepad Control • Gamepad specification defines a low-level interface that represents gamepad devices. • 3 Interfaces defined: – Gamepad, Navigator and GamepadEvent • URL: – https://dvcs.w3.org/hg/gamepad/raw- file/default/gamepad.html
  • 55. http://osama-oransa.blogspot.com/ March, 2012 Initialize the Game function 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 0 state=0; level=0; lives=15; loadLevelData(); }
  • 56. http://osama-oransa.blogspot.com/ March, 2012 Game Data levelsDetails= new Array() levelsStartPoint= new Array(); levelsPinLeftDetails= new Array(); levelsPinRightDetails= new Array(); levelsPinTopDetails= new Array(); levelsPinButtomDetails= new Array(); ////////////// level 0 levelsDetails[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 1 levelsDetails[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 );
  • 57. http://osama-oransa.blogspot.com/ March, 2012 Load Level Data function 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(); }
  • 59. http://osama-oransa.blogspot.com/ March, 2012 Draw Levels function 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 details for (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]); } }
  • 60. 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); }
  • 61. 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 there are other objects that need to be moved , then we must handle them here. function gameLoop(){ if(state==0){ context.putImageData(currentLevel, 0, 0); moveUser(); } }
  • 63. http://osama-oransa.blogspot.com/ March, 2012 Game Flow init() loadLevelData() drawLevel() Click start Level Image Draw Level Image Draw Movement Game Loop Load resources Define variables Define controls Load Game
  • 64. http://osama-oransa.blogspot.com/ March, 2012 MoveUser Method function moveUser(){ collision=false; //Move the user in the current direction ……… Logic of movements….. //detect collision! if(collision==true){ //Draw the boom context.drawImage(boomImg, x, y); lives--; boom.play(); state=1; gameRunning=false; clearInterval(gameloopId); if(lives==0){ gameOver(); } }else{ //Draw the user if(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 collision Or the balloon. Detect Game Over Detect Next Level Draw Game statistics
  • 65. 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(); }
  • 66. 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(); }
  • 67. http://osama-oransa.blogspot.com/ March, 2012 User Movements if(horizontalSpeed>0){ if(x<screenWidth-30){ imagedata = context.getImageData(x+35, y, 1, 35) data=imagedata.data var 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 … }
  • 68. 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 bricks var 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….. }
  • 69. http://osama-oransa.blogspot.com/ March, 2012 Logging • In Java Script coding is some how difficult in troubleshooting 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="+point 1+" "+point2+" "+point3;
  • 70. http://osama-oransa.blogspot.com/ March, 2012 Start/Pause Game function 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); } }
  • 71. 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!"); }
  • 72. http://osama-oransa.blogspot.com/ March, 2012 Load Game function loadGame(){ gameRunning=false; //check if a game is already saved if(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(); }
  • 73. 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.
  • 74. http://osama-oransa.blogspot.com/ March, 2012 Demo • Game Files Structure • Check Game Code • Game Demo
  • 75. 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)
  • 76. 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..
  • 77. 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?
  • 78. 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
  • 79. http://osama-oransa.blogspot.com/ March, 2012 1) Using Physics Engine • Box2D is an open source 2D physics engine with a strong community, numerous ports, and has been tested and deployed in many games (such as Rolando and Angry Birds). • HTML5 games are an exciting new platform, and with modern JavaScript engines and hardware accelerated graphics, browsers are now capable of running more demanding gaming experiences complete with physics emulations.
  • 80. 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/
  • 82. 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 or exist in our demo. • You may remove the un-used features from these imports but you 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 …..
  • 83. http://osama-oransa.blogspot.com/ March, 2012 Initialization window.onload = function(){ init(); // Initialize the world step(); // Update the world }
  • 84. 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);
  • 85. 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 is its type – dynamic , static or kinetic
  • 86. http://osama-oransa.blogspot.com/ March, 2012 Objects Creation • Create ground by creating box/object definition and body definition: 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);
  • 87. 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);
  • 88. 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); }
  • 89. http://osama-oransa.blogspot.com/ March, 2012 Physics & Renders • The render is totally different than physics object.. • The physics control the behavior while render control how we need to shape this. • Example: function drawCursor(){ context.drawImage(blockImg , user_x, 200,60, 20); }
  • 90. 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(); }
  • 91. 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; }
  • 92. http://osama-oransa.blogspot.com/ March, 2012 Game Loop function 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(); } }
  • 93. 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 should move 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);
  • 94. 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++; } } }
  • 95. 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 Revolute joint: var joint = new b2RevoluteJointDef(); joint .body1=circle1; joint .body2=circle2; joint.collideConnected =true; world.CreateJoint(joint);
  • 96. 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 a b2Vec2, 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());
  • 97. 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;} }
  • 98. http://osama-oransa.blogspot.com/ March, 2012 Cursor Control • This line of code set the next position based on user movements: cursor.SetCenterPosition( new b2Vec2(user_x+30,200) , 0);
  • 99. 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),new b2Vec2(100,100)); }
  • 100. 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();
  • 101. http://osama-oransa.blogspot.com/ March, 2012 Example 2 Angry Ball • Example for : Collision , Contact, Destruction , Impulse and Pattern. • Modification of original post by Seth Ladd in his blog.
  • 102. http://osama-oransa.blogspot.com/ March, 2012 Add User Control • Add keyboard control : Space Bar / Enter
  • 103. http://osama-oransa.blogspot.com/ March, 2012 2) Using AI Engine • We will build a simple AI engine to build one of the famous games “Tic Tac Toe”.
  • 104. http://osama-oransa.blogspot.com/ March, 2012 Game Components • Game initialization • Game Control • Game Render / Loop • AI engine.
  • 105. 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();
  • 106. 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 =0 lossValue =1 winValue =2
  • 107. http://osama-oransa.blogspot.com/ March, 2012 Game Render/Loop if(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"); …..
  • 108. 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 the processor. 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; }
  • 109. 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 and mobile browsers. • http://impactjs.com/ – EaselJS: • A javascript library for working with the html5 canvas element • http://easeljs.com/
  • 110. 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.
  • 111. 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
  • 112. 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?
  • 113. http://osama-oransa.blogspot.com/ March, 2012 Packaging The Game • 2 Methods: – Platform specific tools – Generic Tools
  • 115. 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 corresponding folders relative to this parent folder. • In this video you can see detailed steps: – http://www.youtube.com/watch?v=uVqp1zcMfbE
  • 116. http://osama-oransa.blogspot.com/ March, 2012 Generic • MoSync – The MoSync SDK is licensed under GPL2. That means you are free to use it in anyway you want if you 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.
  • 117. 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 native iPhone and Android Apps. – You don't even need a Mac or XCode to get your game into the iPhone App Store.
  • 118. 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?
  • 119. http://osama-oransa.blogspot.com/ March, 2012 What’s Next? • 3D Games using WebGL • Mouse Lock
  • 120. http://osama-oransa.blogspot.com/ March, 2012 3D Games using WebGL • WebGL is a cross-platform, royalty-free web standard for a 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 the WebGL Working Group. • URL: http://www.khronos.org/webgl/
  • 121. 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/
  • 122. http://osama-oransa.blogspot.com/ March, 2012 Mouse Lock • The Mouse Lock API provides for input methods of applications based on the movement of the mouse, not just the absolute position of a cursor. • A popular example is that of first person movement controls in three dimensional graphics applications such as games. – Mandatory for FPS, useful for action games – http://chromestory.com/2011/10/developer-news-mouse- lock-api/
  • 123. http://osama-oransa.blogspot.com/ March, 2012 Cont. • Movement of the mouse is interpreted for rotation of the view-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 to it.) …
  • 124. 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
  • 125. 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
  • 126. 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
  • 127. 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?
  • 128. 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