Por 9.99€ al mes tendrás acceso completo a todos los cursos. Sin matrícula ni permanencia.
Cargar fondo
Cargamos la imagen de fondo del juego.
createSprite();
preload() {
...
this.load.spritesheet('caterpillar', caterpillar, {
frameWidth: 96,
frameHeight: 192
});
};
create() {
...
this.sceneAnimations();
this.createSprite();
}
sceneAnimations() {
this.anims.create({
key: 'caterpillarWalk',
frames: this.anims.generateFrameNumbers('caterpillar', {start: 0, end: 3}),
frameRate: 7,
repeat: -1,
});
}
createSprite(){
const obj = this.physics.add.sprite(0,100, 'caterpillar');
obj.setVelocity(200,0)
obj.play('caterpillarWalk');
}
const config = {
type: Phaser.AUTO,
width: 960,
height: 640,
scene: Escena,
physics: {
default: 'arcade'
},
};
Bichos aleatorios
preload() {
...
this.load.spritesheet('ant', ant, {
frameWidth: 192,
frameHeight: 96
});
this.load.spritesheet('bee', bee, {
frameWidth: 128,
frameHeight: 128
});
};
sceneAnimations() {
...
this.anims.create({
key: 'antWalk',
frames: this.anims.generateFrameNumbers('ant', {start: 0, end: 3}),
frameRate: 7,
repeat: -1,
});
this.anims.create({
key: 'beeWalk',
frames: this.anims.generateFrameNumbers('bee', {start: 0, end: 2}),
frameRate: 10,
repeat: -1,
});
}
createSprite(){
...
const bugs = ['caterpillar', 'ant', 'bee'];
const random = Math.floor(Math.random()*bugs.length);
const spriteName = bugs[random];
...
obj.play(spriteName + 'Walk');
}
Varios sprites
this.time.delayedCall(1000, () => {
this.createSprite();
}, [], this);
Carga en posiciones aleatorias
createSprite(){
const y = Math.floor(Math.random() * gameHeight);
const x = Math.random() > 0.5 ? gameWidth + 100 : -100;
const direction = x == -100 ? 1 : -1;
const obj = this.physics.add.sprite(x,y, spriteName);
...
obj.setVelocity(direction *200,0);
}
Los bichos deben mirar en la dirección del desplazamiento
createSprite(){
...
if(direction == -1){
obj.flipX = true;
}
}
Detectar pulsación
createSprite(){
...
const obj = this.physics.add.sprite(x, y, spriteName).setInteractive().on('pointerdown', this.clickedBug);
...
}
clickedBug(){
alert('bicho pulsado');
}
Explosión
preload(){
...
this.load.spritesheet('crash', crash, {
frameWidth: 199,
frameHeight: 200
});
}
create(){
...
...on('pointerdown', () => this.clickedBug(obj));
...
}
clickedBug(bug){
// Sólo queremos deshabilitar y activar la animación si el cuerpo esta deshabilitado, ya que sino, la animación se ejecutaría varias veces
if (bug.body.enable) {
bug.disableBody();
bug.play('crashAnim');
}
}
sceneAnimations() {
...
this.anims.create({
key: 'crashAnim',
frames: this.anims.generateFrameNumbers('crash', {start: 0, end: 4}),
frameRate: 7
});
}
La explosión desaparece cuando ha concluído
obj.on('animationcomplete', this.animationComplete, this);
...
animationComplete(animation, frame, sprite) {
if (animation.key === 'crashAnim') {
sprite.destroy();
}
}