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

Monday, November 2, 2015

Nothing This Weekend!

Despite my positive outlook from Friday when I talked about starting my new game, I actually got nothing accomplished on it this past weekend. Two things happened.

First, Saturday was Halloween and my daughter's soccer team had an away-game. The game was delayed for a while because no referee showed up. By the time we got home, it was almost time for the trick-or-treat to start. Everyone quickly ate dinner and got into costume. The rest of the night was spent walking around the neighborhood asking for candy.

And then that stupid clock-change thing happened. Actually the inspiration for today's comic, I hate Daylight Savings Time. Well, Daylight Savings Time itself is fine - I hate changing the clocks. It messes me up. It doesn't matter that in the fall we supposedly gain an hour of sleep. I never really do. Especially when there are young children in my house that don't care what the clock says. They are going to get up at the same time no matter what. And now I'm getting hungry an hour before lunch, getting tired at 9:00 in the evening, and just off all day. Why do we do this to ourselves? I'm a big proponent of eliminating the whole time change thing. But I'm also in favor of eliminating local time zones and switching to metric time. Nobody cares what I think.

So instead of some Phaser game code and examples, today I'm just sharing a picture of my kids in their Halloween costumes. We get back to software on Wednesday.


Tasha, on the left, is wearing her R2-D2 dress, which I think counts as a costume. She stayed at our house and handed out candy while my wife and I walk around with the other two. Gladrielle, in the center, is Anna from Frozen. Alexandria, on the right, is Sabine from Star Wars Rebels. We had a total Star Wars theme going if you count the fact that "Anna" held a light saber while we walked around. Gladrielle thinks that Anna might have Force powers. They're all owned by Disney now, so it's plausible.

Here's the comic for today, although this 1-frame sample doesn't do it justice. You have to visit the site.

Amphibian.com comic for 2 November 2015

Friday, October 30, 2015

Starting a New Game

I've been kicking around the idea for a while now, but tonight I finally started a new game for Amphibian.com. Actually starting a new project is almost as difficult as finishing one, but if I never start there's no chance of ever finishing.

I don't have any code or pictures to share yet, but this one is going to star Science Frog. I'm trying to make it in the style of a NES Megaman game, and I happened to find a great resource for information about old video game physics.

TASVideos is a site which, among other things, catalogs lots of data about how the physics worked in games to assist speedrunners. This page on the NES Rockman game (also known as Megaman) has a great breakdown of the horizontal and vertical speed of Megaman as well as the gravity constants and lots of other good information. With this, I should be able to make Science Frog's jumps mimic Megaman's.

So far though, these numbers have not resulted in any great achievements. The jumps are still all out-of-whack probably due to my inability to get the code right using Phaser. I'll keep trying and hopefully by Monday I'll have something to show (along with some pictures of my kids in their Halloween costumes).

And speaking of Halloween costumes, since tomorrow is Halloween I have a Jack-o-lantern theme today in the comic (and the color-change animation effect I talked about on Monday!)

Amphibian.com comic for 30 October 2015

Wednesday, October 28, 2015

Bit Rot. Is it real?

Have you heard of bit rot before? It's the perception that software (the bits) will degrade (or rot) after sitting around for a long time. It will begin to malfunction despite no apparent changes in the environment. I've been writing software long enough to know that it doesn't change on its own, but I've experienced bit rot before. It sure seems real, despite the logical portion of my brain telling me that it can't be.


It sounds crazy, but a system that hasn't been used in a long time just stops working. We have a system at work which we use every few months for demonstrations or training and in between those times it sits idle. Every time we go to use the thing, we find it to be completely crashed in some weird way. Did it get lonely?

And what about the speed of a computer? Have you noticed that they just seem to slow down over time, even if nothing else changes? I had a computer that was new in 2008 and had no real upgrades performed on it for about 5 years. No new software, no upgrades to the operating system. At the end, it was so slow as to be practically unusable. Was it always that slow and I just didn't notice because every other computer I used was similar in speed? Or did it actually slow down over time? I'm fairly certain my cell phone is slowing down as well. Does that count as bit rot too? Or is that something else?

I have no explanations, but this phenomenon can't be ignored. It can be talked about in frog comics though.

Amphibian.com comic for 28 October 2015

Monday, October 26, 2015

Animate Colors with jQuery

