Pool Game - Rack with Balls and Cue

Cue Ball Position Control Basics – Part III – The Draw Shot

In the first two articles of this series on cue ball position control, we looked at using the stop shot and the follow shot for basic position play.

Now, it’s time to look at the draw shot.

The Draw Shot

A draw shot (or screwback shot), occurs when the cue ball has a reverse spin (or backward rolling motion) at the time when it hits the object ball. After it hits the object ball, the reverse spinning motion cause the cue ball to get backward momentum, causing the cue ball to start moving backwards after contact.

draw-shot-straightIf the cue ball is aimed directly towards the center of the object ball, then the cue ball will first come to a dead stop, after which it will slowly start returning towards the cue stick, usually at a lower speed than the object ball. The final speed and distance that the cue ball travel depends on the amount of reverse spin that is imparted to the cue ball.

While it can take some practice, it is possible to draw the cue ball an entire table length by using proper stroke and follow through.

draw-shot-angleIn case the cue ball is aimed off center (a cut shot), just like in the case of the follow shot, the cue ball will deflect off the tangent line path that a stop/stun shot would take. This is the result of the reverse spin adding a component of movement in a direction opposite to the cue ball’s original direction.

In the diagram, the light gray line shows the path the cue ball will take once it strikes the object ball. Notice that draw shots cause the deflection angle to widen.

Now, that we know what this shot is, how do we go about adding the reverse spin to the cue ball?

Unlike the follow and stop shots, the draw shot can be a little tricker to master.

Typically, you add reverse spin by striking the cue ball anywhere from one to three cue tips below center as needed. Unlike with the the follow and stop shot shots it is essential to have a straight stroke, and a smooth follow through during the shot

In fact, I have a detailed set of instructions on the essentials for mastering the table length draw shot.

Try to pot the object ball into one of the side pockets while keeping the cue ball about a half table breadth away along a straight line, so that the cue ball slowly comes back a few inches after striking the object.

A good exercise to build your stroke that I strongly recommend is trying to draw back the cue ball and scratch in the opposite pocket to where you just hit the object ball. This take some very decent cueing and is another shot I’d recommend practicing until you can hit it perfectly at least 9 out of 10 times.

When in a straight line, the draw shot will let you move anywhere from a few inches to a few feet back from the object ball’s position, as needed. When shooting a cut shot, this will widen the deflection angle slightly, allowing you to move the cue ball to different areas than with the stun and follow shot.

Let’s take a look at an example like before.

draw-shot-position-zoomedImagine you had to run the three balls in numerical order, starting with ball in hand, using only the shots you have learned so far. How would you do it?

The simplest solution? Set up for a straight shot on ball 1, and draw back a few inches to get a decent angle for ball 2. Notice the tangent line when trying to pot ball 2 will cause the cue ball to potentially bump into ball 3. To avoid this, again use draw while cutting ball 2 in to deflect the cue ball by a wider angle, to place yourself for a relatively simple shot on ball 3.

Again, this is a simple and easy solution that would have been very difficult using only stop and follow shots.

Between the stop, follow and draw shots, you already have an incredibly powerful arsenal of tools to control the cue ball position and play better than most of your friends who don’t understand these basics of position play.

However, once you master these three shots, it’s time to move on to the more advanced tools, including using the half ball shot, and using side-spin with the rails.

In the next article in this series, we will look at how the half ball shot can become one of the most important tools that you will ever use to build long breaks effortlessly.

Pool Game - Rack with Balls and Cue

Cue Ball Position Control Basics – Part II – The Follow Shot

In the first article of this series on cue ball position control, we looked at the stop shot, and using the stop shot for basic position play.

In this article, we will add to our position play toolkit with the follow shot.

The Follow Shot

Very simply put, a follow shot occurs when cue ball has a forward spin (or forward rolling motion) at the time when it hits the object ball.

After it hits the object ball, the rolling motion cause the cue ball to regain forward momentum, causing the cue ball to continue moving forward after contact.

follow-shot-straightIf the cue ball is aimed directly towards the center of the object ball, then the cue ball will first come to almost a dead stop, after which it will slowly start following the object ball, usually at a lower speed than the object ball.

The final speed and distance that the cue ball travel depends on the amount of forward spin that is imparted to the cue ball.

follow-shot-angleIn case the cue ball is aimed off center (a cut shot), the cue ball will deflect off the tangent line path that a stop/stun shot would take.

This is the result of the forward spin adding a component of movement along the original direction of the cue ball.

