09 May 2011

AeStHete

Here and there I've coyly mentioned that I'm working on a Sonic game engine in Game Maker, for instance in this old thread (in which I unwisely muddied the issue by illustrating the engine with a remake of the 8-bit Sonic 1, which is now indefinitely shelved) or in a now-out-of-date YouTube video or two.

But I realise that nowhere have I really officially announced it. Time to fix that!

Thanks to Overbound for the snazzy logo graphic! ^_^

Announcing AeStHete, "An Excellent Sonic The Hedgehog Engine That's Editable"! (After much struggle I managed to find a name that was obscure, immodest, and annoying to type! Am I cool or am I cool?) It's made in Game Maker, but there's a possibility it will be ported in the future.

Screenies:

Sonic looks annoyed at being in yet one more GHZ remake.

'What's wrong with the HUD?' I hear you asking. Well, how else would you know it wasn't a screenshot of the real game? It's just that good, folks!

The zone graphics are optionally fogged out to make the objects being edited stand out.

Waaaa! What's all this about? Yes, you can enter Edit Mode at any time and create or modify levels as you play - there's no need for a separate level editor. The interface can be customised, and there are several resolution options for Edit Mode.

Though I began making AeStHete expressly for my own Sonic fangame project, I've decided to make it totally Open Source - so, in addition to being able to edit levels and so on using the interface, you'll also be able to modify the interface and engine yourself in whatever way you see fit (that is, if you know Game Maker's scripting language). Think of it like hacking a ROM, only instead you're hacking a fangame.

Because of this, Sonic Time Twisted will be the first game to use AeStHete once it's finished. When will that be? I can't really say (I've as much as promised demos before and missed the deadline, and I'm not interested in doing that again). The thing is I keep finding bugs - and then discovering that these bugs actually exist in the original Yuji Naka engine, and that means I can't simply do more research into the originals in order to solve them. I have to work out how to improve on the engine myself, and this takes some time. (Why not settle for "as good as the original?" I'm a perfectionist, dammit!)

But rest assured that progress (and a lot of it) is being made. On that note, I made a semi-mysterious tweet a couple days ago saying I was happy about some obstacle I had overcome. I was referring to having successfully implemented palette cycling, an effect which classic consoles could do in their sleep, but that Game Maker doesn't natively support (scroll to the bottom of the page for Mark Overmars' list of things he'll never add). In the end, pixel shaders, specifically this shader extension, came to the rescue. Now I can confidently say that AeStHete can do everything the original 16-bit games do, just as well and often better.

Now that the hedgehog's properly and officially out of the bag, I'll probably be blogging and tweeting about AeStHete's progress more often, like this:

 I just typed a line of code.
 
 Oops - made a mistake. Hit backspace a few times.
 
 Compiling and testing now...
 
 Damn, omitted a semicolon.
 
 Okay, that's got it. It works now, but I think I should increase this value a bit...
 
 Pausing for snack. BRB

What, not that often? Whatever.

Ingrates.

04 May 2011

Finally.

I've been waiting 15 years to see a screenshot like this in a magazine article about an upcoming Sonic game.

Thanks, Sega. That is all.

19 April 2011

Thoughts on Sonic Generations

When Project Needlemouse was revealed to be Sonic 4, I made a post which contained a fair amount of (what I hoped was biting) criticism of the trailer, and by extension the game itself. It garnered a few 'Right on, brother!'s from people I respect, but it also incited hateful comments (which were frankly hilarious) and was reposted on a handful of gaming forums, inevitably with some sort of 'look at how much this guy is bitching' topic.

