Sunday, 25 January 2015

Making a Game in a Weekend with MonoGame.

Early last week, I was chatting to a close friend of mine - (Dean Ellis) about Game development and we discussed the possibility of participating in a weekend GameJam. Dean and I having written games in the past, but never together (or at least those shared ventures were never completed).

We had no theme, we had no plan. Just come over to my house on Friday evening with your laptop and let's make a game.

Dean arrived around 6pm with his 8yr old Son in tow. Laptop at the ready and it was clear early on that we were going to need supplies for this adventure. We were going to need beer! Lots of Beer... and snacks.

After cleaning the local shop almost out of junk food and beer, we set to the hard task of deciding what to build - and who was going to do what.

Who does what?
It is an important step in any team to decide what role each of you is to play and to stick with it. Otherwise chaos ensues. We decided to step a little out of our comfort zones with this. We'd use a platform I wasn't familiar with and Dean would provide the artwork (normally my role).

The platform we decided on was Monogame. For those who may not know, Monogame is the opensource cross platform implementation of the Microsoft XNA framework (now sadly discontinued by the big M - but lives on with an incedibly strong community thanks in no small part to Monogame, especially with it's cross platform capability (more on that later).

I'm used to using the MOAI framework, but if there were any parallels - It shouldn't be too hard.

The language of choice would be C#. I'm familiar with C# - Many years of ASP.net and Windows Mobile development have given me those skills, however I will admit a little rust, what better way to polish my metal than with an intensive game development session?. 

Dean on the other hand works at Xamarin and is a C# guru - which is handy when said polishing was needed. Thanks Dean :-)

Dean was in charge of Art. He wasn't to take an active role in coding, Instead, he'd be providing a suit of assets needed for the game. His tool chain was Inkscape, Textturepacker and Spine.

To help out and save time however, Dean did provide a library and example class to handle the Spine animation.

So began the evening. We ordered a curry from my local Indian and began the brainstorming process.

We'd need a game we could handle in the weekend - preferably something we could get to "first light"* in the evening.


*First light is the point when you first see something on screen resembling the thing you're trying to make - it's the first piece of visual progress after what can seem like an eternity of coding. It may be as rough as a bears back end, but it's a thing of beauty.

We decided on an endless runner - similar to Canabalt - in which you play a Kangaroo named ROO! (upper case deliberate, and pronounced in a death metal voice). The story being a parody on the old Skippy the bush kangaroo TV show from the 1960's - in which little Timmy has fallen down the well (again) and ROO must race across the outback to inform ranger Bruce - Crikey!

A very simple story, simple game play requiring a single key-press, button or screen touch. Hold down the control to increase the jump height up to a maximum and clear any obstacles.

The curry arrived, we had our idea - it was time to load up with Curry Power and get to work.

Installing Tools
I installed Xamarin Studio and the Monogame framework. Dean created a Git repo on BitBucket so we could collaborate effectively. I used SourceTree by Atlassian as my Git manager - Dean used the command line.  

It was time to create the project. Thankfully Dean had access to a project template for Xamarin to create Monogame projects. That was easy.

Now faced with a blank canvas - no game, no menu system, just an empty XNA game class.

...and we're off!
It was now around 9pm - Installing tools and setting up environments had taken it's toll.
So the first thing we were going to need was a Kangaroo. Dean set about drawing a Kangaroo which he could then break into pieces and animate using Spine.

He built a skeleton for the marsupial and made a decent hop animation.

In the meantime, I created a state stack to allow us to have different game screens. e.g. a Splash Screen and Menu as well as a gameplay screen. This would allow us to separate the game code out into other classes as we needed to and have the main game code control them as if they were the main game code.

This meant creating an object oriented structure of game objects which catered for everything, states which inherited from game objects, an animated sprite class which would handle the spine animation and a level manager to provide the endless running level... which at this time I had no idea how to accomplish.

I had an idea, an endless runner doesn't care about what was past and what's to come, only what is now. This meant that we could have a queue of only the details needed to display the map queuing and de-queuing items as the player moved through it. 
The levels would be random so there would be no level data to store, only a set of rules which would govern the pieces to place in front of the player as they progressed.

By 2am, we had a level being rendered and an animated ROO! 5 Hours of coding and several beers had brought us to first light. We could see where we needed to go from this point on.

The next morning,
I cooked a breakfast of bratwursts, bacon, eggs and beans - we were going to need the energy. We had a lot to do. The game ran in a demonstration capacity, but there was no gameplay and no level.

So after breakfast we continued. Dean created death animations for the kangaroo and I set about implementing a collision detection system against the level. Normally, collision detection is done against objects with position and size within a level. These items are normally loaded and are generally treated as real things according to the game engine. This game had no physical objects created within the game world. Objects would exist for at most a few seconds before being deleted. This meant that we needed to make sure that the objects were as simple as possible. To that end, I created a class which held the texture names for 4 rows and a height to position the entire column on the screen in relation to the rest of the level. This meant that we could draw challenging levels, but there was no level geometry to test. However as the data was predictable, it did mean that we could perform bounds tests on rectangles which were near to the kangaroo. We'd generate the bounding rectangles for each of the levels near-by tiles on the fly, but it would be fast enough.

I progressed on making the kangaroo collide with the level accurately, ensuring that he stayed on the top of the level's terrain. I've feel so spoiled lately using Box2d to handle all of this stuff properly for me.

As Dean made more animations, I put them into the game. ROO can trip on rocks, faceplant, hit sheer cliffs or even just run into a wall - each needed their own animation. Thanks to Spine, Dean was able to build all of them.

At lunchtime, we took a break and went to the local pub - for a post morning debrief and to gather our thoughts on the remaining work.

And with that in mind, we played the Artemis Bridge Simulator for an hour - Awesome game.





After Lunch
This was mostly putting things into place. Animations, Jumping and the all important Level generation.

With Dean busy tweaking animations, drawing backgrounds and recording some initial game audio, I had to figure out how to make a responsive jump action. In endless runners, the player has to judge how high to make the player jump. He has a maximum height beyond which, he'll fall to the ground. The player must feel like they are in control of the character at all times and that any failure in the game is entirely the fault of the player. This is how addictive gameplay is born. If you make the game feel unresponsive, the player will blame the game and will not become as engaged. Making the player feel completely in control adds to the immersion and therefore into the addictiveness of the game. 

To do this, I'd need to know whether it was possible for ROO to jump. If so, then he'd pay attention to the jump command. However, as soon as the command was halted, he'd ignore any further requests to jump until he was eligible to jump once more - basically, when he was on the ground and hadn't hit anything.

Another decision I made was to place all of ROO's jump logic before anything else in the update methods. So you'd always get to jump. It may not seem like much, but if the update loop runs every 60th of a second, that means that there's an entire 60th of a second where you may have pressed the jump button - but if the level is allowed to move before you've had your command registered, you could hit something instead. The player has to come first, so the controls need to be processed first.

ROO is very responsive.

The day wore on and we made more and more progress on the game and consumed quite a lot of tea. The animations improved, Dean worked hard on the tile set and ROO himself to make gaps in the sprite from being shown. He also built clouds and mountains to act as parallax  backgrounds to add depth.

I wrestled with the level generator - I'd made an assumption about the peek method of the queue in that it would give me the first element in the queue, in fact it gave the element about to be dequeued. On retrospect, it was sensible, however I really wanted the most recent addition to the queue. Afterwards the level generation was working great.

By about midnight, we'd got the game running nicely.


The Next Day
So very tired. Dean and Myself were pulling from resources we didn't know we had. Late nights, beer and game development does not make for happy mornings. Still, we got on with the work of polishing the game. We only had a few hours to make a difference, Dean would have to leave in a few hours so we'd have to make the most of it.

I recorded some additional sounds for Roo while Dean made more animations - basically ROO would be able to run at two faster speeds to keep up with the ever increasing level speed. This coupled with shouts from Timmy in the well to boost ROO's resolve added to the atmosphere. I used BFXR to make simple bounding and jumping sounds while recording the voice of Dean's son for the voice of Timmy.

I altered the generation code to make the later levels harder while in the meantime, Dean took a hiatus from the pure graphical side and worked on the high score table. He'd held out for 2 days without coding anything, an amazing feat.

He also worked on the additional build targets so that the game would compile on other platforms.

By the end of the day. Dean had iOS, OSx, OUYA, Android and Windows via OpenGL and DirectX working. With a little luck the Android version would be relatively simple to put onto the market.

Testing on a few different android devices revealed some graphical bugs which were quickly resolved.


I worked on the music for the game. I only had a couple of hours to spend, so I used a tried and trusted tool Mixcraft. Mixcraft has a vast library of samples as well as virtual instruments to call upon. So I made a piece of music which became more intense as time went on. I feel it complements the mood. But then I wrote it.




So in the end,
We have a completed game with a failure state, sound effects, music and animation. It's fun, addictive and accessible.

It took us about 20 hours from nothing to game.
The tools we used were:

Xamarin Studio
Source Tree
Inkscape
Spine
Audacity
Mixcraft
BFXR

Monday, 12 January 2015

London Gamecraft 2014 : Part Deux - The Movie

OK, that's probably a little grandiose, but at 23 mins long, it sure felt like I was editing an epic. I feel that I know how Peter Jackson must feel. 1 day to shoot, many many hours to edit.

Cards on the table: This was my first attempt at making a video production, so it's a little rough around the edges and it's probably a little too long and could use some cutting - But I didn't want to lose any of the interview footage, some of it is golden. It's also taught me a lot. After Effects is an incredible piece of software, I could probably dedicate months of training time and still only barely scratch the surface.



We arrived early, after getting up incredibly early to get the train to London. We arrived before any of the developers to give us time to set up the greenscreen rig.


After that, and after coffee and breakfast, we set about capturing footage for a potential game. We took a load of props with us, from Nerf guns to teddy bears. The teddy bears would be animated with the assistance of the chroma-key suit.



Unfortunately, we didn't make a game with this footage, but it was a good test to see if we'd got everything set up properly - and we were hoping to inspire the developers in some way.

So instead, we made images of clouds using cotton wool. This worked well and they were useful in one of the games.

We also filmed planes for use as sprites. If you can't draw it, film a real one (or a model)

We filmed a bunch of planes, even recorded rotations for a game which I think Dean will make as soon as I get the processed footage to him.



On the day we were mostly expecting to capture footage for the game developers to use. We did that, and provide special effects for those who needed them. We also introduced a few people to the amazing BFXR online sound generator.

As the hours passed and the developers had gotten used to the idea that they could call upon us for assistance - They're typically a self sufficient lot, and demonstrated amazing skills in their craft.

The special effects (mostly explosions) were created as assets for the developers using the amazing TimelineFx.

At the end of the day, those developers who'd completed their games got an interview against the greenscreen where their game would be played in the background.



Thanks to Global Game Craft for organising the event, SkillsMatter for hosting it and providing sodas,beer and pizza and to .mpegasus and _ensnare_ for the music for the video. Go check out their stuff. It's brilliant programming music.

A good time was had by all and Games we born.

Tuesday, 25 November 2014

London Game Craft

On the 29th of November, Songbird Creations will be attending the London GameCraft Jam at The Skills Matter eXchange.


We won't be working on a game however we will be providing green-screen and image processing facilities for the developers there so they can quickly get some nice real-life graphics made without worrying about it. We'll be taking care of the capture, chromakey and processing - the end result being a nice texture file and plist using texture packer.

We'll be bringing some props with us although, the theme for the day hasn't been announced - so that'll be interesting.


So if you're attending the Jam, pop over and say Hi. I'll probably be decked out in a green-screen suit, so I'll be invisible.... :-)

https://skillsmatter.com/conferences/6610-london-gamecraft-2014-part-trois

Sunday, 5 October 2014

Review the Ancients: Slightly Magic 1991 - Codemasters - 2014 Potassium Frog

Slightly Magic

Written in 1991
Coded by Colin Jones
Graphics: Chris Graham, Colin Jones, Keith Ross
Music: Allister Brimble
Published by CodeMasters

Re-released 2014 by Potassium Frog
Available for PC, Linux, Mac, Android, iOS and OUYA
http://slightlymagic.uk/


I remember this game being fairly tricky.

There were quite a few platform adventure games during the Spectrum's life, Dizzy being one of the most famous (at the time). The idea of a non-combat adventure where you solve puzzles without resorting to violence struck a chord with me, and still does to this day.

With Dizzy you ran around solving puzzles with inventory items while avoiding enemies with running and jumping - a task made more difficult by Dizzy's tendency to roll around.

Slightly Different

Slightly magic was a little different in this regard. Instead of controlling a rolling egg, you controlled a young wizard - complete with wizard's robes and hat; and instead of purely needing the right object at the right time, in Slightly Magic you have use an item with a spell to make the spell work as well as have your spellbook and magic wand. The spells can be used many times and do various things from make ghosts fly away to change your shape; There's even a spell to give a giant an itchy head.
Spells use magical energy which you obtain from stars you collect.
It was a nice and refreshing addition to the regular inventory mechanic which opened up new elements of gameplay.

The main character of the game is a young magician named Slightly. Slightly's Uncle, the wizard Bigwiz has left the castle in a hurry and has forgotten a whole load of things in his haste, one of these things being to take his nephew with him. He also forgot to lock the door to the laboratory and the spell cabinet has been knocked over  sending the spells everywhere. All this coupled with the fact that a sunburned dragon has made off with Princess Croak, it's up to Slightly to fix everything.

Slightly Unusual

I typically review old games which struck a chord with me in some way while I was growing up.
They are normally obscure titles which deserve looking into and will often need the reader to dig around for them. They are the ancient games I grew up with and are not generally available for purchase.

This review will be a little different in that Colin Jones has re-released Slightly Magic on tablets and the OUYA. This review will focus on the OUYA version - mostly to support Colin Jones and the OUYA and in some small way because it's very difficult to get hold of CodeMasters games on-line to play due to CodeMaster's legal block on them.

Thankfully Colin has been able to re-release the game so that future generations can play it and to prevent it from being lost to obscurity. I sincerely hope other CodeMasters games share similar good fortune otherwise they will fade from memory altogether.

This good fortune does present a problem for me though.
Given that the game has been re-released, I am torn whether to review the game from a modern perspective or against its peers of the time - after all, I gave Treasure Island Dizzy a glowing review in spite of the fact that it would probably be responsible for the destruction of TVs through controller impalement.

However given that Slightly Magic is available for purchase and it's peers are contemporary, perhaps a purely nostalgia based review might not be right. I will however review it as fairly as possible.

Slightly Singed

You start the game looking at the young wizard, on the screen you can see a spell book and a magic wand (also belonging to Bigwiz the wizard and also forgotten). The magic wand is in a corner of the screen blocked off with walls. To get the wand you're going to have to work out the way to that part of the castle.. but first of all, you have to get past some dragons.

The dragons burn you if you get too close, not deliberately mind you, they are thirsty and are breathing fire so they need some water to put out the flames. The problem is that they'll only drink from their own buckets. They're the King's dragons so they're picky like that.

This leads me to the first issue I have with the game. It's difficult to know what will kill you and what won't without experimentation and that can be dangerous - also with your lives being limited, you'll be replaying some bits of the game over and over. Not as fury inducing as Treasure Island Dizzy though.

Once you've worked out the solutions to puzzles, you'll optimize your path in no time. This type of gameplay was commonplace back in the 80's and 90's but not really seen any more.

Whether it causes more frustration now than it did back when I was a kid I'm not sure. What I am sure about though is that modern games have removed these gameplay elements for better or for worse and no-one is complaining.

The game appears to rely on the player making mistakes to learn where some off screen platforms will be. Some platforms require the player to jump from one platform on one screen to land on a platform on the next as there is a gap immediately which would cause the player to fall should they just walk off-screen.

However, all of these points are due to the fact that this game is a remake of a 20 year old game so we're going to cut it a reasonable amount of slack. It would have been tempting I'm sure to alter the game in small ways but this could have lead to the loss of the soul of the original - something which thankfully the game has kept.

There is no save system in the game to record your progress.
Once you run out of lives you'll have to restart the game. This is perhaps fair, however should you find yourself running out of time to play, you cannot save the game and come back to it.
This is a real throwback to the original time when saving was more trouble than it was worth however I'm not sure that modern gamers will be able to overlook this.

I feel that this would have been something that could have been implemented behind the scenes, saving progress as the player went along and allowing the player to reload the game state or choose a new game.

Oddly enough in it's defence, the game is quite short and can be completed in about 20 minutes if you know what you're doing.

Slightly Blocky


The graphics are charming and cute, taken pretty much directly from the ZX Spectrum version. This is as close as you're ever going to get to the original Pixel-Art style. Every pixel on the spectrum had to be crafted with care.

It all still works. The graphics are crisp and clear with nice chunky pixels. The remake also doesn't need to worry about the Spectrum's limited number of colours per block of 8 pixels so there's no annoying colour clashing going on.

Whether new potential fans will appreciate the style or be put off by it remains to be seen. I'm pretty sure the discussion was had to upgrade the graphics or not when this project was first floated.

Personally, I like the graphics. As a child from the Spectrum years, they are familiar and look different enough to stand apart from the competition.

Pretty much everything in the game is animated to some extent. From a bouncing glittering spellbook to spooky ghosts. Even the user interface has a bubbling bottle of some magical liquid showing your lives and there's a really cute bouncing star showing the number of stars you have collected.

The game screams cuteness.

Slightly Musical

A jolly tune played throughout Slightly Magic on the 128k Spectrum version and of course on the Amiga version. It matched the tone of the game well feeling like it belonged as the title for a 90's Saturday morning cartoon.

The remake doesn't stick with the spectrum version of the soundtrack. It appears to be taken from the Commodore Amiga version - which as a fan of the original was a little jarring especially with the Spectrum graphics. The tune is basically the same but there are differences.

All those hours from my childhood had burned the theme-tune into my brain (and I do have a great memory for music - if little else) and I do find the 128 Spectrum's sound particularly pleasing.

The newer sound-track is certainly richer and changes song as you visit different areas which is a nice touch. From the jolly tune in the castle to a spookier version to go with the forest outside. What's nice is that it keeps the main melody.

Here are the two soundtracks to play and compare - however they are both walk-through videos so be aware that they will contain solutions to puzzles and spoilers. Viewer discretion is advised.



Slightly Surprised.

Since buying the game for the OUYA I learned that Slightly Magic was the subject of a kickstarter campaign to bring the game back to life for tablets and the OUYA - unfortunately it did not meet its funding goal which is a real shame.

One of the features should it have been successful was to have Allister Brimble re-record the soundtrack with all new and modern technology. I can only imagine what that would be like, but I can imagine it would sound very nice.

The failure of the kickstarter to meet it's goals means that Colin did not receive any money to get this game re-released so I can only guess that he funded the game himself.

The original game when released perhaps had an easier time at defeating it's competition - it certainly gave the Dizzy games a run for their money and received rave reviews from the press at the time.

One thing is for sure, there is a tremendous amount of love to the game. There's not an ounce of bad will in the game or the story. In fact, the only malicious character in the whole game is a witch with a cottage in the forest who has turned Hansel and Gretel into gingerbread people - another thing for Slightly to put right.

The fact that the kickstarter failed and yet Colin still proceeded to make the game is a testament to how much love he has for the game.

In Closing

The graphics are a pleasant throwback to a more innocent time but may not win over newer fans who could dismiss them too easily - which would be a shame. Personally I think they look different to anything else on the OUYA which helps it to stand out.

The music could probably use some higher fidelity samples but is pleasant enough. It still has that jolly feel to it. A modern Allistair Brimble soundtrack would have been amazing.

The controls could use re-mapping. There were many times where I pressed [O] to access my inventory, for something to happen and pressed [O] again to close the message - which did nothing, [A] closes messages. I'd have them both do the same action and have [A] for jumping.

The lack of a save option I feel will put people off, even though the game is short by modern standards, the mobile gaming audience often have limited time to spend playing. So a save as you go feature would really help.

The game's mood is very nice and the screens for each area demand to be explored.

It has more character and charm than a lot of more modern games and was obviously a labour of love.

Thank you Colin Jones for this trip to my childhood and for bringing Slightly back for future generations to enjoy.











Monday, 29 September 2014

Review the Ancients: Treasure Island Dizzy - CodeMasters 1988

Treasure Island Dizzy

Written in 1988
Coded by The Oliver Twins
Graphics: Neil Adamson
Music: David Whittaker
Published by CodeMasters

http://www.worldofspectrum.org/infoseekid.cgi?id=0009333
Play it online http://torinak.com/qaop#!dizzy2

The Egg Who Returned

Back in 1988 we saw the return of The Egg who wears boxing gloves. Dizzy.
His initial game came out the year before but Treasure Island Dizzy turned everything up to 11.
It had a proper masked sprite system as opposed to the XOR rendering of the original and it had a 128k soundtrack by the ever wonderful David Whittaker. He included a 48k soundtrack for those with older spectrums but the 128k version was the best by far. It also gave us in-game music. Music who's pleasant jaunty tones concealed any malevolence within.



Treasure Island Dizzy was much in the same vein as it's predecessor, a flip screen adventure game with inventory puzzles and platforming. Very simple game-play. Move, Jump and collect/use.

There were changes though.

Original Dizzy only allowed the player to carry a single item, which must be dropped should the player want another item whereas Treasure Island Dizzy allowed for three items.. a design decision which would alter the gameplay and difficulty in ways they probably didn't foresee (..or did they?).

Another decision they took was to remove the lives system used in the original whereas the player had 3 lives to start with but could collect more as the player progressed. This was removed and was replaced with Permadeath.

They also removed the random flying enemies (see God Damned Bats trope ) from the original and replaced them with enemies which followed a specific and predictable path - if they moved at all. This made things a little easier. a little.

Treasure Island Dizzy is very hard.

I mean seriously really very hard. Don't underestimate this game.
Kids today are not prepared for how soul crushingly hard this game is. Seriously!

It's not hard in a dark souls way where you have to memorize attack patterns and weaknesses to succeed - no, Treasure Island Dizzy is harder than that. You see, in Dark Souls, should you die (and you will.. a lot) you don't have to start from the beginning again.

With Treasure Island Dizzy, should you make any mistake - like fail to avoid one of the few traps, get hit by a creature, burned by fire, fall in water without a snorkel, or drop your snorkel while underwater while trying to pick up another item - Then it's back to the start of the game.

No matter how far you have progressed.

And it wasn't a small game either. Here is the map for your viewing pleasure:


As you can see, there are items to collect, hidden coins which you need and the same puzzles to solve over and over and over again.

It sounds terrible right? So why does this game invoke such fond memories with it's players?

Well, for me it was initially the cuteness of the thing. The happy egg waving along with the jaunty tune, jumping and rolling. Dizzy was innocent. He was happy. Every time Dizzy died and I had to restart the game from scratch, it was my fault. Each and every time. There were no random actions, no traps that couldn't be avoided. With each death was a failure - My Failure.

I don't like to fail so I persevered. I learned where items were. I made sure that my snorkel was always the most recent item in my inventory so that when I picked up an item under the water, I wouldn't drown.

I timed the jumps, the rolls and even memorized the most optimal route through the story to get things done.

After a lot of work, trial and error and a home made map, I finally got to the end screen.
I had collected all 30 of the coins (some were hidden in evil places)  and I completed the game.

I DID IT!

To be greeted by a message.

CONGRATULATIONS! You have successfully solved all the puzzles and truely earned your freedom. Good luck Dizzy.

I nearly had a psychotic breakdown.. after all of the work and retries the game was over with a simple message - then it was right back to the title screen again.

"Welcome to Treasure Island Dizzy!"

I sat in shocked silence watching the title screen for several seconds before I calmly put the tape back in its box and reset the computer.

I never tried to complete it again. That was it.. I was done.

But did I have fun? Yes. Absolutely. The feeling of solving a seemingly difficult problem and making progress was amazing. Making the jump to land on the top of the mine, jumping the crab and drowning the Sinclair Abuser magazine.

Collecting some items and solving puzzles opened up new and interesting areas which really helped to sell the mystery of the island. Because there were no enemies trying to kill you generally, you were free to explore - just be careful.


In modern terms, 

I do wonder whether it would be more fun if the permadeath was removed. Would the game still be fun if instead of a "Restart from the beginning" or "several lives" approach that a restart from a checkpoint system would be better. It would certainly be more forgiving.

However restart-checkpoints didn't really come into existence until Sonic the Hedgehog and even Sonic had lives.

This was the 80's/early 90's we had what we had and we had Dizzy and that was alright.

Finally

I would recommend that anyone interested in game design and gameplay gives this little old gem a shot. It's got a lot of heart and is worth the time. Whether you want to devote enough time to complete the game will depend on several factors, one of which being your sanity.

If anyone complains about how hard a modern game is, if you've played Treasure Island Dizzy, you can scoff at their ineptitude. Pah! You don't know hard until you've played Treasure Island Dizzy!


I've placed a link at the top of the review so you can play it on-line. CodeMasters have not yet given permissions to reproduce any of their games online which is a shame because they'll be lost in time in a few years unless they're allowed to hosted by fans.


For my mind, The Oliver Twins made the games which made CodeMasters a household name.
I owned a great number of their games and enjoyed them all. They still make games as Blitz Games Studios - They have a simply staggering collection of titles to their name. To call them prolific would be an understatement.

Gentlemen, I salute you!




Sunday, 28 September 2014

Box2D Raycasting with Category Masking with MOAI

What is Ray Casting?

Ray Casting is a technique used to determine whether something intersects a line drawn between one point and another. Normally Box2D uses circles, rectangles and polygons to determine collisions and resolve the forces and positions appropriately. However sometimes you just want to check for collisions along an imaginary line.

Imagine a Laser Pointer

One example for this is if you imagine a laser pointer.
Its beam is emitted from the end of the laser pen and it continues until it hits the wall at the far end of the room and leaves a pleasant red dot.

Should something break the beam, the red dot shows on the object breaking the beam and no longer on the wall.

Before MOAI 1.5

For a long time, MOAI did not support the ray casting features of Box 2D. Version 1.5 supports the closest raycast implementation where the closest object on the path of the ray is returned.

The Closest raycast feature is very much like the laser pen example. A ray is cast and the first thing which intersects the ray is returned.

A lot of the time, this is all you need.

It will find the closest Box2D fixture intersecting the ray no matter what it is.

Category Masking?

I needed something a little extra. Box2D supports categories. This is so you can designate an object as a particular type of thing so it can be included or excluded in specific collisions.

For my game I have several categories for objects.

  • FLOOR = 1
  • PLAYER = 2
  • OBJECT = 4
  • MONSTER =8
  • SWITCH = 16
  • POWERUP = 32

My laser beams should only be stopped by Players, Monsters and the Floor. Objects, Powerups and Switches should not get in the way - let alone be blown up by lasers.

I need a mask to filter only the categories I'm interested in.
FLOOR + PLAYER + MONSTER = 11

By performing a bitwise AND against the category for the object intersecting the ray and the mask, we can check to see if we're interested in it.

Here's a little binary refresher so you can see why the mask works.

Floor   = 00000001
Mask    = 00001011
Yup

Player  = 00000010
Mask    = 00001011
Yarp

Monster = 00001000
Mask    = 00001011
Yessir

Switch  = 00010000
Mask    = 00001011
Nope

However... 

Box2D doesn't support category masking for RayCasts, even though it supports categories and masks for all other types of collision detection.

This meant that even with the implementation in MOAI release 5, I couldn't use the Box2D ray casting. In fact, it meant I couldn't use Box2D* at all without making some changes.

*I'm using Box2D v 2.2.1 within MOAI - the most recent appears to be 2.3.0 (as of time of writing) however it too does not support masking.

So I modified Box2D to suit.

UDiff for Box2D 2.2.1


 3rdparty/box2d-2.2.1/Box2D/Collision/b2Collision.h     |  1 +
 3rdparty/box2d-2.2.1/Box2D/Collision/b2DynamicTree.h   |  1 +
 3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.cpp        | 18 ++++++++++++++++--
 3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.h          |  3 +++
 3rdparty/box2d-2.2.1/Box2D/Dynamics/b2WorldCallbacks.h |  2 +-
 5 files changed, 22 insertions(+), 3 deletions(-)

diff --git a/3rdparty/box2d-2.2.1/Box2D/Collision/b2Collision.h b/3rdparty/box2d-2.2.1/Box2D/Collision/b2Collision.h
index 8bb316c..62c7ee8 100644
--- a/3rdparty/box2d-2.2.1/Box2D/Collision/b2Collision.h
+++ b/3rdparty/box2d-2.2.1/Box2D/Collision/b2Collision.h
@@ -147,6 +147,7 @@ struct b2RayCastInput
 {
  b2Vec2 p1, p2;
  float32 maxFraction;
+ uint16 maskBits;
 };

 /// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2
diff --git a/3rdparty/box2d-2.2.1/Box2D/Collision/b2DynamicTree.h b/3rdparty/box2d-2.2.1/Box2D/Collision/b2DynamicTree.h
index 0787785..ed4afce 100644
--- a/3rdparty/box2d-2.2.1/Box2D/Collision/b2DynamicTree.h
+++ b/3rdparty/box2d-2.2.1/Box2D/Collision/b2DynamicTree.h
@@ -254,6 +254,7 @@ inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) con
  b2RayCastInput subInput;
  subInput.p1 = input.p1;
  subInput.p2 = input.p2;