An interesting thing to note is that, in roughly half ball shots the cue ball is deflected off its original path by approximately 30 degrees. This is a special case that we will study in greater depth when we look at the uses of the half ball shot in positional play.

In the diagram, the light gray line shows the path the cue ball will take once it strikes the object ball. Note how the deflection is lesser than if you had used a stun shot.

Now, that we know what this shot is, how do we go about adding the follow to the cue ball?

As we discussed in the previous article on the stop shot, any cue ball given reasonable time to slide on the table cloth will slowly start rolling forward as the friction from the cloth acting on it. If you hit a cue ball center ball over a large distance, by the time it arrives at the object ball, it will having rolling motion.

This is one of the reasons lots of beginners end up with the cue ball following the object ball into the pocket and scratching on long straight shots. The only way to avoid this is to either hit low on the cue ball to cause a stop-shot/draw shot, or not hit a straight shot in the first place.

For shorter distances, it is usually necessary to force the follow onto the cue ball by striking the cue above center, usually between half a cue tip and 2 cue tips depending on the amount of follow. By combining this with a good follow through, and a medium to hard strength, you can also get the cue ball to keep rolling a significant distance after striking the cue ball.

As with the stop shot, by using a combination of hitting hard and above center as needed, we can have the cue ball spinning forward when it hits the object ball. Calibrating how hard or how high to hit the ball is a matter of practice.

Try to pot the object ball into one of the side pockets while keeping the cue ball about a half table breadth away along a straight line, so that the cue ball slowly follows the object ball atleast a few inches.

A good exercise to build your stroke that I strongly recommend is trying to follow the cue ball and scratch in the same pocket where you just hit the object ball. This take some very decent cueing and is another shot I’d recommend practicing until you can hit it perfectly at least 9 out of 10 times. If you have trouble doing this, I’d recommend working on your stroke using the bottle drill.

This shot should now increase the positional options available to you.

When in a straight line, the follow shot will let you move a few inches to a few feet beyond the object ball’s position, as needed. When shooting a cut shot, this will narrow the deflection angle slightly, allowing you to move the cue ball to different areas that with the stun shot.

follow-shot-positionLet’s take a look at an example like before.

Imagine you had to run the three balls in numerical order, starting with ball in hand, using only the shots you have learned so far. How would you do it?

The simplest solution?

Set up for a straight shot on ball 1. Of course, since the 7 ball would come in the way of aiming for the 2 ball, a stop shot will no longer work. We can use a follow shot to allow the cue ball to move a little further to a more convenient location.

Once there, a stun shot would cause the cue ball to bump into the 5 ball, so we use another follow shot while shooting ball 2, to reduce the angle that the cue ball is deflected, placing yourself for a relatively simple shot on ball 3.

Simple isn’t it?

Choosing between the stun/stop shots and the follow shots is usually dictated by which provides easier and simpler position, and just causes subtle differences in the way the cue ball moves. However paying attention to the table and applying this information can be the difference between perfect position on the next shot and blaming bad luck or the table for being difficult.

How many players do you know, who complain or blame luck when they make a shot, but are out of position or blocked by another ball for the next shot?

Well, knowing what you do now, do you still think it is bad luck?

One last thing to keep in mind. Whenever you are aiming for an object ball that is far away from the cue ball, it is usually easier to use follow since the cue ball naturally tends to get forward spin when moving over large distances.

In the next article in this series on the draw shot, we will look at the last piece of the puzzle – how draw (reverse spin) can be used to either modify the angle at which the cue ball leaves the object ball or to have the cue ball move backwards, allowing for position play that is just not possible with the stop and follow shots.

Continue on to the next article in this series, Cue Ball Position Control Basics – Part III – The Draw Shot.

Pool Game - Rack with Balls and Cue

Cue Ball Position Control Basics – Part I – The Stop Shot

When watching a master pool or snooker player in action, what stands out isn’t the difficult shots that they hit, but how rarely they seem to need to make difficult shots; how they automatically end up with relatively simple shots; and how they seem to magically make the game seem incredibly easy and effortless.

One of my favorite players to watch for this is Ronnie O’Sullivan.

In fact, why don’t you take a few minutes to watch one of his classic breaks and look at how easy he makes the game look.

You could have made most of the shots that he made, couldn’t you?

The fact is, I wouldn’t be surprised if you said that you could. Most of the shots Ronnie had in that break were fairly straight forward, medium distance shots.

However, the trick isn’t just making the shot, it is making sure that you get an easy next shot as well; and then finding a way to keep getting easy shots until you have cleared the entire table.

That is the real secret of break building – cue ball position control.

