3D Printing is More Than Just for Making Pretty Things

When it comes to using 3D printers, I think the general consensus by most people is that they are used to make jewelry or 3D miniatures for tabletop games like D&D.

Kanji pendants made with 3D printer and finished with paint and sealant: Faith, Love, and Hope

While using a 3D printer for that sort of application works wonderfully, I also find them very useful for making functional items. In the last post, I showed how I utilized my 3D printer to print out a PCB.

Now I needed it for another application. I’ve had an issue with a retaining clip in my Honda for quite some time. It holds the trim by the front windshield and comes loose after a while due to the vibrations from driving. The plastic clip itself had broken so I figured I’d replace it as I was tired of dealing with it.

Broken retaining clip

I did not want to spend $10.00 on 30 of these guys…I just needed 1. I did also look at AutoZone, but even they were pretty expensive at ~$4.00 for just 1.


At this point, I figured I could use my 3D printer to just make the part I needed. After looking around a bit, I found a 3D model of a retaining clip for a Renault Clio, luckily nearly all the dimensions fit to what was needed. I imagine there are a lot of small parts like this shared across all sorts of vehicles. The only issue I saw offhand was the bottom part was a bit too thick and there were some steep angles that were on this model. 3D printers aren’t that great at printing steep angles.


After cleaning up the model a bit in Blender and importing it into Simplify3D, some of the settings needed to be tweaked from when I had printed out the PCB. Since this was a much smaller part, the thickness of each printed layer needed to be reduced. This allows for printing much finer detail but increases the printing time. When I printed the PCB, the layer height was set to 0.3 mm. With this part, I set it to 0.1 mm. It always amazes me how these devices can print out a layer of plastic that is only 0.1 mm thick…calibrating the print head though is a bit of a pain.


The final print turned out well enough. The underside of the ledge there was pretty ugly (is that an oxymoron?), but I expected as such due to the angle it was trying to print. The only thing I needed to do was grind down the bottom tab thickness a bit so it would fit

3D printed retaining clip compared to broken retaining clip

The newly printed clip fit right into the new spot without any issues. On the left image you can see a factory original clip there in the distance that was holding the bottom part on…I imagine it will break at some point soon too. The new clip snapped into place easily. The red circle there on the right image is about where that clip is located.

Installing new retaining clip

Now to see how long it will last. Only costing $0.01 in material, I don’t mind printing another one if I need to.

Necessity is the Mother of Invention

Well, not an original invention mind you.

The Inspiration…

I bought this monster fan some time back to cool my computer system. I often run some fairly intense processing which ends up utilizing a large percentage of my CPU therefore heating it up more than I’d like. it’s approximately 4.7″ square and claims an airflow of > 200 CFM. Most computer fans airflow is < 100 CFM.

BGears 120mm fan

I figured I’d just control the fan from my Motherboard since that is what you normally do with computer fans. For some reason though, the Motherboard was not able to control this beast of a fan reliably as it would never hold it at a constant RPM. The fan would constantly “rev” up and down. I had to overcome a similar issue later in the circuit I’d create, so I figured the Motherboard circuitry had the same issue. i.e. It wasn’t meant to control such a large load. I know there are fan controllers you can outright purchase, but there is no fun in that. Besides, I figured I’d use this opportunity to digress back to my college years and play with some circuits.

The Planning…

First things first, I need to find the components that were required. I originally just thought to slap a potentiometer on the fan and drive it with the 12V supply from my computer, but I quickly realized it would not work. The fan has a pretty large current draw at 1.5A. So at 12V I needed something that could dissipate 18W of power if I went that route…but I only had 2W resistors on hand. At this point, I’m realizing just how much I’ve forgotten about circuits. So, I started looking at DC Motor Controller ICs like the L298N and the DRV8840 but I had a hard time finding them in a packaging I could easily use or could handle 1.5A output. Most of them came as SMT, but I needed something like a DIP.

555 Timer in DIP-8

After doing a bit more research, I decided to use a 555 timer with a transistor. The 555 timer handled the PWM part of the circuit while the transistor could handle the large current. I had an old 12V/1A DC power supply I had been holding onto for a while that seemed to fit the bill just fine.

Since this was going to control a fan in the computer, I did think about just using the Power Supply in the computer, but ultimately decided against it. After finding a few different schematics online, I was able to combine them into something that looked like it might work. All in all, it didn’t require many components though I did need to purchase a few, luckily they were cheap.

The Prototype…

First part was to work out the circuit on the breadboard. I also needed a barrel connector for the power, so I tore apart an old router I had and also salvaged some thin metal while I was at it to use as a heatsink for the TIP122 transistor later in the build.

Prototype on breadboard

At first, I had what seemed to be a similar problem as the Motherboard. The fan would not keep a constant RPM, yet a smaller fan did not have any issues. Swapping out the 100pf capacitor with a 10pf capacitor seemed to resolve it. I imagine the Motherboard’s PWM circuit had a similar issue. The transistor did heat up more than I wanted when increasing the RPMs, but that is why I put a heatsink on it. I don’t plan on having the fan up too high anyway, it sounds like a jet engine when turned to full throttle.

The Design…

The original plan was to use a 1.8″x1.4″ prototyping mini-breadboard, but they were just too small…and quite honestly I felt it would have looked pretty ugly. Even though it would have been contained in a box, the ugliness would have still bothered me, gnawing away at my soul.

1.8″x1.4″ mini-breadboard