While working on an upcoming comic, I wanted to add a color-change effect to an element. I soon learned that jQuery's animate() function doesn't support animation of non-numeric CSS properties. So while I can animate a width between 100px and 200px, for example, I can't animate a color between #000000 and #FF00FF.

But all is not lost! There is a plugin, appropriately named jQuery Color, which adds the color animation feature. It is trivial to use and extremely small to download.

To start using it, just download the .js file from their GitHub page. I am using the minified version. Include it in your page after jQuery. Then, just animate colors the same way you would animate other CSS properties and it will magically work!

In the following example, the page starts out containing a DIV with a black background. As soon as jQuery is ready, an animation changes the background color to purple over a span of 10 seconds.

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Color Animation</title>
</head>

<body>

  <div id="test-div" style="width: 500px; height: 300px; background-color: #000000;"></div>

</body>

<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
<script>

$(function() {

    $('#test-div').animate({backgroundColor: '#FF00FF'}, 10000);

});

</script>

</html>

It doesn't get much easier than that! But what comic prompted me to use this? It's not for today's. You'll just have to wait to find out (or look in the repository on GitHub).

Amphibian.com comic for 26 October 2015

Friday, October 23, 2015

Froggy Pictures from Texas

You may not know this, but whenever I travel away from home I always have a plush frog with me. This started way back, probably 8 years ago, when my daughter Alex told me to take her Froggy with me on a business trip. I took pictures of him doing various things with me, and continued the tradition with every subsequent trip. When our second daughter was born, Alex gave Froggy to her but he still comes with me on trips.

Since I've been in the Dallas, Texas area this week, I thought I might as well share some of the Froggy pictures. This frog has been many places. This is his third time in Texas.

Plush frogs like to take selfies, just like people.

He likes to eat green foods. We eat dinner together every night.

He helps me write my blog. His typing is poor.

I often find him sitting by the pool.

We sometimes share a pizza. This one was pretty good.

Big storm in the Dallas area tonight. Froggy watches the rain.
Froggy was not the inspiration for Amphibian.com. I was drawing frogs and putting them on websites years before Alex was born. In fact, I started drawing frogs when I was 11 years old, just a year older than Alex is now. Which is probably why someone thought a plush frog would make a nice gift for my newborn daughter (Froggy is technically a Mary Meyer Sweet Rascals Freda Frog if you want one of your own. They're getting hard to find nowadays).

Amphibian.com comic for 23 October 2015

Wednesday, October 21, 2015

Bleeding Edge JavaScript Math

In today's comic, Science Frog finds himself on the bleeding edge by accident - literally. Just so I have a nice tie-in with that, I'm going to share some bleeding edge JavaScript math functions. Not literally. You won't actually bleed. Unless you cut yourself on your keyboard, in which case you really should get a better keyboard.

Why do I say this is bleeding edge? I guess I could say cutting edge or leading edge. I could also just drop the idioms and say that these are new language features. The first is only available in the Firefox nightly builds at the moment. How's that for the edge of some kind?!

What is that new feature? An exponentiation operator! That's right, no more need for Math.pow()! Just use double asterisks. This is a feature currently planned for ECMAScript 7 next year, but you can try it in a Firefox nightly build today (it may be included in next month's standard release):

var e = 2 ** 8;
var p = Math.pow(2, 8);

console.log(e === p);  // prints true

Not exciting enough for you? Come on, Java doesn't even have an exponentiation operator and it's been a legitimate language for at least 10 years! I guess Python does, but now all you Python devs don't have an excuse for not switching to JavaScript.

Now for something slightly less edgy. Since Math.pow() will become obsolete, I guess it's only fair that it get a new function. Added as part of ECMAScript 6 this year, Math.fround() is that function. Given a number, it returns the nearest single-precision floating point number. What? Try this (it works in standard Firefox releases since 26 and Chrome since 38):

var x = Math.fround(2.567);
console.log(x); // prints 2.566999912261963

var y = Math.fround(3);
console.log(y); // prints 3

var z = Math.fround(3.3);
console.log(z); // prints 3.299999952316284

I'm sure it makes sense now - Math.fround() gives you the most precise floating point equivalent of a number.

That's all I have to share today. I'm actually away from home this week - in the Dallas area for some software architecture training. But I did all the comics for this week before I left, so no problems there! Missing the comics is fround upon. Sorry, couldn't resist that one.

Amphibian.com comic for 21 October 2015