code of the Ninja();

// in search of swift, efficient, and invisible code

Showing posts with label controls. Show all posts
Showing posts with label controls. Show all posts

2011-02-28

Checking Multiple Joypad Buttons

Welcome back, Code Ninjas!

I apologise for not posting in such a long time (I know ninjas are supposed to be silent, but not that silent), but I've been working on a couple of projects that I hope will soon suprise and delight.

Right now, though, I want to talk about an improvement to my earlier Joypad code. I've been interacting a lot recently with disassemblies of Sonic the Hedgehog, and it's a great learning experience. Regardless of what might have happened to the Sonic series over the years, Yuji Naka's programming remains an inspiration to me. Studying his code has taught me plenty of little tricks, not least because the Genesis is very limited by today's standards and it took a lot of skill to squeeze great results out of it.

Anyway, last time I had described a system that updates a variable called JoyCurrent each step with the current state of the joypad, with each bit representing one button. There was also a second variable called JoyPrevious in which JoyCurrent is stored right before JoyCurrent gets updated. And finally, a third variable called JoyPast, only there to smooth out problems with cheap joypads that occasionally glitch up.

There were three scripts: joy() for checking if a button is down; joy_pressed() for checking if a button is down now but not one step ago; and joy_released() for checking if a button is up now but not one step ago (or even two steps ago, in the case of the aforementioned glitchy controllers).

But I've since discovered a serious deficiency with the joy_pressed() and joy_released() scripts. They can't check for more than one button at a time without causing problems. Let me explain.

The Problem

Since JoyCurrent and its related variables contain bits that are either on or off to represent the state of buttons on the joypad, checking the state of a button is as easy as testing any given bit with code like this:

where argument0 is a power of two such as 1 (for testing the first bit), 2 (for testing the second bit), 4 (for testing the third bit), and so on. It's best to define these values as constants so that they can be sensibly named after the buttons, like A, B, LEFT, or START.

Anyone paying enough attention can see that you can test for more than one button simultaneously just by passing a value as argument0 that has more than one bit on. For instance, you could pass a value like 65535 to test if any button was down, or you could use binary OR to test any combination such as LEFT | RIGHT.

Now, the way the script was written it will return true if any bit of argument0 matches up with one in JoyCurrent. If you want to be sure all the bits match, then you'd have to write something like this:

This is all very well and good, but it falls apart when we get to joy_pressed(). This is how it was written:

Now suddenly, because of that boolean and, the value being returned is degraded - it's now only useful as true or false and doesn't give us as much information. Worse, the following happens:

Imagine you want to check whether A, B, or C are pressed, like in the old Sonic games where any of the three buttons makes him jump or Spin Dash. You don't care if one of the buttons is already down when another is pressed - you still want to detect the new press. The way my code was written, this is impossible with only one call to joy_pressed() because if any of the bits is on in JoyPrevious, the new press won't be detected. The only solution would be to make multiple calls something like this:

which is just tacky and consumes more processor time. It would be far better to be able to type:

and have it be done with. (Of course, A | B | C could be a constant called JUMPBUTTON or something, too, to make it even nicer.)

Well, then, how can we change the code so that this is possible? I'm glad you asked that.

The Solution

At the end of the script joy_step() (the one that updates JoyCurrent and JoyPrevious), we need to update two new variables, JoyPressed and JoyReleased (not to be confused with the scripts that have similar names!) These should be global variables, declared in joy_init().

These variables are destined to behave just like JoyCurrent, only for pressed and released. Just like how you can test to see if buttons are down by checking JoyCurrent as joy() does:

you'll be able to check which buttons are newly down or up in one simple comparison by rewriting joy_pressed() like so:

and joy_released() like so:

(At this point these scripts are all so simple you might not even want to make them scripts at all, but merely type anywhere you would have typed joy_pressed(BUTTON), but it's up to you.)

This sounds great, and it will solve all of the problems I mentioned above, but I haven't told you yet how to update JoyPressed and JoyReleased at the end of joy_step(). It requires a little bit of explanation, though, so we can understand the underlying principles. Otherwise, it would get confusing and complex if you ever need to expand upon it.

First, let's look at a visual representation of our variables. I'm assuming only 8 buttons for convenience. Here's a state with no buttons down:

JoyPrevious: - - - - - - - -
JoyCurrent:  - - - - - - - -

Let's press the first button (we'll call it A).