Controlling cue ball position is the most important thing you can learn once you understand the basics of aiming and making shots. It is what separates the beginners who can make breaks of one or two balls, the intermediate players who can make 5-7 balls and the masters (You just saw Ronnie clear 36 balls on a 12 foot table without missing even once).

Over the next few articles in this series, I will be breaking down a few fundamental elements of positional control that when combined, will massively improve your ability to control the cue ball and make long breaks. These core shots and principles should be more than enough to handle most of the situations that you will encounter in your games.

None of these will be hard or flashy shots, or require vast amounts of skill. The key to good position play is trying to keep things as simple as possible.

Before you focus on position play, you should already have a decent stance and be able to make shots. If you are still struggling with these basics, you should check out my article on how to play pool well in under 30 minutes. Also, if you want to be able to consistently and confidently run tables, you should also develop a good pool stroke and fine tune it using practice techniques like the bottle drill.

Once you have got these out of the way, it’s time to look at the three basic shot types.

  1. Stop/Stun shot
  2. Follow shot
  3. Draw/Screw back shot

There are a few more shot names that you might have heard being mentioned such as drag shots and stun run-throughs, however once you master the fundamental shots, you will find that these are just simple variations of the three basic shots.

The Stop Shot

The most fundamental of all shots is the stop/stun shot.

Very simply put, a stop/stun shot occurs when the cue ball has no forward or reverse spin at the time when it strikes the object/target ball.

What this means is the cue ball is essentially sliding on the table cloth (and not rolling) when it hits the object ball. Once the cue ball hits the object ball, momentum is transferred from the cue ball to the object ball.

stop-shotIf the cue ball is aimed directly towards the center of the object ball, then the cue ball will come to a dead stop and the object ball will start moving at almost the same speed as the cue ball, in the same direction.

In the diagram, the light gray circle shows the point where the cue ball will stop once it strikes the object ball.

stun-shotIn case the cue ball is aimed off center (a cut shot), the cue ball will move along a perpendicular line (also known as the tangent line) to the object ball’s path.

The speed of the cue ball is then distributed between the two balls – In case of a thin shot, most of the speed remains with the cue ball, while in the case of a more solid contact, most of the speed will be transferred to the object ball and the cue ball will slow down significantly.

In the diagram, the light gray line shows the path the cue ball will take once it strikes the object ball.

Now, that we know what this shot is, how do we go about making the cue ball purely slide when it hits the object ball?

Well, here’s the deal – any cue ball when struck reasonably hard in the center, will start by sliding forward and then slowly start rolling forward as the friction from the cloth starts acting on it. If you hit the cue ball below center, then the ball will start rotating backwards while sliding forward, then the friction will take over and reduce the backward rotation until it stops rotation and starts purely sliding, and finally just like in the center-ball shot, will start rolling forward.

By using a combination of hitting hard and below center as needed, we can have the cue ball purely sliding when it hits the object ball. Calibrating how hard or how low to hit the ball is a matter of practice.

For the most common half-table-breadth distances a firm shot, within half a cue tip below center is usually enough.

Try to pot the object ball into one of the side pockets while keeping the cue ball about a half table breadth away along a straight line, so that the cue ball stops while the object ball goes into the pocket. This is one shot I’d recommend practicing until you can hit it perfectly at least 9 out of 10 times.

Now try setting up a cut shot, and watch the object and cue ball go in perpendicular directions.

Learning this shot alone should significantly improve your ability to control the cue ball. So how do you use this shot in practice?

stun-positionLet’s take a look at a simple example shown in the illustration.

Imagine you had to run the three balls in numerical order, starting with ball in hand, using only the shot you have learned so far. How would you do it?

The simplest solution? Set up for a straight stop shot on ball 1, then stun the cue ball slightly while shooting ball 2, so that the cue ball is deflected to place yourself for a relatively simple shot on ball 3.

By keeping your cue ball off the straight line shot, you can move the cue ball as far along the tangent line as you need for your next shot, by controlling the pace of the cue ball and the angle at which you are shooting.

In fact by planning one or two balls ahead, you should be able to make fairly long runs as long as you maintain a little angle which will allow you to move the ball along tangent lines instead of just stopping it in place.

Of course, not ever ball is an easy tangent line position away. Sometimes you might need to go in a slightly different direction from the basic tangent line. That is where follow and draw shots come in.

In the next article we will look at how follow (forward spin) and draw (reverse spin), can be used to modify the angle at which the cue ball leaves the object ball to achieve finer control over position.

Continue on to the next article in this series, Cue Ball Position Control Basics – Part II – The Follow Shot.

