HTML Tour - Programación de Videojuegos HTML5
-
Upload
plain-concepts -
Category
Technology
-
view
3.161 -
download
0
description
Transcript of HTML Tour - Programación de Videojuegos HTML5
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
¿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]
Preguntas / Dudas / Sugerencias
#htmltour
http://sh4wn.net/htmltour/demos_html5.zip
SVG y Canvas
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.
SVG - Sintaxis
<svg xmlns="http://www.w3.org/2000/svg" height="200px">… </svg>
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" />
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" />
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
Canvas – Modo de pintado
• Canvas utiliza “modo inmediato”
• SVG, Flash y Silverlight utilizan “modo retenido”
Canvas - Contexto
var canvas = document.getElementById("miCanvas");
var context = canvas.getContext("2d");
Canvas – Comprobar compatibilidad
function IsCanvasCompatible() { var canvas = document.getElementById("miCanvas"); if (!canvas || !canvas.getContext) return false; else return true;}
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);
Canvas – Más elementos básicos
• Imágenes
context.drawImage(newImage, 200, 100);
• Pathscontext.beginPath();context.closePath();
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();
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";
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);
Programación de videojuegos HTML5
Introducción
• <CANVAS></CANVAS>
• <SVG></SVG>
• <AUDIO></AUDIO>
• <VIDEO></VIDEO>
• Transiciones CSS
• LocalStorage
• WebSockets
Volviendo al Old School
• Limitaciones de los actuales navegadores
• Viejas técnicas y recursos cómo:• Sprites para animaciones• Repetición de fondos.
<!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
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 } })();.
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.
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.
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(); }
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);
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; } }
Otros eventos
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.
Sonidos
var audio = document.createElement("audio"); //también sirve new Audio(); audio.oncanplaythrought=function(){ //sonidoCargado. audio.play(); } audio.src = “sound.mp3”;
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>
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:
Librerías 3D
WebGL:three.js http://mrdoob.github.com/three.js/
Otras:WaveJS http://www.plainconcepts.com/wavejs
PROJECT PROMETHEUS
http://www.projectprometheus.com/trainingcenter/
THE HUNGER GAMES
Preguntas / Dudas / Sugerencias
#htmltour
http://sh4wn.net/htmltour/demos_html5.zip