So, before I could move any further, I needed to find out what medium I could use for my PCB. I had seen folks used carboard, wood, and plexiglass for a PCB. Cardboard and wood sent the same ugliness vibes as the mini-breadboard, and I didn’t have any plexiglass I could use. That is when I remembered my 3D Printer. I did find other folks that had luck printing a PCB out of plastic. With the medium for the PCB sorted, I needed to find some software that would let me design a PCB and print it out…preferably for free. Enter EasyEDA. One thing I had to keep in mind because I was using a 3D Printer to design the PCB, the traces needed to be kept pretty wide to facilitate the soldering I’d need to do. I’d find out later they still weren’t quite wide enough. Not sure if this was the correct way to design a “proper” PCB, but it seems to work for my needs.

Final schematic for custom DC Controller designed with EasyEDA

The Build…

Now that I had a schematic and PCB layout, I needed to make it into something tangible. I wanted to do a sort of test fit before I went too much further. With moving this schematic through a few different applications, there was a pretty good chance the scale of the image had changed at some point. EasyEDA will export the top and bottom layer PCB separately allowing me to print both layers on paper, then position them back-to-back for the test fit. Luckily so far, everything fit well in the place the components were to go.

Test fit of components

Next, Blender needed to be used. It has a nice feature for importing B&W images and then creating a height map out of that. This is exactly what I’d need to quickly build a 3D model for the 3D Printer to print.


I hadn’t used the 3D Printer in a while, so the build plate needed to be leveled and the rails/gears oiled up. Took a few hours to finish the prep and maintenance along with a test print before trying to print the PCB. Quite a bit more time than I had anticipated. I guess it didn’t help that I also decided to move it into the same room as my computer. Once everything was ready to go, the model was imported into Simplify3D. It’s an application that “slices” the model into horizontal layers so that the 3D Printer knows how to print the object.


Once it all looked good in Simplify3D, I fired off the 3D Printer. Yes, the 3D Printer is in a cardboard box. I usually keep the “front door” of the enclosure closed to try and keep the temperature moderated. Drafts of cooler air can potentially cause a 3D print to crack. These prints are not very big at all, so there is nearly zero chance for that. The PLA plastic I’m usually is usually heated to between 210c and 220c, it’s pretty versatile stuff. The build plate itself is also kept warm at around 60c- 70c.

3D Printer in action

The top and bottom layer were printed separately and then I’d use a bit of superglue once they were done to attach them to each other. I forgot how noisy the stepper motors are on the 3D Printer; the carboard box does help deaden the noise though. The top layer only needed one trace, all the other traces were able to fit on the bottom layer. Since this wasn’t a print that needed a lot of detail, the resolution of the 3D Printer was reduced to increase the speed of the print. This made the PCB a little rough, but not as ugly as what those mini-breadboards would have looked like, well, maybe.

Top and Bottom layer 3D print

It took about 40 minutes for each side to print. If the “cost” shown in Simplify3D is accurate, it estimated about $0.50 to print this PCB. A real custom PCB would have cost me much more. All in all, I’m happy with this so far. I did have to punch out holes in the “PCB” for the components with a sharp object. Once I started to wire/soldered everything in place…it ended up being a lot more tedious than I expected, but at least all the components fit really well. Taking the time to do a test fit really paid off there. In retrospect, I think making the traces even wider and not so deep would have made the soldering/wiring process go much smoother. The problem I had is my soldering iron tip isn’t very small so I ended up melting more of the plastic than I wanted to which mixed in with the solder. So okay, it’s not as pretty as I had envisioned.

Components assembled on the “PCB”

I still needed to have an enclosure for this PCB, so back to Blender for the design and Simplify3D to print. This went fairly well, except for the fact that I made the DC plug hole a little too small. Dremels work well for making holes bigger…and for making holes bigger than they need to be.


Once everything was assembled, I wanted to cover up the screws on the bottom that held the PCB in place. The head of the metal screws would slide around easily and I was afraid it’d scratch up whatever it was sitting on. Of course my daughter had an immediate answer, “Just use hot glue”. Well, that was a really great idea. Now I can properly utilize this monster fan. The funny thing is, I had bought two fans. So at some point, I’ll have to do this again.

Final build

What’s next?

Lately, I’ve wanted to make an automated Pan/Tilt cradle for a video camera with face/body detection…then attach a machine gun to it and turn it into a sentry. Well, maybe not that last part.

Math to the rescue…again!

Specifically trig…and you thought you’d never use trig outside of school, huh?

If you just want to see some things blowing up, you can scroll down to the bottom if you really want to. But if you are a math nerd, this just might interest you.

One of the reasons I majored in Computer Science was because I saw a potential to merge both math and computers together…my two favorite subjects. So what in particular did I need math for this time? It’s a little more complicated than the last time I wrote a post about some of the math used while developing Shape Sprout, although…I’m a little embarrassed to say I still initially forgot about Mathf.Rad2Deg and Mathf.Deg2Rad. 

Working on our new game, Castle Clans, we are in a 3D environment rather than just a 2D environment like Shape Sprout, so it adds another dimension (pun intended) of complexity to our calculations. If you haven’t read my previous post about Castle Clans, the overall gist of the game is you own a castle with some sort of medieval weapon(s) protecting it. Your weapon(s) shoot boulders toward the enemy castle in hopes that you will either destroy all their weapons or their castle first so you can win the round, loot their gold and buy/upgrade your stuff to take out more difficult opponents. There are a ton of physics going on here between boulders flying between both castles and the fragments of destroyed objects. Well, to get to that point in my game, I had to tell each boulder that gets launched from the weapon how much velocity it needed to reach the enemy side of things. Since each brick in your castle is independent from every other brick, and each weapon is independent as well, the weapons have to target those objects very accurately.

