Wednesday, November 18, 2015

Adding Enemies to my Phaser Platformer

So far, my 8-bit style platformer has been nothing but a frog walking around. It was too safe. There was nothing bad for the frog to hit. To make a proper platformer, there must be some enemies. In response to this problem, I added some toads.

To accomplish this, I first added an Object Layer to my game map in Tiled. On this layer, I placed some tiles that were pictures of the toad. You don't actually have to use tiles here - the objects are only placeholders for Sprites that will be added in the game. You could just use rectangles or whatever, but I think it's nice to be able to see the enemies in the map editor.

In my example, as seen below, I called my Object Layer "others." The name will be important later.

Before changing the game code to utilize this new layer, I also had to add the toad spritesheet to my assets pack. The key name is "toad." Here is that part of the pack.json file:

    {
        "type": "spritesheet",
        "key": "toad",
        "url": "assets/sprites/toad.png",
        "frameWidth": 64,
        "frameHeight": 64
    }

Now it's time to make the toad appear in the game. This is made (almost) easy by Phaser's map.createFromObjects function. It takes objects from an Object Layer in your map and turns them into Sprites. I added the following lines to my game's create function:

enemies = game.add.group();
enemies.enableBody = true;

map.createFromObjects('others', 6571, 'toad', 0, true, false, enemies);

You should be asking, "What do those parameters mean? Especially that 6571." The first parameter is simply the name of the object layer. Remember, I named mine "others". The second parameter is tricky - it is the gid of the objects that should be converted to Sprites. Where is the gid set, or even displayed, in Tiled? I have no idea. The only way I could find it was to look in the JSON after I saved the map. Basically, if you use a tile as your object all of them that use the same tile will have the same gid. You just have to figure out that that gid is. The following snippet from the map JSON shows the gid:

     "objects":[
            {
             "gid":6571,
             "height":64,
             "id":14,
             "name":"toad1",
             "properties":
                {
                },
             "rotation":0,
             "type":"toad",
             "visible":true,
             "width":64,
             "x":1056,
             "y":704
            }] 

The third parameter is the name of the spritesheet from the asset pack, and the fourth parameter is the frame to use as a start. My toad sprite only has one frame right now, so I just set that one to 0. The next parameter is if the new Sprite should exist. I don't know why this would ever be set to false, so I set it to true. The sixth parameter selects for auto-culling. Auto-culled sprites are culled from the camera if not in range. The final parameter that I use is the group in which all these new sprites should be placed. I put them all in an enemies group so that it's easy to check for collisions later.

With these simple steps, I was able to add some evil toads to my game - and adding more is just as simple as editing the map. Phaser makes it very convenient for you to do stuff like this. If you want to see the game in action, it is playable at http://amphibian.com/eight-bit/. And make sure you read today's comic as well!

Amphibian.com comic for 18 November 2015

Monday, November 16, 2015

Review of my TopWebcomics Ad

Instead of doing another post about game progress today, I thought that I'd just give a quick update on my ad I ran on TopWebcomics.com for the past several weeks. My run just ended on Saturday, and I'd like to review it.

To review, I put a special parameter in the link from the ad that I could use to track people who visit Amphibian.com as a direct result of clicking the ad. Here's the stats for the past 4 weeks:

Total Comics Viewed44,121
Comics Viewed by Someone Who Clicked on the Ad15,285
Comics Viewed not related to the Ad28,836

So much like last time I checked, which was only a few days after the ad started running, about a third of the comics viewed were a direct result of the advertising. Combine this with the fact that overall site traffic has increased by around 50% since the ad started, and I would have to conclude that TopWebcomics advertising has blown away my Facebook advertising in terms of getting traffic to the site. As a bonus, 6 people added my comic to their "Favorites" list on TopWebcomics.com over the past 4 weeks. While that doesn't seem like a big number, it is an increase of 50% as well.

My ad, in case you missed it.
I ended up with a cost-per-click of around $0.04. But once someone clicked through to my site, it was highly likely that they stayed and viewed several comics. Most of the increase in views was a direct result of people browsing through the complete set of comics after visiting the site for the first time. About 25% of the people who originally came from the ad came back on their own at least once.

Overall, I would say that I am highly satisfied with my experience advertising with TopWebcomics. I would do it again.

In other news, the test level for the 8-bit style platformer that I'm making with Phaser is now live at https://amphibian.com/eight-bit. Give it a try if you have a few minutes, and feel free to send feedback. I'll try to make some significant updates this week, but I'm also working on adding some new features to the comic as well. Here's the link to today's comic, even without those new features.

