Thursday, August 7, 2014

[HTML JS] Hexagonal or Diamond Shape Masked Image

I am not entirely sure when did the creatives decide that hexagonal or diamond shaped images are the cool trend, because since last year I had been working on a project that requires user's avatar to be presented in such matter. At first, it presented a reasonable challenge because it's not possible to process all the images with Javascript to mask out the shape that we want, because that would be too taxing for any ordinary PC. Which would spells trouble especially client's PC tend to have weaker processing power and will very soon complain about the site being slow.

Hexagonal Image using HTML and CSS only

So, the other option that I could think of, would be to use canvas, but that too, didn't solve the problem of incrementally heavier load. And this dawn me, that I should utilize what new CSS has to offer and uses multiple overflow:hidden and css transform to rotate the image clockwise once and counter clockwise again. And the result is simply amazing, of course it takes some experimentation to get it correct.

Which, coincidentally, at the same time, I was working on a project that needed those techniques. But this time around, the mechanism is alot more complex and the hexagonal tiles are required to move around as desired. And this creates another problem that conventional html with CSS couldn't achieve with ease. Though that's not to say that we can achieve the same using just the layout with html and CSS, it's just a lot harder to predict the outcome.

I Chose Canvas

And so, I chose the easier way out, which is to use canvas based technology, which I had very recently been using in my game projects, the amount of learning and the amount of flexibility is amazing using PhaserJS. 

This project uses only PhaserJS as the main engine driving this website, even down to the hexagonal orange tiles that is laid out throughout the screen. The challenge here is to make the tiles arranged in such a way that they all tightly fit together and is able to change position with each other.

The bigger challenge is to have a center point where I could populate selectively avatars from, so there is no cheating here. It takes some thinking to put those code together.

The logic isn't rocket science once you know how to find the middle one, but to arrange the tile in a more meaningful way that you could arrange avatar from the middle point is a little bit more hair pulling. And the solutions that I had was gracefully short, around 4 lines of code to achieve that. I broke the problem into smaller problem and solve from there.

The Simple Algorithm

Firstly, we push all the hexagonal tiles into an array that we can use.
Then, we sort the array by comparing each one to the middle hexagonal tile
Finally, We can use. And here is the code snippet:

alltiles.sort(function(a, b) {  
return distance(yourself,a)-distance(yourself,b); 
function distance(p1, p2) {return Math.sqrt(Math.pow(p1.x-p2.x,2)+Math.pow(p1.y-p2.y,2));}

Now, isn't the solution simple?

As for the moving around part, it's easily achievable if you have work considerably with PhaserJS. The sprite class provides adequate support for animating things around with absolute ease. If you haven't start using any canvas game engine, you have to give PhaserJS a try. It's good.

Monday, July 21, 2014

[Objective-C Swift] My First Look

Swift, is Apple's next step to make coding fun and fresh again while not forgetting the productivity gained that results in simpler, tidier code. I went through the WWDC videos about the fundamental differences between Objective-C and Swift, went through the intermediate and advanced Swift introductions. I must say that I am very impressed with how well-thought the whole transition to the current Swift must have been.

The Transitions

I mean, if you were following the development of Objective-C for the past few years, you might notice that while the documentation of Objective-C is probably one of the best in the world, the language itself requires a lot of efforts for you to keep your code clean and memory in check. That's when they introduce ARC, Automatic Reference Counting, new LLVM, new Xcode! No longer will we need to juggle between multiple windows and tab between the old Xcode and interface builder, the transition simple took place slowly during the last few years. Leading to the now Xcode 6 beta. The best of all, is that Apple didn't rush any of those stuff out in a hurry, I guess they have certain practice of launching new stuff, is that they keep developing those features and at the same time maintain those that public uses, so by the time the framework is mature enough, they release to the public and started getting feedback to make it better and they did make it better, one way or another.

Difficult Start

I still remember when I first started learning Objective-C, it was quite a difficult time. Mainly because I never know that I am responsible for each allocated memory and every action has to take into account for memory leaks. It was where I learnt about delegation that is in the very core of Objective-C and Cocoa that makes me rethink of how I approach a problem in an algorithm that make sense every single time. It was also the time where I know then, that OOP suits my style and I should practice them more often!

Practice Makes Perfect!

That said, I did practiced OOP for the next few years in Action Script 3.0 and JavaScript. I still do JavaScript nowadays, in fact, it's my bread and butter. And talking about JavaScript and looking at the now called "Swift" file. It feels like JavaScript all over again! Apple did away with header and implementation files and now only one Swift class file that's all you need. In fact, if you have been downloading examples code snippets from apple developer site, you may notice, from the past 2 years, they have been putting stuff that you are supposed to put in header files into implementation files! I notice that when I was studying how certain code should be written in Objective-C, but being a stubborn me, I would still keep those @property @interface and others in the header files and only keep implementation in the implementation file, because that's what I believe to be true.

May be, Apple wants us to transition slowly with them as well, who knows?

// Show a dialog with an "Okay" and "Cancel" button.
    func showOkayCancelActionSheet() {
        let cancelButtonTitle = NSLocalizedString("Cancel", comment: "OK")
        let destructiveButtonTitle = NSLocalizedString("OK", comment: "")
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
        // Create the actions.
        let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
            NSLog("The \"Okay/Cancel\" alert action sheet's cancel action occured.")
        let destructiveAction = UIAlertAction(title: destructiveButtonTitle, style: .Destructive) { action in
            NSLog("The \"Okay/Cancel\" alert action sheet's destructive action occured.")
        // Add the actions.
        presentViewController(alertController, animated: true, completion: nil)

Now look at this code snippet and tell me you don't see the resemblance between Swift and JavaScript! Notice the way functions are now defined, and also the way dot syntax plays a bigger role that the old time square bracket accessors!

I was playing with the code for a few hours, trying to make a simple prototype of a TableView that reads data from CoreData and able to write simple data to CoreData. Suffice to say, it was all too similar to the old implementation of Objective-C, in fact, it has gotten simpler and nicer this time around with Swift. May be because I know the ins and outs of Objective-C, but I think mainly because the way it works still stay pretty much the same, it's just that, it's different. Just like one of the first video tutorials that taught me about Objective-C.

Objective-C is not better than other languages, it's just different.

And I have the same feeling for Swift, too. And I feel like I can focus more on delivering the solutions faster and better and worry less about the transitions, the framework, the architectures and so on. Happy Swifting!

Friday, July 18, 2014

[HTML JS] Animating Infographics Numbers

On one of the projects that I am working on, requires text animation. We are not talking about transitions that we can either use Ease.js, TweenLite.js or any sort. It's the type where the words slowly increasing in value and you have to sort of animate or display them in such a way that it feels like the words are alive and its animating. I wanted to show a number say, 33.53%, but because this number will be shown alongside with some infographics, I need to make them slowly accumulate in value, transition all the way from 0.00%. And that was the plan, to make the infographics looks a bit real and feels a little fresh.

And apparently, jQuery has made the process very simple and easy,

function animateNumber(selector, value, precision){
 $({countNum: $(selector).text()}).animate({countNum: value}, {
   duration: 1000,
   step: function() {
    var number = new Number(this.countNum);
    number = number.toFixed(precision);
   complete: function() {
    var number = new Number(this.countNum);
    number = number.toFixed(precision);

animateNumber('.percentage-something', 33.53034, 2);

Can you believe it. It's just that simple. Pass in a class where you want the action to happen, a value to count towards to, and of course optionally, pass in the precision because you might get more than what you wish to display since infographics are a little more accurate than usual in terms of its number.

Tuesday, July 15, 2014

[HTML JS] Game with PhaserJS On Mobile Device!

Ah... finally, being able to practice some wizardry using just HTML and JavaScript really makes me feel like a child inside. Last month,  I've made a HTML game that uses only PhaserJS on top of Dojotoolkit and the little web app framework that I had developed for very rapid-paced development.

The Easy Part

The game's mechanic is rather straight forward, it must be playable on mobile device, and user will need to swipe to throw the drumstick out to hit the players on the field and make some sort of scoring system to keep track of the score. And that were the only easy parts from the development perspective, because I had already chosen my platform of choice and also framework of choice. The only thing I could do then, was just to explore what could be done to make the game happening. And I must not forget that since it's a game, it has to be somewhat fun to play with, easy to play with but with certain level of difficulty because I want to challenge the player to get the highest score but wouldn't want to give the game away too easily. It takes days of tuning to get the final algorithm right, it wasn't an overnight thing.

The Unsaid, Difficult Part

But how to achieve all of them in HTML and JavaScript is a whole different matter altogether, and on top of that PhaserJS is not a 3D game engine and so, I would need to also make that happen and try to simulate the 3D environment as close as possible, and that requires a fair bit of planning and thinking before I could even try to develop the game.

It looks and feels daunting until I finally chalked the details down and split the problems into smaller, manageable chunks. One of the problems that I have for this project when I chose PhaserJs is 3D space in the game. To tackle this problem, I split the problem down into the following:

1. PhaserJS is a 2D game engine, there is no way that I am ever going to have an easy time making it happen. But there are things that I could tap onto, for instance, the gravity, the particles, velocities, directions of projectiles and many more. And once I know what I currently have in PhaserJS, I worked out formulas to calibrate throwing items away and further into the game. All these while mimicking the realism that it actually flew inwards towards the target and getting smaller when it flies. It takes some tuning and calibration, but all in all, it works out pretty good!

var swipeHandle = topic.subscribe("throw.item.swipe", function(velocity, distanceTravelled,direction){
  var absoluteDistance = Math.abs(distanceTravelled);
  if(absoluteDistance <= 0)
          absoluteDistance = vs.h;
                velocity *= 1.2;
                if(typeof hand === "undefined")
      'throw', 4, false);
          'normal', 1, true);
                //distance has to be small to go futher.
                //velocity range is from .11 - .4;
                var distance = vs.h - absoluteDistance;
                var howmanypixelPerSecond = 400 + (distance/vs.h)* 300;
                var updateInterval = 10 + (distance/vs.h)*10 ;//Math.round(velocity *10);
                var smallest = (1 - velocity)/10;
                var cameraOffset = vs.w/2 -50;
  var newbot = game.add.sprite(cameraOffset,  vs.h , 'bot');
  newbot.animations.add('run');'run', 15, true);
  game.physics.enable( [ newbot], Phaser.Physics.ARCADE);
  newbot.body.collideWorldBounds = false;
  newbot.body.bounce.y = 0;
                var directionInfluence = (direction/(vs.w*0.5))*vs.w*0.125;// * 1;
                var finalXDirection =  cameraOffset +directionInfluence+0.5;
                 game.physics.arcade.moveToXY(newbot,finalXDirection, distance, howmanypixelPerSecond); 
   context.deteriorate(smallest, newbot, distance, howmanypixelPerSecond);
                }, 200);

This code snippets feature one of the key mechanics for simulation of 3D space in this particular game, as you can see I even comment the velocity range from 0.11 to 0.4 because that was the range of value that make sense when the projectile launches towards the target, it determine how fast it should fly, and it's in sync with its scale value and also the distance value. Took me around 5 hours to get it perfect. Nothing big deal here.

Depth of field, on the other hand, is a little tricky in this scenario, although I can simulate a close-to-perfect 3D simulation for this throwing drumstick game. It will still lack true realism if it doesn't have certain level of Depth of Field. Just imagine no matter how far the drumstick seems to had flown towards the target, it still fall flat to the ground of your feet. That's where I implemented a simple deterioration technique where I clean off the projectile when the flying should ends. Hence, it will appear it dropped at the place where it flew to, but in actual case, it didn't.

Collision detection in PhaserJS is rather practical and useful, in the sense that it's easy to use and in this game, it's actually powerful enough to detect how the collision should work. Because as you can imagine, if the projectile were to only engage when it comes down due to gravity and hence being able to hit some target in the far distance. But if the target is just on top of the projectile, if PhaserJS didn't offer the type of options for collision detection, I would have to burn midnight oil just to figure this part out! And yes, PhaserJS' collision detection can let you configure whether a particular object is to be collided from top, left, right or bottom direction. Ain't that cool!

 game.physics.enable( realTarget, Phaser.Physics.ARCADE);
 realTarget.body.immovable = true;
 realTarget.body.allowGravity = false;
 realTarget.body.checkCollision.down = false;
 realTarget.body.checkCollision.left = false;
 realTarget.body.checkCollision.right = false;

But I do wish they would state in the documentation clearer that you will need to explicitly enable physics for any object that you want collision to even happen. I found out that Phaser.Physics.ARCADE is most suitable for this game's requirement hence I use it instead of other Physic engine in PhaserJS, do check them out!

All in all, I am looking forward to developing my next HTML game, it has been a fun ride, so far.

Friday, June 13, 2014

[JavaScript] HTML5 Game Engines

Until very recently, I have been developing games that uses HTML elements, using CSS transitions and TweenLite to animate things around in a DOM element. Which I think is fair and good enough if all I wanted is simple interaction with no physics and particles, but when I was into a web game project that requires gravity and physics, I knew then that I have to look for a reliable, well documented, well supported HTML5 game engine. And I found a huge list of game engines available, most are free while others need a little token of appreciation.

From is where I learnt that there are so many game engines out there that just scream for developers to use them, the list is quite comprehensive considering it covers almost 20 game engines in a nicely done, tidy table that includes the popularity, cost and rating. I am not so sure how they come up with popularity, may be this list comes after a series of surveys and a research for the user base of each game engines. Either way, it presents a nice informative table where you can choose for yourself which one you want to take up for your work.

So, as anybody who had just seen this list would do, is to start looking into the list from top to bottom, going through lines and lines of introduction, features, documentations, forums and support to get a gauge of which one I should filter out. And very quickly, I settled on PhaserJS.

Why PhaserJs

Its simple, hackable framework that fits into your work. Most framework out there, whether they are MVC, game engine or just tweening engine. I find that some require a lot of conformation to their practice and strict rules to follow if you don't want to suddenly fail or have errors cropping out of nowhere. And as a person who likes to hack around code before I can make production scripting, because that's the best way to learn any engine/framework. Though I am not saying following best practice and standards of the engine/framework is not good, it's just better if I can hack around. PhaserJS practice just that, it allows you to hack around with the engine while you can fit it wherever you want in your framework. It's nice!

The Documentation

It's awesome, but I believe there are still more improvement needed, especially the implementation example. For people like me, who has zero experience on PhaserJs, have to scratch my ass for a few nights before figuring out how to do certain things in PhaserJs. Those barrier can be totally removed with just a simple example. It's not that hard. But I think if it's too easy, it ain't worth my time! :D

The Examples!

There are over 300++ examples providing at, it's by no way complete but it provides a very good start up place for beginner to know the in and out of PhaserJs and how to use the engine/framework. It just provided the right amount of examples for you to start your game right up because I feel like a game needs a good setup, physics enabled, collision detection, interactivity and etc. Once you have gone through some of the stuff inside, you are good to go, trust me.

The Online Community

This is where my biggest concern lies, because this is the single biggest factor that decide whether whatever time you will invest in learning is well worth for at least another 1-2 years. We all know how fast technology moves, and even faster is the web technology. 6 months is the limit where you will need to do more catch up work, because that's the expiry date for all web technology.

While I find most of my quick answer on It doesn't provide me with enough information for some of the very basic stuff about game engines. And so, I found another website that is just awesome with wonderful people sharing their knowledge and keeps the community rich and alive.

And there you go, a good engine/framework requires just these three simple aspect to be well worth your time investment. May be, one day another engine/framework gets better, and I will inevitably change my work to that engine/framework, but until then, I will stick with PhaserJS.

Wednesday, May 21, 2014

My Little Rant on Youtube iOS App

Has anyone else out there that uses Youtube while they are on a slower 3G network, or sometimes LTE or 4G network. And your video doesn't stop stuttering to a halt and then the ever-hated buffer animation kicks in and you have your video for another 10 seconds before another buffering happens. Yes? If you have been into the situation that I have briefly wrote above, you may find that you can't lower the quality of the video played in the Youtube iOS app for crying out loud!

I mean, people of Youtube, you should know UX better than the rest of the world. Firstly, it's a common practice to developer that we should always monitor the network state of the device, which is either the device has access to 3G/4G/LTE or WIFI and in which case we should choose the best option for our users. But that's the best practice endorsed by Apple themselves in the documentation.

However, it's ignorant to think that users might not need to have access to those Quality option when they only have 3G/4G/LTE network. Do you know I just close the Youtube app down whenever I am hit with such situation where the video just can't load fast enough in my network for me to enjoy seamlessly and effortlessly. It buffers for 1 minutes for every 30 seconds played. It's just totally unacceptable. Has anyone from Youtube tested this app in realtime? As in testing it around the world to see if those UX make sense?

If you don't want your user to ACCIDENTALLY and STUPIDLY switch to a 1080p quality, just make sure you offer a downgrade quality option. It isn't rocket science, people. Come on Youtube. I know you can do it. If you can't do it, let me help you with it. It's just a few lines of codes. It just irks me so much that I have to rant out here. You Sir, have caused me to lose some hairs in the process.

Just give me the option to downgrade my Youtube video quality whenever I don't have WIFI network. Please, it's so frustrating.