Monday, January 4, 2016

Falling Down - Disable Some Phaser World Bounds Checks

Since adding the ability to have more than one level in the platformer I'm building with Phaser, I actually created a second level. Like many platformers, it has...ummm...platforms. What I mean is that unlike my first test level that just had the ground and some boxes to jump on, this second level has no ground and is just a bunch floating clouds on which to jump. If you miss your platform and fall to the bottom of the world, you die.

Hey, you! Get off of my cloud!

Well, not really. The way the game worked was that the player just landed on the bottom of the world bounds and stood there. When I create the player's frog Sprite, I turn on collision with the world bounds. What are the world bounds? Basically that's the defined map. The world bounds collision check prevents the player from walking off the world on the far left and right, but it also prevents the player from falling through the bottom or jumping off the top.

var frog = group.create(50, 50, 'frog');
game.physics.enable(frog, Phaser.Physics.ARCADE);

// stay inside the world boundaries
frog.body.collideWorldBounds = true;

I had a hard time finding an example of what I wanted to do. I performed a great number of fruitless searches, which is fine because I wasn't really looking for fruit. I just wanted to find the easiest way to keep the left/right/top world collisions but turn off the bottom. I read some rather complex solutions that actually replaced the bounds check function on the Sprite, but the simplest solution turns out to be really...simple.

First, the player's frog object needs some minor settings adjusted.

frog.checkWorldBounds = true;
frog.outOfBoundsKill = true;

I already had collideWorldBounds set to true on the physics body, but I also need to set the checkWorldBounds property directly on the Sprite to true. By itself, this has no effect, but it is necessary if I also want to set the outOfBoundsKill property to true. Independent of the physics collisions, these two settings tell Phaser to check on each frame to see if the sprite in question is inside the bounds of the world, and if not, to kill it.

With just this change made to the frog, nothing seems any different. The player can't actually fall or walk off the world because collideWorldBounds is also set to true. It takes just one more line of code to turn off the bottom-of-the-world bounds check and allow the frog to fall to his death. Here it is, on line 6 below:

function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);

    // turn off the collision with the bottom of the world
    game.physics.arcade.checkCollision.down = false;

    // ... other stuff ...

}

As you can see, I make this adjustment immediately after starting the physics system. I only turn off the down collision checks, but you could just as easily turn off up, left, or right depending on your game's needs.

Now the frog can't walk off the left or right of the map but can fall in a hole or off a platform. If you want to see the complete source code for the game, it is freely available on GitHub. If you want to see today's Amphibian.com comic, it is also freely available. Just click on the image of the first frame below...

Amphibian.com comic for 4 January 2016

Friday, January 1, 2016

Particle Emitters in Phaser

Happy New Year!

I had a list of things I wanted to get done with the platformer I'm building with Phaser before 2016. One of them was to add bosses to the levels. Not like manager bosses. Bosses like the big enemy at the end of the stage.

The basics of adding a boss were the same as adding another type of "regular" enemy. I placed the enemy in the level editor, took note of the gid assigned to it by Tiled, and added a setup function to add specialized behavior. I wrote about this process in more detail previously (read those posts here and here).

The big addition here is that I want the boss to throw something at the frog. To accomplish this, I decided to use a Phaser Particle Emitter.

Phaser's Particle system is very nice. Using an Emitter, you can generate bursts of Sprites easily and with randomized attributes. In my game, I made a level boss dinosaur that throws plates off his tail. Those plates are the particles.

First, I had to define the image for the plate and put it in my asset pack. I did this and gave it a key of "dino-plate." After that, making an Emitter that throws the plates is simple. Look at this sample code from my game (you can see the complete source code of the game on GitHub):

var e = game.add.emitter(0, 0, 5);
e.makeParticles('dino-plate', 0, 5, true);
e.gravity = 30;
e.maxParticleSpeed.x = -700;
e.minParticleSpeed.x = -400;
e.maxParticleSpeed.y = -500;
e.minParticleSpeed.y = -300;

The first line creates the Emitter. The first two arguments to the function are the X and Y coordinates of the emitter. I don't have to worry about the real position right now because I'll move it every time I use it to be in the same position as the dinosaur. The third argument is the maximum number of particles this emitter will contain.

The second line calls the makeParticles function to actually create the particles that will be emitted. The first argument is the key for the image or spritesheet to use for the particle. The second argument is the frame of the sprite, but I'm using a single image so I just use 0. The third argument is again the number of particles to create. The fourth argument is set to true to enable physics bodies on the particles. I need this set to true because I want the particles to be able to collide with the frog.

The rest of the lines control the properties of the particles tossed out of this emitter. For this boss, I want the things thrown to have less gravity than the rest of the game. This makes them fall slower purely for dramatic effect, and is completely optional. The max and min speed settings define the bounds for the speed of the particles. Phaser will assign a random speed to each particle within these bounds.

When the time comes for the boss to attack, it's simple to start the emitter.

e.x = boss.position.x + 100;
e.y = boss.position.y;
e.start(true, 2000, null, 5);