JoyPrevious: - - - - - - - -
JoyCurrent:  - - - - - - - A

Now let's, without advancing a step yet, add a third variable to this visual guide, temp. It's contents will be JoyPrevious binary AND-ed with JoyCurrent (i.e. ).

JoyPrevious: - - - - - - - -
JoyCurrent:  - - - - - - - A
temp:        - - - - - - - -

As far as temp is concerned, nothing has happened! But what happens when we do advance one step, without letting go of A?

JoyPrevious: - - - - - - - A
JoyCurrent:  - - - - - - - A
temp:        - - - - - - - A

JoyPrevious becomes JoyCurrent, JoyCurrent remains the same, and temp finally notices what's going on. Clearly, temp is no good for checking buttons that are newly down, because for one temp has only detected the new press one step late, and for two if we continue to hold A temp will not revert to 0. Merely using binary AND isn't enough. We need to do one more calculation - binary XOR. Let's go back to our previous step:

JoyPrevious: - - - - - - - -
JoyCurrent:  - - - - - - - A
temp:        - - - - - - - -

and add a fourth variable, called JoyPressed. It's contents will be temp binary XOR-ed with JoyCurrent (i.e. JoyPressed = temp ^ JoyCurrent;).

JoyPrevious: - - - - - - - -
JoyCurrent:  - - - - - - - A
temp:        - - - - - - - -
JoyPressed:  - - - - - - - A

By binary XOR-ing temp and JoyCurrent, JoyPressed contains only bits that are different between them. In the next step, the magic happens:

JoyPrevious: - - - - - - - A
JoyCurrent:  - - - - - - - A
temp:        - - - - - - - A
JoyPressed:  - - - - - - - -

Now JoyPressed has reverted to 0, meaning it accurately represents buttons pressed - bits will only trigger for one frame when their corresponding button is pressed. The same thing will happen even if A is released instead of held down:

JoyPrevious: - - - - - - - A
JoyCurrent:  - - - - - - - -
temp:        - - - - - - - -
JoyPressed:  - - - - - - - -

And, if a new button is pressed while another is held down, it will still be detected as a new press:

JoyPrevious: - - - - - - - A
JoyCurrent:  - - - - - - B A
temp:        - - - - - - - A
JoyPressed:  - - - - - - B -

Fantastic! Let's add another variable, JoyReleased, that is temp binary XOR-ed with JoyPrevious instead of JoyCurrent (i.e. JoyReleased = temp ^ JoyPrevious;) and advance one step while releasing B (but not A).

JoyPrevious: - - - - - - B A
JoyCurrent:  - - - - - - - A
temp:        - - - - - - - A
JoyPressed:  - - - - - - - -
JoyReleased: - - - - - - B -

The same principle operates as with JoyPressed. We just solved the problem. Hooray! The actual code at the end of joy_step() would look something like this:

Really the only thing to be done now is make sure that cheap joypads don't cause false press and release events simply because the signal is interrupted for a step once in a while. This is easily done by binary OR-ing JoyPrevious and JoyPast together to create a sort of "buffered" previous state when checking for presses, and binary OR-ing JoyCurrent and JoyPrevious together for a buffered current state (and using JoyPast in place of JoyPrevious where it used to appear in the line) when checking for releases. For example:

Conceivably you could also, instead of doing everything in 2 lines, store more information like so:

This way you could check JoyDown or JoyUp to see whether a button is down but not pressed, or up but not released, which might be useful. Hey, you never know.

That takes care of today's subject. I'll be posting again soon. Until then, happy coding!

2009-09-05

Smart Triggers

Welcome to another lesson, Code Ninjas! This time I'll be demonstrating a game design concept, and not actual code. It's pretty simple, actually, but it requires a bit of backstory.