+ subInput.maskBits = input.maskBits;
  subInput.maxFraction = maxFraction;

  float32 value = callback->RayCastCallback(subInput, nodeId);
diff --git a/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.cpp b/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.cpp
index d77e80a..b3497e1 100644
--- a/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.cpp
+++ b/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.cpp
@@ -1013,7 +1013,7 @@ struct b2WorldRayCastWrapper
  {
  float32 fraction = output.fraction;
  b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2;
- return callback->ReportFixture(fixture, point, output.normal, fraction);
+ return callback->ReportFixture(fixture, point, output.normal, fraction, input.maskBits);
  }

  return input.maxFraction;
@@ -1023,7 +1023,7 @@ struct b2WorldRayCastWrapper
  b2RayCastCallback* callback;
 };

-void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const
+void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2 ) const
 {
  b2WorldRayCastWrapper wrapper;
  wrapper.broadPhase = &m_contactManager.m_broadPhase;
@@ -1032,6 +1032,20 @@ void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b
  input.maxFraction = 1.0f;
  input.p1 = point1;
  input.p2 = point2;
+ input.maskBits = 0;
+ m_contactManager.m_broadPhase.RayCast(&wrapper, input);
+}
+
+void b2World::RayCast2(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2, const uint16 maskBits ) const
+{
+ b2WorldRayCastWrapper wrapper;
+ wrapper.broadPhase = &m_contactManager.m_broadPhase;
+ wrapper.callback = callback;
+ b2RayCastInput input;
+ input.maxFraction = 1.0f;
+ input.p1 = point1;
+ input.p2 = point2;
+ input.maskBits = maskBits;
  m_contactManager.m_broadPhase.RayCast(&wrapper, input);
 }