Amphibian.com comic for 16 November 2015

Friday, November 13, 2015

Hit the Ground? Play a Sound!

I didn't get to add any enemies to my Phaser 8-bit style platformer this week, but I did add some sound effects. Even though I hadn't used background music before in a game before, it was very easy to add. Playing a sound when the frog jumps was also simple.

But what about playing a sound when the frog lands back on the ground? Not as easy.

First, the simple sounds. For background music, I used "Ouroboros" by Kevin MacLeod (http://incompetech.com). The jump and landing sounds were public domain from FreeSound.org. I added them all to my asset pack file. I gave the background music the key bgmusic1, the jump sound the key jump, and the landing sound the key thud.

In the create function I made the sound objects.

function create() {

    // ... other create stuff ...

    bgmusic = game.sound.add("bgmusic1");
    bgmusic.volume = 0.3;
    bgmusic.loop = true;
    bgmusic.play();

    jumpSound = game.sound.add("jump");
    thudSound = game.sound.add("thud");

}

I start playing the background music right away, after setting it to loop and lowering the volume. I don't like the background music so loud that you can't hear the other sound effects. In Phaser, volume is set with a number between 0 (not audible) and 1 (full volume).

What do I do with the jump and thud sounds? Jump is easy.

function update() {

    // ... other stuff ...

    if (spacebar.isDown) {
        if (frog.body.onFloor() && jumpTimer === 0) {
            // jump is allowed to start
            jumpTimer = 1;
            frog.body.velocity.y = -400;
            jumpSound.play();
        } else if (jumpTimer > 0 && jumpTimer < 31) {
            // keep jumping higher
            jumpTimer++;
            frog.body.velocity.y = -400 + (jumpTimer * 7);
        }
    } else {
        // jump button not being pressed, reset jump timer
        jumpTimer = 0;
    }

    // ... other stuff

}

In the jump function I made on Wednesday, I simply add a call to jumpSound.play() there on line 10 when a jump starts. Couldn't be easier. Now for the hard part...

Playing a sound when the frog collides with the ground seemed obvious at first - just call thudSound.play() in the optional collision function. The collide function lets you specify an optional function that is called when the sprites being checked actually hit each other. But this is not a good place to play a thud sound. The reason is that the frog and the ground are in collision for every frame in which the frog is sitting on the ground. The sound will play all the time, except when the frog is in the air because of a jump or a fall. Not exactly what I wanted.

function update() {

    game.physics.arcade.collide(frog, layer, function(f, t) {
        // -------------------------------------------
        // don't do this!
        // the sound plays almost all the time!
        // -------------------------------------------
        thudSound.play();
    });

    // ... other stuff ...    

}

The trick is to set a flag when the frog is falling - that is, when the y-velocity is greater than 0. This could happen because he jumped or because he walked off a ledge. In either case, gravity pulls him down and the game engine sets the y-velocity to a value greater than 0. When this happens, I set a falling flag on the frog object. Then, I check to see if the frog's physics body is on the floor and the falling flag is true. If these two cases are both met, it means that the frog just hit the ground after a fall. It's there that I call thudSound.play() and reset the falling flag to false. That was some alliteration.

function update() {

    game.physics.arcade.collide(frog, layer);

    if (frog.body.onFloor() && frog.falling) {
        frog.falling = false;
        thudSound.play();
    }

    // ... other stuff ...    

    if (frog.body.velocity.y > 0) {
        frog.falling = true;
    }
    
}

Now whenever the frog hits the ground, a thud sound is heard just once. I'm happy with these results and you'll be happy with today's comic. And remember, you can get the full source code of this game on GitHub! Okay, now for the comic:

Amphibian.com comic for 13 November 2015

Wednesday, November 11, 2015

Tuning the Jumps in my Phaser Platformer

I found just a few minutes to work on my 8-bit-style Phaser platformer since the weekend. Just about everyone in my family is sick in some way, including myself. So with my limited time I decided to fine-tune the jumps.

In my really basic code so far, a jump was accomplished by hitting space on the keyboard. If the frog was on the ground while space was pressed, the frog's y-velocity was set to a constant number. This worked fine, but it resulted in every jump being the same height. Tapping the spacebar for a millisecond caused the same jump as holding down the key for ten seconds. Well, actually holding down the key caused the frog to jump over and over and over again. I wanted to fix that too.

I was looking for a way to make a longer keypress result in more height, up to a limit. After reading a few ideas tossed out there by other people on the Internet, I decided on what to do. Here is part of my new update function, with the enhanced jump logic (remember, you can find the complete source code on GitHub):

var jumpTimer = 0;

function update() {

    game.physics.arcade.collide(frog, layer);

    if (spacebar.isDown) {
        if (frog.body.onFloor() && jumpTimer === 0) {
            // jump is allowed to start
            jumpTimer = 1;
            frog.body.velocity.y = -400;
        } else if (jumpTimer > 0 && jumpTimer < 31) {
            // keep jumping higher
            jumpTimer++;
            frog.body.velocity.y = -400 + (jumpTimer * 7);
        }
    } else {
        // jump button not being pressed, reset jump timer
        jumpTimer = 0;
    }

    // ... other stuff ...

}

Here's how it works... I've introduced a new variable, jumpTimer, which will keep track of how long the jump lasts. If the spacebar is not being pressed, jumpTimer is always set to 0. No jumping is taking place. But when the spacebar is being pressed, some other stuff happens.

First, I check to see if the frog is on the floor of something and jumpTimer is 0. Obviously, I only want a jump to start if the frog is on the ground. But the other part of that ensures that a new jump can start only if jumpTimer has been reset - and it won't be reset until the player releases the space key. This prevents the endless bouncing when holding down the button. Anyway, if both of those conditions are met, jumpTimer is set to 1 and the frog's y-velocity is set to -400. Why -400? I just liked that value after playing around with it. You might want a different value.

In the other case, jumpTimer is greater than 0 but less than 31, the jump is continuing. Each time in here, jumpTimer is incremented. This happens once per frame, so this function keeps the frog moving up for a maximum of 30 frames. After that, no more velocity will be added and gravity pulls the frog back to the ground. I reduce the amount of velocity added by the value of jumpTimer times 7 in order to slow down the vertical rise the longer the button is held down. This looked slightly more natural. Again, I chose 7 just by playing around with it until I found a number I liked.

Animation of the new jump tests.

I'm happy with how it turned out. Next I think I'll try to add an enemy or something and work on the attack mechanics. While you wait for me to write about that, read today's comic. It's almost time to start thinking about Christmas shopping. Maybe it's already that time. Depends on how much of a procrastinator you are.

Amphibian.com comic for 11 November 2015

Monday, November 9, 2015

Single-Direction Collision for your Phaser Tiles

I was working on my platformer (full source code on GitHub) using Phaser, and I wanted to add some platforms to the map. You know, like you do in platformers. Specifically, I wanted to have some box-like things in the environment that the frog could jump on top of, but also walk in front of. Like those box things with the screws in the corners from Super Mario Bros. 3. Mario walked in front of them, but if he jumped up he would land on top and walk across them. You remember:

I wanted boxes like the one upon which Mario stands.

The tileset I was using had some things like that in it, so I used them and made some nice platforms in my sandbox level. It was then I realized that I had a problem. If I set the tiles that made up the boxes to collide with the frog, he could jump on them but not walk in front of them. Maybe if I just set the top tiles as having collisions, or put the lower halves in the background layer, I could walk in front of them. Yes, but I still couldn't jump straight up and land on top because the frog would bump into the top tiles from below.

I want to jump on these.

Phaser supports one-way collisions for physics bodies with the Arcade Physics module that I am using, but since I was dealing with a tilemap there didn't seem to be a way to set it up. When you want to set up collision with some of your tiles, you use one of the setCollision functions (setCollision, setCollisionBetween, setCollisionByExclusion). They don't take any parameters to fine-tune the collisions. Internally, those functions call setCollisionByIndex. Looking at the source for that function, I could see that every tile was indeed set to collide on all sides. It took me a little while, but I found a way to override that behavior and get the effect I wanted.

Here is the function I came up with:

function setTileCollision(mapLayer, idxOrArray, dirs) {

    var mFunc; // tile index matching function
    if (idxOrArray.length) {
        // if idxOrArray is an array, use a function with a loop
        mFunc = function(inp) {
            for (var i = 0; i < idxOrArray.length; i++) {
                if (idxOrArray[i] === inp) {
                    return true;
                }
            }
            return false;
        };
    } else {
        // if idxOrArray is a single number, use a simple function
        mFunc = function(inp) {
            return inp === idxOrArray;
        };
    }

    // get the 2-dimensional tiles array for this layer
    var d = mapLayer.map.layers[mapLayer.index].data;
    
    for (var i = 0; i < d.length; i++) {
        for (var j = 0; j < d[i].length; j++) {
            var t = d[i][j];
            if (mFunc(t.index)) {
                
                t.collideUp = dirs.top;
                t.collideDown = dirs.bottom;
                t.collideLeft = dirs.left;
                t.collideRight = dirs.right;
                
                t.faceTop = dirs.top;
                t.faceBottom = dirs.bottom;
                t.faceLeft = dirs.left;
                t.faceRight = dirs.right;
                
            }
        }
    }

}

Despite the weird-looking top half of the function that is just setting up a way of matching against either a single tile id value or an array of values, overall the function is very simple. It gets the 2-dimensional array of all the tiles in the given layer and loops over them. If the tile index matches one of the specified index values, the collision settings for that tile are altered in accordance with the dirs object. The dirs object should have 4 boolean fields, top, bottom, left, and right. A value of true for any of them indicates that you want Phaser to check for collisions with other objects coming from that direction. In my case, only top was set to true. I only want to cause a collision when the frog hits the tile from above.

Here is how I use it from my create function:

function create() {

    game.physics.startSystem(Phaser.Physics.ARCADE);
    game.physics.arcade.gravity.y = 1500;

    var map = game.add.tilemap("stage1");
    map.addTilesetImage("ground", "tiles");

    layer = map.createLayer("layer1");
    layer.resizeWorld();

    map.setLayer(layer);
    
    // set collisions on ground tiles
    map.setCollisionBetween(1, 275);

    // set collisions on tiles that are the top parts of the boxes
    map.setCollisionBetween(3354, 3356);
    map.setCollisionBetween(2900, 2903);
    map.setCollisionBetween(3714, 3716);

    // set those box top tiles to only collide from above
    setTileCollision(layer, [3354, 3355, 3356, 2900, 2901, 2902, 2903, 3714, 3715, 3716], {
        top: true,
        bottom: false,
        left: false,
        right: false
    });

    // ... other stuff ...    

}

The end result is just what I wanted - the frog can walk in front of the boxes and jump up to land on top of them. The following video shows the box-jumping in action.


And speaking of jumping on boxes - if it's that time of year at your workplace in which you check boxes on reviews of your coworkers, you might enjoy today's comic. In it, we find that the frogs have a more basic approach to the classic forced ranking system.

Amphibian.com comic for 9 November 2015

Friday, November 6, 2015

Background Layers in a Phaser Platformer

I'm still playing around with my 8-bit style platformer that I'm building with Phaser. In my sandbox level I'm trying to get the feel of the game. One of the things I wanted was to have trees (or some other scenery) in the background that would scroll at a reduced rate. This creates the illusion of depth. Fortunately, Phaser provides me with a simple solution.

First, I used Tiled to add a background layer to my map. In the "Layers" pane, there's an icon for adding a new layer on the lower left. I called my background layer simply bg. The order is important - the lower the layer is in the last, the further back it is in the display. After creating the new layer I had to drop it down with the down-arrow icon (right next to the new layer icon).

Adding a background layer in Tiled

With the bg layer selected, I added some trees to my map and saved it. At that point I could modify the game code to make use of the new layer.

First of all, adding a background layer and then doing nothing resulted in failure. The frog was no longer colliding with the map tiles. I believe this was caused by the fact that map.setCollisionBetween works on the current layer, and when I had a second layer the current one was not what I expected. I had to call map.setLayer explicitly before turning on collisions.

To get the slower-scrolling effect on the background layer, I simply set the scrollFactorX property of the background layer to 0.5. With that, the horizontal scroll with be half that of the main layer. You can play around with that number to get faster or slower scroll. A value of 1.0 is the default scroll speed. Setting the value over 1 will make the layer scroll faster, and values under 1 make it scroll slower.

Here is my updated create function.

function create() {

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

    game.physics.arcade.gravity.y = 1500;
     
    game.stage.backgroundColor = "#D3EEFF";
  
    var map = game.add.tilemap("stage1");
    map.addTilesetImage("ground", "tiles");

    // create the background layer
    var bglayer = map.createLayer("bg");
    bglayer.scrollFactorX = 0.5;

    layer = map.createLayer("layer1");
    layer.resizeWorld();

    // setup tile collisions with main layer
    map.setLayer(layer);
    map.setCollisionBetween(0, 6569);

    group = game.add.group();

    frog = createFrog(group, 50, 50, "frog", 200, "left");

    game.camera.follow(frog);

    cursors = game.input.keyboard.createCursorKeys();
    spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

}

This short video clip shows the scrolling effect in action.


Next I'm going to work on fine-tuning some of the tile collisions and then maybe fix the frog spritesheet (I'm still using the one from Frog Soccer - not quite right for this game). At some point I need to add an enemy as well and try to work out some sort of attack capability. Check back Monday! In the mean time, enjoy today's comic.

