Phaser Example With Baddies

Phaser offers some great tutorials and hopefully you've had success working through the 'making your first game' tutorial series:
https://phaser.io/tutorials/making-your-first-phaser-game

This is a great way to learn the basics.

phaser example

If you have downloaded the example from the phaser website you will notice that there are some extra assets included with the source code.  We have implemented these in order to create our own version.

phaser example baddies

We've turned things up by including the following additions:

  • Sound effects
  • optional full screen support
  • Optional game pad support
  • A moving and killable enemy
  • Life indicator
  • Improved physics

oh and we made the good guy the bad guy and the bad guy the good guy! Just like terminator 2...

terminator2

Phaser Example With Baddies

This is not a very polished demo but demonstrates several important principles that you can use in your own projects.

You can check out the source code below and and there is also a download link to the full  zip file.

Download Phaser Example With Baddies from FileFactory

Experiment with the code and tweak it to create the next masterpiece, we can't wait to see what you come up with!

Enjoy

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>Phaser Baddies Demo</title>
    <script type="text/javascript" src="js/phaser.min.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body style = "background-color:#6ac1f7">

<script type="text/javascript">

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'game', { preload: preload, create: create, update: update });

function preload() {

    //Allow the user to go full screen
    game.scale.fullScreenScaleMode = Phaser.ScaleManager.EXACT_FIT;
    game.scale.startFullScreen(true);
    
    //center game on screen
    this.game.scale.pageAlignHorizontally = true;
    this.game.scale.pageAlignVertically = true;
    this.game.scale.refresh();
    
    //Load images
    game.load.image('sky', 'assets/sky.png');
    game.load.image('ground', 'assets/platform.png');
    game.load.image('star', 'assets/star.png');
    game.load.spritesheet('badguy', 'assets/dude.png', 32, 48);
    
    //add the dog sprite included in the assets folder
    game.load.spritesheet('dog', 'assets/baddie.png', 32, 32);
    
    //Load sound effects
    game.load.audio('barksound', 'assets/bark.wav');

}
    //Public Variables - These can be accessed from anywhere!
    
    var player;
    var enemy;
    var platforms;
    var cursors;
    var stars;
    var score = 0;
    var scoreText;
    
    //health indicator
    var life = 100;
    
    //sprite controls
    var playerLeft;
    var playerRight;

    //gamepad support
    var pad1;
    var indicator;


function create() {
    
    
    // To listen to buttons from a specific pad listen directly on that pad game.input.gamepad.padX, where X = pad 1-4
    game.input.gamepad.start();
    pad1 = game.input.gamepad.pad1;

    // Maintain aspect ratio
    game.scale.fullScreenScaleMode = Phaser.ScaleManager.SHOW_ALL;
    
    //Go full screen if user clicks game canvas
    game.input.onDown.add(gofull, this);

    //  We're going to be using physics, so enable the Arcade Physics system
    game.physics.startSystem(Phaser.Physics.ARCADE);
    
    //  A simple background for our game
    game.add.sprite(0, 0, 'sky');

    //  The platforms group contains the ground and the 2 ledges we can jump on
    platforms = game.add.group();

    //  We will enable physics for any object that is created in this group
    platforms.enableBody = true;

    // Here we create the ground.
    var ground = platforms.create(0, game.world.height - 64, 'ground');

    //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
    ground.scale.setTo(2, 2);

    //  This stops it from falling away when you jump on it
    ground.body.immovable = true;

    //  Now let's create two ledges
    var ledge = platforms.create(400, 400, 'ground');
    ledge.body.immovable = true;

    ledge = platforms.create(-150, 250, 'ground');
    ledge.body.immovable = true;

    // The player and its settings
    player = game.add.sprite(72, game.world.height - 150, 'dog');
    
    //  We need to enable physics on the player
    game.physics.arcade.enable(player);
    
    //  Player physics properties. Give the little guy a slight bounce.
    player.body.bounce.y = 0.2;
    player.body.gravity.y = 410;
    player.body.collideWorldBounds = true;
    
    //  Our two animations, walking left and right.
    player.animations.add('left', [0, 1], 10, true);
    player.animations.add('right', [2, 3], 10, true);
    
    //The enemy and settings
    enemy = game.add.sprite(500, game.world.height - 248, 'badguy');
    game.physics.arcade.enable(enemy);
    enemy.body.collideWorldBounds = true;
    enemy.animations.add('left', [0, 1, 2, 3], 10, true);
    enemy.animations.add('right', [5, 6, 7, 8], 10, true);
    //initialise enemy movement
    enemy.body.velocity.x = 350;
    enemy.animations.play('right');
    
    //  Finally some stars to collect
    stars = game.add.group();

    //  We will enable physics for any star that is created in this group
    stars.enableBody = true;

    //  Here we'll create 12 of them evenly spaced apart
    for (var i = 0; i < 12; i++)
    {
        //  Create a star inside of the 'stars' group
        var star = stars.create(i * 70, 0, 'star');

        //  Let gravity do its thing
        star.body.gravity.y = 1000;

        //  This just gives each star a slightly random bounce value
        star.body.bounce.y = 0.1 + Math.random() * 0.2;
    }

    //  The score
    scoreText = game.add.text(16, 16, 'Score: 0', { fontSize: '32px', fill: '#000' });
    
    //Life Guage
    lifeText = game.add.text(16, 46, 'Life: 100', { fontSize: '32px', fill: '#000' });

    //  Our controls.
    cursors = game.input.keyboard.createCursorKeys();
    //Sound effects
    barksound = game.add.audio('barksound');
}