During the wait for Sonic Colours, I ended up keeping mum about the whole thing; not because I'd become shy of touching off another controversy, but because I realised that I just didn't feel very strongly about it. There wasn't anything for me to say that wasn't already being endlessly said passim (if you'll excuse the gratuitous and clumsy use of Latin). There's such a fine line between adding to the conversation, and adding to the noise.

Despite the above, and despite the fact that lately I've been rather busy as well as feeling sort of apathetic about things and letting this blog languish, I feel I just have to weigh in on Sonic Generations.

And this time I have no complaints. I never thought I'd live to see the day!

First, just to get it out of the way, I have to chuckle at the obvious similarities to Sonic Fan Remix. The concept of trying to recapture the awesomeness that was Classic Sonic is of course a natural one, and one that well predates both SFR and Sonic Generations, but seeing Sega's offering come so hot on its heels makes me chuckle inwardly. We'll probably never know, of course - Sega would never admit it - but it would be cool to think that Pelikan and I had a tiny part in making Sonic Generations a reality. As if I wasn't insufferable enough as it is.

Second, I have to talk about Classic Sonic's return (or, as he's referred to now in a fast-spreading meme, C.Sonic). I've always been a pretty vocal detractor in regards to Sonic's Dreamcast redesign (which somehow stuck and has now lasted quite a bit longer than the original design), calling it everything from a "green-eyed monster" to "octopus-headed gurning freak". (And to those who always countered by pointing out - condescendingly, always condescendingly - how little difference there really was between the two designs, I say HAH - see them side by side and say that now.) Call me simple, call me afraid of change, call me mired in the past - whatever the case may be, whether the failing is on my part or Sega's, it remains true that I prefer C.Sonic and always will. As much as I like him over M.Sonic, though, I was completely unprepared for how much of an impact it would actually make on me to see Sega bring him back. Having now seen it happen for real, I realise that it was in fact the crux of the issue the whole time, the deciding factor that makes me smile uncontrollably when watching previews of the game instead of reaching for a nearby chalice (or pot) in which I can empty the contents of my stomach.

Does that make me a horrible, shallow person? Sega just slaps C.Sonic in a game and I'm suddenly their undying apostle, an unthinking thrall who will follow them, lemming-like, wherever they may lead? Well, no... otherwise I would be over the moon for Sonic Schoolhouse. I think what it comes down to is that, while C.Sonic is no panacea, no matter how good every other aspect of a game might get, M.Sonic still needles me and prevents my pure and unadulterated enjoyment of it. It's hard to describe exactly why, but M.Sonic's presence (especially in Sonic 4) feels like a slap in the face, like someone saying, 'you know that thing you like more than anything else in the world? Yeh, it's laaaame, and this one's better. Oh, and you're a stupid delegitimate ludite if you don't admit it!'

Grrr, enough about this M.Sonic stuff. The point is that this time I'm actually happy, yes happy, and unreservedly so, about an upcoming Sonic game. Not only am I over the moon about cuddly C.Sonic's return, something about seeing him and M.Sonic teaming up makes me also - incredibly - like M.Sonic more as well. All it takes is Sega admitting that C.Sonic is valuable too, officially saying that the two of them can peaceably coexist, and it's like there's finally closure. (And it's not just the return of Sonic's classic design itself, but the apparently loving attention to detail on the model and the presence of other things like yellow springboards and classic Eggman/Robotnik that do it for me too. I can't wait to see C.Tails now!)

And now I'm going to say something I really thought I'd never say in all my years - Sega's idea for this game is deeply ingenious. Yes, that's what I said - deeply ingenious. What makes me think so? Isn't it just another pathetic rehash-fest like Sonic 4 and... well, everything else we've seen in the last few years?

No, at least not to me. And not just because this interpretation of Green Hill Zone is the best I've ever seen it (with the possible exception of Sonic Fan Remix, but even still there are some things in Sonic Generations' version I prefer. 'You speak blasphemy, sir!' 'Yes, fluently.'). The biggest reason why I think Sonic Generations works fabulously well on a fundamental level is because I look at it like this: Why did Sonic Unleashed suck? Why did Sonic and the Black Knight suck? Because they kept adding horrible gimmicks that fans of Sonic gameplay just couldn't stand. But Sega didn't do this just to be perverse - they aren't stupid or cruel after all. These things were added to pad the experience because no one will buy a 2-hour long game these days - at least not for upwards of 50 bucks.

But finally, with Sonic Generations, a solution that works. Play as M.Sonic for an exhilarating, Unleashed-day-stage, run-till-your-feet-bleed rollercoaster ride. There is no doubting that this is extremely fun, if a little shallow. So what does Sega add for depth? A sword? A Werehog? Of course not - what kind of fool would come up with ideas like that? Instead they add C.Sonic gameplay, with the technical platforming that classic players crave. In one stroke they've solved the schism that has been the franchise's most glaring flaw and padded their game to a respectable size. It's amazing this wasn't thought of before.

The only sad thing in all this good news is the sobering thought that this can't possibly be true for the next Sonic game. There can't be temporal warps for the rest of time - after the blow-out anniversary celebrations it'll be back to business as usual. My fervent hope is that this could be the start of a branch in the franchise - sort of like how Zelda's Windwaker-style Link has his own independently running series. Hey, a guy can dream, right?

Now if you'll excuse me, I have to go watch a certain trailer over and over.

19 March 2011

Code of the Ninja: Jump Height Calculator

If you haven't already, read the Code of the Ninja: Introduction

Hello again, Code Ninjas!