Amphibian.com comic for 6 November 2015

Wednesday, November 4, 2015

Building a Basic Platformer with Phaser

Like I said last week, I've started work on a new game for Amphibian.com. I'm once again using the Phaser HTML5 game framework, but this time I'm trying to make a classic platformer. Specifically, I want to make a game staring Science Frog in the style of NES Megaman.

While very similar to the approach I took creating Frog Soccer, this game will use very different mechanics. It needs to be side-scrolling, include jumping (and also falling), and have some sort of enemies that must be defeated.

To make this game, my first goal was to create a sandbox stage to test things out. I've been told that this is an important part of making any game. It lets you play around with the mechanics until you get the right behavior. After that, you can make the "real" levels.

My simple map in Tiled 

Dealing with the side-scrolling part was simple. In much the same way I created the soccer field for my last game, I used Tiled to make a map that was wider than it was tall. To get that 8-bit feel, I used a set of tiles from OpenGameArt.org. To start, I have a single layer named "layer1" and I called the tileset simply "ground." I saved the map in JSON format as "stage1.json" and added the tileset image, my frog spritesheet image, and the tilemap file to my pack.json file, shown here:

{
    "main": [
        {
            "type": "image",
            "key": "tiles",
            "url": "assets/images/nestle2.png"
        },
        {
            "type": "spritesheet",
            "key": "frog",
            "url": "assets/sprites/frog.png",
            "frameWidth": 79,
            "frameHeight": 60
        },
        {
            "type": "tilemap",
            "key": "stage1",
            "url": "assets/stage1.json",
            "data": null,
            "format": "TILED_JSON"
        }
    ]
}

