Category: Uncategorized

GameMaker Tutorial: Audio speedup with sync

In so many games, music speedup is a great way to get the message to the player that they need to hurry up and get things done.

It’d be great if you could simply set a new tempo with a simple GML function, and have the current background music adjust on the fly. Something like audio_sound_set_speed(sound, speed) would be lovely. But it’s not as simple as that in GameMaker, as I found out recently.

Here’s how I implemented a speedup for my GMLTetris project:

First, I created two music tracks, one at normal speed, and one at double speed, and added them to the game project as sound assets.

Everything else is just programming:

if <condition> {stop slow_music; start fast_music;}

This is easy enough, the trickiest part is probably getting the condition right to switch tracks, but depending on the game, that condition could be very simple, too.  The only real complication is that if you’re checking the condition repeatedly, as you normally would every Step, you only want to trigger the changeover once.  So to do that, set up a variable to track whether the switch has happened already, and check it, too, even if the condition that triggers the changeover continues to remain true on successive steps.

if <condition> && !music_switched {stop slow_music; start fast_music; music_switched = true;}

The music speedup that happens in a game like Super Mario Bros., where the music speedup occurs when the level timer hits 100, is a typical example of such a technique. If you only need to do a single, one-way switch, this is all you need.

If your game needs to switch back and forth between slow and fast music, your conditional needs to be more sophisticated.

if <condition>
{
   if !<fast_music_already_playing>
   {stop slow_music; start fast_music;}
}
else
{
   if !<slow_music_already_playing>
{stop fast_music; start slow_music;}
}

Here, because the game can switch multiple times, when the condition check happens, we can’t get away with a music_switched variable that changes one time. What we need to do is check to see if the music we need to switch to is already playing, and if not, stop the current music and switch to the other music.

One thing to keep in mind, this basic technique will start the fast music from the beginning of the track. This might be what you want, but it would also be good if you could start the fast music at the position where the slow music was, for a seamless transition.

GML has the functions to do this: audio_sound_get_track_position() and audio_sound_set_track_position(). But in order to make use of them, we need to do a bit more work.

First, since the gml functions return the absolute time position of the track, and since two tracks play at different speeds, we need to adjust the position proportionately when we switch tracks, so that the position is at the same position percentage-wise. This is actually easy, as long as we know the tempo change, which we do. Since the fast track is double speed, we can easily calculate the equivalent position in the other track by multiplying or dividing by 2.

Slow to fast: position *= 0.5;

Fast to slow: position *= 2;

Where I ran into trouble was, I needed to be able to switch both ways. It seemed like it should be simple — just check whether the desired track is already playing, and if not, get the position of the current track, adjust it proportionately, start the desired track, set the position. Easy, right?

Let’s look at it in pseudocode first:

if <condition to switch to fast music>
{
   if audio_is_playing(slow_music)
   {get position; stop slow music; start fast music; set position;}
}
else
{
   if audio_is_playing(fast_music)
   {get position; stop fast music; start slow music; set position;}
}

This was when I discovered that audio_play_sound() returns a handle for identifying the specific instance of the sound that is playing. This is necessary to use to set the track position of the playing sound. You can’t just set the position for the sound_index; you have to set it for the specific handle of the currently playing instance of the sound. If you set the track position for the sound_index, any time that sound resource is played in the future, it will start from that position.

///Create Event:
bgm = audio_play_sound(slow_music, 10, true);
///Step Event:
if <condition>
{
  if audio_is_playing(slow_music)
  {
  var pos = audio_sound_get_track_position(bgm);
  audio_stop_sound(bgm);
  bgm = audio_play_sound(fast_music, 10, true);
  audio_sound_set_track_position(bgm, pos * 0.5);
  }
}
else
{
  if audio_is_playing(fast_music)
  {
  var pos = audio_sound_get_track_position(bgm);
  audio_stop_sound(bgm);
  bgm = audio_play_sound(slow_music, 10, true);
  audio_sound_set_track_position(bgm, pos * 2);
  }
}

