SEGA Megadrive game development #5
Added 2020-03-21 20:00:02 +0000 UTCMoving our character
I wanted to allow our hero to move in only 4 directions in order to give a retro vibe to our game.
I also wanted to be able to keep track of a general direction when walking, even if another direction is pressed.
Imagine you are walking toward the top of the screen, then decide to go to the left or to the right while still pressing up on your controller.
Once you release left or right, you should still go up and should not walk diagonally before that. You may alternatively have released up meanwhile and should therefore keep going left or right in that case.
These requirements led to the following implementation (with Stef's help!):

Let’s roll-out this function with an example.
Joypad directions can be represented as follow:

We assume previous direction (prevDir) was LEFT and still maintained, and that UP is now currently pressed on top (dir)(meaning current direction is UP+LEFT).
- prevDir= 0100
- dir= 0101
- dirCom= 0100
As dir and prevDir differ, we then do dir = dir ^ dirCom.
- dir = 0001
We will now go into if(dir & BUTTON_UP).
Lastly, we may overwrite prevDir with dir in case there are no longer bits in common between both of these values (!dirCom), meaning that previous direction (LEFT) was released and that current direction is UP alone and no longer UP+LEFT.
I hope this is understandable... If not, feel free to ask! :-)