In The Legend of Zelda: The Windwaker for the Gamecube, you can target enemies with the L trigger. They call this L-Targeting. In the options menu of the game, you can change the behaviour of the L-Targeting. The two settings are Switch and Hold. The difference between them is thus: In Switch Mode, you begin targeting by pressing and releasing the L trigger once. You then stop targeting by pressing and releasing the L trigger again. In Hold Mode, you begin targeting by pressing and holding the L trigger down, and you stop targetting by releasing the L trigger.

Now, this option is an important one. I use Hold Mode, myself, and play miserably in Switch Mode. Some of my friends, however, use Switch Mode, and perform admirably. One mode isn't really better than the other. It all depends on the type of player.

However, when using either mode, sometimes things still don't work out so well. For instance, in Hold Mode, during long battles against one enemy, your finger can get tired out squeezing the trigger the whole time. In Switch Mode, in battles with many enemies, pressing the L trigger again sometimes cycles to the next enemy instead of ceasing to target altogether. This makes terminating a confrontation and retreating a confusing process. Continually switching between modes through the option menu would be tedious, though, so a player tends to pick one mode and stick with it, warts and all.

While thinking about these issues, I thought of a simple third setting, which I called Smart Mode. Perhaps it does not solve all of the problems, and I can't quite test it out in Windwaker, but here is how it would work.

Basically, when a press of the L trigger is detected, a timer begins. In Game Maker, you would use an alarm event, or increase a variable every step. Anyway, then when a release of the L trigger is detected, one of two things would happen:

1 - If the timer was below a certain time (say two-thirds of a second, about), you wouldn't stop targeting. It's rare that a player would want to target something for so short a time. At this point, it would require another press of L to cease targeting.

2 - If the timer was above that time, then you would cease targeting. In this way, a natural quick press and release of the trigger would enter Switch Mode, and pressing and holding down the trigger would enter Hold Mode. In a way, both modes would be available to you at any time, without having to change anything in the options menu. The computer could detect which you wanted it to be based on how you pressed the button. It is for this reason that I call it Smart Mode. It's like the computer knows what you're thinking.

This "smart toggling" system could be used for anything. It doesn't have to be targeting in a 3D adventure game. It could be used for opening and dismissing a Seiken Densetsu style menu ring, or activating a protective shield, or even for changing between two different weapon types in an action sidescroller.

And I'm sure that you Code Ninjas could think of many more applications that I couldn't. So, think about how you might add "smart" triggers or toggles to your game. It might make it a little more user-friendly.

Happy coding!

2009-08-07

At the Movies

Welcome back, Code Ninjas!

Last time, we learned how to implement a joypad system using binary values. Now we're going to be expanding on that a little by adding some scripts for recording joypad "movies".

Joypad movies can be useful in many ways. For one, you can easily record yourself playing a level of your game to make a demo, which might play if the player lingers on the title screen for too long. Or, you might allow players to record themselves, and share these movies as a way to show off their skills.

But they are also useful to you, as the game developer. If there is a bug or unexpected behaviour in your game, just start recording the joypad, and then trigger the bug. Now you can replay that sequence over and over until you determine the source of the bug. Then, once you think you've fixed the bug, you can play it once more to make sure that it's absolutely gone.

Also, if you want to record a true video movie of your game, for instance to make a YouTube trailer, many programmes that record video of the game window will slow down your game. If you record a joypad movie first, and then make a video of the joypad movie being played back, you won't have to actually be playing the game while it's slow.

Well, let's get to it!

Joypad movies will be saved to binary files. Our first script is save_joypad_file, which will set things up to start writing input to a file. It takes one argument, which is the name of the file to write to.

save_joypad_file()

close_joypad_file();
joy_mode = 2;
jfile = file_bin_open(argument0,1);
file_bin_rewrite(jfile);

You'll notice that the first thing it does is perform the script close_joypad_file. That's our next script. It takes no arguments.

close_joypad_file()

if joy_mode > 0
  {
  joy_mode = 0;
  file_bin_close(jfile);
  }

This script has to be called first so that if you call save_joypad_file while it is already recording or playing back a joypad movie, it will close the first one automatically.

It is also important to call close_joypad_file in the game end event of the Joypad object.

Next, let's write our next script, open_joypad_file. Like save_joypad_file, it takes one argument - the name of the file to read back.

open_joypad_file()