I also discovered that detecting which track is playing with audio_is_playing() does not work for this purpose. I still don’t have a clear understanding of what was happening in my code, but some debugging showed that my track position calculations were being distorted by being called multiple times. This doesn’t make sense to me because the song should no longer be playing after the first step when the switch condition is met. But my theory is that since the audio is played in another process from the main program, there’s some messaging going between the two processes asynchronously, and as a result audio_sound_is_playing() can still return true a step later, even after the message is sent to stop the track playing.

By trying to set the track point multiple times in quick succession, weird and unexpected results happened, and the tracks switched but did not set to the correct position.

So I had to come up with a surer method of knowing which music is playing.

Debugging was tricky, since I couldn’t tell from listening where the audio position was. To aid debugging, I drew the position of the playing track to the screen, and then I was able to see that the position was not being set correctly as expected. Somehow, switching from slow to fast would drop the track back from about 10 seconds to 2 seconds, and then switching from fast to slow would jump from 2 seconds to 38 seconds. It wasn’t consistently the same timing, but depending on when the switch was triggered, it would jump around, seemingly at random, but within a range of a second or so around these positions.

I couldn’t figure out why that was happening, so I tried using show_debug_message() and watched the output console, and saw that the track position would update 2 or 3 times when the tracks switched; I was expecting it to only update once.

This is what clued me in to what I believe was happening due to the multiple processes communicating asynchronously.

The solution I used in the end was easy and simple: instead of checking which track was currently playing using the audio functions to directly check whether it was playing, and then switching from slow to fast or vice versa based on the currently-playing audio asset, I just added a new variable, condition_previous, and compared condition to condition_previous, and made the switch happen only when the current condition didn’t match condition_previous. This only happens in one step, when the condition changes from false to true, or vice versa, and so the track position is set once, when the bgm switches tracks and syncs up the new track to where the old track left off.

switch_previous = switch;

switch = <condition to check for switching to the fast music>;

if switch && !switch_previous
{
var pos = audio_sound_get_track_position(bgm);
audio_stop_sound(bgm);
bgm = audio_play_sound(fast_music, 10, true);
audio_sound_set_track_position(bgm, pos * 0.5)
}
else
{
if !switch && switch_previous
{
var pos = audio_sound_get_track_position(bgm);
audio_stop_sound(bgm);
bgm = audio_play_sound(slow_music, 10, true);
audio_sound_set_track_position(bgm, pos * 2);
}
}

This works, because it guarantees that the condition checks will be accurate, as they do not depend on checking the status of the audio playing in another thread.

Steam and Censorship

A recent announcement by Valve on Steam’s community blog has created a great deal of controversy.

I’m not entirely sure how I feel about this, but my inclination is that Valve is trying to do the right thing, in a situation where they cannot possibly please everyone, and prefer to be neutral and let the market sort this out, allowing gamers to play games they want to play, and developers develop games they want to develop.

I tend to agree with their stance and reasoning.  I haven’t thought about it a whole lot, and I haven’t looked into specifics of what problems have been going on within the Steam community that gave rise to this decision, so this is just a preliminary reaction.  But I like free expression, I don’t like censorship in any form.  I think people should use their discretion when it comes to what they say, and what they choose to experience as entertainment.  I want games to be as powerful a medium as film or literature, and I believe in their potential to be more powerful than either.

Obviously, there’s a lot of nuance to this — we don’t always get to choose our experiences.  Games can surprise and shock people. But I don’t believe that games should be simply light entertainment that never offends anyone.  Part of what makes art powerful is its ability to shock, offend, or even traumatize.  When an authority attempts to exercise control over ways in which it is permissible to shock, offend, and traumatize, you end up with art that is safe for the establishment and promotes the interests of the powerful, and serves to persist the status quo.  Whether that’s good or not, depends on whether your values align to that of the authority.

I believe in authority that defends the rights of individuals to speak out in ways that contradict the establishment, challenge it, and can force it to re-evaluate, change course, and reform as needed, as times and prevailing attitudes change.

Obviously, people can be and are sometimes hurt in the course of this.  This is something I think most of us try to avoid.  Even so, it happens — occasionally deliberately, but often not.  Perhaps some degree of mitigation of this is not bad.  But it is dangerous, and needs to be considered very carefully.  I’d rather allow the offensive, controversial content to exist, and surround it with robust discussion, than to prevent it from being published and distributed.

