Monday, January 18, 2016

A Phaser Game With Mouse/Touch Input

I'm back from Texas and have mostly recovered from the events of last week. I still have a bit of a cold, but I'm not letting it stop me from getting a simple game ready for inclusion in a comic this week. This game will use mouse/touch input instead of the keyboard like my last one did, so I had to figure out how to use sprite dragging in Phaser.


Like most things have been with Phaser so far, it took a few tries to get it all correct but in the end it all seems really simple. It revolves around enabling input on individual Sprites, enabling drag, and then optionally listening for drag-related events.

Here is the complete source code for a Sprite-dragging demo:

var init = function() {

    var game = new Phaser.Game(width, height, Phaser.CANVAS, "gameArea", {
        preload : preload,
        create : create
    });

    function selectFrog(sprite, pointer) {
        console.log("selected");
        sprite.frame = 1; // frog in the air
    }

    function releaseFrog(sprite, pointer) {
        console.log("released");
        sprite.frame = 0; // frog sitting
    }

    function preload() {
        this.load.spritesheet('frog', 'assets/sprites/frog.png', 79, 60);
    }

    function create() {

        this.stage.backgroundColor = "#999999";

        var frog = this.add.sprite(50, 50, "frog", 0);
        frog.inputEnabled = true;
        frog.input.enableDrag(true);
        frog.events.onDragStart.add(selectFrog, this);
        frog.events.onDragStop.add(releaseFrog, this);

    }

};

window.onload = function() {
    init();
};

The selectFrog and releaseFrog functions are the event handlers for the drag start and drag stop events. In this example, all they do is log something to the console and change the frame of the sprite. In my upcoming game, I do more in here such as tween animations and game logic.

When I make the frog sprite in the create function of my example, setting inputEnabled to true is the first step. Without this, you can't do anything with input to the individual sprite. Once that is done, you can set the specific input behaviors. The very next line, frog.input.enableDrag(true), turns on drag-ability. The single parameter passed to the function sets whether or not the Sprite should re-center itself to the cursor upon being drug. I passed true, which will cause the center of the sprite to jump to the position of the cursor when the drag starts. If this isn't what you want, you can also say false and drag from any part of the sprite - not just center.

When dragging is enabled, the sprite will fire off events for drags starting and stopping. I added the selectFrog and releaseFrog functions as event handlers using the onDragStart and onDragStop fields of the sprite's events field. Note the parameters that get passed to these event handlers when they fire. The first is the sprite object that was the subject of the drag and the second is the Pointer object. There's lots of information on the Pointer object about the state of the pointer if you want any of that to matter in your game.

If you've tried the code above and are using a mouse, you might be disappointed that the cursor changes to that text-select I-beam cursor thing while you drag the frog. If you'd like it to stay as the default cursor while you drag, no problem! You can simply override the cursor style in the create function. Just add this line:

this.game.canvas.style.cursor = "default";

Now the cursor will always be the default pointer regardless of what you are clicking or dragging in the game. If you'd like the cursor to turn into the click-here hand whenever it's over the frog (dragging or not), there's also the useHandCursor field on the input object. If you add this line to the create function instead...

frog.input.useHandCursor = true;

...it will turn the cursor into the hand when you mouse-over the frog. I didn't care for that personally, but it might be useful in certain situations.

Now that you've read all this, you probably want to see this sprite-dragging in action. Sorry, but the game I was making is not actually in today's comic. You have to wait until later in the week. Click the image or link below for today's comic.

Amphibian.com comic for 18 January 2016

Friday, January 15, 2016

Least Productive Day Ever

This hasn't happened in a very long time, but I have absolutely nothing of interest to share today. I've been in training all day, ate some dinner, and then couldn't get anything to work with the comic game for next week. I think I'm too tired. I have one more day here in Dallas, so I found a nearby movie theater and went to see Star Wars again. I took the stuffed frog with me.


Hopefully I'll have something better next week, including better comics. For now, you get this one.