Fitness Healthy Living

Six Pack Abs and a Toned Body – You don’t really want it

Do you want to be extremely fit and healthy? Maybe have a toned body with a six-pack instead of a growing belly with flabby arms? Is getting fit and healthy a priority in your life?

Over the last year, while focusing on fitness and nutrition, I dropped nearly 14 Kgs (31 lbs) and 6 inches off my waist. I’ve now reached the point where people automatically stereotype me as “the fitness guy”, or “the bodybuilder”.

Since then, more and more people have reached out to me for fitness, nutrition and weight loss advice. Everyone wants to know exactly what I did, and how easy or difficult it would be for them to replicate.

I usually go out of the way to try and help friends when they ask for advice, since fitness is still a very big part of my life, and I’m always happy to help others on the same path. I freely share information about my diet/nutrition, exercise routines, and how I keep myself motivated.

It’s a pleasure to see the excitement in their eyes when they see how simple it can be to get into great shape; when they realize that their “stretch goal”, is in fact realistically possible in just two or three months.

However I’ve come to a bitter realization over the last year of trying to help people get fit.

Most people don’t really want to get fit and healthy. Most people don’t want to look like the models they see in magazines. In fact, they don’t even want to get half-way to that point to look “not unhealthy”.

All most people really want to do is talk about how much they want it, while continuing to remain in their current unhealthy state, or worse getting even more unfit.

Every time someone takes home one of the workout programs I recommend, I get hopeful that maybe this one person will stick with it and achieve great results. Often they message me after a few days about how amazing it feels and share the initial results they are getting, which gets me optimistic since unlike ninety percent of their peers, they actually started and committed to it.

And then, even though they see the results they have already got in just a few days, even though they know that this program works, without fail, they stop.

They abruptly stop messaging updates, and just as abruptly stop talking about fitness.

When I make the effort to reach out and check up, out come the excuses – no time, too tired, suddenly very busy.

Almost consistently and without fail, each of them usually says that they haven’t quit, they have just stopped for a little while and they plan to start again when they “have the time”. I still don’t know of one person among dozens of friends who started again or managed to find time.

I had someone tell me once, “exercise is a priority for me, however I just don’t get the time“.

My response? “No. It isn’t. Your priority is eating and drinking with your friends, watching movies, or relaxing and watching tv. If exercise was your priority over these things you would first exercise, and then say you didn’t have time to watch movies or hang out with friends. The fact that exercise doesn’t come before these things clearly means, by definition, that fitness isn’t the priority in your life.

So now let me ask again – Do you want to be fit and healthy? Is being healthy a priority in your life?

Answer honestly, and if the answer is no, then learn to accept it. Start admitting to people that you find it easier to be fat and unhealthy and prefer making excuses to getting fit and healthy. That you don’t want to be the best that you can be.

Don’t lie to yourself. At least this way you won’t feel guilty about missing out on exercise or eating unhealthy.

And when you truly decide to make fitness your priority, you can commit fully and achieve results.

Thank you – Expressing your feelings so others can feel them too

I was still in school. I think it was 7th grade.

I was just another shy school kid who brought his teacher a card for teacher’s day. I didn’t really put much effort into the card. She wasn’t even my favorite teacher. But she was a good teacher who loved her job and taught like it meant a lot to her. I just gave her the card because lots of other students were giving cards in class and I thought even I should.

When I gave her the card, she looked me in the eyes and said “Thank you”. Nothing more.

But that moment changed my life in a way that I can never really explain. Because what really shocked me, was the fact that I didn’t just hear that Thank you. I felt it !!!

Maybe it was the way she looked at me like I was the only person in the room. Maybe it was the way her eyes were glistening, almost with tears, when she said it. The way that she seemed to really, really mean it.

I knew she meant it, and I knew she was trying to convey what she was feeling. At that moment she was sharing everything that she felt – the joy, the gratitude, everything. And as I looked at her, I felt every bit of it, almost radiating from her.

And all she had said were the two words – “Thank you”.

Until that day, in my mind, “Thank You” was just something you automatically said when people gave you something, whether you cared about it or not. It was something you said because your parents taught you that you were supposed to say it.

It was never said like this!!! Words weren’t supposed to have so much feeling and emotion in them. Words were just words. How was she doing this?

But that day she changed my life. Because from that day, I kept wondering how someone could say something with so much emotion. Wondering what I had been missing because I didn’t even know it was possible.