Like I said above, I re-position the emitter before I start it each time to make it appear as though the particles are actually coming from the dinosaur's position. After that, calling start causes the Emitter to burst out the particles. The first argument to start is true because I want it to emit the maximum number of particles (in this case, 5) all at once. The second argument is the life of the particles in milliseconds. I want them to exist for 2 seconds. The third argument, which I set to null, is the frequency of the emissions. It's not used when the first argument is set to true, so I use null. The last argument is the quantity to emit. I use 5 so all the particles are thrown out.

The effect is very nice when you see it in action. The randomization of the various attributes makes the burst look natural and realistic. I captured an animation of it...



I like it. I hope you like the comic today, and the rest of the comics that will be coming this year.

Amphibian.com comic for 1 January 2016

Wednesday, December 30, 2015

This is Why I Love Phaser

One of my stated goals when I started the Amphibian.com web comic was to include interactive experiences directly in the comics. My idea is that this kind of thing takes web comics more towards the web. It uses more of the browser as a medium. It's the next level of comics.

That means every so often, when the joke calls for it, I include some interactive or dynamic content in the comics. Today's comic has a game embedded in the third frame.

And that's why I love Phaser.

I had to take a break from working on my platformer to make today's hedge maze game, but thanks to Phaser it didn't take all that long. I only wrote somewhere around 150 lines of code and I have a small game playable in a desktop browser. When I first tried Phaser (making my 404 page game) I was a little skeptical. I am very careful about which frameworks I use for any of my projects, but at this point I am totally sold on Phaser as an HTML5 game development framework. It just saves me so much time. The way it works makes sense, and it performs very well. Prior "games" that I've put in the comics have taken a lot more time to develop and done a lot less than this hedge maze one today. Expect to see more like this in the future.

I don't mention it often anymore, but the entire source code for Amphibian.com is on GitHub, and that includes the JavaScript for the hedge maze game. Check it out here and use it to start making your own games!

Amphibian.com comic for 30 December 2015

Monday, December 28, 2015

More Levels, Fewer States

A New Level
Last week when I added a second level to my platformer, I used multiple Phaser State objects. I had one for each level plus one for the "select a level" mode. While this worked, I wasn't particularly happy with it because every one of the level's State object was identical. It seemed to me that there should have been a better way.

As is often the case with me, I work on these games late at night and usually only for an hour or so, and I don't think of what is later the obvious solution until I've been away from it for a while. Over the weekend, I came to the conclusion that I should only be using a single State for all the different levels and merely changing which map gets loaded by other means.

Here are those other means... First, I created some simple objects which contain the map and music asset keys for each level. I put them all in a map inside an object I called gameState. This is different from a Phaser State object - I use it to keep track of my own personal state information. So far, that means which map is being played and what background music to use. I pass this gameState object to the constructors for both the stage select and the playable stage.

var sandboxLevel = {
        map: "LevelSandbox",
        music: "Ouroboros"
};

var levelOne = {
        map: "Level1",
        music: "DangerStorm"
};

var gameState = {
        levels: [],
        currentLevel: "sb"
};

gameState.levels["sb"] = sandboxLevel;
gameState.levels["one"] = levelOne;

var theStage = stage(gameState);
var stageSelectState = selectStage(gameState);

var game = new Phaser.Game(width, height, Phaser.CANVAS, "gameArea");

game.state.add("stageSelect", stageSelectState, true);
game.state.add("level", theStage);

As you can see in my code snippets above, I now only have to add two States to the Game. Inside the update function for the stage select state, I simply manipulate my gameState object before switching the Phaser State to the playable level.

function update() {

    if (keys.s.isDown) {
        // sandbox level is selected...
        gameState.currentLevel = "sb";
        this.state.start("level");
    } else if (keys.o.isDown) {
        // level one is selected...
        gameState.currentLevel = "one";
     this.state.start("level");
    }

}

Once a new State is started, the create function gets called on it. In my create function, I use the gameState object to get the current level's map and background music.

function create() {

    mapKey = gameState.levels[gameState.currentLevel].map;
    musicKey = gameState.levels[gameState.currentLevel].music;

    // ... other stuff ...

    var map = this.add.tilemap(mapKey);
    var bgmusic = this.sound.add(musicKey);

    // ... other stuff ...

}

That's it. I like this much better than that first attempt. It should be trivial now to add as many stages as I want. I really only want 8. But anyway...

You can play the game at http://amphibian.com/eight-bit and you can view the complete source code on GitHub. Take a look at today's comic before you go. I brought back Science Frog doing tech support for the other frogs, because it's funny.

Amphibian.com comic for 28 December 2015

Friday, December 25, 2015

Merry Christmas!

This will be a short post today, and contain no significant content. I figure everyone will probably be doing something more important that reading my blog today, Christmas 2015.

Anyway, I hope you read and enjoyed my Amphibian.com version of A Christmas Carol. In the end, today's comic, the CEO frog decides to never give thoughtless gifts again. I feel like it's an important lesson for all of us today. But I was surprised to learn that it was an important lesson for us 100 years ago - a lesson that NO ONE LEARNED!