Today is something very simple: a formula that allows you to plug in variables for "jump force" and "gravity" and get the maximum height of a jump as the result.

When designing platformers, tweaking the physics until they're just right is very important. Having a formula such as this will be useful for zeroing in on exactly what values constants like gravity should have.

Another use might be this: say you already have established physics, for instance because you're hacking a Sonic game. But you want to add a new object, such as a new kind of bumper or spring, that bounces Sonic exactly 5 times his height. Determining the force at which Sonic should be impelled by the object in order to achieve that height would be a snap using the following formula.

The simplest way to write the formula is this:

g = gravity;
f = jumpForce;
h = 0;
t = 0;
while ( f > 0 )
{
  h += f;
  f -= g;
  t += 1;
}
return h;

g is your gravity, and f is the jump force, which can be set to anything. In Sonic, for example, gravity is 0.21875pps (pixels per step) and the jump force is 6.5pps.

h is the height value we are trying to find out - the number of pixels the character will travel given the jump force f with gravity g. t is time, which is optional - it will be the number of steps it takes to reach the apex of the jump. Both h and t are initialised at 0.

Then we run a loop while f is greater than 0. In the loop, first f is added to h, then g is subtracted from f. This simulates the jump: the force acts upon the character's position, then the gravity acts upon the force. t is then incremented by 1 in order to count the time.

When the loop is finished, h will be the ultimate height of the jump.

Note that this code assumes your physics to handle similarly to Sonic's. In Sonic, because of the particulars of the original code, the jump force is added once to the character's position before gravity acts upon it. If this is not the case in your game, then the loop should be restructured accordingly; g should be subtracted from f before f is added to h.

Earlier I said "the simplest way" to write the formula. The truth is that this, while simple, is a rather brute force method. Depending on the strength of the jump force and gravity, the loop could run dozens of times. Yes, modern computers can handle this without breaking a sweat, and yes, you probably won't even be using the formula in a running game, anyway. But for the sake of mathematical beauty, we can find a better way that doesn't employ a loop.

So let's build this new formula piece by piece. First, we need to find how many steps it will take for gravity to whittle the jump force away to 0 (or less). This will be time t again.

g = gravity;
f = jumpForce;
t = ceil(f/g);

We find t by dividing f by g and rounding up to the nearest 1. Why the rounding up? Well, if the jump force isn't perfectly divisible by gravity, the remainder would still count as upward velocity and the player would still move up by a little bit during that step. Since it counts toward the total, it must be taken into account.

Now that we know how long the jump will take to reach the apex, we can easily discover the distance the character would travel during that time, without gravity, merely by multiplying f by t.

h = f*t;

Of course this seems a little silly, because we're trying to find the height covered with gravity taken into account. But knowing this value is useful; 'cos if we can also determine how much force is deducted by gravity from the jump force over t steps, we can multiply gravity by that number, subtract it from h, and have our correct result.

In the first step (t = 0), the jump force is unaffected. In the next, it is lesser by gravity. In the next, it is lesser by gravity again, i.e. it is equal to the initial jump force value minus gravity times two. Next step, times three, then in the next, times four, and so on, until gravity overcomes the jump force in step t-1.

Visually represented, you might think of the amount of force lost to gravity as a triangular stack like this:

----- (t=0)
g---- (t=1)
gg--- (t=2)
ggg-- (t=3)
gggg- (t=4)
ggggg (t=5)
...

Fortunately it is easy to find the area of a triangle such as this by finding the area of a square the size of t*t-1 and then cutting that value in half. (If, as mentioned above, your physics subtract gravity before the character moves once, the square should have a size of t*t+1 instead).

h -= t*(t-1)*0.5*g;

Et voilĂ , you have the correct height of the jump, identical to the result of the while statement method used above.

Finally, because multiplication is a commutative process, the formula can be recast in a simpler way for our final code:

g = gravity;
f = jumpForce;
t = ceil(f/g);
h = (f-((t-1)*0.5*g))*t;
return h;

You can find a small example .gmk here that lets you play with the variables to get different jump heights. Until next time, happy coding!

If you use my code or scripts in your game or engine, no credit is necessary. But I'd love to hear about your project if you do! Just drop me a comment below, or e-mail me at us.mercurysilver@gmail.com

02 March 2011

Code of the Ninja - Partially Erasing Surfaces in GM

If you haven't already, read the Code of the Ninja: Introduction

Hey there, Code Ninjas!

One of the cool things about Game Maker 8 is the ability to export PNGs with an alpha channel for transparency. There's no separate functions for doing so, though; if you want to be sure the exported image is in PNG format, you have to make sure the extension is explicitly ".png", like so:

Code:

sprite_save("sprite.png");
screen_save_part("screenie.png",320,224);

It's especially cool to create partially transparent surfaces and export them. After creating a surface, you can use the draw_clear_alpha() function to make it completely transparent:

Code:

surface_set_target(surface);

draw_clear_alpha(c_black,0); // clear the entire surface with fully transparent colour

surface_reset_target();

One thing that's annoying, though, is the way that drawing with a partial alpha to a surface works. Instead of blending with the colour underneath, the colour is completely replaced, alpha and all. Effectively this punches "holes" in the surface image.

You'd think this could exploited to create some kind of eraser tool. Draw pixels with an alpha of 0 to the surface to erase pixels that are already there, leaving fully transparent pixels behind.

This doesn't work, though, for some reason. Very low alpha values such as 0 or 0.01 function exactly as you'd normally expect when drawing to the screen, even though higher values such as 0.7 differ when using surfaces.

So much for the ability to erase pixels from a surface using that method... But there is another way.

Set the blend mode to bm_subtract before drawing to the surface and you'll effectively be able to erase from the image:

Code:

surface_set_target(surface);

draw_set_blend_mode(bm_subtract);
draw_set_color(c_white); // color doesn't actually matter
draw_set_alpha(1); // alpha must be 1 to fully erase pixels

// erase an "X" across the surface
draw_line(0,0,surface_get_width(surface),surface_get_height(surface));
draw_line(surface_get_width(surface),0,0,surface_get_height(surface));

draw_set_blend_mode(bm_normal);

surface_reset_target();

This trick may come in handy on occasion, especially when making games where the user is allowed to paint custom textures for things - an erase tool is essential.

Until we meet again, happy coding!

If you use my code or scripts in your game or engine, no credit is necessary. But I'd love to hear about your project if you do! Just drop me a comment below, or e-mail me at us.mercurysilver@gmail.com

01 March 2011

Code of the Ninja: Looking Up and Down

If you haven't already, read the Code of the Ninja: Introduction

Hello again, Code Ninjas!

In most 2D platformers the player has the ability to shift the camera a short way by holding up or down on the D-pad. In Sonic games, it works great but there is minor flaw that's hard to notice and really doesn't cause any problems, but I thought it would nice to show how to fix it anyway.

The problem arises when the player looks up or down near the top or bottom boundaries of the level (or whatever current boundaries the camera is limited to). In order to understand the problem, we need to look at the basic idea behind shifting the camera.

If there were no ability to look up or down, the process would be really simple. The camera would simply follow the player's position directly, with a simple check to make sure it doesn't leave the level boundaries. In order to shift the camera up and down, though, an extra step is needed. An offset is added to the player's Y position before the camera follows it. By increasing or decreasing the offset value when the up or down buttons are pressed, the camera will shift vertically relative to the player's position.

Clearly there need to be maximum and minimum values that the offset can't exceed, otherwise the player could continue to scroll the camera freely until it reached the top or bottom of the level. Normally this behaviour is not desired, so limits are set that will keep the player visible on the screen.

Imagine for a moment, though, that there aren't. Say the player is looking up - the offset decreases and decreases. It will continue to decrease even after the camera stops at the top of the level, because the offset doesn't know when to quit. The camera is limited, sure, and the player never sees beyond the boundary of the level, but the offset value is still decreasing away.

Now what would happen if the player stops pressing up? The offset value will start increasing until it returns to 0 (no shift at all). But depending on how long you've been pressing up, you'll have to wait a few moments before the camera starts to visibly scroll back to the neutral position. After all, the offset has been invisibly counting away for an undetermined amount of time, and that extra time has to be made up for when it tries to return.

This example with no upper/lower limit for the offset illustrates the problem I'm talking about, and that we're going to fix. It's less noticable when limits are present for the offset, because the value can't continue to increase or decrease indefinitely, but it's still there. If you've got a copy of any Genesis Sonic game, try looking up or down near the top or bottom of a zone and see for yourself. Scandalous, isn't it?

It may not be the worst problem in the world, but it can be fixed, so let's give it a go.

There are actually two solutions. One would be to reduce the offset by the appropriate amount when the player lets up from pressing up or down, but that's not the solution I'll describe. Why not? Because that method would require the detection of when up or down is released, which - while certainly possible - is harder to slot right into the way the code already works in the original Sonic.

Let's look at some basic code for handling the offset, and then we'll apply the fix to it.

cam_step()