close_joypad_file();
joy_mode = 1;
jfile = file_bin_open(argument0,0);
jsize = file_bin_size(jfile);

You'll have noticed by now that the preceding three scripts all set the variable joy_mode to a value - 0 for normal, 1 for playback, and 2 for recording. Where joy_mode comes into play is in the next script - joy_step.

This script, joy_step, is not new. We wrote it in the last lesson, but it needs to be rewritten to accomodate the joypad movie system. Replace the whole script with this code:

joy_step()

JoyPast = JoyPrevious;
JoyPrevious = JoyCurrent;

if joy_mode = 1
  {
  JoyCurrent = file_bin_read_byte(jfile)+
  file_bin_read_byte(jfile)*256;
  jpos = file_bin_position(jfile);
  jprog = jpos/jsize;
  if jpos >= jsize
    {
    close_joypad_file();
    }
  }
else
  {
  JoyCurrent = 0;

  for (t=0;t<6;t+=1)
    {
    if joystick_check_button(1,Joy[t])
    or keyboard_check(Key[t])
    JoyCurrent |= 1<<t;
    }

  if AnalogCount
    {
    if joystick_xpos(1) < -AnalogDeadzone JoyCurrent |= LEFT;
    if joystick_xpos(1) > AnalogDeadzone JoyCurrent |= RIGHT;
    if joystick_ypos(1) < -AnalogDeadzone JoyCurrent |= UP;
    if joystick_ypos(1) > AnalogDeadzone JoyCurrent |= DOWN;
    }
  }

if joy_mode = 2
  {
  file_bin_write_byte(jfile,JoyCurrent mod 256);
  file_bin_write_byte(jfile,JoyCurrent div 256);
  }