It was the day I realized that I too wanted to be able to say and express what I felt. To be able to communicate not just with words, but with emotions and feelings. And I wanted to be around more people who could talk to me the same way. People who could connect with more than just words.

That day, as much as any other, has made me who I am today. And for that I am truly grateful.

computer keyboard

HTML5 Game Development: Using sprite sheets for better performance (and protecting your server)

When I started developing the HTML5 version of Command and Conquer, I never expected more than a few close friends to look at the game. (Based on the experience with my last game, Breakout).

Command and Conquer Javascript ScreenshotSo while I spent a lot of time making the game look as close to the original Command and Conquer as possible, I never spent much time optimizing the code. Most of my development and testing was on my own Macbook, and I didn’t pay attention to the image loading time or network traffic.

Unfortunately, this game uses a lot of images.

Each unit can face 32 different directions. This means at least 32 different images for each unit (more if there are animations like ‘harvesting’).

Buildings need a whole set of images for each state – under construction, regular – with different sets of images for healthy and damaged buildings, and for any additional states (like ‘unloading a harvester’). The Construction Yard for example needs 82 different images for it’s animations.

As a result, when the game loaded, it made nearly 1,000 HTTP requests to load all the assets (including images and sounds).

Since most browsers only make a few simultaneous requests at time, downloading all these images took a lot of time, with an overload of HTTP requests.

While this wasn’t a problem when I was testing the code locally, it was a bit of a pain when the code went onto the server. My patient friends ended up waiting for the game to load for 5-10 minutes (sometimes longer) before they could actually start playing.

AdityaRaviShankar.com - Traffic Screen ShotThe problem came when my game hit the front page of Hacker News and Wired.com on the same night, resulting in a slight spike in traffic :). It then got worse when the game got 1,000+ tweets and 1,000+ FB likes in just a few hours. The last time I checked, searching for my game gave over 5,000 google results.

What this meant was my shared hosting server was getting close to 14,000,000 HTTP requests in one day from just my domain.

I don’t think too many shared hosts are designed to take this kind of load, which resulted in my account being disabled with this interesting email from my provider.

Hello,

Your account adityaravishankar.com on the server quebec.unisonplatform.com was recently found to be causing high load that resulted in slowness/outages of various system services. In order to ensure quality of service to the other clients on this server we regret to inform you that the account had to be disabled to prevent any further interruption of service to our other clients.

If nothing can be done to lower the resource usage you may need to look into purchasing a dedicated server or cloud server which you can find more information about at http://www.eleven2.com. Please contact us as soon as possible to resolve this issue.

I was able to find temporary hosting on another server but the biggest priority was to optimize the way I stored images, which of course brings us to sprite sheets.

Hand of Nod Sprite SheetSprite sheets store all the sprites for an object in a single large image file.

When displaying the images, we calculate the offset of the sprite we want to show and use the ability of the drawImage() method to draw only a part of an image.

Creating these sprite sheets is incredibly simple using ImageMagick’s montage command line tool. This single command will convert a folder full of images into a single row sprite sheet.

After comparing PNG and GIF, I found that PNGs tend to compress the sprite sheets a lot more.

The advantages of using Sprite Sheets?

  1. Fewer HTTP requests – The Command Center went from 81 requests to a SINGLE HTTP request
  2. Better Compression – An advantage of storing the images in a single file is that the header information doesn’t repeat and the combined file’s size is much smaller than the sum of the individual files. The command center went from 496KB in 81 files to only 37KB in a single file. (Less than 8% of the original size, which is incredible)
  3. Easier Manipulation – With all the sprites in a single image file, it became easier to do RGB color manipulations, and I was able to optimize the drawing code for performance.

From almost a 1,000 requests to 120 requests in one simple code rewrite. And the total download size went from a few MBs to around 200KB.

Game load time went from 10+ minutes to under a minute. The bandwidth usage dropped to a tenth of the original. The number of requests dropped to a tenth of the original. And now my shared hosting can survive a very decent amount of traffic.

Moral of the story? When developing a large game that is image heavy, track your network usage and when possible use sprite sheets :)

Computer Keyboard

Command and Conquer – Programming an RTS game in HTML5 and Javascript

ANNOUNCEMENT: My Book, Pro HTML5 Games is out!!!

Pro HTML5 Games - Aditya Ravi ShankarA lot of people have been asking me for details on how I built the HTML5 version of Command and Conquer.

Based on my experience developing this game, I have just written a book showing readers how to build a complete RTS game in HTML5.

My book, Pro HTML5 Games takes readers through the process of building two complete games – a Box2D Engine based Angry Birds clone and a realtime strategy (RTS) game with multiplayer support.