Adobe Flash EOL in 2020 – how will we preserve games?

Adobe announced today that it would cease development and support of Flash in 2020.

Of course, there were (and are) a lot of issues with Flash:

  • the proprietary nature of the Flash Player plugin;
  • memory and CPU usage;
  • stability problems;
  • security problems;
  • privacy concerns over Flash cookies;
  • Flash advertising/malware;
  • lack of accessibility in many Flash objects, resulting in issues for people with disabilities, screen readers, search engine indexing spiders, or for anyone who simply didn’t have the Flash Player installed, etc.;
  • and poorly programmed Flash objects.

So it’s not entirely a bad thing that Flash’s time is nearly at an end.

While this news doesn’t exactly come as a surprise to those who have been following the life of Flash since the iPhone launched, it does raise a serious question:

What will happen to all the games created in Flash when Flash is dropped from mainstream web browser support?

How will the history of games developed in Flash be preserved?

[Update 5/2/2018:] Here’s an article on one effort to preserve Flash games.

This is no small question. Over the 20+ years that Flash has been around, thousands of games have been built with it. Many of them are good games that still hold replay value. But without a viable platform with which to play them, will they wink out of existence and be forgotten?

I think the best approach to preserving Flash’s historical legacy would be to create a version of the Flash Player in Javascript or Web Assembly, and then any web site can use that to backfill support for any Flash objects that they wish to serve.

What are your favorite Flash games?

The Ongoing Sale

Since I announced yesterday that I’d finally earned my first $100 payout through the GameMaker Marketplace, I dropped my price on all paid assets to $0.99. I had another purchase today, so to celebrate that, I decided to adjust the terms of the sale.

The payday celebration sale will continue through 4/10/17 as planned.

For each paid purchase I get during the sale, I will extend the sale by one day.

Update, I had another sale today, 4/11/17, which will extend the discounts another day.

So as of right now, the sale on all my paid assets will last until 4/12/2017.

Get csanyk GameMaker assets on GameMaker Marketplace!

Galaxian is a triumph on the Atari 2600

As a child of the 1970’s, I’ve been attracted to arcade video games since I was tall enough to reach the controls. This was 1981-84, during the heyday of the arcade’s Golden Age, a time when games like Pac Man, Dig Dug, and Galaga were new, hot, and everywhere. Grocery stores, gas stations, seemingly anyplace people might spend time, you’d find a couple of arcade games, ready to suck the quarters out of anyone who passed by.

Just slightly older than these games were the ever-popular Space Invaders, and its evolutionary next step, Galaxian. Although these titles were top shelf games in their day, I found that I didn’t enjoy them very much.

Space Invaders was just frustratingly slow at first, but then sped up to an unfair pace by the end, and I could never manage to destroy that last invader on the first wave. You had to have perfect aim to hit it, and it moved so fast it was seemingly impossible to track, so you had to be lucky. If you missed, the slow-moving missile took forever to disappear at the top of the screen, and you couldn’t fire again until it did. Usually this delay meant your death, as the hyper-paced final invader would reach the ground, ending your game. Plus, it was black and white. It felt old. I respected it — even then I could tell that it was a important game — but grudgingly, I had to say that I just didn’t enjoy it that much, although I wouldn’t have admitted it to anyone back then.

Galaxian, too, was a game I found too slow and frustrating to play at arcades. It seemed like the next step in the vertical space shooter. Graphics were now in color. A formation of aliens marched back and forth across the screen, but this time instead of descending toward the earth, they stayed at the top of the screen, while one by one, or in pairs, individuals would peel off from their formation and dive bomb you. Their bullet patterns and flight paths seemed to make it all but certain that they would hit you if you didn’t hit them first. I could usually survive for a while, maybe clear a screen, but it never failed that if I happened to miss a dive bombing enemy, it would corner me in the side of the screen and crash into me, or hit me with too many bullets to dodge. You could always dodge one, but there’d always be another one following up, and your first dodge would put you right in its path. It seemed unfair, and so, not very fun. I always gravitated toward the games that I could last a bit longer on, so I could get my money’s worth out of my quarters.