diff --git a/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.h b/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.h
index 965a366..d910e23 100644
--- a/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.h
+++ b/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2World.h
@@ -121,6 +121,9 @@ public:
  /// @param point2 the ray ending point
  void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const;

+ void RayCast2(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2, const uint16 maskBits ) const;
+
+
  /// Get the world body list. With the returned body, use b2Body::GetNext to get
  /// the next body in the world list. A NULL body indicates the end of the list.
  /// @return the head of the world body list.
diff --git a/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2WorldCallbacks.h b/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2WorldCallbacks.h
index 82ffc02..a485d8c 100644
--- a/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2WorldCallbacks.h
+++ b/3rdparty/box2d-2.2.1/Box2D/Dynamics/b2WorldCallbacks.h
@@ -149,7 +149,7 @@ public:
  /// @return -1 to filter, 0 to terminate, fraction to clip the ray for
  /// closest hit, 1 to continue
  virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point,
- const b2Vec2& normal, float32 fraction) = 0;
+ const b2Vec2& normal, float32 fraction, uint16 maskBits) = 0;
 };

 #endif


As you can see, the changes merely extend Box2D's raycast feature to include a request for a specific set of maskBits.  Box2D doesn't perform any filtering internally with this change.

Category checking against the mask will be done within MOAI's implementation coming up next.