This book is now available for purchase at Amazon (Pro HTML5 Games on Amazon), Barnes & Nobles (Pro HTML5 Games on Barnes & Noble) as well as the Apress Site (Pro HTML5 Games on Apress).

If you are interested in building professional looking HTML5 games, you should check the book out.

If you know anyone who would be interested in this book, please do share this book URL (http://www.adityaravishankar.com/pro-html5-games/) with them.

Read more details about Pro HTML5 Games here.

————–

After writing my first HTML5 game I decided to take on a more challenging project.

Command and Conquer Javascript ScreenshotMy latest project is a recreation of the original Command and Conquer entirely in HTML5 and Javascript.

Command and Conquer is the grand-daddy of all Real Time Strategy games and is probably the game that made the genre popular. My friends and I spent countless hours playing the original as well as subsequent sequels (Tiberian Sun, Red Alert).

Check out the demo video.

You can play the actual game here. Command and Conquer – HTML5 version

This project was a lot more challenging than my previous game, Breakout. In hindsight, I might have wanted to take smaller steps and make a tower defense game instead of jumping directly into an RTS.

Creating even this simple version of the game covered a lot of things.

  1. Using images to recreate the sidebar and game interface.
  2. Using mouse input for unit selection, panning, attacking and user input
  3. Using images as sprites for unit and building animation, and using sprite sheets for better performance
  4. A lot more sounds for units and buildings
  5. Using a finite state machine for handling unit commands, movement, attacking etc.
  6. Using path finding (A*) to navigate around obstructions like buildings, mountains and trees
  7. Using hidden canvas’s for things like fog of war and image manipulation

Obviously because of the size of the project, trying to do the whole thing in under a month all by myself wasn’t the smartest idea. I ended up spending lots of 18 hour work days during this time.

I used to switch between playing the original Tiberian Dawn in a Wine window on my Mac and my JS version on the browser to make sure my version looked EXACTLY like the original. I spent a LOT of time going through C&C forums to understand how to reverse engineer the Tiberium Dawn files to extract the building/unit sprites and audio and reading up on unit specs to figure out how to make the units behave exactly like the original.

Every little thing took time – things like selecting single units, multiple units, being able to select by drawing the box from left to right or from right to left; making sure the panning was smooth; Figuring out a decent fog of war implementation; Allowing for building construction, dependencies (Power Plant needed for Refinery, which is needed for Factory), building placement (buildings cannot be constructed on top of other buildings); Depth sorting when drawing so units could move behind buildings and trees.

The next big headache was smooth unit movement. I wanted to do better than the original game, and spent a lot of time going through Starcraft 2 videos to see if I could get a smoother movement closer to the way SC2 handles it. Pathfinding using A* can do some of the work, but gives a clunky movement and causes units to take behave badly/take longer routes when going through bottle necks. I decided to mix A* with a repelling force/steering behavior to improve it. It still has some bugs I need to work out.

I had to fine tune the way units behaved (during patrolling, guarding, attacking). Even the fact that a MCV couldn’t attack and turned into buildings.

Harvesting was a whole different pain in the ass since my collision detection and steering code meant my harvester was initially afraid to return to the refinery :).

While a lot of people have been giving me props for just getting this project out, one of the things that I am proud of is that I completed the first version in around 3 and a half weeks, all by myself.

For people who have been criticizing this project, I’ll say this – “I did this, entirely on my own, unpaid, in three and a half weeks – including one week where I had a fever. Give me a break. It isn’t that bad :)”.

The current iteration of the project contains several levels from both GDI and NOD campaigns. I am also currently testing multiplayer using Node.js, which should be coming soon.

Check out the video demo of the new version of this game that I am working on.

This game has got a lot of attention from online media and FB/Twitter/Google+. The extra traffic brought my server down on its knees and got my account temporarily suspended. This forced me to optimize the game using sprite sheets so it could handle requests more efficiently. You can read more about the whole story here – HTML5 Game Development: Using sprite sheets for better performance (and protecting your server)

Real Time Strategy Game - Pathfinding, Collision Detection & Steering Demo - ScreenshotAfter lots of feedback, I’ve specifically researched and worked on improving the pathfinding of the game. Check out the Pathfinding, Collision Detection & Steering Demo. This is a demonstration of the improved unit pathfinding and movement/steering strategies used in RTS games. Units use A* to plot a path and avoid collision using a ‘soft collision’ radius. They also ask static units to move aside.

Here is a video demonstrating all the features of the new pathfinding code.