Even though I only have 3 game assets at this point, putting them in an asset pack file now will save time later. In my game's preload function, I only need one line to load everything.

function preload() {

    game.load.pack("main", "assets/pack.json");

}

With all the assets loaded in preload, I can set up the game in the create function. Here's where things start to diverge from my last game. Here, I need to use gravity. The frog (and presumably other characters) should be pulled down to the bottom of the screen until they hit a platform or the ground. I want only gravity on the y-axis, so I set game.physics.arcade.gravity.y = 1500. Why 1500? I basically played around with it until I got the frog to fall as fast as I liked. I might change it later. The other thing here is that the frog has to stop falling when he lands on something - specifically one of the ground tiles. Phaser gives us an easy way to specify which tiles should have collision turned on. The map.setCollisionBetween function turns on collisions for all tiles with ids between two values. There is also a similar function that takes an array of ids instead of a range. In my example code below, I am basically turning on collision with all tiles. I might fine-tune this later.

function create() {

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

    // set up gravity to pull everything down
    game.physics.arcade.gravity.y = 1500;

    game.stage.backgroundColor = "#D3EEFF";

    var map = game.add.tilemap("stage1");

    // associates "ground" from the tilemap with the "tiles" image
    map.addTilesetImage("ground", "tiles");

    // collide with everything for now
    map.setCollisionBetween(0, 6569);

    layer = map.createLayer("layer1");
    layer.resizeWorld();

    group = game.add.group();
    frog = createFrog(group, 50, 50, "frog", 200, "left");
    game.camera.follow(frog);

    cursors = game.input.keyboard.createCursorKeys();
    spacebar = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);

}

Just turning on collisions for tiles isn't quite enough. In the update function, I have to check for collisions between the frog and the map layer. Again, this is very simple. There's also a trick to make sure holding the jump button (the spacebar in my case) doesn't cause the frog to fly up forever. Phaser's arcade physics gives us a function, onFloor, which returns true if and only if the body is at rest on a platform. If that is true, I give the frog upward velocity. The gravity setting I discussed above takes care of bringing him back down.

function update() {

    game.physics.arcade.collide(frog, layer);

    frog.body.velocity.x = 0;

    if (spacebar.isDown) {
        if (frog.body.onFloor()) {
            frog.body.velocity.y = -600;
        }
    }

    if (cursors.left.isDown) {
        frog.body.velocity.x = -150;
    } else if (cursors.right.isDown) {
        frog.body.velocity.x = 150;
    }

}

And with those steps, I have the basic functions of an 8-bit style platformer. I have a lot more work to do, and I'll keep writing about my progress here. As always, the complete source code is available on GitHub. Check it out!

My first HTML5 platformer made with Phaser!

Also, check out today's comic for a deep conversation about the use of COTS in software development...or pictures of frogs falling asleep on the job.

Amphibian.com comic for 4 November 2015