Note also that I create a function called RayCast2 which can be called with the maskBits parameter. This is just in case the Original RayCast function is used internally by Box2D and to ensure that other programs using it won't be broken by this change.


Initially it felt like overkill to modify Box2D to just pass a number through and back again. However this is required because the raycast function uses a callback to notify the program that it found something - this callback doesn't have any context as to how it's being called really to know what type of fixture you're looking for.

So apart from hard coding it to ignore sensor type fixtures, you're stuck just returning the closest object of any category unless you pass the mask through to the callback function.

Basically, Box2D doesn't know to inform the callback function that you're really only interested in UFOs and it can ignore Clouds.

Here's the UDiff for the MOAI code 

(Note patch is for 1.4r2 not for MOAI v1.5 - although the change is simple to apply to 1.5 )

 src/moaicore/MOAIBox2DWorld.cpp                  | 104 +++++++++++++++++++++++
 src/moaicore/MOAIBox2DWorld.h                    |   1 +

 2 files changed, 105 insertions(+)

diff --git a/src/lua-headers/run.sh b/src/lua-headers/run.sh
old mode 100755
new mode 100644
diff --git a/src/moaicore/MOAIBox2DWorld.cpp b/src/moaicore/MOAIBox2DWorld.cpp
index 943cbf0..20b39fe 100644
--- a/src/moaicore/MOAIBox2DWorld.cpp
+++ b/src/moaicore/MOAIBox2DWorld.cpp
@@ -46,6 +46,8 @@ MOAIBox2DPrim::MOAIBox2DPrim () :
  mDestroyNext ( 0 ) {
 }