shiftMode = 0; // reset shift mode
if ( joy( UP ) ) shiftMode = -1; // player is looking up
if ( joy( DOWN ) ) shiftMode = 1; // player is looking down

switch ( shiftMode )
{
case 0: // camera is recentring
  if ( shiftOffset < 0) shiftOffset += 2; // scroll down if too high
  if ( shiftOffset > 0) shiftOffset -= 2; // scroll up if too low
  break;
case -1: // camera is shifting up
  if ( shiftOffset > -shiftLimit ) shiftOffset -= 2; // scroll up until reach negative limit
  break;
case 1: // camera is shifting down
  if ( shiftOffset < shiftLimit ) shiftOffset += 2; // scroll down until reach positive limit
  break;
}

The problem occurs in case -1 and case 1: stopping at the shiftLimit isn't good enough, because at the top and bottom of the level, we need to stop increasing or decreasing early.

How close to the top or bottom of the level must one be in order for the undesired behaviour to occur? Close enough that the distance between the top/bottom of the camera and the top/bottom of the level is less than the shiftLimit.

This suggests the solution. Instead of using the shiftLimit alone, we should use whichever happens to lesser - the shiftLimit or the difference between the view boundary and the level boundary.

cam_step()

case -1: // camera is shifting up
  r = min( shiftLimit, view_yview - shiftOffset );
  if ( shiftOffset > -r ) shiftOffset -= 2; // scroll up until reach negative limit
  break;
case 1: // camera is shifting down
  r = min( shiftLimit, levelBottom - ( ( view_yview - shiftOffset ) + view_hview ) );
  if ( shiftOffset < r ) shiftOffset += 2; // scroll down until reach positive limit
  break;

(The reason why shiftOffset has to be subtracted from view_yview is so the difference won't change once the screen starts scrolling and the offset starts to change.)

And that's all that's needed. It may not be much, but obsessive compulsives will enjoy the game more!

If you enjoyed this and the previous Code of the Ninja, be sure to come back tomorrow for one more before I slip back into the shadows. =P

If you use my code or scripts in your game or engine, no credit is necessary. But I'd love to hear about your project if you do! Just drop me a comment below, or e-mail me at us.mercurysilver@gmail.com

28 February 2011

Code of the Ninja: Checking Multiple Joypad Buttons

If you haven't already, read the Code of the Ninja: Introduction

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.

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:

Code:

return ( JoyCurrent & argument0 );

where argument0 is a value 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 1 bit on. For instance, you could pass a value like 65535 to test if any button was down, or you could use 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:

Code:

if (joy(LEFT|RIGHT)==LEFT|RIGHT) then ...

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

joy_pressed()

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

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:

Code:

if (joy_pressed(A) or joy_pressed(B) or joy_pressed(C)) then ...

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

Code:

if (joy_pressed(A|B|C) then...

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.

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:

joy()

return ( JoyCurrent & argument0 );

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

joy_pressed()

return ( JoyPressed & argument0 );

and joy_released() like so:

joy_released()

return ( JoyReleased & argument0 );

(At this point these scripts are all so simple you might not even want to make them scripts at all, but merely type JoyPressed&BUTTON 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 AND JoyCurrent (i.e. "temp = JoyPrevious&JoyCurrent;").

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 bitwise AND (&) isn't enough. We need to do one more calculation, 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 ^ JoyCurrent.

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

By XORing 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 ^ JoyPrevious (instead of JoyCurrent) 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:

JoyPressed = ( JoyPrevious & JoyCurrent ) ^ JoyCurrent;
JoyReleased = ( JoyPrevious & JoyCurrent ) ^ JoyPrevious;

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 ORing JoyPrevious and JoyPast together to create a sort of "buffered" previous state when checking for presses, and ORing 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:

joy_step()

JoyPressed = ( ( JoyPrevious | JoyPast ) & JoyCurrent ) ^ JoyCurrent;
JoyReleased = ( ( JoyCurrent | JoyPrevious ) & JoyPast ) ^ JoyPast;

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

joy_step()

JoyCurrentBuffered = JoyCurrent | JoyPrevious;
JoyPreviousBuffered = JoyPrevious | JoyPast;

JoyDown = JoyPreviousBuffered & JoyCurrent;
JoyUp = JoyCurrentBuffered & JoyPast;

JoyPressed = JoyDown ^ JoyCurrent;
JoyReleased = JoyUp ^ JoyPast;

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!

If you use my code or scripts in your game or engine, no credit is necessary. But I'd love to hear about your project if you do! Just drop me a comment below, or e-mail me at us.mercurysilver@gmail.com