I had a cousin who owned an Atari 5200, and played Galaxian on it once or twice while visiting them. The 5200 port was a very faithful reproduction of the arcade experience, not exactly arcade-perfect, but nearly so. I still didn’t care much for it, because it suffered from the same shortcomings. It wasn’t as bad to lose at home, since it cost nothing, but I still preferred to play games that felt fair.

It never entered into my mind that maybe I just wasn’t very good at Space Invaders or Galaxian. But probably, I was. Ok, not probably. I sucked. But in my defense, I was like 6, and just tall enough to reach the stick and see the screen. But back then, I blamed arcade games for being “greedy” in contrast to home consoles, which seemed to reward players with longer games that were still challenging, but more fun because they weren’t so brutally ass-kicking hard.

I never played Galaxian on the Atari 2600 back in the day. I’d played the 5200 version and was impressed with its arcade-quality graphics, and I remember seeing the pictures on the back of the box on the 2600 version, and being unimpressed. Since I never particularly enjoyed the game, I didn’t have any interest in owning it on the 2600, never knew any kids who had it in their collection, and so never played it. At some point, we had an Atari 7800, which had Galaga, the sequel to Galaxian, and one of my very favorite games, so I played a lot of that.

I’m not sure when exactly, but at some point I picked up a copy of the 2600 port of Galaxian, probably a few years ago. I recognized it was a significant title in videogame history, and so I wanted it for my collection, despite not having favorable memories of it from its heyday.

I finally got around to playing it today, and came away very impressed. Here’s a video review so you can see what it’s like:

The 2600 port plays much better than I remember the arcade. The motion is extremely fluid, which, considering the limitations of the Atari 2600 hardware, is nothing short of amazing. Maybe I’m just better at videogames than I was at ages 5-8, but I found that the game felt very fair, with divebombing enemies that are actually dodge-able. I’m sure, the horizontal aspect ratio of the screen plays into this somewhat, as you have more room to dodge, and also your shots that miss take less time to leave the screen, meaning that you can fire follow-up shots that much faster.

I was always a fan of vertical shooters of the Atari 2600, my favorites being Megamania, Phoenix, Threshold, and Tac-Scan, and Space Invaders. Galaxian is every bit as good as the best of these, and is still fun to play even now.

Playing Galaxian tonight, I found that my strategy was different from how I played the arcade original some 35 years ago. My old strategy was to try to shoot the enemies still in formation. They were easier to hit, since they didn’t swoop or shoot at you, and it seemed to me safer to eliminate them before they could turn into a threat. I’d try to shoot the divebombing aliens as they flew over me, and dodge out of the way of them and their shots, but mostly I concentrated on blowing away he ranks of Galaxians in formation, much as I approached Space Invaders.

My new strategy was much more successful, and rewarding: I ignored the galaxians in formation, since they don’t do anything that can hurt me, and focused on the divebombing aliens. It turns out, this has many advantages. First, by focusing on the divebombers, you are focusing on the only thing in the game that can threaten you. Shooting them is a much more reliable way to avoid them than dodging. You will need to dodge sometimes, but if you focus on developing skill in shooting the moving enemies, it gets pretty easy to pick them off before they can collide with you. The green Galaxians are simple, slow moving, and easy to hit. The purple ones are harder to hit, but with a little bit of practice the timing becomes easily mastered.

Hitting divebombing enemies in mid-flight makes you safer in two ways: enemies are destroyed before they’re low enough to collide with you, and they can’y get all their shots off. Typically, you’ll hit them as they cross ahead of you, and so you’ll be moving in the same direction, to track them, and the shots they do get off will fall harmlessly behind you, and by destroying the alien as it passes directly above you, you prevent it from getting ahead of you where it can drop bombs that would be dangerous to you.

Additionally, by hitting them as they’re diving toward you, your shot has less distance to travel, which means that you can get off more shots — since you can have only one shot on the screen at a time, when they hit something low on the screen, the shots don’t have as far to travel, meaning they hit the target sooner, meaning that your bullet is consumed and you can then fire another shot more quickly. If you miss one of the bombers, you might still end up hitting one of the galaxians still in formation, especially early in the stage, which isn’t so bad either. But the lower your shots are when they connect with an enemy, the faster you can shoot.

