Transcript
Page 1: HTML Tour - Programación de Videojuegos HTML5

Programación de videojuegos HTML5

Page 2: HTML Tour - Programación de Videojuegos HTML5

¿Quién soy?

www.plainconcepts.com

UX Developer at Plain [email protected]#htmltour

Proyectos destacados:

Jesús David García Gómez

Page 3: HTML Tour - Programación de Videojuegos HTML5

¿Quién soy?

www.plainconcepts.com

Desarrollador PHPDesarrollador HTML5 / JavascriptDesarrollador Flash AS3

Proyectos destacados:

Project Prometheus The Hunger Games

Fernando Oteros Pastrana

Twitter: @[email protected]

Page 4: HTML Tour - Programación de Videojuegos HTML5

Preguntas / Dudas / Sugerencias

#htmltour

http://sh4wn.net/htmltour/demos_html5.zip

Page 5: HTML Tour - Programación de Videojuegos HTML5

SVG y Canvas

Page 6: HTML Tour - Programación de Videojuegos HTML5

SVG

• SVG son las siglas de Scalable Vector Graphics

• Es un lenguaje para describir gráficos en 2D en XML.

• Con HTML5, podemos agregar un SVG al DOM

• Acceso a sus elementos.

Page 7: HTML Tour - Programación de Videojuegos HTML5

SVG - Sintaxis

<svg xmlns="http://www.w3.org/2000/svg" height="200px">… </svg>

Page 8: HTML Tour - Programación de Videojuegos HTML5

SVG - Componentes

• Circle:<circle cx="100" cy="100" r="40" fill="red" />

• Rect:<rect x="50" y="140" width="100" height="20" fill="green" />

• Line:<line x1="40" y1="40" x2="40" y2="170" style="stroke: red; stroke-width: 2" />

Page 9: HTML Tour - Programación de Videojuegos HTML5

SVG – Más Componentes

• Ellipse<ellipse cx="100" cy="50" rx="100" ry="50" fill="url(#gradient)" />

• Polygon<polygon points="50,140 150,140, 100,170" fill="blue" />

• Polyline<polyline points="0,0 0,190 200,190 200,0 0,0" fill="transparent" style="stroke: red; stroke-width: 3" />

Page 10: HTML Tour - Programación de Videojuegos HTML5

Canvas

• El elemento <canvas> se utiliza para pintar gráficos.

• Es un contenedor, debemos usar scripts para pintar los gráficos en el.

• Podemos tener más de un <canvas> en nuestra web

Page 11: HTML Tour - Programación de Videojuegos HTML5

Canvas – Modo de pintado

• Canvas utiliza “modo inmediato”

• SVG, Flash y Silverlight utilizan “modo retenido”

Page 12: HTML Tour - Programación de Videojuegos HTML5

Canvas - Contexto

var canvas = document.getElementById("miCanvas");

var context = canvas.getContext("2d");

Page 13: HTML Tour - Programación de Videojuegos HTML5

Canvas – Comprobar compatibilidad

function IsCanvasCompatible() { var canvas = document.getElementById("miCanvas"); if (!canvas || !canvas.getContext) return false; else return true;}

Page 14: HTML Tour - Programación de Videojuegos HTML5

Canvas – Elementos básicos

• Textocontext.fillText(today, 150, 10);context.strokeText(today, 150, 10);

• Rectánguloscontext.fillRect(0, 0, 150, 75);context.strokeRect(0, 0, 150, 75);context.clearRect(0, 0, 150, 75);

Page 15: HTML Tour - Programación de Videojuegos HTML5

Canvas – Más elementos básicos

• Imágenes

context.drawImage(newImage, 200, 100);

• Pathscontext.beginPath();context.closePath();

Page 16: HTML Tour - Programación de Videojuegos HTML5

Canvas - Path

• Lineascontext.beginPath();context.moveTo(10, 10);context.lineTo(20, 20);context.stroke();context.closePath();

• Arcoscontext.beginPath();context.arc(100, 100, 50, 0, Math.PI);context.fill();context.closePath();

Page 17: HTML Tour - Programación de Videojuegos HTML5

Canvas - Formato

context.textAlign = "center";context.measureText("texto").width;context.font = "60px Arial";context.fillStyle = "red";context.strokeStyle = "red";context.shadowBlur = 10;context.shadowColor = "black";

Page 18: HTML Tour - Programación de Videojuegos HTML5

Canvas – Más formatos

context.lineWidth = lineWidth * 2;context.lineJoin = "round";var gradient = context.createLinearGradient(x, y, dx, dy);gradient.addColorStop(0, primaryColor);gradient.addColorStop(1, secondaryColor);

Page 19: HTML Tour - Programación de Videojuegos HTML5

Programación de videojuegos HTML5

Page 20: HTML Tour - Programación de Videojuegos HTML5

Introducción

• <CANVAS></CANVAS>

• <SVG></SVG>

• <AUDIO></AUDIO>

• <VIDEO></VIDEO>

• Transiciones CSS

• LocalStorage

• WebSockets

Page 21: HTML Tour - Programación de Videojuegos HTML5

Volviendo al Old School

• Limitaciones de los actuales navegadores

• Viejas técnicas y recursos cómo:• Sprites para animaciones• Repetición de fondos.

Page 22: HTML Tour - Programación de Videojuegos HTML5

<!DOCTYPE html><html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><meta charset="utf-8"><title>Demo 01</title><link type="text/css" rel="stylesheet" href="style.css"><script src="demo01.js"></script></head><body onload="game.init()">         <canvas id="canvas" class="gameLayer" width=“700" height=“500"></canvas></body></html>

Elemento CANVAS Hoja de estilo JS

Estructura básica de los juegos html5