That's right, over a hundred years ago Eleanor Robson Belmont started the organization known as SPUG - the Society for the Prevention of Useless Giving. It was a response to what was seen as wasteful spending on gifts for the sake of gifts at Christmastime. Sound familiar? I guess some things never change. SPUG got a lot of attention back in the second decade of the twentieth century, but the outbreak of World War I took the focus off of revolutionizing the way Christmas was celebrated. The Society doesn't officially exist anymore.

Maybe it's time for a comeback?

In any event, have yourself a Merry Christmas. I'll post again on Monday with some more progress on my platformer and we'll all play it and be joyous as we await the start of 2016.

Amphibian.com comic for 25 December 2015

Wednesday, December 23, 2015

Adding More Stages to my Phaser Platformer

Last week I started getting my platformer set up to have more than just one stage. I created some State objects, one for the title screen and one for the sandbox stage. Today I wanted to continue that process by adding a second playable stage.

Let's call this new stage Stage 1. I think I'm going to number the stages by the bit positions, so we'll have Stage 1 (1), Stage 2 (10), Stage 4 (100), etc. For now, I'm going to leave the sandbox stage in there as Stage 0.

Because of the groundwork I laid over this past weekend, adding the additional stage was easy. If you remember, I created a playingState function which returned a Phaser State object representing the playable stage. Today, I modified that function and renamed it to stage. It now takes a single numeric argument and uses that to select which map and music will be loaded.

Here is a simplified example of my code:

function stage(n) {

    var thisLevel = n;

    // ... other variable declarations

    function preload() {
        this.load.pack("main", "assets/pack.json");
    }

    function create() {

        // load the map for thisLevel
        map = this.add.tilemap("stage" + thisLevel);

        // load the music for thisLevel
        bgmusic = this.sound.add("bgmusic" + thisLevel);

        // ... all the other stuff ...

    }

    // ... all the other functions ...

    return {
        preload: preload,
        create: create,
        update: update
    };

}

For the above code to work as expected, I had to add more game assets to my pack.json file. I now have two tilesets with keys stage0 and stage1, and two audio types with keys bgmusic0 and bgmusic1. Adding more stages is as simple as adding more tilesets and music to the asset pack.

In the game setup, I simply call stage twice. The first time to create the State object for the sandbox and the second time to create the State object for stage 1.

var stageSelectState = selectStage();

var sandboxStage = stage(0);
var stageOne     = stage(1);

var game = new Phaser.Game(width, height, Phaser.CANVAS, "gameArea",
  stageSelectState);

game.state.add("sandbox", sandboxStage);
game.state.add("one", stageOne);

While this works and was fairly simple, it bothers me a little bit. Since 99% of the stage is exactly the same (the only behavior that differs based on the input parameter is in the create function) I really hate calling the stage function more than once, each time creating a functionally identical closure. I think I'm going to optimize this a little more. Stay tuned.

As I've mentioned before, you can play the in-progress game at https://amphibian.com/eight-bit and you can check out the complete source code on GitHub. Leave a comment with any feedback, and don't forget to read today's comic. It's part 4 of my Christmas story and includes the third and final goat!

Amphibian.com comic for 23 December 2015

Monday, December 21, 2015

The Gift of No Gift

Merry Christmas!

I hope everyone is looking forward to Christmas this Friday for all the right reasons. It's gotten difficult to teach my children that Christmas isn't about providing a list of expensive items that will be purchased for them in exchange for good behavior. The Santa-Industrial Complex is working hard to convince us all that we need to buy stuff for everyone we love this time of year.

The series of comics I'm running right now at Amphibian.com is my attempt to poke fun at this modern tradition. Last week, the Goat of Christmas Past reminded the CEO frog that no matter how good presents might seem, they don't last. Odds are, you don't currently have many (if any at all) gifts you were given as a child that are still valuable to you today. In today's comic, the Goat of Christmas Present shows the frog that too many people are giving gifts that aren't really needed. How many coffee mugs do you really use?

Please don't think I'm some kind of villain worthy of mention in a Dickens story. I don't hate the giving of gifts on Christmas. I am just suggesting that as a society we should take a closer look at our motivations. Why do we go crazy and spend $59 bazillion between Thanksgiving and Christmas each year? Is it because we've all lost the ability to show our love for each other without enlisting the help of Wal-Mart and Target?

There is an aspect of the gift-giving craze that I suspect few people stop to consider. Many people don't feel loved when they are receiving gifts. At least that's what Gary Chapman wrote in his book about the Five Love Languages. While there seems to have been little research done to confirm his theories, I've read it and it does seems to fit extremely well with my experiences. Some people feel love by receiving gifts. But a bunch of other people don't, or at least not as much. So if our goal at Christmas is really to show our love for each other, shouldn't we desire to do that in the way the recipient will most feel love? There's a good chance that won't be a gift.

But if we're really just buying gifts because advertising agencies have fooled us into believing that we need to in order to conform to the Christmas rules, maybe we should stop.

Just something to think about.

Amphibian.com comic for 21 December 2015