This in turn sets up a rapid flow of firing, hitting a dive bomber, then hitting the next dive bomber with a rapid follow-up shot. Once mastered, you can mow through the entire formation in quick succession in this manner. This turns out to be very enjoyable. You feel more skillful, since you’re targeting the fast-moving enemies, getting more points for them, and it looks more risky, since you’re often hitting the enemies pretty low on the screen, when it looks like they’re most dangerous — but at the same time you’re actually playing the least risky style of play. Of course, that’s what skill is — finding the right pattern of actions to minimize your risk, while doing what looks the most daring.

It’s clever, because the more intuitive way to avoid risk would be to try to avoid the dangerous enemies and attack the enemies that aren’t a threat. But counter-intuitively, when you focus on the dangerous enemies, and take the aggressive approach of destroying them rather than running from them, it minimizes the risk they pose to you, while the enemies that aren’t a threat remain a non-threat.

At this point, I recognized what a truly well-designed game Galaxian for the Atari 2600 is. I’m curious to see whether this strategy applies to arcade Galaxian. Since I don’t have ready access to an arcade with Galaxian in it, the next best thing is to watch a YouTube video of a skilled player.

And it looks like this is indeed the strategy to employ, although this player also has enough time to target plenty of enemies still in formation. I think the 2600 and arcade versions are different enough in their game play that they feel like different enough that while the basic strategies are more or less the same, the specifics are different. In the arcade, there’s much more space between the bottom of the screen, where you are, and the top of the screen, where the enemy formation is. But ultimately, I think the Atari port gives you less time to target the enemies in formation, forcing you to spend most of your time focusing on the swooping divebombing enemies.

In any case, Atari 2600 Galaxian is a fantastic game, and if you’re into vertical shooters is a must have, being one of the finest examples of the genre on the Atari, as well as an outstanding port of a historic and classic game.

GameMaker Asset: Rolling Average

In creating my last tutorial and demo, I needed to calculate the rolling average for the fps so I could measure performance differences between Instance Pooling and Create-Destroy.

It turned out that the functions for setting up a rolling average were pretty simple, yet were a pain to do well. So once I got them working, I decided to make them into an asset for GameMaker: Marketplace, so they’ll be easy to re-use in any project, with any series of numeric values, and so I can share them with the community.

Calculating a rolling average over a series of streaming values is now simplified by these new functions:

rolling_mean_create()
rolling_mean_destroy()
rolling_mean_add()
rolling_mean_read()
rolling_mean_size()
rolling_mean_resize()

Rolling Average on GameMaker Marketplace (free download)

Rolling Average on itch.io (free download) (free download)

Full documentation

Ludum Dare 37

Ludum Dare 37 is next weekend!

This is a milestone for Ludum Dare, as they are running this jam on their new website, ldjam.com. The old website had served admirably for many years, but lately the scale of the event has exceeded its capability, and the ad hoc customizations to the wordpress site were such that it was difficult to maintain the site. The new site will be a welcome renovation as well as a new foundation from which a better LD will be possible.

I am planning on using GameMaker Studio 1.4 one last time (probably) for LD37, because GMS2 is still in beta, and YYG have not yet released the HTML5 module, and I prefer to be able to create a HTML5 build of my project so that more people can play it. I’m looking forward to learning what the theme will be.

KB Tester utility helps you see what value to check for when a key is pressed.

KBTester is a utility/demo I made to help out with coding your keyboard_check routines. It is born out of frustration and necessity for handling certain inputs from a very fundamental input device for computer games, the standard keyboard, which are not supported out of the box.

If you program keyboard input in your games, you’ll find that, for most keys on a computer’s keyboard, you can use vk_constants and ord(letter)… but for some odd reason YYG didn’t create a vk_constant for every key on the keyboard, and don’t plan to. Not only that, but there are certain keys that don’t return the right value for ord() to work with keyboard_check.

For example, say you want to check if the period key is pressed. You might think that you can do keyboard_check(vk_period) but to your surprise, there is no vk_period constant defined in GML. So, then it must be that you need to do keyboard_check(ord(“.”)) only… it doesn’t work!