So what did we have and what did we need to figure this out? What we needed is the initial velocity of the boulder so it could reach its target from the angle that it was shot. Unity has a few features that make vector math a little easier.  So, what we DO have is distance to the target (on the xz plane), the direction it needs to head, the initial and final height of the boulder, and the angle at which the boulder will be launched…in this case, the ballista’s launch angle is about 30°.

Now that we have determined what we know, we can figure out our initial velocity by using this equation in our code.





So lets see what that looks like:

 // Makes for easier readability 
 Vector3 target = parentEntity.GetEntityData().GetTarget().transform.position;
 Vector3 origin = transform.position; 

 // Pull out our angle
 float radians = transform.eulerAngles.z * Mathf.Deg2Rad;

 // First need a direction on xz plane
 Vector3 direction = new Vector3(target.x, 0, target.z) - new Vector3(origin.x, 0, origin.z);

 // Now we need to see what the distance is on the x/z plane
 float distance = direction.magnitude;

 // Now need to calculate the height on the Y axis for the angle it shoots at
 direction.y = distance * Mathf.Tan(radians);

 // We will also need our height offset between the two objects
 float heightOffset = origin.y - target.y;

 // Now we need to normalize the direction into a single unit
 Vector3 normalizedDirection = direction.normalized;

 // Calculate what our velocity should be
 float firstPart = 1f / Mathf.Cos(radians);
 float secondPart = 0.5f * -Physics.gravity.y * Mathf.Pow(distance, 2);
 float thirdPart = distance * Mathf.Tan(radians) + heightOffset;
 float initialVelocity = firstPart * Mathf.Sqrt(secondPart / thirdPart);
 // And apply it to our final velocity
 Vector3 velocity = normalizedDirection * initialVelocity;

Our “target” variable is the position that the boulder will hit and the “origin” variable is the initial location of the boulder. Direction on the “xz” plane is done pretty easily by creating new Vectors that don’t have a “y” component, then just subtracting them. Like I said, Unity make is pretty easy to do vector math. Does anyone else think of “Dispicable Me” now anytime you hear the word “Vector”? No?tmb_990_480

Okay, never mind then, guess it’s just me.

After getting the direction to the target on the xz plane, we can also get the distance by retrieving the magnitude of our direction vector…again, Unity makes this pretty easy. We still do need to calculate the “y” component of the vector so the boulder launches at a 30° angle. We know this because when we attached the boulder to the launch rail, it placed it at that angle. To calculate our launch angle (so it looks like the boulder is leaving the launch rail), we can use (distance * Tan(θ)) to give us the “y” component. So now the direction vector is complete up to this point. One of the last components we need is the height difference between the initial and final locations…that is pretty important considering the boulder doesn’t leave and land on the same height. Taking our origin height and subtracting the target height from it gives us this value. Before we calculate the actual velocity (we’ve only calculated direction up to this point), we need to normalize our direction vector which gives us a unit vector. From there we can use our unit vector and multiply it by the velocity we are about to calculate to give us the final vector in 3D.

I split the velocity function into three parts in my code to make things easier and I could see what the values were as I was debugging the code if needed. The first part is (1/Cos(θ)) in front of the radical, the second part is the numerator under the radical and the third part is the denominator under the radical. Once I had these three parts calculated, I put it all together according to the function and then multiplied it by our unit vector and voila, you have the correct vector needed to apply to the rigid body component of your boulder. Lets see how well it works now…

In this particular test run, the enemy’s weapons have an accuracy of about 48%, that is why some boulders miss and some don’t. It wouldn’t be as exciting if your boulders hit the target every single time!

There is something oddly satisfying about watching a structure being destroyed one brick at a time…

And yes, there WILL be flaming boulders…there WILL be.

A classic game reimagined