Check out the demo here. Switch on “DEBUG MODE” to see how it works. This is still a work in progress. Any comments or feedback (including bugs), is appreciated.

Check out some of the HTML5 games I have written. If you are just starting out with game programming, check out my earlier tutorial on developing a simple Breakout game in HTML5.

HTML5 Game Development Tutorial: Breakout Part III – Collisions, Scoring and Sound

Breakout v0.6 ScreenshotThis is the third in a series of tutorials on developing a full featured version of Breakout.

In the second tutorial, we used setInterval() to add some animation and capture keydown and keyup events to respond to user input.

In this tutorial, we will bring back the bricks we drew before, handle the ball colliding with these bricks, and finally increase the score when a brick gets destroyed. We will also add some sound effects to make the game more fun.

We will use the code from the last tutorial as our starting point.

Lets get started.

First we add back two lines at the beginning of the animate() function to draw the scoreboard and the bricks.

Right now the ball will move over the bricks without bouncing off them.

We need the ball to reverse X direction if it hits the sides of the bricks, reverse Y direction if it hits the top or bottom of the bricks and damage the bricks every time it touches them.

Lets create functions to check whether the ball is colliding with a brick along the X or Y direction, and to damage the brick if it collides.

The collisionXWithBricks() and collisionYWithBricks() functions return true when they bounce against a brick and automatically call explodeBrick() to weaken the brick and update the score. To start using these functions, we modify the collision checking conditions in moveBall() slightly.

At this point, the ball bounces off the bricks as expected and weakens the brick when it hits them. Once the brick is completely destroyed, it disappears and gives the player an extra points.

Not bad. The game works fine, however there is still something missing.

A little sound tends to give players a much more immersive experience and will make the game more fun. With HTML5 Audio, implementing sound is surprisingly easy.

To play sounds, we load files using the Audio() object and play them using its play() method. Browsers are still a little inconsistent about which formats they support. The OGG file format is an open format supported by both Chrome and Firefox (my favorites), which is why we will stick with them for now.

To create the sound we place the two files at the same location as the HTML file and load them by creating new Audio() objects and storing them in variables. The OGG sound files used here are included with the source code.

To play these sounds, all we need to do is invoke the play() method.

We can play the breaking sound whenever a brick is completely destroyed (inside the explodeBrick() function).

And the bounce sound anytime we change X or Y direction for the ball (inside the moveBall() function)

That’s really all there is to it. We have a game with sound effects, animation, keyboard control and increasing scores written entirely in HTML and Javascript.

To make the game more fun, we can add more interesting brick types, sounds and game mechanics.

In my version of the game, the bricks start falling down, we have Cash bricks to give money, Bomb bricks that explode everything nearby, Laser Ammo bricks that let us shoot laser from the paddle and Spider bricks that shriek and start crawling down at the user. Check out the game to see what you think. Leave a comment if you enjoy the game.

I don’t see much point showing people how to implement the exact same features in a game, because at this point it is fairly simple to do. However if you have an interesting idea that you would like to add to the game, leave me a comment below. If we get a few interesting ideas, we can have one more tutorial where we implement the ideas and create our own new version of the game.

If not, stay tuned to learn how to implement a Real Time Strategy game engine entirely in HTML5 and Javascript. Check out Command and Conquer – Programming an RTS game in HTML5 and Javascript.

You can download the finished source code for this tutorial below.

computer keyboard

HTML5 Game Development Tutorial: Breakout Part II – Animation and Keyboard Input

Breakout v0.6 ScreenshotThis is the second in a series of tutorials on developing a full featured version of Breakout.

In the first tutorial we covered drawing primitive objects on the screen using the Canvas element and developing the basic game screen.

In this tutorial, we will use setInterval() to add some animation and capture keydown and keyup events to respond to user input (so we can move the paddle).

We will use the code from the last tutorial as our starting point.

Lets get started.

To animate objects in the game, we need to draw them, move them a little, and then redraw them. To do this, we create an animate() function and place our calls to the drawing functions inside it. For now, lets focus on only the paddle and the ball.

Now we need to figure out a way to call animate() repeatedly at regular intervals. Luckily, Javascript has a function called setInterval() which keeps calling a given function repeatedly at fixed time intervals until the clearInterval() function is called.

We create two functions called startGame() and endGame() to begin the animation and end it. We can also use startGame() to do any pre-game initialization of variables.

Now that the game loop is setup, we need to start moving the elements during the loop.
We start by creating a moveBall() function and calling it from within animate().

The moveBall() function adjusts the ball coordinates by adding the ball speed. We initalize balldeltaX and ballDeltaY when the game starts.