Amphibian.com comic for 15 January 2016

Wednesday, January 13, 2016

A Stuffed Frog Returns to Texas

Again I have returned to the Dallas area for a week of work that is slightly different from my usual work. Since living out of a hotel is not extremely conducive to either my game development or comic writing hobbies, I present you instead with more pictures of my daughter's stuffed frog doing things with me on my trip.


At our airport, there's a phone on the wall after you go through the security line. It links to the other side of these big glass windows so you can talk to people after going through security. It's been there for a long time, since before people could do that with cell phones I guess. But anyway, here is Froggy talking to my youngest daughter using that phone. My wife is helping her.


When I do these types of posts, you'll notice that Froggy is eating in many of the pictures. Since I have to work most of the day, dinner time is when Froggy and I get to spend the most time together. I always try to feed him well. Here he is eating some macaroni-and-cheese with bacon and mushrooms in our hotel room. It was from the Potbelly Sandwich Shop. I ate the sandwich (not pictured).


What does Froggy do all day while I'm working? Mostly he just sleeps in my backpack, as seen here.


We don't always eat in the hotel. Above is a picture of Froggy eating at the Texas Land & Cattle Steakhouse. He doesn't eat much but is always stuffed.

Now please enjoy today's Amphibian.com comic where the frogs are no more real but no less entertaining.

Amphibian.com comic for 13 January 2016

Monday, January 11, 2016

Tweens in Phaser

I was playing around with another simple game-in-a-comic idea today and I started using Phaser's Tweens. No, Phaser doesn't actually have children between the ages of 10 and 12. Phaser's Tweens are a convenient way of updating one or more object properties over a specified time range.

I'd never used a Tween before, but after playing around with them for a little while I decided that I could use them to replace an effect I had been doing "the hard way" in my platformer. Recall that when the frog gets hurt, I temporarily set his alpha value to 0.5 and then start a timer to set it back. Along with the alpha value, I also set/unset an immune flag on the frog. I can do this same thing better using a Tween.

I've replaced my frog-hurting-alpha-adjusting code with the following...

var t = game.add.tween(frog);
t.onComplete.add(function() {
    frog.immune = false;
});
t.to( { alpha: 0.5 }, 50, Phaser.Easing.Linear.None, true, 0, 2, true);

On line 1, I create the Tween object using the familiar GameObjectFactory (game.add). When creating a Tween, you pass in the object on which it will work. In my case, that's the frog sprite.

Before starting any tweening, I add a listener for the onComplete event. I do this because I want to turn off the frog's immunity when the alpha animation is over.

The final step is to create and start the tween. The last line above calls the to function, creating a tween that moves the specified properties of the object TO the given values. The properties and the target values are given by the object that is the first argument to the function. In my example above, that's { alpha: 0.5 }, which means I want to move the frog.alpha property from whatever it is currently to 0.5. The second argument is 50, which means I want the transition to the new alpha value to take 50 milliseconds. The third argument specifies the easing function to use in the transition. The fourth argument specifies auto-start. I want this tween to start immediately upon creation, so I specified true. The 5th argument is start delay, which is none because I used 0. The 6th argument, which I have set to 2, is the number of times to repeat. The final argument, which I set to true, is the yoyo parameter. Turning on yoyo means that the tween with play backwards automatically at the end. This means that after reaching the alpha value 0.5, it will start transitioning back to the original alpha value. For me, this created a nice flashing effect.

So how long does the whole thing take? I specified 50 milliseconds, but that's just for the one-way transition from 1 to 0.5. Since I turned on yoyo, it doubles to 100 milliseconds. And I also set it for 2 repeats, so the whole flashing alpha thing should complete around 300 milliseconds after it starts. Just remember to do all that math if the length of time is important to you.

The frog's alpha flashes after being hit - thanks to Tweens!
Tweens give me the ability to do some nice things with animating Sprite properties which would be very difficult to do in other ways. I'm glad I discovered them. You can discover the complete source code for the game on GitHub. Just click on this link!

