Files
phaser/examples/wip/book/part2.html
T

436 lines
10 KiB
HTML

<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<title>Creating a game in Phaser, part 2</title>
<style>
body {
background-color: #000;
margin: 0;
}
</style>
<script src="phaser.js"></script>
</head>
<body>
<div id="gameContainer"></div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
function makeFilter () {
PIXI.FireFilter = function(width, height, texture)
{
PIXI.AbstractFilter.call( this );
this.passes = [this];
var d = new Date();
var dates = [
d.getFullYear(), // the year (four digits)
d.getMonth(), // the month (from 0-11)
d.getDate(), // the day of the month (from 1-31)
d.getHours()*60.0*60 + d.getMinutes()*60 + d.getSeconds()
];
this.uniforms = {
resolution: { type: 'f2', value: { x: width, y: height }},
mouse: { type: 'f2', value: { x: 0, y: 0 }},
time: { type: 'f', value: 1 }
};
// http://glsl.heroku.com/e#11707.0
// Heroku shader conversion
this.fragmentSrc = [
"#ifdef GL_ES",
"precision mediump float;",
"#endif",
"uniform float time;",
"uniform vec2 mouse;",
"uniform vec2 resolution;",
"vec3 iResolution = vec3(resolution.x,resolution.y,100.);",
"vec4 iMouse = vec4(mouse.x,mouse.y,5.,5.);",
"float iGlobalTime = time;",
"uniform sampler2D iChannel0;",
"// by @301z",
"float rand(vec2 n) {",
"return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);",
"}",
"// Genera ruido en función de las coordenadas del pixel",
"float noise(vec2 n) {",
"const vec2 d = vec2(0.0, 1.0);",
"vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));",
"return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);",
"}",
"// Fractional Brownian Amplitude. Suma varias capas de ruido.",
"float fbm(vec2 n) {",
"float total = 0.0, amplitude = 1.0;",
"for (int i = 0; i < 4; i++) {",
"total += noise(n) * amplitude;",
"n += n;",
"amplitude *= 0.5;",
"}",
"return total;",
"}",
"void main() {",
"// Colores",
"const vec3 c1 = vec3(0.5, 0.0, 0.1); // Rojo oscuro.",
"const vec3 c2 = vec3(0.9, 0.0, 0.0); // Rojo claro.",
"const vec3 c3 = vec3(0.2, 0.0, 0.0); // Rojo oscuro.",
"const vec3 c4 = vec3(1.0, 0.9, 0.0); // Amarillo.",
"const vec3 c5 = vec3(0.1); // Gris oscuro.",
"const vec3 c6 = vec3(0.9); // Gris claro.",
"vec2 p = gl_FragCoord.xy * 8.0 / iResolution.xx; // Desfasa las coordenadas para que haya más cambio de un resultado a los colindantes.",
"float q = fbm(p - iGlobalTime * 0.1); // Ruido con offset para el movimiento.",
"vec2 r = vec2(fbm(p + q + iGlobalTime * 0.7 - p.x - p.y), fbm(p + q - iGlobalTime * 0.4));",
"vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);",
"gl_FragColor = vec4(c *",
"cos(1.57 * gl_FragCoord.y / iResolution.y), // Gradiente más ocuro arriba.",
"1.0);",
"}"];
}
PIXI.FireFilter.prototype = Object.create( PIXI.AbstractFilter.prototype );
PIXI.FireFilter.prototype.constructor = PIXI.FireFilter;
Object.defineProperty(PIXI.FireFilter.prototype, 'iGlobalTime', {
get: function() {
return this.uniforms.time.value;
},
set: function(value) {
this.uniforms.time.value = value;
}
});
}
var game = new Phaser.Game(1024, 672, Phaser.AUTO, 'gameContainer', { preload: preload, create: create, update: update });
var filter;
var sky;
var land;
var logo;
var player;
var bullets;
var aliens;
var explosions;
var started = false;
var alienSpeed = 200;
var alienReleaseRate = 1000;
var alienReleaseQuantity = 3;
var scrollSpeed = 8;
var alienTimer = 0;
var bulletTime = 0;
var cursors;
var fireButton;
var score = 0;
var text;
var music; // note: music by teque of aggression from the Atari STE version of Stardust
var sfxLazer;
var sfxExplode;
function preload () {
game.load.image('background', 'images/sky.png');
game.load.image('land', 'images/landscape.png');
game.load.image('logo', 'images/logo.png');
game.load.image('player', 'images/ship.png');
game.load.image('bullet', 'images/bullet.png');
game.load.spritesheet('kaboom', 'images/explode.png', 128, 128);
game.load.spritesheet('alien', 'images/invader32x32x4.png', 32, 32);
game.load.bitmapFont('robofont', 'images/robofont.png', 'images/robofont.xml');
game.load.audio('music', [ 'audio/title.mp3']);
game.load.audio('sfxLazer', [ 'audio/shot.wav']);
game.load.audio('sfxExplode', [ 'audio/explode.wav']);
}
function create () {
console.log('dom?');
console.log(Phaser);
console.log(PIXI);
game.world.setBounds(-64, 0, 1300, 672);
sfxLazer = game.add.audio('sfxLazer', 0.1, false);
sfxExplode = game.add.audio('sfxExplode', 0.5, false);
music = game.add.audio('music');
sky = game.add.sprite(0, 0, 'background');
makeFilter();
filter = new PIXI.FireFilter(sky.width, sky.height, sky.texture);
sky.filters = [filter];
// sky = game.add.sprite(0, 0, 'background');
land = game.add.tileSprite(0, 544, 1024, 128, 'land');
bullets = game.add.group();
bullets.createMultiple(30, 'bullet');
bullets.setAll('outOfBoundsKill', true);
// The aliens
aliens = game.add.group();
aliens.createMultiple(50, 'alien');
aliens.setAll('outOfBoundsKill', true);
aliens.callAll('animations.add', 'animations', 'fly', [ 0, 1, 2, 3 ], 20, true);
player = game.add.sprite(64, 256, 'player');
player.body.collideWorldBounds = true;
player.visible = false;
// An explosion pool
explosions = game.add.group();
explosions.createMultiple(30, 'kaboom');
explosions.callAll('animations.add', 'animations', 'kaboom');
explosions.setAll('anchor.x', 0.5);
explosions.setAll('anchor.y', 0.5);
text = game.add.bitmapText(8, 8, 'click to start', { font: '16px AtomicRoboKid' });
text.alpha = 0.9;
logo = game.add.sprite(0, 24, 'logo');
// And some controls to play the game with
cursors = game.input.keyboard.createCursorKeys();
fireButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
sky.alpha = 0;
land.alpha = 0;
logo.alpha = 0;
showTitle();
}
function showTitle () {
game.input.onUp.add(hideTitle, this);
game.add.tween(logo).to( { alpha: 1 }, 2000, Phaser.Easing.Linear.None, true);
game.add.tween(sky).to( { alpha: 1 }, 3000, Phaser.Easing.Linear.None, true);
game.add.tween(land).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.None, true);
logo.visible = true;
started = false;
music.play('', 0, 1, true);
}
function hideTitle () {
game.input.onUp.remove(hideTitle, this);
var tween = game.add.tween(logo).to( { alpha: 0 }, 1000, Phaser.Easing.Linear.None, true);
tween.onComplete.add(hideLogo, this);
game.add.tween(sky).to( { alpha: 0.4 }, 2000, Phaser.Easing.Linear.None, true);
player.reset(-64, 256);
player.visible = true;
game.add.tween(player).to( { x: 64 }, 1000, Phaser.Easing.Linear.None, true);
score = 0;
text.setText('score: ' + score.toString());
alienSpeed = 200;
alienReleaseRate = 1000;
alienReleaseQuantity = 3;
alienTimer = 0;
bulletTime = 0;
started = true;
music.stop();
}
function hideLogo () {
logo.visible = false;
}
function update () {
filter.iGlobalTime = game.time.totalElapsedSeconds();
land.tilePosition.x -= scrollSpeed;
if (started == false)
{
return;
}
// Reset the player, then check for movement keys
player.body.velocity.setTo(0, 0);
if (cursors.up.isDown)
{
player.body.velocity.y = -400;
}
else if (cursors.down.isDown)
{
player.body.velocity.y = 400;
}
if (cursors.left.isDown)
{
player.body.velocity.x = -400;
}
else if (cursors.right.isDown)
{
player.body.velocity.x = 400;
}
// Firing?
if (fireButton.isDown)
{
fireBullet();
}
// Release a new alien?
if (game.time.now > alienTimer)
{
releaseAliens();
}
// Run collision
game.physics.collide(bullets, aliens, collisionHandler, null, this);
game.physics.collide(aliens, player, alienHitsPlayer, null, this);
}
function releaseAliens () {
for (var i = 0; i < alienReleaseQuantity; i++)
{
alien = aliens.getFirstExists(false);
if (alien)
{
alien.reset(game.rnd.integerInRange(1024, 1200), game.rnd.integerInRange(200, 400));
alien.body.velocity.x = -alienSpeed;
alien.body.velocity.y = game.rnd.integerInRange(-100, 100);
alien.play('fly');
}
}
alienTimer = game.time.now + alienReleaseRate;
}
function alienHitsPlayer (alien, player) {
alien.kill();
player.kill();
sfxExplode.play('', 0, 1);
// And create an explosion :)
var explosion = explosions.getFirstDead();
explosion.reset(player.x, player.y);
explosion.play('kaboom', 30, false, true);
showTitle();
}
function fireBullet () {
// To avoid them being allowed to fire too fast we set a time limit
if (game.time.now > bulletTime)
{
// Grab the first bullet we can from the pool
bullet = bullets.getFirstExists(false);
if (bullet)
{
// And fire it
bullet.reset(player.x + 8, player.y + 10);
bullet.body.velocity.x = 700;
bulletTime = game.time.now + 100;
sfxLazer.play('', 0, 0.1);
}
}
}
function collisionHandler (bullet, alien) {
// Increase the score
score += 20;
text.setText('score: ' + score.toString());
// For every alien we kill we're going to increase their speed slightly and reduce the release rate
if (alienReleaseRate > 250)
{
alienReleaseRate -= 2;
}
if (alienSpeed < 600)
{
alienSpeed += 2;
}
if (alienReleaseRate % 300 == 0)
{
alienReleaseQuantity++;
}
// And create an explosion :)
var explosion = explosions.getFirstDead();
if (explosion)
{
explosion.reset(alien.x + 8, alien.y + 16);
explosion.body.velocity.x = 400;
explosion.body.velocity.y = 10;
explosion.play('kaboom', 30, false, true);
sfxExplode.play('', 0, 0.5);
}
// When a bullet hits an alien we kill both sprites, putting them back into the pool
bullet.kill();
alien.kill();
}
});
</script>
</body>
</html>