First it checks to see if joy_mode is 1, for playback. If so, it reads from the file, updating a variable called jprog (you can take that bit out if you want, but it's useful for drawing a progess bar), and calling close_joypad_file automatically when it reaches the end. If joy_mode is something other than 1, input is received from the joypad and keyboard as normal, instead of from the file.

Next, it checks if joy_mode is 2, for recording. If so, it simply writes the value of JoyCurrent to the file as two bytes. If you choose to use more than 8 buttons (this tutorial only uses 6), the second byte will be necessary.

Okay! Now, all you have to do is include some interface for calling open-, save-, and close_joypad_file, and the rest will be taken care of. The simplest way is to call them in events for the press of function keys in the Joypad object.

Before we close this lesson, there is one more cool thing that recording joypad movies can do for you. Ghosts!

In Mario Kart, one of the coolest features is the ability to race against "ghosts". A ghost is just another driver, but with one important distinction. Instead of being controlled by computer AI, it is being controlled by a joypad movie. In this way, you can race against yourself, or go head to head with legendary runs by expert players, made years ago!

So, how do you include ghosts? If you simply play back the joypad file, JoyCurrent will receive its value from the file, and not the joypad, and your player object will follow the movie. We don't want that, though. We want the player object to be left alone, and have a new ghost object that follows the movie, co-existing with the player object. How do you get a ghost to play from the file, but leave the player object controlled by the joypad?

Well, you have to use a second set of variables besides JoyCurrent, JoyPrevious, and JoyPast. Let's call them gJoyCurrent, gJoyPrevious, and gJoyPast. These won't be global, but local to the ghost object, which should be a copy of the player object. Next, we'll need another set of scripts for checking them. Duplicate the joy, joy_pressed, and joy_released scripts and call them gjoy, gjoy_pressed, and gjoy_released. Then edit them so that they query gJoyCurrent, etc, instead of JoyCurrent.

Now, in the ghost object's code, replace anywhere the joy scripts were called with the gjoy scripts. Finally, you have to add code for opening, reading and closing the joypad movie in the ghost object, so that it does it all independently of the rest of your game.

I'd go into more detail about this last step, but it's easier to just look at it to see how it's done. You can use the link below.

Download the GML scripts and a GMK example of this lesson here.

Next time - Smart Triggers! Until then, happy coding, fellow Code Ninjas!

2009-08-03

Joy to the World

Welcome to your first lesson, my esteemed Code Ninjas in training! You have come here seeking knowledge of the Code in order to create your own video games. This is a worthy goal. It is my hope that I can teach you valuable lessons that will allow you to fulfill your dreams more quickly and capably. Armed with the secrets I shall reveal, you will be able to make your game engines more professional and - dare I say it - more fun. I do not mean to illude you - in no way can I make the path you have chosen easy. Game design is hard work. But I can make it easier.

Today's tutorial is about handling the player's input. Almost everyone playing your game will have a keyboard, but the keyboard is not the ideal input device for classic games of the type we want to make. Mario, Sonic, Metroid, Zelda, Final Fantasy, Klonoa - all these games are designed for joypads. So, ideally, for players who have access to PC compatible joypads, they should have the choice to use either their joypads or keyboards.

But it can be somewhat tricky to programme your game to either query both, or decide which one to query depending on the player's choice. Furthermore, Game Maker doesn't natively have very complete joypad functions.

These things are what I aim to teach you to overcome.

First, create a new object. We'll call it Joypad. It should be set to persistent, so that it is always present, even when the player moves between rooms. It shouldn't be visible, or have a sprite. Then you should place an instance of Joypad in your initial room, the one that your game starts in.

Make a script - we'll call it joy_init, and put it in the create event of Joypad.

Let's start writing joy_init:

joy_init()

globalvar JoyCurrent, JoyPrevious, JoyPast, Key, Joy, AnalogCount, AnalogDeadzone;

AnalogCount = joystick_axes(1) div 2;
AnalogDeadzone = 0.25;

What we're doing here is setting up a few global variables that can be referenced easily by every object in your game. The variable AnalogCount is set to the number of analog sticks the player's joypad has. We determine this by returning the number of axes and dividing by 2. Then we set up the variable AnalogDeadzone. A dead zone is essential when an analog stick is concerned. Neutral is 0, full on is 1. But due to the sensitivity of most controllers, the stick is never exactly at neutral, but fluctuates around .1 or even .2. A lot of driver software lets people set up dead zones for their joypads automatically, but we can't always bet on that. It's better to have your game take them into account. You can supply any value you think is reasonable (I've used .25 here), but it's even better if you include some option for the player to adjust the dead zone values manually - perhaps even independently for each stick.

Next, we add this to joy_init:

joy_init()

Joy[0]=3;
Key[0]=97;
Joy[1]=10;
Key[1]=13;
Joy[2]=13;
Key[2]=38;
Joy[3]=15;
Key[3]=40;
Joy[4]=16;
Key[4]=37;
Joy[5]=14;
Key[5]=39;

These are the joypad buttons numbers (Joy[]), and the keyboard keycodes (Key[]) we'll be using later to check for input. I've only done 6 buttons here, 0-5, because that's all a classic Sonic game really needs, but you can include as many as you'll be needing in your game. Any more than 16, though, is probably not a good idea, since most joypads won't have that many buttons. I've also entered the keycodes as raw numbers, but you can use the vk_... constants, or the ord() function as well.

Alternatively, you can read values into Joy[] and Key[] from an ini file, or even include an interface for the player to change them manually, which is best. Control configuration interfaces would be a tutorial in their own right, though.

Now that we know which buttons and keys we'll need to be checking for, we need to give them names. This is just a convenience for the programmer. I suggest using constants, and naming them after buttons on a console controller, such as A, START, LEFT, etc.

For example:

Code:

A = 0;
START = 1;
UP = 2;
//etc...

If you did the above, then you could type Joy[A] or Joy[START] instead of Joy[0] or Joy[1]. This is useful, especially for the direction buttons, since remembering which number corresponds to each of the four can be difficult.

But, actually, we're going to be doing something just a little more complicated than just making A = 0 and START = 1. We're going to be using some binary shifting, and you'll see why a little later.

Instead of setting A to 0 (or whichever number you want to call "A"), we'll be setting it to 1 left-shifted by 0. START will be set to 1 left-shifted by 1, and so on. This is what the code should look like:

Code:

A = 1<<0;
START = 1<<1;
UP = 1<<2;
//etc...

That means, in binary, A = 1, START = 10, and UP = 100.

Now that we've got our constants named, it's time to make a new script - let's call it joy_step - and put it in the begin step event of Joypad.

joy_step()

JoyPast = JoyPrevious;
JoyPrevious = JoyCurrent;
JoyCurrent = 0;

for (t=0;t<6;t+=1)
  {
  if joystick_check_button(1,Joy[t])
  or keyboard_check(Key[t])
  JoyCurrent |= 1<<t;
  }

What the for loop does is set up a binary variable, JoyCurrent, where each bit corresponds to one of the buttons being active. It checks both the joypad and the keyboard, so either one the player uses will work.

So, by default, both the joypad and keyboard are detected by the game and no setup or choice between the two is necessary. Although, it's very easy to rewrite the loop to not check for one or the other, if for instance you wanted to let the player choose which mode they'd rather use. Some people may not have a joypad at all and there's no reason to do extra checks.

So, if either the joypad button or the keyboard key (or both) is detected for button 0, JoyCurrent becomes a value of 1. If no other button is detected, it remains a value of 1. But if another button is detected, the new value is or-ed together. If both buttons 0 and 1 are detected, for instance, JoyCurrent becomes a (binary) value of 11. In this way, with only one variable, you can store which buttons are being detected during this step.

Of course, before the loop runs, we dump the value of JoyCurrent into a buffer value called JoyPrevious (and, one step further, dump JoyPrevious into JoyPast). This is going to be used to detect pressing and releasing the buttons, akin to the keyboard_check_pressed() and keyboard_check_released() functions. We could probably get by with only two values, JoyCurrent and JoyPrevious, but some joypads are subject to signal noise, and the addition of JoyPast will improve things in those cases. For instance, the device I use to convert my Nintendo Gamecube to be compatible with a PC stops detecting some buttons for an instant while others are rapidly pressed. This makes performing the spindash in Sonic 2 nearly impossible, because the Down button stops registering when the A button is tapped, causing Sonic to launch early.

Now we write another script, just called joy.

joy()

return (JoyCurrent&argument0);

Now, as long as the Joypad object is present in the room, any object can call the joy script to test for buttons. For example:

Code:

if joy(A)
  {
  //make the player jump
  }

if joy(B)
  {
  //make the player attack
  }

if joy(LEFT)
  {
  //move the player left
  }
else
if joy(RIGHT)
  {
  //move the player right
  }

Now, what about presses and releases? If you used something like the code above, the character would continually jump as you held down the A button. What we need is another script - joy_pressed.

joy_pressed()

return (JoyCurrent&argument0) and !(JoyPrevious&argument0) and !(JoyPast&argument0);

This will only return true when the button is active in this step, but not in the previous step, or the one before that.

And now for joy_released.

joy_released()

return !(JoyCurrent&argument0) and !(JoyPrevious&argument0) and (JoyPast&argument0);

This script only returns true if the button is not active during this step or the one previous, but was active in the step before that.

And there you have it. A very simple way of having robust joypad and keyboard support for your game, that's fully customisable to boot. If you don't feel like including an interface for mapping keys and buttons in your game, at least include an ini settings file. Nothing is more annoying than actually having joypad support in a game, but then finding that the buttons are all mapped wrong!

And finally, if you want to use an analog stick to emulate the directional buttons, you can add this code to the joy_step script we made.

joy_step()

if !AnalogCount exit;
if joystick_xpos(1) < -AnalogDeadzone JoyCurrent |= LEFT;
if joystick_xpos(1) > AnalogDeadzone JoyCurrent |= RIGHT;
if joystick_ypos(1) < -AnalogDeadzone JoyCurrent |= UP;
if joystick_ypos(1) > AnalogDeadzone JoyCurrent |= DOWN;

You can check as many axes as you want, of course. You can even use code like this to make the right-hand analog stick emulate the X, Y, and Z buttons like in The Legend of Zelda - Ocarina of Time (Nintendo Gamecube version). The great thing is, since the values are or-ed together, either the buttons or tilting the stick both work.

And that's it! You've got a complete joypad system that takes input from either the joypad or keyboard, and is incredibly easy to use.

Download the GML scripts and a GMK example of this lesson here.

Until next time, happy coding, fellow Code Ninjas!