function update() {

    //  Collide the player, enemy and the stars with the platforms
    game.physics.arcade.collide(player, platforms);
    game.physics.arcade.collide(enemy, platforms);
    game.physics.arcade.collide(stars, platforms);

    //  Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
    game.physics.arcade.overlap(player, stars, collectStar, null, this);
    //  Checks to see if the player overlaps with any of the enemies, if he does call the touchEnemy function
    game.physics.arcade.overlap(enemy, player, touchEnemy, null, this);

    //  Reset the players velocity (movement)
    //enemy automatic movenemt
        if (enemy.x < 400){
            enemy.body.velocity.x = 350;
            enemy.animations.play('right');
        } else if(enemy.x > 760){
            enemy.body.velocity.x = -350;
            enemy.animations.play('left');
        }
        
    player.body.velocity.x = 0;
    

    
    // Controls
    //Check if Game Pad is connected otherwise use keyboard controls
    if (game.input.gamepad.supported && game.input.gamepad.active && pad1.connected){
        
        if (pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_LEFT) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) < -0.10){
            //  Move to the left
            player.body.velocity.x = -150;

            player.animations.play('left');
            playerLeft = true;
            playerRight = false;
        } else if (pad1.isDown(Phaser.Gamepad.XBOX360_DPAD_RIGHT) || pad1.axis(Phaser.Gamepad.XBOX360_STICK_LEFT_X) > 0.10){
            playerLeft = false;
            playerRight = true;
            //  Move to the right
            player.body.velocity.x = 150;

            player.animations.play('right');
        } else {
            //  Stand still
            player.animations.stop();
        
            if (playerLeft == true){
                player.frame = 0;
            } else {
            player.frame = 3;
            }
        
        }

        if (pad1.justPressed(Phaser.Gamepad.XBOX360_A) && player.body.touching.down){
            player.body.velocity.y = -350;
        }
   
    } else {
    
        //keyboard controls
        if (cursors.left.isDown) {
            //  Move to the left
            player.body.velocity.x = -150;

            player.animations.play('left');
            playerLeft = true;
            playerRight = false;
        }
        else if (cursors.right.isDown) {
            playerLeft = false;
            playerRight = true;
            //  Move to the right
            player.body.velocity.x = 150;

            player.animations.play('right');
        } else {
            //  Stand still
            player.animations.stop();
        
                if (playerLeft == true){
                    player.frame = 0;
                } else {
                    player.frame = 3;
                }
        
        }
    
        //  Allow the player to jump if they are touching the ground.
        if (cursors.up.isDown && player.body.touching.down) {
            player.body.velocity.y = -350;
        }
    }
    
    //Check if player has collected all the stars and won the game
    if (score == 120) {
        enemy.kill();
        player.kill();
        //player.scale.setTo(3, 3);
        //player.y = game.height/2;
        var style = { font: "bold 32px Arial", fill: "#fff", boundsAlignH: "center", boundsAlignV: "middle" };
        var text = game.add.text(game.world.centerX, game.world.centerY, "YOU WIN!", style);
    
    }

}


function collectStar (player, star) {
    
    // Removes the star from the screen
    star.kill();
    barksound.play();
    //  Add and update the score
    score += 10;
    scoreText.text = 'Score: ' + score;

}


function touchEnemy (enemy, player) {

    if ( player.y < enemy.y ){
        enemy.body.velocity.x = 0;
        enemy.y -= 500;
        enemy.kill();
        player.y -= 30;
        
    } else {
    
        // Removes the star from the screen
        barksound.play();
        //  Add and update the score
        life -= 10;
    }
    
        lifeText.text = 'Life: ' + life;
        //Gameover
        if(life == 0){
            player.kill();
            var text = game.add.text(game.world.centerX, game.world.centerY, "YOU LOSE!", { font: "65px Arial", fill: "#ff0044", align: "center" });
    
        }
}

function gofull() {

    if (game.scale.isFullScreen) {
        game.scale.stopFullScreen();
    } else {
        game.scale.startFullScreen(false);
    }
}

</script>

<div id="game" style=""></div>



</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*Error Please Try Again