Page 23: HTML Tour - Programación de Videojuegos HTML5

Game.js var game = (function () { var canvas,           canvasCtx; //Initialize: Crea los objetos que vamos a usar en el juego. function initialize() { //Crear objetos } //Loop: Se ejecuta en cada ciclo actualizando objetos y pintando el canvas . function loop() { update(); draw(); } //Update: Actualiza cada uno de los objetos de nuestro juego, su posición, disparos, etc… function update() { player.update(); } //Draw: Pinta en el canvas nuestros objetos function draw() { ctx.drawImage(buffer, 0, 0); } return { init: initialize } })();.

Page 24: HTML Tour - Programación de Videojuegos HTML5

GameLoop: setTimeOut vs RequestAnimationFrame

GameLoop o bucle principal Llama a la función Update y Draw.

Antes: setTimeOut(function,time);

Con html5: requestAnimationFrame (function);Hasta que no termina de realizar todas las operaciones no vuelve a ser llamado, optimizando de esta manera la experiencia de usuario.

Page 25: HTML Tour - Programación de Videojuegos HTML5

Uso de requestAnimationFramethis.loop = function () { this.update(); this.draw(); gameInterval = window.requestAnimationFrame(loop); } this.update = function () { player.update(); }

gameInterval = window.requestAnimationFrame(loop);

Una vez inicializado el requestAnimationFrame, lo volvemos a llamar desde el metodo update cuando finaliza cada ciclo.

Snippet incluído en la demo.

Page 26: HTML Tour - Programación de Videojuegos HTML5

Pintando nuestro juego

Función “Draw” llamada desde el bucle principal.

this.draw = function () { this.canvasCtx.clearRect(0, 0, this.canvas.width, this.canvas.height); this.canvasCtx.beginPath(); this.canvasCtx.rect(this.rectangulo.x, this.rectangulo.y, this.rectangulo.w, this.rectangulo.h); this.canvasCtx.fillStyle = "#000"; this.canvasCtx.closePath(); this.canvasCtx.fill(); }

Page 27: HTML Tour - Programación de Videojuegos HTML5

Canvas buffer

Canvas oculto. Lo copiamos al Canvas visible.

Evita la sensación de flickering (parpadeo).

this.bufferCtx.clearRect(0, 0, this.buffer.width, this.buffer.height); this.bufferCtx.beginPath(); this.bufferCtx.rect(this.rectangulo.x, this.rectangulo.y, this.rectangulo.w, this.rectangulo.h); this.bufferCtx.fillStyle = "#000"; this.bufferCtx.closePath(); this.bufferCtx.fill(); this.canvasCtx.clearRect(0, 0, this.buffer.width, this.buffer.height); this.canvasCtx.drawImage(this.buffer, 0, 0);

Page 28: HTML Tour - Programación de Videojuegos HTML5

Events && keyHandlerswindow.addEventListener('keydown', doKeyDown, true); function doKeyDown(evt) { switch (evt.keyCode) { case 38: /* Up arrow was pressed */ //acciones de salto; player.salta(); break; case 40: /* Down arrow was pressed */ //agacharse; player.agacha(); break; case 37: /* Left arrow was pressed */ //caminar; player.move(1); break; case 39: /* Right arrow was pressed */ //caminar; player.move(2); break; } }

Page 29: HTML Tour - Programación de Videojuegos HTML5

Otros eventos

Page 30: HTML Tour - Programación de Videojuegos HTML5

Animando Spriteshttp://www.w3schools.com/html5/canvas_drawimage.asp

game.bufferCanvasCtx.drawImage(spriteObject,posicionXdelPuntero,

posicionYdelPuntero,anchoSprite,

altoSprite, posicionXenCanvas, positionYenCanvas, anchoEnCanvas, altoEnCanvas); }

Función drawImage.Permite desplazarnos a un punto de una imagen, y seleccionar una región a mostrar.

Page 31: HTML Tour - Programación de Videojuegos HTML5

Sonidos

var audio = document.createElement("audio"); //también sirve new Audio(); audio.oncanplaythrought=function(){ //sonidoCargado. audio.play(); } audio.src = “sound.mp3”;

Page 32: HTML Tour - Programación de Videojuegos HTML5

Video en HTML5

<video loop controls id="thevideo" width="320" height="240" preload="auto"> <source src="muirbeach.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"' > <source src="muirbeach.webm"type='video/webm; codecs="vp8, vorbis"' > <source src="muirbeach.ogg" type='video/ogg; codecs="theora, vorbis"'> </video>

Page 33: HTML Tour - Programación de Videojuegos HTML5

Video con canal Alpha

function processFrame() { buffer.drawImage(video, 0, 0); var image = buffer.getImageData(0, 0, width, height), imageData = image.data, alphaData = buffer.getImageData(0, height, width, height).data; for (var i = 3, len = imageData.length; i < len; i = i + 4) { imageData[i] = alphaData[i - 1]; } output.putImageData(image, 0, 0, 0, 0, width, height);}

http://jakearchibald.com/scratch/alphavid/ImageData Structure:

Page 34: HTML Tour - Programación de Videojuegos HTML5

Librerías 3D

WebGL:three.js http://mrdoob.github.com/three.js/

Otras:WaveJS http://www.plainconcepts.com/wavejs

Page 35: HTML Tour - Programación de Videojuegos HTML5

PROJECT PROMETHEUS

http://www.projectprometheus.com/trainingcenter/

Page 36: HTML Tour - Programación de Videojuegos HTML5

THE HUNGER GAMES

Page 37: HTML Tour - Programación de Videojuegos HTML5

Preguntas / Dudas / Sugerencias

#htmltour

http://sh4wn.net/htmltour/demos_html5.zip


Recommended