Growing up playing on older video game systems, there are certain games that stick out in your head because the game play itself was simple and addictive. InspirationOne of those games was named Artillery for the old Apple ][e. It was a simple game in which you try to guess the correct angle and power of your cannon to hit your opponent. This is the inspiration for our next game, Castle Clans! We want to try and keep the game pretty simple but at the same time put our own spin on it as well. Because of my fascination with 3D graphics and the mathematics that are involved, I’ve always wanted to delve into that side of game development. Some years back I had created a simple transform and rotation class in C++ for basic 3D objects by utilizing matrices. The code didn’t take visual perspective into account, so what you saw on the screen was only orthogonal in nature but it stoked my interest in learning more. I haven’t had a chance to really play with that side of things since then but I believe this game will be a good opportunity to get back into that. We’ll be using Blender for all the 3D models that are created along with Gimp to help with the textures our models will use. I had used Blender off and on in the past just because I was curious about it, it’s nice I can put some of what I learned to use in this game. Importing models from Blender is as easy as copying the .blend file over into Unity. There are some things you still need to do with the model before creating a prefab out of it, especially if you have animations attached to the model. You also have to be a little careful in that Blender considers “up” as the Z-axis while Unity considers “up” as the Y-axis. There is a trick I found that helps with this “up” axis issue. Unity implements a lot of the groundwork for physics and detecting collisions to your meshes just like it does when you create a 2D based game. That will let us concentrate more on the game content and less on the boilerplate code.

Speaking of game content…we want to try and embody the simplicity of the original game but give it a bit of our own twist. You’ll be protecting your own castle with a couple of different types of weaponry that can be purchased. As you destroy enemy castles you can take their gold and use it to upgrade your stuff or even buy bigger castles. We don’t want to make the management part of the game too detailed and cumbersome as we think it’ll take away from the core of keeping the game simple, instead, we want to use it to give the player a longer game play experience and more challenges. I’ve already created some of the initial 3D models that we’ll be using and finally got a chance to play with Inverse Kinematics in Blender to create some of the animations we’ll use in our game.

This is a sort of “first go” at creating an animated ballista. I’ll use the multiple animation sequences I have to make it look like it’s loading up a boulder and shooting it out…no boulder just yet on here, it’s just the animation,

I plan on adding some other things to this ballista, but it gives me a basic animated model to work with in the game so I can flesh out some other parts. The challenge will be to keep the complexity of the models down to a minimum while still making them look decent so the game can be played on a wide range of mobile devices. The terrain for each map area (I call them domains) are on the scale of 2000 meters x 2000 meters…there are quite a few vertexes/triangles that make up the landscape alone. Your castle will use a “magic portal” to move from one land to another (how else are you going to attack enemy castles in other parts of the world?) Magic solves everything, right? I see it as sorta the duct tape of the fantasy world.

Optimizing each mesh’s material (the actual texture used on the 3D object) was also something I had to take into consideration. I had read about it before in the past but haven’t dealt with it yet until now. Essentially, the more separate textures per model, the lower the performance of your game. I saw it explained as each texture you have for the same model is like the device having to take a pause to “dip” it’s paint brush into another color so that it can paint that part of the 3D model. The idea is to have one texture for your whole model and specify areas on that texture that the certain parts of your model use for it’s particular texture. For instance, the castle has multiple rock/stone textures but they all reside on the same texture file. The bricks will just grab from one part of that texture while the base of the castle grabs from a different part of it.  Here is an example of what the texture for one of the castles look like. So instead of there being three separate textures, I combined them all into just one.

Needless to say, I was able to significantly improve performance once I figured out how to do it. There is still a TON of stuff to do on this game, it’s going to be a a great adventure!

Wrapping up Kung Pow Cards

We’ve just released Kung Pow Cards on the Google Play Store and the Apple App Store!

I can say this project has certainly been a much more complex journey than any of the projects I’ve done so far. Our initial plan was to have KPC out within about 10 months from paper design to the stores, it ended up taking us closer to 15 months as we hit some snags along the way. We worked on the design itself for a good couple of weeks and I feel it was pretty solid; we didn’t have any major changes that deviated from the design. While testing an early version of KPC, we realized that Push Notifications aren’t guaranteed to be delivered to the device…and Push Notifications were going to be the primary means of communication during a game. We had already decided we were going to make a custom game server to handle app communications on a future game we were going to design, but needed to move that timeline up so KPC could use that as its primary form of communications instead of Push Notifications. So began the journey of getting that setup. The version of Unity we use to create these apps doesn’t support network communications like we needed it to so I had to create native plugins for both iOS and Android along with a PC version so things could be tested. I imagine that is what set us back the furthest in our timeline, luckily most all the functionality we needed had already been created and only the framework for the Client/Server needed to be created. As a bonus, the app runs much more smoothly using our custom game server. Also during testing, we noticed some parts of the KPC UI seemed a little cluttered so we decided to re-skin them…even though that took a little time to do, I’m glad we did. At the moment, we are in a support phase, just watching things to see how they run on the server.

We’d love to hear your feedback on our new game, Kung Pow Cards. if you like card games, why not give it a try?

Kung Pow Cards – Milestone 3…Done!

“Wait…what happened to Milestone 2??”

Well, I sorta blew through Milestone 2 without posting an update. You know how it is, you get in the coding zone and don’t want to stop for anything.  Or is that just me?

So on the last post for Milestone 1, we had a lot of the basic core features and GUI layout figured out, we’ve added quite a few things since then. For Milestone 2, you are now able to play against another player or against one of the NPCs.  We are using our custom Game Server to serve up the matches so the app won’t have to rely on Push Notifications for communications or on slower Web-services. If something does happen to the Game Server, the app will fall back to one of the other two communication methods to keep the game going. For Milestone 3 we added the store to the app. We don’t have the in-app purchases implemented just yet, but you are able to purchase Skill Cards with coins that you have from winning matches and sell any Skill Cards you don’t want. For Milestone 4, we’ll have the in-app purchases in place and the ability to buy “bundles”. Bundles are groups of themed Skill Cards you can purchase for a small discount vs. buying them one at a time.

wpChallenges1“So, what exactly does that all look like?”

Glad you asked! We’ve changed up the Challenges screen just a bit to make room for longer profile names. The summary section at the top was organized a bit differently and we’ve added a symbol on the right side of the summary area to designate your current belt color so you don’t have to go back to the Profile screen. When you look at the Match Info (by touching your opponent’s name), you can see what Events are active on them so you can get a good idea of what you are up against.

“Wait…Events? You didn’t say much about that!”


wpChallenges2Right, I only briefly mentioned them. Basically, Events are effects applied to your profile on a Personal or a Global scale. We will occasionally make Global events that apply for everyone playing the game. i.e. Bonus match points when you play during a certain weekend. Personal events are those you create by using Camp type Skill Cards. [GM] Michael here has a Camp card that guards his stamina, meaning he can go into a match without using any stamina. We also have another Camp type Skill Card named “Shinatobe’s Wrath” that will steal one point from the base value of your opponent’s card and give (transfer) it to you. When you use this Camp card, this effect will be applied to your profile and last for 90 minutes (Skill Card names and effect times are subject to change!).
So, this effect will be applied to every hand you play for the next 90 minutes wpEvents. It gives you quite a bit of an advantage but not a guaranteed win! If your opponent is strategic enough in using the Skill Cards they bring into the match, they can still win…never underestimate your opponent! These types of Skill Cards will not be available in the store for purchase. They can be acquired from random drops after defeating your opponent. We didn’t want to give an unfair advantage to people who would buy a lot of coins to purchase these cards vs. people who just want to play the game casually. Let’s face it, not everyone will spend money on a game but they still want to be able to enjoy it!


We changed one of the names of the screens from Friends to Players. The Players screen will give you the list of your Rivals and anyone you’ve Blocked. wpPlayersIf someone is bothering you via messages or they continually try to create matches with you, you can block them. Rivals are people you like playing against and would like to create a match against at any time.

We originally were going to call this the Friends list…but it didn’t quite fit…so we thought maybe Enemies…but that didn’t fit either….and we BRIEFLY though about naming it Frenemies, but quickly decided against it, so we settled on Rivals.

We still have one issue at the moment we are trying to figure out. Finger scrolling on every device I have EXCEPT an iPad  (which I DON’T have) works like it is supposed to.  Now why does it work correctly on an iPhone but not an iPad? My development iPhone is an older one that can only be upgraded to iOS 7…my brother uses an iPad with iOS 8…hmm…wonder if there is something with that?

wpStoreOur store is pretty self explanatory. You touch the skill cards you want to buy and how many (depending on how many times you touch it or use the slider) and then purchase them by touching the “Buy these!” button. Coins can be acquired in different ways. When you create a profile, you’ll start out with a pretty good amount of coins to get you started. Winning matches gives you coins of course, but even if you lose a match, we’ll still give you some coins! Some of the Skill Cards in the Bundle drops can give you coins as well when you activate those Skill Cards.

“Umm…what’s with all the question marks?”

Yeah…just ignore those, I haven’t gotten around to creating the graphical assets for those just yet and needed a placeholder…

wpKPC3During a game, you can use the Skill Cards you brought into the match. You simply pick one before you lay down your next card. You can pick a Skill Card by touching the tab for the slide out tray on the right. You’ll be able to see what the card in your hand is before you play it, so you can better strategize which Skill Card would help you the most. Just don’t take too much time or your card will be auto-played! You don’t have to use Skill Cards if you don’t want to. “Kari the Shape Fairy” and I play each other without using Skill Cards and we still have a blast! The other two tabs at the top are for sending short in-game messages to your opponent and seeing a history of what in-game messages your opponent has sent to you.



wpMatchResultsAfter the match is over, you’ll see the final results. This tells you how many coins and match points you won (or match points you lost if you lost the match), if you received any drops from playing your opponent along with a few other stats.

One of the big steps that we’ve accomplished toward getting this released  is running the app on the production code, production databases, production Game Server and production APN servers. Only working and testing in the Dev environment up to this point, we weren’t 100% sure of the changes we’d have to make when we “flipped the switch” to go to production as there is various logic in the code to respond differently depending on if you are in the Dev or Production environments. There were only a few things that needed to be tweaked to this point, but for the most part it has been fairly painless.

“Wait, you don’t have a QA/Test environment?? For SHAME!”

Yeah, well, live with it.

wpSettingsAnd of course, in the process of uploading KPC to iTunes to try out their TestFlight program, I discovered they don’t accept builds unless you compile it for 64-bit. I vaguely remembered reading about it, but hadn’t uploaded anything to iTunes since we released Jumble Attack. This was before they changed their agreement. Luckily I was able to figure out fairly quickly what settings needed to be changed in Unity (4.6.x) to make it compile for 64-bit.  In the Player Settings for iOS, just change the Scripting Backend from Mono (2.x) to IL2CPP. I also changed the Architecture to Universal. I noticed the amount of files that Xcode compiles is about 10x of what it was before…so unfortunately, build times went WAY up.

So what’s left? Lots of testing and implementing in-app purchases and implementing the purchases of bundles…I think. Hopefully I can remember what I learned about SOOMLA during the last project and implement it fairly quickly. I still have to finish setting up the app store listings for iTunes, Google Play Store and the Amazon appstore…those can take a bit of time to do. Oh yeah…and we want to try to get “Kari the Shape Fairy’s” voice into the game more just cause she’s so stinkin’ cute AND those final graphical assets.

And what’s next after KPC? Yup, that’s right, we are already thinking about our next project! We’ve got a lot of ideas for an old school RPG type game…but first we’ll finish up KPC!


Update on Kung Pow Cards

It’s been a while since I last posted an update on Kung Pow Cards, as any adult knows, life tends to get pretty busy at times with other responsibilities. We are still pushing forward pretty hard on getting Kung Pow Cards out the door and we’ve made some good progress on game play itself. My brother and I are currently doing initial testing on both iOS and Android devices. We also decided to implement some AI on our server as a form of an NPC that you will be able to challenge; these NPCs will gain match points and work up their levels just as any normal player would as they play against other people.  These special players will reward you with increased match points and coins if you win against them. We figured having a chance to challenge an NPC for extra rewards would add some excitement to the game play.

“Kari the Shape Fairy” tends to take over anytime I’m testing our games…here she is playing against…uh…her alter ego on a second Android device. She always promptly lets me know when something doesn’t work like it is supposed to.P1070521

Now for the technical part…warning, if your eyes glaze over after the first sentence, feel free to stop.  That is unless you are trying to go to sleep, in that case read on, you should be asleep by the fourth sentence.

We’ve decided to implement an additional method of communication that we’ll use primarily during actual game play. Beforehand, I had implemented two forms of communication between the database and the two devices that were playing a match; those were web-services and Push Notifications. Web-services are mainly used while on the Camp screen for things like updating your profile, your skill cards book, pulling down any challenges you may have, messages from other players, etc… The Push Notifications were used to to let the device know if it needed to pull down information that had been updated in the database. We were using a combination of web-servcies and Push Notifications during the match, and while it seemed to work okay, I wasn’t okay with depending on a 3rd party server (Google Cloud Services & Apple Push Notification Servers) to reliably deliver these messages when they needed to. Thinking of how many thousands of messages per second these 3rd party servers probably process, any small hiccup could delay game play. Users want smooth and fast game play especially when playing a card game, so we decided to go ahead and create a game server on our web server that the devices could connect to. This would give both devices a dedicated communications channel to the database and hopefully limit any delays that could happen waiting for a Push Notification to be delivered to a device. So now we have three forms of communication between the devices and the database. The device’s primary communication channel will be the game server during game play, secondary will be web-services + Push Notifications and the last one, will be just web-services if Push Notifications fail. Since Unity does not support sockets for iOS and Android in the free version, we had to create our own plugins using Java (Android) and Objective-C (iOS). That set us back time wise a bit but luckily I was already familiar with sockets programming in C++; however, doing this in Objective-C was a bit of a challenge as it feels quite different than your C/C++/C#/Java flavor. So, with the Java plugin done, the Objective-C plugin done, the C# plugin (for testing in PC Standalone Unity) done and the PHP Game Server done, it’s just a matter of testing and working out any bugs in the Server/Client setup for this part of Kung Pow Cards. The only thing I’m not too sure about is how well a PHP Game Server will be able to keep up with traffic. I imagine I’ll probably end up creating a C based Game Server that runs on the web-server instead of going the PHP route…I guess we’ll see if that needs to happen during testing!


Kung Pow Cards – Milestone 1…Done!

So…what does that mean exactly? It means we’ve implemented a certain set of basic features and functionality of the game and have tested them to be working across both Android and iOS devices.

“Oh, so you are almost done then?”

AH HA HA HA…AH HA HA HA HA…..sniff…..no. But we are getting there fairly quickly. The features we’ve implemented so far are for the basic operation of one part of the game…managing your profile and everything that goes with it. We didn’t say this was your standard run-of-the-mill card game of War/Battle now did we? So what exactly was implemented in Milestone 1? When playing Kung Pow Cards (KPC for short), you will spend most of your time either on the Camp screen or on the Playing Mat. The Camp screen and anything needed to implement its features (such as profile creation) is what we are focusing on at the moment. challengesScreenShotThe Camp screen has multiple sections that will allow you to see various pieces of information. One of these sections is called the Profile section which allows you to see attributes of your profile such as how your journey to the top is progressing. Another section is the Skill Book section which allows you to decide which skill cards you want to take into the next game. And the Challenges section will let you see what challenges have been received, which ones you’ve sent out to other people and if there is one you can join right now. There are quite a few other sections as well on the Camp screen that I’ll talk about as the game’s development progresses. For this to all work together, a communications framework had to be setup to allow the devices to “talk” to each other so they knew who was online, offline and busy in another match, what challenges they had, who was waiting for them to join them right now on the playing mat, etc.. This communication framework also gives us the ability to setup various events that happen on a global or personal scale. i.e. Receive 2x more coins if you play during this weekend.

Granted we can’t play an actual game of War just yet (that will be milestone 2 BTW), it gives us the ability to test out matchmaking based on players ranks and to synchronize the players once they enter the playing mat.

There just aren’t enough hours in the day…

So, whats going on with Kung Pow Cards?

We’ve been head deep working on our next app, Kung Pow Cards so it’s been a while since anything has been posted. This app is quite a bit larger and more challenging than any of our other ones to date, but the challenge is half the fun! Lots of parts and pieces are going into making Kung Pow Cards…a bit more complex than I anticipated in some areas. We are implementing push notifications via the app42 plugin for Unity and there is a ton of backend work required to setup push notifications on both Android and iOS. app42 has TONS of plugins not just for Unity but for other platforms as well…and they have a free version just for us Indie devs! Up to this point, we’ve worked out most of the game design and rules, designed and implemented a pretty good backbone to the database…we have created about 17 tables and only minor changes have had to be made up to this point, implemented a working push notification test on Android devices, created about 70% of the graphical assets, implemented around 25% of the PHP web services and implemented around 20% of the code in Unity. We haven’t implemented anything SOOMLA yet for our purchases, but we did implement it in our last game, so we have a pretty good handle on how that all works. When the app is closer to being finished, we’ll post a few pictures. We are very excited about this project and the multiplayer gameplay it will allow players to experience!

So, you want to communicate data between your app and web server?

Before we delve into this, you may want to read about the legal implications on including encryption in your app, how to configure an HTTPS server and how to encrypt data in your app.

Once we are done here, you’ll have a good foundation for being able to send encrypted data between our app and web server. This just adds an extra layer of protection on top of HTTPS along with giving you the chance to store encrypted data on the local device. So, what’s the first thing we need to do? Let’s take a look at the functionality Unity provides to communicate with a web server. There are two classes we’ll look at for this, “WWW” and “WWWForm”. Unity makes it pretty easy to send info to a web server and wait for the result. Here is a basic example of how to do this:

// Set up form to send POST data
WWWForm wwwForm = new WWWForm();
wwwForm.AddField("yourField", data);

// Send data and wait for result
www = new WWW("https://yourUrlHere", wwwForm);
yield return www;
error = www.error;

// Process the data
if (String.IsNullOrEmpty(error) == true) {

You can add as many fields as you would like for sending data to your web server. So if you were sending a player name and a score, you create two fields on your WWWForm object. When you send the data, your script on the web server will process the data and send back a result that your app can then respond to. One thing to point out, we use a “yield return www” statement, this effectively allows the app to continue without waiting for a response from our web server. That yield statement is where the app is just waiting for the script shown below to complete while allowing the other code to run. This is done through coroutines which I’ll talk about in a bit. For now lets jump to the PHP side to see how we’d process this info and then we’ll get into a more complicated example that includes retrying our result if there was a problem and encrypting the data before we send it to our web server.

So in PHP on your web server we’ll access the data in the request using the $_POST variable. This will look something like this:

// Note that we named the variable "yourField" from
// the C# portion of the code above
$yourFieldData = $_POST["yourField"]; 

// Do something here with $yourFieldData like insert it in a database

header("Access-Control-Allow-Origin: *");
print("Some sort of return value(s) for your app to process");

That is what we are looking at from the PHP side. We take the data sent in from our app, process it, then respond by outputting something that our app will then read  Maybe like a return code so it knows if things were process properly or the ranking of the record just inserted in comparison to all the other records in that table. Now that we’ve got the basic idea down of how that all works, we can add things to it like encryption and retrying if there was a communications issue. I’ll cover caching the results to the device in another post so that if the user quits out of the game and the data hasn’t been saved yet to our server or there was a complete loss in communications, the request will be retried again later. For now, we are going to assume the transaction goes through the 2nd or 3rd time we try it if there was a slight hiccup in the communications between our app and the web server.

First thing we’ll do is setup our code for making calls to our web server. I created a script named DAO.cs (This stands for Data Access Object) and made it a static singleton instance. The reason I did this was because StartCoroutine is a method of the Monobehaviour class and needs an instance to be able to be called since StartCoroutine is not static. If StartCoroutine is called from a script that can be destroyed (i.e. calling your StartCoroutine then calling Application.LoadLevel() right afterwards), the StartCoroutine also dies because it is called from your scene’s instance (derived from Monobehaviour) even if that call to StartCoroutine isn’t finished yet. This had me very confused at first when my coroutine was killing out during an HTTPS request because I had called a LoadLevel() to get to the next scene of my app. I assume (falsely) that a coroutine was similar to a thread and would continue independent of what had called it. So came the necessity to make our DAO script and attach it to a game object that just goes with us through the life of that gaming session. In the script below, you see the methods themselves of the DAO class are static, but we still use the static singleton instance of the DAO object to call StartCoroutine from. I guess you don’t have to make the DAO methods static since you have a static singleton instance of the DAO class following you around, but when I first designed it, I didn’t think I’d need this static singleton DAO instance. The following code is more of a guide/example, I pulled it from one of my working projects and cut it down a bit, so you’ll have to modify it to fit your needs.

For passing data in your POST, you could pass a separate key/value for each and just encrypt the values on each key. What I decided to do is have just one key and pass in multiple key/values on that one parameter and separated each key/value with a pipe. I let my PHP code split up everything once the payload made it there. You could also use serialization or pass the data in an XML string if you wanted. So, in effect, what I have is a query string passed to the web server that looks something like “https://some-web-page.php?data=key1=value1|key2=value2|key3=value3“. However you decide to pass data to your web server is really up to you.

Some things to note:

  • Wait…you can’t pass an equal sign/spaces/whatever special character safely to your web server without URL encoding it! Yes, you are right, but my payload is encrypted (via the Crypt class) and effectively URL encoded. So passing equal signs are okay here since the value part of the “data” parameter looks something like “g1tThXzmX1Mjunux1Eto5YA” when it is sent along its way to the web server.
  • Make sure the function you want to call via StartCoroutine has a return parameter of IEnumerator. This will allow us to do some nice things like yield for a return while allowing the rest of the code to run. Pseudo-multi-threading I guess is the best way to define this.
  • We define a maximum amount of attempts we’ll try the request ALONG with a slight pause in between trying multiple times. If there is a small hiccup in communications, we want to give the device a little bit of time to correct before retrying.
  • www.text will be the response we receive from the web server. Again, this is up to you on how you want your PHP script to respond to this request. For your PHP script to respond, all you have to do is simply print() something before exiting the PHP script.
  • You did read How can I securely save my app data?, right?
  • Don’t hate on the use of prepended underscores for private variables 🙂
using UnityEngine;
using System;
using System.Collections;

public class DAO : MonoBehaviour {

  // Specific instance of this class
  public static DAO instance = null;

  // Max attempts to send data to the web server
  private static int _maxAttempts = 3;

  void Start() {
    // Making sure we only have one instance of this game object
    if (DAO.instance == null) {
      DAO.instance = this;
    else {

  public static IEnumerator GetScores() {
    int attempts = 0;
    string error = "ERROR";
    WWW www = null;
    // This is the payload to your web server. For a simple
    // GetScore type of functionality, you might pass it
    // a date to get scores inserted past a specific date
    string data = "key1=value1|key2=value2";
    // This is the key you share between your app and
    // your web server so that you can encode/decode
    // information
    string key = "yourKeyHere";
    string encryptedData = Crypt.Encrypt(data, key);

    // Try maxAttempts times to get the data
    while (attempts < DAO._maxAttempts && String.IsNullOrEmpty(error) == false) {
      // Sleep for 3 seconds before trying multiple times
      if (attempts > 1)
        yield return new WaitForSeconds(3f);

      // Set up form to send POST data
      WWWForm wwwForm = new WWWForm();
      wwwForm.AddField("data", encryptedData);

      // Send data and wait for result
      www = new WWW("https://yourURL", wwwForm);
      yield return www;
      error = www.error;

      // Process the data and put it into an
      // array if there were no errors
      if (String.IsNullOrEmpty(error) == true) {
      else {
        // Handle any errors here

  public static void PopulateScores(string text) {
    // This is the key you share between your app and
    // your web server so that you can encode/decode
    // information
    string key = "yourKeyHere";
    try {
      string decryptedText = Crypt.Decrypt(text, key);
      if (decryptedText.Contains("|") == true) {
        string[] scores = decryptedText.Split('|');
        // Do something with "scores"
      else {
        // Invalid return from web server
    catch (Exception e) {
      // Handle exception here

To call this from your app, all you have to do is something like:


This uses the instantiated static singleton DAO object “instance” to call StartCoroutine on the static method GetScores(). And because we are using a static instance, we don’t have to worry about the coroutine killing out if we go to another scene while the coroutine might still be running.

So how about the PHP side of things? In this example, we are retrieving scores from a database and returning the data so the app can do something with that data like display it. Again, how you decide to structure the return data is up to you. We could easily return something like “score1|score2|score3|score4” (which is the structure this example is expecting) and when our app receives the data, splits the string into an array or you could use serialization on your objects or even XML as well. It would probably be more “proper” to use serialization or XML. I’m actually not very fond of using XML in this instance due to how verbose XML can be. I want the smallest amount of data transfer as possible…especially with mobile devices.

For pulling back the scores, let’s pretend we have a table named “PlayerScores” in our MySQL database and it consists of three columns, an “id”, “name” and “score”. Below is some PHP code that uses this structure to query for the data and send it to our app who is patiently waiting for a response from our web server via the “yield return www” C# statement.

Some more things to note:

  • Procedural code? That’s so 1990s. Yeah well, think of it as an exercise to convert it to object oriented code.
  • Wait…where did “Decrypt” come from? That isn’t a PHP function. Yup, you are right. “Decrypt” is one of the the sister functions to our Crypt class in C#. More on that a little later.
  • Again, this code is cut down from one of my projects and so doesn’t have some error handling, so it may not be fully functional as is but it gives you a very good direction on how to go about doing something like this.
  • Depending on how you passed the data in your POST from your app, you will need to design your “WhateverFunctionYouCreateToExtractYourData” function to handle it.
  • Whats up with the header(“Access-Control-Allow-Origin: *”); code in your PHP? This just has to do with my Unity Web Player hosted on Dropbox trying to call my PHP scripts on a different domain. I’m just letting the browser know it is okay to do this.

  // Include whatever classes and files you need here

  // Make sure things look right from the request
  // This simply makes sure we are communicating across HTTPS
  // and "data" is present in our POST
  if (!isset($_SERVER["HTTPS"]) || !isset($_POST["data"])) {

  $key = "whateverKeyYouUsedInTheAppToEncryptTheData";
  $decryptedData = Decrypt($_POST["data"], $key);
  $values =

  // Check to make sure all expected keys are present
  if (!isset($values["key1"]) || !isset($values["key2"])) {

  // You'll have to supply the connection information below
  // based on how your database is setup
  $link = mysqli_connect($server, $userName, $password, $database);
  $result =
    mysqli_query($link, "SELECT score FROM PlayerScores ORDER BY score DESC");

  // Putting scores into data
  $allScores = array();
  while (($scores = mysqli_fetch_assoc($result)) != false) {
    $allScores[] = $scores;

  // Cleaning some things up

  // Encrypting the data and sending it back to the requestor
  $encryptedData = Encrypt(implode("|", $allScores), $key);
  header("Access-Control-Allow-Origin: *");

For this to all work like it needs to, our PHP code needs to be able to decrypt the data sent to it and then encrypt a response. Before returning our scores, we encrypt the string and print() it out. Once the script does this, the “yield return www” completes and we now have our response data in www.text on the C# side. Here is how you’d create some Encrypt/Decrypt functionality on the PHP side. Most of this encryption/decryption code here is NOT mine.

   * @param Info to encrypt $data
   * @param Used to generate key $secret
  function Encrypt($data, $secret) {
    // Generate a key from a hash, use 192 bit key
    $key = bin2hex(substr(md5(utf8_encode($secret), true), 0, 12));

    // Pad for PKCS7
    $blockSize = mcrypt_get_block_size('tripledes', 'ecb');
    $len = strlen($data);
    $pad = $blockSize - ($len % $blockSize);
    $data .= str_repeat(chr($pad), $pad);

    // Encrypt data
    $encData = mcrypt_encrypt('tripledes', $key, $data, 'ecb');
    return (base64_encode($encData));

   * @param Info to decrypt $data
   * @param Used to generate key $secret
  function Decrypt($data, $secret) {
    // Generate a key from a hash, use 192 bit key
    $key = bin2hex(substr(md5(utf8_encode($secret), true), 0, 12));
    $data = base64_decode($data);

     // Decrypt data
    $data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
    $block = mcrypt_get_block_size('tripledes', 'ecb');
    $len = strlen($data);
    $pad = ord($data[$len-1]);
    return (substr($data, 0, strlen($data) - $pad));

The PHP code feels a bit simpler than the C# code for encrypting/decrypting. Once you have this in a PHP script, include it in the other script above, then you can call Encrypt() and Decrypt() to your heart’s desire! Now your app and web server should be able to send encrypted data to each other across HTTPS! Got any suggestions or tips? Share them in the comments below, I’m always looking for ways to make my code better.