Now that everything is in place, the ball should start moving.
Screenshot
However when we open the file in a browser, we see something weird.

Instead of a moving ball, we have a long black line. The ball keeps moving, however the old balls stay behind, leaving a long trail along the path. We need to clear the earlier objects before drawing new ones.

To do this, we can use the clearRect() method.

This line clears the entire canvas at the beginning of the animation loop. When we run the code now, it looks like a moving ball instead of a long snake.

The next problem is that our ball doesn’t bounce off the walls. It keeps moving past the edge of the canvas and disappears. To fix that, lets add some conditions to check when the ball is moving outside the boundary.

Great! Now the ball is bouncing off the walls properly and when it touches the ground the game ends.

Now lets animate the paddle. To move the paddle, we need to first track the left and right keys and keep track of where the paddle should move during the next animate(). We do this by using the keydown() and keyup() jQuery methods to assign event handlers for these events.

The event handlers check if the key pressed or key released is Left (key code 39) or Right (key code 37) and stores this in a paddleMove variable. We will check this variable every time we animate to see where the paddle needs to move next.

The next thing we need to do is define another movePaddle() function that is called just like moveBall().

We now call this new movePaddle() function from animate() as well.

Great! Now the paddle moves to the left and right when we use the cursor keys.

The last thing we need to do is make the ball bounce if it hits the paddle. We just need to add a condition to the other collision checks in moveBall().

And thats it! The paddle moves perfectly, the ball bounces off the wall and the paddle, and if the ball hits the ground, the game ends.

We have come a long way from an empty rectangle on the browser. Of course, this game is still a little boring with just a ball and paddle.

In the next tutorial, we will bring back the bricks that we drew before, handle the ball colliding with these bricks, and finally increase the score when a brick gets destroyed.

You can download the finished source code for this tutorial below.

Continue to part 3 of this series. HTML5 Game Development Tutorial: Breakout Part III – Collisions, Scoring and Sound

computer keyboard

HTML5 Game Development Tutorial: Breakout Part I – Introduction to Canvas

Breakout v0.6 ScreenshotThis is the first in a series of tutorials on developing a full featured version of Breakout. This tutorial will cover drawing primitive objects on the screen using the Canvas element and developing the basic game screen.

Before we get started, check out the finished Breakout game demo. With flying bats, falling spiders, laser turrets and exploding bricks, its probably a little different from the typical breakout game. We will be recreating this game over the series.

All of our development will be for HTML5 capable browsers that properly support the HTML5 Canvas and Audio tags (Chrome, Safari, Firefox, Opera and maybe Internet Explorer 9). Make sure you have one of these browsers.

Now let’s get started.

First we create a simple HTML file with a canvas inside it.

We also include jQuery to make cross browser development easier.

To start using the Canvas we need to get its 2d context which then gives us access to all the drawing methods we need.

With this context object, we now have access to the methods that we will need for our game like fillRect(), clearRect() and drawImage().

Now that we can draw, lets start with creating the paddle.

Note that we store all the parameters in variables so that we can easily modify and reuse them later. Drawing the paddle is as simple as using the fillRect() method.

Now lets draw the ball.

Drawing the ball requires the arc() method to draw a circular shape and the fill() method to fill the shape we just created. While drawing the arc, the starting angle is 0 and the ending angle is 2xPI radians (or 360 degrees) which makes a full circle.

Now lets draw the bricks on top.

First we store the bricks layout in an Array making it easier to visualize and modify. Feel free to try adding a few more rows, or changing the numbers to modify the layout.

We then iterate over each row and column and call the drawBrick() method to place the brick correctly. Within drawBrick(), we use a switch statement to set different fill colors for different types of bricks. This function can be extended to add more brick types.

Finally, lets create a simple scoreboard or status bar below.

This uses the fillText() method to write text at the bottom of the canvas.

We can check the output of the code so far by calling each of the functions that we wrote.

Breakout - Tutorial 1 - ScreenshotThis is the final result. We have a complete game screen with all the elements drawn on it programmatically – the bricks, the paddle, the ball and the scoreboard.

It doesn’t seem like much yet. Everything is static. However, because we stored the parameters in variables, all we need to do to move objects around is change the parameter values and call the same functions again. Thats when things start getting interesting.

In part II of this series, we will use setInterval() to add some animation and capture keydown and keyup events to respond to user input.

You can download the finished source code for this tutorial below.

Continue to part 2 of this series. HTML5 Game Development Tutorial: Breakout Part II – Animation and Keyboard Input