+
 //================================================================//
 // local
 //================================================================//
@@ -600,6 +602,107 @@ int MOAIBox2DWorld::_getAutoClearForces ( lua_State* L ) {
  return 1;
 }

+// local
+ //================================================================//

+// RayCast modification from: http://getmoai.com/forums/post2723.html?hilit=raycast#p2723
+// Additional box2d modification to return fixtureIndex as well.
+class RayCastCallback : public b2RayCastCallback
+{
+public:
+    RayCastCallback()
+    {
+        m_fixture = NULL;
+ m_point.SetZero();
+ m_normal.SetZero();
+    }
+
+    float32 ReportFixture(b2Fixture* fixture, const b2Vec2& point, const b2Vec2& normal, float32 fraction, uint16 maskBits)
+    {
+        
+ b2Filter filter = fixture->GetFilterData ();
+

+ //MOAILog ( state,MOAILogMessages::MOAIRayCast_MaskBits, maskBits );
+ if( (filter.categoryBits & maskBits) != filter.categoryBits )
+ {
+ return -1; 
+ }
+ /*if( ( MOAIBox2DFixture* )fixture->IsSensor()){
+ return -1; //filter
+ }*/
+
+ m_fixture = fixture;
+        m_point = point;
+        m_normal = normal;
+
+        return fraction;
+    }
+
+    b2Fixture* m_fixture;
+    b2Vec2 m_point;
+    b2Vec2 m_normal;
+};
+
+//----------------------------------------------------------------//
+/**     @name   getRayCast
+        @text   return RayCast 1st point hit
+
+        @in     MOAIBox2DWorld self
+        @in     number p1x
+        @in     number p1y
+        @in     number p2x
+        @in     number p2y
+        @out    bool true if hit, false otherwise
+        @out    number  hitpoint.x or nil
+        @out    number  hitpoint.y or nil
+ @out MOAIBox2DFixture fixture that was hit, or nil
+*/
+
+int MOAIBox2DWorld::_getRayCast ( lua_State* L ) {
+ MOAI_LUA_SETUP ( MOAIBox2DWorld, "U" )
+ float p1x=state.GetValue < float >( 2, 0 ) * self->mUnitsToMeters;
+ float p1y=state.GetValue < float >( 3, 0 ) * self->mUnitsToMeters;
+ float p2x=state.GetValue < float >( 4, 0 ) * self->mUnitsToMeters;
+ float p2y=state.GetValue < float >( 5, 0 ) * self->mUnitsToMeters;
+ uint16 maskBits = ( uint16 ) state.GetValue < u32 >( 6, 0 );
+
+ b2Vec2 p1(p1x,p1y);
+ b2Vec2 p2(p2x,p2y);
+
+ RayCastCallback callback;
+ self->mWorld->RayCast2(&callback, p1, p2, maskBits);
+
+ if (NULL != callback.m_fixture)
+ {
+ b2Vec2 hitpoint = callback.m_point;
+
+ lua_pushboolean( state, true );
+ lua_pushnumber ( state, hitpoint.x / self->mUnitsToMeters );
+ lua_pushnumber ( state, hitpoint.y / self->mUnitsToMeters );
+
+ // Raycast hit a fixture
+ MOAIBox2DFixture* moaiFixture = ( MOAIBox2DFixture* )callback.m_fixture->GetUserData ();
+ if ( moaiFixture )
+ {
+ moaiFixture->PushLuaUserdata ( state );
+
+ return 4;
+ }
+ else
+ {
+ return 3;
+ }
+ }
+ else
+ {
+ // Raycast did not hit a fixture
+ lua_pushboolean( state, false );
+
+ return 1;
+ }
+}
+
 //----------------------------------------------------------------//
 /** @name getGravity
  @text See Box2D documentation.
@@ -998,6 +1101,7 @@ void MOAIBox2DWorld::RegisterLuaFuncs ( MOAILuaState& state ) {
  { "setGravity", _setGravity },
  { "setIterations", _setIterations },
  { "setLinearSleepTolerance", _setLinearSleepTolerance },
+ { "getRayCast", _getRayCast },
  { "setTimeToSleep", _setTimeToSleep },
  { "setUnitsToMeters", _setUnitsToMeters },
  { NULL, NULL }
diff --git a/src/moaicore/MOAIBox2DWorld.h b/src/moaicore/MOAIBox2DWorld.h
index 61a6641..7d0880c 100644
--- a/src/moaicore/MOAIBox2DWorld.h
+++ b/src/moaicore/MOAIBox2DWorld.h
@@ -98,6 +98,7 @@ private:
  static int _getAutoClearForces ( lua_State* L );
  static int _getGravity ( lua_State* L );
  static int _getLinearSleepTolerance ( lua_State* L );
+ static int _getRayCast ( lua_State* L );
  static int _getTimeToSleep ( lua_State* L );
  static int _setAngularSleepTolerance ( lua_State* L );
  static int _setAutoClearForces ( lua_State* L );

So there you go. Raycasts with masking.
If I only want to shoot UFOs with my lasers, not the clouds in the sky, now I can.

So how do we use this in game?

Somewhere in your game code you'll have something which creates your MOAIBox2DWorld.
You'll be calling the getRayCast method on this object.

gameworld = MOAIBox2DWorld.new ()

Then somewhere you'll need a function to actually cast the ray and return the data back.
The function returns several parameters (typical for Lua).

  • Whether the ray hit something or not, 
  • the X co-ordinate of the hit,
  • the Y co-ordinate of the hit 
  • the object with a category matching the maskBits that the ray hit.


return gameworld:getRayCast( x1,y1,x2,y2, maskBits)



Sorry for the ugly formatting - I'm sure there's a nicer way to present a UDiff.

Have fun.


Special thanks to FiveVoltHigh.com for getting me started with their initial tutorial on patching MOAI with support for RayCasts.

http://www.fivevolthigh.com/2013/10/moai-exposing-box2d-world-ray-casting-to-moai/