That’s because ord(“.”) returns a value of 46. But for some reason, if you want keboard_check() to return true when the period key is pressed, you need to check for the value 190. Why? Why are certain keys on the standard keyboard treated as second-class citizens? Because, sadly it’s not in YYG’s vision to improve keyboard support.

To paraphrase a certain “Evil YoYo Games Employee” who commented on my suggestions for ways the current keyboard support badly needs to be improved:

<paraphrase>Why should we improve keyboard support when you can just research what codes map to your keyboard keys, make an extension that has a few constants in it, and then hope that these will work with all keyboards and all target platforms? Just code it once and then put it up on the Marketplace. Now that the marketplace exists to provide stopgap coverage of GM:S shortcomings, we don’t have to pay our own programmers to fix those holes anymore.</paraphrase>

So, I guess we’re supposed to figure out the numbers and then code some constants for the missing vk_constants, and use those. This, despite the helpfile recommending against using hardcoded numeric values in keyboard_check because you never know if it’ll work on the target platform if it’s not Windows/Mac/Ubuntu:

NOTE: These functions are designed for Windows/Mac/Ubuntu desktop platforms only. You may find some of the in-built variables and constants aren’t valid on other platforms and many of the functions won’t work on mobiles.
Now, each key is normally defined by a number, called the ascii code, and you can directly input this number into these functions and they will work fine… But, as it’s a bit difficult to remember so many numbers and the relationship that they have with your keyboard, GameMaker: Studio has a series of constants for the most used keyboard special keys and a special function ord() to return the number from ordinary typed characters (either letters or numbers).

The implication is that, YYG seem to be saying, “Despite the promise of GM:S to be a development environment that supports multiple target platforms, we didn’t see the need to ensure that your code will run the same on all target platforms we support, or all region/localities, or with all keyboard layouts. After looking into it we decided it was too hard for us to deal with, so we’re passing it along to you to figure out for yourself. So just be aware that these may or may not work on all platforms, and that’s all the info we’re going to give you about that. You’re on your own to figure out how to solve keyboard input from any platforms that don’t work with our keyboard input functions.”

Well, for whatever reason, YYG doesn’t provide FULL keyboard coverage between ord() and vk_constants, and it’s not in their vision to address this shortcoming, so I guess you’re going to have to go out and find some reference that will tell you what numbers represent what key, and then hope they still work.

In the meantime, you can use KBTester, press a key, and get the answer without having to hunt the info down on the internet and hope it’s correct. If you’re having trouble getting keyboard_check to work, and need to verify that the magic number you’re using is indeed the right one, you can run KBTester. Press the key you want to use, and KBTester will tell you the value that GameMaker sees when it is pressed.

Open Letter to Smart Phone Manufacturers

Dear Smartphone Industry,

I don’t need a bigger screen, OK? I need a screen that will fit comfortably in my pocket. My front hip pocket to be exact. The dimensions of the Samsung Galaxy S5are about as big as I can go. Really, the S2 was more comfortable.

I don’t need a thinner phone. I need a phone that feels comfortable in the hand.

I don’t need a thinner phone. I need a phone with ample battery, such that I don’t need to charge for several *days*, despite heavy use of the device. If you made the phone phone that was inch thick, and all that extra space was battery, and I could go a week without charging, that would be AMAZING.

While we’re at it, I would also really like intelligent battery management. I would like apps that need to use the network to not talk to the network directly, but talk to a network handler, which will determine if/when to allow the data to be transmitted. I can then configure the network manager to either not allow any transmission (like airplane mode; saving maximum battery), or allow all transmissions at any time (fastest response but lousy battery), or burst mode (leaving the transmitters off most of the time, but waking up and reconnecting every N minutes, sending/receiving data that has accumulated in that time, or when I request it).

Lastly, tell network providers to quit bundling apps with their phones. I don’t want or need so many of them, and there’s no way to uninstall the ones that are baked into the firmware. I can figure out what I need and install it. If I’m upgrading or migrating from an old phone, it should carry all that stuff over, with all my settings and data anyway. There’s no need to bundle anything. Just provide me with a bare phone.

And tell network providers that they must roll out security updates in a timely fashion (days, not months) so that users aren’t left vulnerable. Frequent, more granular updates rather than one or two monolithic updates before support for my handset model is dropped entirely, would be great.

Thanks,