And speaking of discovering things, have you discovered how much you like reading my Amphibian.com comics yet? Look at today's, and maybe look at some other ones while you're there.

Amphibian.com comic for 11 January 2016

Friday, January 8, 2016

You Can't Play Forever

With my one hour of game development time this evening, I decided to finally add "lives" to my Phaser platformer. While I don't want to actually kill Science Frog, the concept of getting more than one life (or attempt) in a game is a fairly standard concept. So far, my game was once-and-done.

The glasses represent the number
of tries (or lives) you get in the game.
Keeping track of how many lives you currently have in the game was simple. I added a lives field to my gameState object. That's the one that I am using to keep track of aspects in the game that need to be shared between the two main game states - the picking a stage and the playing.

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

Now to use that... First, to display the number to the player I added an image of the frog's glasses next to some text beside it. I decided that the glasses would be a good representation of Science Frog. Maybe when he gets beat up too much his glasses will break and that's why he has to restart. That way, I don't have to say he gets killed. Anyway, those steps are simple.

var g = game.add.image(40, 15, "glasses", 0, meters);
g.fixedToCamera = true;

var livesText = game.add.text(78, 5, "x " + gameState.lives, {
    fontSize: 20,
    fill: "#FFFFFF",
    stroke: "#000000",
    strokeThickness: 3
}, meters);
livesText.fixedToCamera = true;

First, I add an Image to the game at position (40, 15). The key for the image is "glasses" which is what I assigned to this image in the asset pack. The 4th parameter, 0, is unused here because as an Image (as opposed to a Sprite) there is only one frame. The last parameter is the group to which this image is added. I am putting it in my meters group, the same one that contains the health bar. After creating it, I set it to be fixed to the camera. This way it doesn't scroll with the rest of the world.

Adding the text for the lives is also simple. Calling game.add.text is all it takes! The first two arguments are the X and Y coordinates. The third is the text itself. The fourth argument is the style object. Its fields define the style of the text. I set the size, fill, stroke, and stroke thickness. Since the background can be very light, putting a black border around the text makes it more readable. The fifth argument is once again the group to which this text should be added - again I use my meters group. Finally, this also gets fixed to the camera.

I've had an onKilled listener on my frog object for some time now, but it didn't do a whole lot. I expanded on that today to take advantage of the lives counter.

frog.events.onKilled.add(function() {
    dieSound.play();
    gameState.lives--;
    bgmusic.stop();
    if (gameState.lives === 0) {
        console.log("game over!");
        game.state.start("stageSelect");
    } else {
        console.log("try again!");
        game.state.restart();
    }
}, this);

The player's frog is killed by Phaser when its health reaches 0 (from colliding with enemies) or when it falls off the bottom of the map. This onKilled event listener is called when that happens. It plays the death sound, decrements the number of lives, and stops the music. If the player has no more lives, the game is returned to the stage select screen, but otherwise the current level just gets reset and the frog starts over back at the beginning.

I suppose this means I need to add in extra-life power-ups somewhere...

You can access the complete source code for this game on GitHub, and you can access the complete Amphibian.com comic on Amphibian.com! Or click on the picture below.

Amphibian.com comic for 8 January 2015

Wednesday, January 6, 2016

Back to Work

I might not get anything done for the rest of the week. Yes, after an extended end-of-year vacation, I've had to return to my real job. My next holiday is in five months. I'm getting extremely limited exposure to sunlight. This is my least favorite time of year.

It's also 8 degrees outside right now. That's Fahrenheit. For you non-Americans, it's -13.

The good news is that I already took down the Christmas decorations. Last year, it was so cold outside for so long, I left them up until March.

But I feel like I have to share something valuable on my blog today...so here is a link to a great frog wallpaper for your computer. I'm using it right now. The site has more.


I feel better now. Maybe today's comic is too depressing. I don't know, read it and tell me what you think.

Amphibian.com comic for 6 January 2016

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