DIY Sample Series—Clicky Ticky Sounds

One of the frustrations in recording is searching for just the right sounds. Percussion elements can very daunting to sort through. In this tutorial series you will learn how make your own sounds that are one hundred per cent yours. 

Throughout this series you will see how to sample unique shakers and drums, stick noises and claps, and more unique elements for impacts. I will cover how to sample some more traditional elements that I like use all the time such as cymbal hits, chokes, and rolls. 

In this tutorial you are going to learn how to sample and program something that I like to call clicky ticky sounds. These are very short, very dry, high frequency noises that work really well layered over other percussion elements. Things like drum stick clicks, brushes on shakers, and chopsticks hitting all kinds of stuff. 

You will also learn how to chop them up and program them with a free sample player that works on Mac and PC called sforzando

Screencast

Download DIY Sample Series—Clicky Ticky Sounds

5 Common Mistakes Made by Guitar Players

The key to improvement is practice. It’s very important to have a strong and healthy self-criticism. I’ll point it out before you read this tutorial: these are just common mistakes I’ve seen over the years in lots of guitar player and I’ve been making the same mistakes as well. Although it doesn’t mean you’re making them yourself, you may take this tutorial as a starting point to analyze your weaknesses.

1. Vibrato

Vibrato. A super-underestimated technique that everyone in the guitar world thinks they can do, but in reality they can’t. 

Vibrato technique doesn’t mean you have to shake your hand super fast until the string will swing from the top to the bottom of the neck. In fact, good vibrato technique derives from a relaxed motion that will add just a little extra natural vibe to the note you’re playing. 

The point most people are missing, when playing vibrato, is time. Vibrato as to be in time as well as the other notes. Adding an effect to a note doesn’t mean you can call yourself out from being in time, or in tune. 

This leads to tune. Using vibrato on a note doesn’t mean doing a quarter tone of a bend. Again both these mistakes are the result of a stressed out player. 

Finally, don’t use vibrato on every note that lasts more than a quarter note. Holding a note doesn’t necessarily mean you have to add vibrato on it. Think of it like this. If you use a special effect every single time, it is no longer special. So use vibrato with only when appropriate, just as you would with other techniques. 

2. Time

This is very common. If you’ve ever recorded yourself, at some point, during your musical career then you have probably noticed how out of time you were. Maybe you improved over years, maybe not. 

Although it’s very odd how guitar players have bad reputation in both timing and reading. 

The reason why playing in time is such a pain is the fact that you start playing thinking of guitar as a instrument that has just pitch. So you take care of learning scales, chord but you never stop for a second to think that everything in music has to be put in time regardless of the instrument played.

The key to improvement is a metronome. 

As a player in general you shouldn’t consider using a metronome something extra as well as you don’t consider the skill of reading a book something extra as a member of a society. 

3. Neck Visualization

This point is something of which I’m really fond and it may be that some people underestimate or even don’t care much about it. It may sound like an advanced skill to have as a guitar player, but to me the earlier you see everything—notes, intervals, dots—on the neck then the better it is. 

I’ll start with this idea: using patterns—or shapes—to play scales and chords has pro and cons. 

  • Pro: once you’ve understood the concept, you can play the same scale in every key without change fingering or thinking about the notes in that scale
  • Cons: By not thinking about the notes risks you risk becoming lazy and ignorant about music. You get to the point where you’re just imitating some dots on a paper without actually knowing anything. 

I’m not saying that you have to learn all the notes when you first pick up the guitar. Learn the pattern first. Then learn the intervals you’re playing, then learn the notes. 

None of us will learn everything in the first instance; seeing what’s happening on the neck should be everyone’s goal.

This is because a good knowledge of fretboard means you not only know what you’re doing you also care about the notes you’re playing. 

4. Too Many Notes

Perhaps you’ve had that feeling of “When I’m soloing I just run the patterns up and down and I don’t know what else to do”. This is because you don’t think in terms of note, you think in terms of shapes. Every notes has its own character and sound. The soon you learn, the more authentic your motifs will become. 

Such mistakes are not immediately apparent in a guitar player, like timing or vibrato. Although the effects of this lack is totally recognizable: arhythmic, non-sense, not memorable solos. 

And this mistakes has to deal with two aspects of music: neck visualization but most of all, ear training. 

I’ve already considered the first point; now consider the point of ear training and solos. You should always use your ear when learning a scale. And by that, I mean always

Learning a scale just by staring at the dots on a paper won’t take you anywhere. You need to sing the scale while you’re playing. You need to be able to sing that scale starting from a given root. 

This training will make experiment with your ear more and, above all, will make you understanding the direction of every note in a scale. 

5. Laziness 

I can’t find a more specific word to describe this last point. The guitar is an easy instrument to play, but a really hard one to master. Also, guitar is that kind of instrument that everyone state to play even if they know a couple of open chords. 

So when someone starts to play guitar, they learn the basic chords and maybe some scale and they think they can play because they have friends that do the same. 

Saying this, I’m not trying to say that if you want to play guitar you have to study 10 years of conservatory or dedicate your entire life to it. What I’m pointing out is the fact that we give up learning stuff too quickly.

If playing guitar—or even another instrument—would be considered as a hard thing to do, something you really have to push yourself through, then I’m sure that only people with  commitment would dive into it. 

To be able to play an instrument is something that has to be develop over years of study as well as other skill you learn. So be patient with yourself but also, don’t be lazy and always try to be enthusiastic about something new to learn. 

Conclusion

I hope you won’t take this article like a fool critique against guitar players: after all, I play guitar as well and I’m definitely not mistake-free. I think that the first thing to fix a mistake is to recognize them. So, being honest, consider whether you’ve found yourself falling into one of those categories.

Download 5 Common Mistakes Made by Guitar Players

New Course: Getting Started With Express

What You’ll Learn

Express is one of the most popular frameworks for building web applications in Node. Recently, version 4 of Express was released, and with it there are a bunch of new features. 

In this course, expert instructor Andrew Burgess will teach Express from the ground up: not just the new features, but everything. If you haven’t had a chance to look into Express before, our new course is a great place to start!

Watch the Introduction

Start Learning With a 14 Day Free Trial

You can take our new Express course straight away with a completely free 14 day trial of a Tuts+ subscription.

Take a look at our subscription options to get started or, if you’re just interested in this course, you can buy it individually for $15!

Download New Course: Getting Started With Express

How to Write in the Sand in Adobe Photoshop

Final product image
What You’ll Be Creating

Adobe Photoshop’s Layer Styles are one of the quickest, yet most effective ways of achieving many different effects. This tutorial will show you how to combine the power of Layer Styles along with a couple of textures, brushes, and selection options to create a realistic-looking sand writing text effect.

Tutorial Assets

The following assets were used during the production of this tutorial.

1. Load the Nature Patterns Set

Go to Edit > Preset Manager, and choose Patterns from the Preset Type drop down menu. Then, click the little arrow to the right of the Preset Type drop down menu, and click Nature Patterns in the middle of the pop-up menu. When the dialog box appears after that, just click Append.

Loading the Nature Patterns Set

2. Create the Background

Step 1

Open the SoilSand0204 image, then go to Image > Adjustments > Color Balance. With the Midtones option under Tone Balance selected, change the Color Levels‘ values to 8, -1, and -26.

Adjusting the Color Balance

Step 2

Click the Highlights option, and change its Color Levels‘ values to 5, -1, and -5. This will adjust the coloring of the sand texture.

Adjusting the Color Balance

Step 3

Duplicate the Background layer.

Duplicating the Background Layer

Step 4

Go to Image > Adjustments > Levels, and change the Gamma value to 0.80 to darken up the texture a little bit.

Adjusting the Levels

3. Create the Text

Step 1

Create the text in All Caps using the font GelPen Medium. The font Size is 350 pt, the Tracking value is 100, the color is #6c6760, and if you’re creating more than one line of text, make sure to adjust the Leading value as needed. Here, it is set to 300 pt.

Creating the Text

Step 2

Change the text layer’s Blend Mode to Soft Light then duplicate it.

Changing the Blend Mode

4. Style the Text Layers

Step 1

Double-click the original text layer to apply an Inner Shadow effect using the following values:

  • Uncheck the Use Global Light box
  • Angle: -180
  • Distance: 20
  • Size: 20
Inner Shadow

Step 2

This will add a simple inner shadow effect.

Result

Double-click the copy text layer to apply the following Layer Style:

Step 3

  • Technique: Chisel Hard
  • Direction: Down
  • Size: 70
  • Check the Anti-aliased box
  • Shadow Mode – Opacity: 100%
Bevel and Emboss

Step 4

  • Contour : Log
  • Check the Anti-aliased box.
Contour

Step 5

This will help define the inner text shape.

Result

5. Create the Outer Edges’ Brush and Stroking the Text

Step 1

Right-click any of the text layers and choose Create Work Path. Create a new layer on top of all layers, call it 1, and pick the Brush Tool.

Work Path

Step 2

Open the Brush panel (Window > Brush), choose a hard round brush tip, and modify its Settings as shown below:

Brush Tip Shape

Brush Tip Shape

Step 3

Shape Dynamics

Shape Dynamics

Step 4

Pick the Direct Selection Tool (A), right-click the path, and choose Stroke Path.

Choose Brush from the Tool drop down menu, and click OK. Then hit Enter/Return to get rid of the work path.

Stroke the Work Path

6. Modify the Edges’ Stroke

Step 1

Command-click the stroke layer (layer 1)’s thumbnail to create a selection.

Create a Selection

Step 2

Go to Select > Modify > Contract, and type in 3.

Modify the Selection

Step 3

Go to Select > Modify > Feather, and type in 2.

Modify the Selection

Step 4

Make the stroke layer invisible by clicking the eye icon next to it, then select the Background copy layer.

Modify the Selection

Step 5

Press Command-J to duplicate the selection into a new layer. It will be called Layer 1 by default. Drag Layer 1 on top of all layers.

Modify the Stroke

7. Style the Modified Stroke

Double-click Layer 1 to apply the following Layer Style:

Step 1

  • Check the Anti-aliased box
  • Highlight Mode: Soft Light
  • Color: #ffe1ba
  • Shadow Mode: Linear Burn
  • Color: #d0c1ab
Bevel and Emboss

Step 2

Use the default Contour values.

Contour

Step 3

  • Pattern : Spiky Bush
Pattern

Step 4

This will style the stroke.

Result

8. Create the Transition Area

Step 1

To help blend the stroke with the sand texture more seamlessly, we’re going to add a transition area that feathers out to make the effect look more natural, so create a selection based on layer 1 again.

Create a Selection

Step 2

Go to Select > Modify > Expand, and type in 7.

Modify the Selection

Step 3

Go to Select > Modify > Feather, and type in 5.

Modify the Selection

Step 4

Command-Shift-click a text layer’s thumbnail to add it to the selection you have, so that the selection doesn’t have any empty areas inside.

Modify the Selection

Step 5

Select the original Background layer, then press Command-J to duplicate the selection in a new layer. That layer will be called Layer 2. Drag it on top of both Background layers and right below the original text layer.

Modify the Transition Area

Step 6

Double-click Layer 2 to apply a Drop Shadow effect using the values below:

  • Blend Mode: Linear Burn
  • Color: #e8e3dc
  • Uncheck the Use Global Light box
  • Angle: 139
  • Distance: 19
  • Size: 18
Drop Shadow

Step 7

You can see how this is starting to blend in more nicely.

Result

9 Create the Raised Sand’s Stroke

Step 1

Pick the Brush Tool and open the Brush panel again. With the hard round tip still selected, modify the Settings as shown below:

Brush Tip Shape

Brush Tip Shape

Step 2

Shape Dynamics

Shape Dynamics

Step 3

Scattering

Scattering

Step 4

Right-click a text layer and choose Create Work Path, create a new layer below the original text layer and call it Stroke Shadow, pick the Direct Selection Tool, and set the Foreground color to #404040.

Create the Work Path

Step 5

Stroke the path just like you did before, and don’t forget to get rid of the work path afterwards.

Stroke the Work Path

10. Modify and Style the Raised Sand’s Stroke

Step 1

Command-click the Stroke Shadow layer’s thumbnail to create a selection.

Create Selection

Step 2

Select the Background copy layer, press Command-J, rename the duplicated layer to Stroke, then drag it on top of the Stroke Shadow layer.

Duplicate the Selected Area

Step 3

Right click Layer 1, choose Copy Layer Style, then right-click the Stroke layer, and choose Paste Layer Style to style the raised sand stroke.

Apply Layer Style

11. Modify the Raised Sand’s Shadow

Step 1

Select the Stroke Shadow layer, then go to Filter > Blur > Motion Blur. Change the Angle to -30 and the Distance to 20.

Motion Blur

Step 2

Change the Stroke Shadow layer’s Blend Mode to Linear Light, then, using the Move Tool (V), click-drag the shadow to place it so that it extends diagonally away from the sand.

Modify the Stroke Shadow

Step 3

Command-click a text layer’s thumbnail to create a selection, make sure that the Stroke Shadow layer is still the active one, then hit Delete to get rid of the shadow’s inner parts. Go to Select > Deselect when done.

Modify the Stroke Shadow

12. Add the Starfish

Step 1

Open the Red Seastar Isolated On White Background image, use the Magic Wand Tool to select the white area around it, and invert the selection by going to Select > Inverse. Then go to Edit > Copy to copy the selected star.

Select the Starfish

Step 2

Back to the original document, go to Edit > Paste, and place the starfish’s layer on top of all layers. go to Image > Adjustments > Hue/Saturation, and change the Saturation to -15 to tone the color vibrancy down a bit.

Adjust the HueSaturation

Step 3

Double click the starfish’s layer to apply the following Layer Style:

  • Opacity: 35%
  • Uncheck the Use Global Light box
  • Angle: -30
Inner Shadow

Step 4

  • Blend Mode: Multiply
  • Opacity: 55%
  • Color: #d8d2ca
  • Size: 16
Outer Glow

Step 5

  • Blend Mode: Linear Light
  • Color: #404040
  • Uncheck the Use Global Light box
  • Angle: 138
  • Noise: 20
Drop Shadow

Step 6

This will add a simple shadow to the starfish.

Result

Step 7

What you’ll need to do next, is use the same brush modified in Step 8 to manually add some sand to the starfish’s edges, then follow the Steps 9-1 to 10-2 to modify and style the stroke and its shadow. And finally, Command-click the starfish layer’s thumbnail to create a selection, select the starfish stroke shadow layer, and hit Delete to get rid of the shadow inside it.

Adding the Sand to the Starfish

13. Adjust the Colors

Step 1

Click the Create new fill or adjustment layer icon down the Layers panel and choose Curves.

Curves

Step 2

Adjust the curves as shown below. You can also click the little hand with arrows icon then click and drag in the image to modify the brightness as you like.

Curves

Step 3

Click the Create new fill or adjustment layer icon again and choose Solid Color.

Solid Color

Step 4

Use the color #b1a99c, change the layer’s Blend Mode to Color Burn and its Opacity to 20%.

Solid Color

14. Add the Foam

Step 1

Place the WaterFoam0018 image on top of all layers and change its Blend Mode to Screen, then go to Image > Adjustments > Desaturate. Move the foam downwards as needed, then, you can pick the Eraser Tool (E) with a soft round tip, and remove any parts you don’t like.

Adding the Foam

Step 2

Create a new layer below the foam layer and call it Water. Pick the Lasso Selection Tool then draw a selection following the foam’s edges, leaving some distance away from it. Fill that selection with the color #b2b3ad.

Adding the Foam

Step 3

Go to Select > Deselect. Change the Water layer’s Blend Mode to Multiply and its Opacity to 20%.

Adding the Foam

Step 4

Go to Filter > Blur > Gaussian Blur, and change the Radius to 5.

Gaussian Blur

Step 5

Duplicate the Water layer, then change the copy’s Opacity to 15. Drag the copy down some more to create a darker layer in between the Water layer and the foam layer.

Adding the Foam

15. Apply the Lighting Filter

Step 1

Select all layers except for the foam and Water layers, duplicate them, then go to Layer > Merge Layers. Rename the merged layer to Final.

Lighting Effects

Step 2

Go to Filter > Render > Lighting, choose the Spot light, then move and scale it around as you like.

Lighting Effects

Step 3

Change the rest of the settings as shown below. The colors used in RGB are:

  • Color: 246, 242, 234
  • Colorize: 247, 240, 223
Lighting Effects

Step 4

The brush tip will give you a different result each time you use it. So you can always try it a couple of times until you get a result you like if needed.

Getting Different Stroke Outcomes

Congratulations! You’re Done.

In this tutorial, a sand texture background was modified, and the text was created and styled to add the inner shadow and some depth.

Then, a couple of brushes were modified to create a couple of stroke layers to achieve the outer sand and raised sand parts, as well as a simple transition stroke to help blend the text with the sand nicely. All created layers were styled and modified to create the sand-like appearance and add the shadows.

A simple starfish was then added to the scene using the same techniques to blend it in, and a couple of adjustment layers were added to enhance the coloring and the brightness of the final outcome.

The foam was then added as well, and the rest of the layers were merged to apply a lighting filter to get the final result.

Hope you enjoyed the tutorial and found the tips and tricks used helpful. Please feel free to leave your comments below, and share your outcome with us.

Download How to Write in the Sand in Adobe Photoshop

Quick Tip: Fewer Nodes = Lighter SVG

Recently I found myself playing about on the snap.svg site (take a look if you haven’t used it yourself yet). It has a really nice SVG polygon background on the header, which weighs in at a meagre 2.2Kb. Because I’m weird, I decided to try and make it smaller.

In Illustrator

The SVG file itself looks like this when opened up in Illustrator:

Then if you check the outline view (View > Outline) you see all the vector paths laid out without fill colours:

“What a mess!” I thought “I’m sure I can tidy that up and reduce the file size.” So I went about cleaning up the lines to remove all the unnecessary over-lapping. 

Puzzling

With the Pathfinder tool you can use objects to “cookie cut” their form from objects underneath. In this way you can avoid having any shapes over-lapping, instead creating a more “jigsaw puzzle” effect.

from this
From this..
to this
..to this

Much better. Once I’d done the same with the whole illustration, I was looking at this:

I Was Wrong

In doing this, the file size didn’t shrink, it grew. Whereas the original weighed 2.217Kb, the new version weighed 2.269Kb. A tiny difference in real terms, but “tidying” things up had nevertheless made the file heavier. On a larger graphic the effect could have made a big difference.

But why? It’s all down to nodes, or anchors; the joints along a vector path. SVG files are nothing but XML data, and each node along a path requires additional coordinates. The original file may have been built from a bunch of over-lapping triangles, but layering doesn’t cost file size at all (any objects within an XML document are inherently displayed in order). What created the extra size was my having made quadrilateral (four-sided) polygons from the triangles. Oops.

Here’s how they look as SVG code, first one of the originals:

<polygon fill="#46CEB4" points="1434.5,-21.75 1644.5,-21.75 1524.5,158.25 "/>

And now one of my “improved” shapes:

<polygon fill="#97E8DA" points="1584.5,258.2 1744.5,228.2 1745,228.2 1634.5,88.2 1550.2,256.8 "/>

More data. Simple as that.

Clean Your Nodes

The take away lesson from this is to remove any unwanted nodes from your SVG files, but don’t worry about overlapping. Shedding nodes is the number one way of reducing complexity and thereby file size.

Use the Delete Anchor Point tool (-) to remove an anchor from a path. You’ll be surprised how few anchors a vector path needs whilst still retaining its form! One well-placed anchor will do the job of three poorly thought out ones.

Stray Points

One final tip is to remove stray points from your SVG. Stray points are often invisible because they can’t be filled, but they’ll cost you data all the same. In Illustrator, go to Select > Object > Stray Points to select them all, then hit delete to remove them.

Pesky stray anchor points

I hope you learned something from this! It’s one of those seemingly obvious things which I’d just never thought about before. Had you?

Download Quick Tip: Fewer Nodes = Lighter SVG

The Snowball Effect (and How to Avoid It) in Game Design

We play games to have fun. Most (but not all) games use some sort of competition to drive this fun: from chess to Street Fighter, players enjoy pitting their skills against each other.

A competitive game without real competition isn’t fun. If I go up against a chess grand master, or a Street Fighter pro player, I will be obliterated. Short of my opponent being seized by temporary insanity, the likelihood of me winning is approximately zero. There’s no competition; it’s not fun for me.

So why isn’t it fun for me to play against them? Because I know I’m going to lose. This burden of knowledge removes any enjoyment I can get from the game. Unfortunately, this “inevitable defeat” situation is common throughout gaming, even outside of skill mismatches. If we’re playing Monopoly and I complete two streets (with hotels) while everyone else is squabbling over railroads, then my victory is virtually guaranteed—I can afford to sit back and wait for everyone else to slowly lose everything they have.

The main reason for my inevitable Monopoly victory is the snowball effect. Once I’ve gained some advantage, then that advantage continues to grow—like a snowball rolling down a mountain, picking up more snow, growing bigger and bigger. When players land on my properties, I gain more money (which I can use to buy more properties) and they lose money (giving them fewer options); it’s a situation which can be very hard to recover from.

Similarly, in Risk, once you’ve safely captured a few continents, your extra troop income will make you you incredibly difficult to defeat.

When Do We Snowball?

Snowballing exists in nearly any game where resources give you more resources. Or, to put it in a simple form: wherever you can use money to buy stuff which gives you more money (or minerals, gold pieces, wood, or any in-game forms of currency).

In games like Monopoly or Civilisation, there’s an obvious correlation between acquisitions and power. You have cities; you have more money to build more cities. In most RTS games, you build workers to mine gold to build more workers to mine more gold. And Farmville uses snowballing as a central tenet of its design: you buy crops to make money to buy better crops to make more money to buy better crops…

Snowballing can be especially brutal in games like Quake or Unreal Tournament. When a player dies, they respawn with nothing, while the victor keeps their weapons, their armour, and any bonuses they picked up. In 1v1 matches, its fairly common to see an endgame score of 15-3, even for a “close” game.

Some games don’t allow you to buy resources, but do allow you to remove enemy resources. In chess, you do this by “taking” enemy pieces—every pawn killed removes options for your enemy and reduces their overall board presence.

And some games have resources which are not relative to your position in the game. In Street Fighter or Pong, it generally doesn’t matter how badly you’re doing; as long as the game isn’t over, you can pull it back.  Because there is no feedback loop, these games don’t really suffer from snowballing, so we won’t discuss them further. 

Although the game starts off slowly at 2-2, dkt takes a strong early lead of 15-2 before he dies and ends up losing 19-16 to ZeRo4.

Why Do We Care?

So why do we even care about snowballing? Because for many games, it’s simply not fun. As I said earlier, when the end result of a game has been established, the game stops being fun for the loser (and maybe even the winner). 

If the inevitable losing player can concede with grace, then that’s fine—but sometimes, conceding gracefully isn’t possible. When you’re playing a multiplayer game, then one player leaving can radically alter the game state. In turn-based games, the next player to go may be able to snatch up the absent player’s resources, causing an unpredictable and massive power swing. Similarly, if a player leaves during a 5v5 game, then the resulting 4v5 may simply be too unbalanced, infuriating the former team-mates of the absent player.

A good game should be competitive throughout. The chess term endgame can be used to describe the final state of a game in which all that remains is to finalise the victory or defeat. An endgame state isn’t harmful, as long as the players are able to finish up in a respectable amount of time.

An Important Caveat

So, we need to add a caveat: snowballing isn’t necessarily bad, as long as the game ends once a victor becomes apparent. In other words: a game is no longer fun when a player becomes unable to influence the end result.

This point is vital, not just to “snowballing”, but also to general game design. A player should always be able to win. If a player can’t win, then the game is over, and forcing people to play out a defeat is punishing and unfun in a serious way.

Its worth noting, though, that snowballing isn’t all bad. For the victor, it can feel great: attaining god-like status, crushing all those beneath you, and generally laying waste to everything in your path. And achieving “perfection” in a game is often a goal of players outside of simply winning. For single player games, this is fine: AIs don’t get bored and rage-quit. When playing against humans, though, we need to be more discerning.

Snowballing in Competitive Play: A Look at the Data shows some interesting statistics regarding the percentage of winrates by objective in League of Legends. Note that a simple objective, such as achieving the first kill of the game (first blood), gives the team a 61 to 79% chance of winning the game overall.

So how do we deal with the problems that come with snowballing? Let’s look at some possible fixes.

Fix: Resource Management

One option is to make resources “bad”, so that the player wants to get rid of them. It might seem strange, but this is already present in games like billiards: having balls on the table is a bad thing. This is an excellent balancing mechanic, as the more balls you pot, the fewer options and shots you have available to you.

Counter-Strike had an interesting “gun game” mod, a variant of which also contained a self-balancing mechanic. Players start with one of the best weapons (often the sniper rifle), and killing other players would downgrade their weapon, to a rifle and then a pistol. After a certain number of kills, the player is left with just a knife—if they can score a kill with that, then they win.

Arsenal, Valve’s “official” gun game variant, and its self-balancing mechanic.

Although using a reduction mechanic might feel counter-intuitive, there’s no reason it can’t be cleverly worked into a game. Imagine if, in Monopoly, the goal wasn’t to become the richest, but to become the poorest; players would be assigned properties and houses at the start of the game, and through careful trading would have to get rid of all their acquisitions. 

Fix: Punishment

Its also possible to add certain “winner-punishment” mechanics. Mario Kart has the infamous blue shell weapon, a turbo-powered missile that homes in on the player that’s in the lead and stuns them upon collision. It’s nearly impossible to avoid, and is incredibly damaging for a player to be hit by one. Because of this, many good players will deliberately avoid taking too much of a lead, so if a blue shell appears they can drop back to second place and let someone else take the hit.

At face value, this seems like an excellent system; it encourages players to stick together, which means that the game is a constant struggle, rather than one player taking an early lead and zooming off to victory. However, as many Mario Kart players will attest, blue shells feel unfair. There’s very little you can do to predict the arrival of a blue shell, and, as we’ve talked about before, randomly punishing players often has a very negative effect on “fun”. 

On top of this, Mario Kart is a racing game, so it seems counter-intuitive to punish players for racing well. While “Gun Game” hinders any player that gains an advantage, Mario Kart is an unpredictable, specific punishment against a single player. If that player finds themselves on the receiving end of two or three blue shells, they may begin to feel victimised.  

On rare occasions, you may see a skilful or lucky player dodge a blue shell.

Of course, that’s not to say that winner punishment mechanics are necessarily bad, but it’s preferable to apply them with a light touch, rather than making them feel like targeted punishment. For example, some racing games will put previous race winners to the back of the starting line-up. This gives them a little further to race and prevents them from taking an easy lead, but generally won’t feel like specifically singling that player out—after all, someone has to start at the back. 

Now, it may seem obvious that players dislike being punished and like being rewarded. This isn’t particularly noteworthy, but what makes it interesting is that we can sometimes change punishment into reward with simple rewording.

In early builds of World of Warcraft, there was an experience penalty for players who played too long. After a certain amount of time, players would find their experience progression halved, putting casual gamers on slightly more equal footing with players who could spend their whole day playing. Players, of course, hated it. 

To fix this, the designers simply halved the normal experience progression rate, and gave players a “rest bonus”: spending time out of game would net them double experience for a certain amount of time. Of course, this is exactly the same mechanic as before, but rather than it being a punishment for playing, it was a reward for not playing. And players loved it.

Simple renaming might not work for all cases, but its worth examining how players perceive these aspects of your game. If something is frustrating, then try to understand why players dislike it, and see if a minor change can make a difference.

Fix: Rubber Banding

Rubber banding means giving losing players a bonus or boost of some sort. Much like how a rubber band stretches and pulls, a rubber banding mechanic will pull players towards the current game leader. The further behind you are, the stronger the pull.

Rubber banding only really works in games when one player is clearly in the lead. In a strategic game like chess, simply counting the pieces on each side isn’t enough to determine this: positioning and the ability to dictate the game matter immensely. But for most games, being able to determine a winner is often as simple as checking lives or gold.

Mario Kart famously uses a rubber banding system which gives players bonuses when they fall behind. Players at the end of the track can expect to pick up items like the Bullet Bill, which will often shoot them into third or fourth place with no effort required. Players leading the race can expect to find green shells and banana peels, which are considerably less advantageous. Additionally, CPU racers will automatically speed up when the player shoots ahead, and slow down when the player lags behind.

The Bullet Bill power-up in action.

League of Legends uses a reward system that emulates rubber banding. Killing enemy players is worth gold—which then makes it easier to kill enemy players. To mitigate this, players that die constantly are worth less gold each time they die, which helps ensure that one bad player on a team does not completely determine the outcome of the match. At the same time, players that do exceptionally well, earning killing sprees, find their bounty increased, so when a player does manage to take them down, they may find they’ve earned nearly double the normal reward. 

Implementing rubber banding depends on what you’re aiming to achieve. For some games, basic rubber banding might feel cheap, and a more complicated method may be required. For casual games or minor game elements, a simple damage boost or resource bonus may be sufficient. Its important, however, that these bonus are used to help the player claw themselves back into the game, and not something the player can rely on for sudden victories.

Fix: Reset the Board

Points systems are another way to “reset” the playing field, and stop snowballing. Super Smash Bros has an interesting snowball mechanic: the more hits you take, the longer you are incapacitated for.  A “smash” move on a healthy player might stun them for a fraction of a second, whereas “smashing” a seriously damaged player will stun them for much longer, giving their opponent time to collect items or line up a secondary attack. The result of this is that a damaged player will find it harder and harder to defend themselves, until they die.

Mario smashes Bowser, showing the increased effect of damage.

Dying, though, completely resets your damage counter. Upon death, you are placed back on the field of battle (after losing a life) and—assuming you previously managed to get a few hits in—you now have the advantage as your opponent will still be damaged. When similarly matched players fight, they might end a game with a score of 5 to 4; without the damage reset, then a score of 5-0 would be much more likely.

Counter-Strike has a similar reset mechanic: rounds will last a set amount of time, and then be reset. This allows players to recover from expired weapons, low health, death, and poor positioning. Although a minor form of snowballing exists in the form of cash, an abundance of money does not automatically confer an advantage, as the best weapons are not necessarily the most expensive. A hard cap on the amount of money carried also helps to mitigate this.

Fix: Game Over

Of course, you can simply end the game early. If the game never enters a state where it becomes “unfair”, then no issues will occur. In chess, the game ends when the enemy king is checkmated. You don’t have to take every enemy piece, or achieve a certain amount of points: you simply move towards a single goal (checkmate), and you win. 

The Civilisation series of games may be, at their core, a war game, but players are able to achieve victory through a variety of means. If you choose not to crush all your opponents, then winning the space race or convincing other players to elect you as their leader are valid options for technological or diplomatic victories.

Finally, it’s worth noting that it’s not always necessary to include balancing effects. Sometimes, you can just let a player concede. This is fairly easy for 1v1 games, and its common to see chess players concede once they find themselves in an unwinnable position. But for multiplayer games, it can be harder to let players exit gracefully. This is often one of the problems that team games face—MOBAs, such as League of Legends, are notorious for poor sportsmanship. While it’s not fair to blame a game’s design for poor player behaviour, when players face punishment for leaving games (such as temporary bans), it can exacerbate a problem which already exists.

Letting a player leave a game in progress can lead to further difficulties, though. If you keep them in the game, then how do you control them in a sensible way? If you remove them entirely, then can someone else come in and take the items or settlements they leave behind? You can replace them with an AI player, but will the AI act appropriately? You might be able to replace them with another player, but what if the original player comes back from a network disconnection? There is, sadly, no perfect way to deal with losing a player mid-game; there’s only a “least bad” option, the nature of which will vary wildly with the type of game you’re making.

Conclusion

Remember, people play games to have fun. No-one enjoys losing, and if you force someone to play an unwinnable game, then they’ll end up frustrated and angry. If you end the game properly then while the player might not be happy about losing, they’ll hopefully be more willing to play again. 

Adding these solutions is not a magic bullet to make your game perfect, and poor implementation can cause problems of their own. When done well, players will be engaged by the constant challenge provided. When done poorly, players will feel cheated by others gaining sudden boosts, or an AI that cheats itself to victory. At the end of the day, snowball mitigation is another aspect of game design, and we need to consider how best to implement it.

References

Download The Snowball Effect (and How to Avoid It) in Game Design

Help Me Switch to a Mac

For the last three and a half years, I’ve used a Windows-based PC for my work, but now that I’m starting a new gig, I’m switching to a brand spanking new MacBook Pro. The thing is that I haven’t used OS X regularly since 2010 so I’m going to need some recommendations and help to get my new computer setup for web development.

I have a bit of an idea of some of the software I’ll use, but I know that I’ll be missing some cool and modern stuff and thought it would be a great idea to ask the Tuts+ audience for some help. 

Specifically, I’ll list out the stuff I’ll be working on and what I will likely use for said task, and I’m hoping you guys can help me fill in the blanks.


What I’ll Work On

Like many of you, I focus on building for the web. I live in my text editor and need to stay on top of the latest and greatest tools. My primary focus is client-side development, especially single-page app development using frameworks like Ember.js. But I’ve recently set a new goal to shift back to the server-side and will be taking a serious look at both Ruby on Rails and Node.js as my goto server technologies. I’ll also be working on mobile web development as well as Cordova-based hybrid mobile apps.

I’ll also be doing a lot of outbound communication in my role as a developer advocate. That means using social media, speaking at conferences, writing blog posts, and talking extensively with developers both online and offline. Twitter, IM, IRC and other communication mediums are a top priority on my list of tools.

And of course, I’ll be here at Tuts+ writing tutorials, helping the community, working and communicating with authors, and trying to set the tone for the site. So tools that help my writing workflow and help make writing in Markdown easier are essential.

Note that I’m okay with spending money on software that will make things easier, and that will increase my productivity, so please feel free to recommend premium applications just as much as paid applications.


Tools I Know I’ll Use

Thankfully, there are a lot of cross-platform tools out there and in chatting with some buddies, I’ve got a short list of things I know I’ll be using from day one:


Development

Editor: Sublime Text Editor

When I used to own a MacBook, TextMate ruled the roost but since then Sublime has taken the throne. It’s been my goto editor on Windows so I’m pretty excited that I can carry that over to OS X.

HTTP Sniffer: Charles Debugging Proxy

This is a really tough one for me because I absolutely love Fiddler by Eric Lawrence. It’s not a knock at Charles (which I think is a great app) but Fiddler just had more features to it. Unfortunately, Fiddler is Windows-only for the moment. Charles is an excellent alternative.

Virtualization: VMWare Fusion

I’ve advocated for cross-browser development so just because I’ll be using a Mac doesn’t mean I get to neglect Internet Explorer. I’ve previously used VMWare Fusion with success and, looking at the comparative reviews, it seems it’s still the top dog on OS X. Let me know if I’m wrong.

Command-Line: iTerm 2

Since I’ll be living on the command-line now, I figured I should get a feature-rich terminal client that I can tweak to my liking. iTerm 2 seems to be the best option for this.

Package Manager: Homebrew

I’m still floored that something like this doesn’t come standard on Windows and OS X. Seriously, I used it for a little bit on a borrowed MacBook and it’s great. I couldn’t believe how easy it made installing and managing third-party packages.

Git: Tower

Fournova Software was having a great sale on Tower recently and since I knew I was shifting to OS X, I picked up a license. It’s supposed to be one of the best visual Git interfaces around. Yeah, I can do Git via the command-line, but old habits die hard.

FTP: Transmit

I still use FTP and Transmit is still the best client I’ve found. Plus, Panic still have such a great eye for user interfaces, so the app is gorgeous to boot.

Web Server: MAMP Pro

I know OS X comes with Apache built-in but I really do love the isolated nature of MAMP and the pro version’s ability to let me define virtual hosts. I won’t be doing any PHP development but having a easily-accessible web server is incredibly useful.


Productivity

Office Suite: Office for Mac 2011

Microsoft’s Office suite is ubiquitous and the company I’m heading to uses it extensively so I’ll definitely need this.

General Productivity: Alfred

Looks like when QuickSilver met its end, it left a pretty big hole which Alfred seems to fill nicely. Having seen it in action, I can see where it would be incredibly useful. We happen to have an extensive tutorial on how web developers can leverage it for their productivity.


Communication

Instant Messaging: Adium

I’m really glad to see that Adium is alive and well. I remember using it and it was a solid instant messaging app with support for a variety of chat protocols.

IRC: Colloquy

Again, an old favorite. I’ve looked at other IRC clients like LimeChat and can’t seem to get into the flow of it. Colloquy just feels right and it’s probably because the UI reminds me a tad of HexChat.

Video Chat: Skype

This is a must-have nowadays since everyone uses it for video chat.

Screencasts: ScreenFlow

I used TechSmith’s Camtasia extensively on Windows but ScreenFlow offers equally great screencasting features at a lower price. Plus they’ve been focused on OS X forever.


Miscellaneous

Cloud Storage: Dropbox and Box

Dropbox is an obvious choice. Everyone I know uses it because it works very well. I’ve also become a fan of Box and use it as much as Dropbox. Plus I got 50GB of storage available so it’s great to have multiple options.

Video Playback: VLC

I really haven’t found a better open-source media player than VLC. Cross-platform, easy to setup and supports a ton of codecs. It’s near perfect in my opinion.

Password Management: LastPass

I’ve been pretty happy with LastPass but their recent 3.0 release has left me a little underwhelmed. I’ll stick with them for now but will definitely check out 1Password now that I’m back on OS X. What is your experience with the former and the latter?

Window Management: Divvy

One thing I love about Windows is the ability to tile equally-sized open windows side-by-side by pressing Window key + left or right arrow. OS X doesn’t offer that but Divvy does.


Tools Under Consideration

Now that you’ve seen some of the tools I’ll be using, let me list some of the ones that I’m still considering:


CodeKit

Seems like it automates a lot of the tedious tasks of your development workflow and it gets mentioned a ton by developers.

LiveReload

I see the benefit of it but it seems that if I got CodeKit, I get the same functionality and then some.

Path Finder or TotalFinder

When I had my previous MacBook, I remember that Finder sucked and I purchased Path Finder to replace it. TotalFinder also came up as a good alternative. Should I replace Finder or has Apple improved it enough to make it usable?

TotalSpaces2

I read somewhere that removed Spaces from Mountain Lion and a lot of people felt it was a negative impact on their productivity. Seems like TotalSpaces2 aims to fill that void. Is it worth it?

Snippets

Quick access to common code snippets seems like a good idea.

Hammer for Mac

I may be off but I see overlap between CodeKit and Hammer.


Recommendations Needed

Alright, I could scour the Internet for days but I’m hoping you guys will save me some time. Here are some of the things I need recommendations for:

  • A good screen capture program
  • A markdown editor
  • Something with which to create mockups
  • Some type of task management software (is Things still awesome?)
  • Something for managing databases
  • Apps that make using social media easier

Thanks in Advance!

As you can see, I’ll be a bit of an OS X newbie for awhile so every bit of advice helps. What I plan on doing is using your feedback to get myself setup, and then follow this post up with a comprehensive roundup of the tools you’ve recommended and I’ve begun to use. 

Hopefully, this will help make this type of transition easier for developers as they shift between platforms.

Download Help Me Switch to a Mac

Bad Game + Bad Game = Good Learning Experience

What You’ll Be Creating

For my One Game a Month projects, I
have chosen to undertake a unique challenge. Every other month I choose
one “bad” video game and remake it into something playable and
hopefully even entertaining.

For May, I decided to remake the NES classic Hyldide, and combine it with its official remake, Virtual
Hydlide. Together, they would create Virtually Super Hydlide Special!

While Hydlide is considered a
groundbreaking classic in Japan, its late American release made
it a laughing stock prime for AVGN. Virtual Hydlide, on the other hand, was pretty much universally panned. At best, it was a poorly
implemented game with some good ideas.

Combining a game that half the world
hates with a game the whole world hates… What could possibly go
wrong?

The Plan

One of the biggest issues players have
with Hydlide is the combat system. Long before Zelda’s exciting blend
of action and exploration, Hydlide was all about walking into
things.

No, I’m not kidding.

To attack an enemy in Hydlide, you walk
into him. You and the enemy each trade blows every time you step onto
his tile or vice-versa. The deepest strategy you can apply is to hold the A
button to enter Attack Mode. While in Attack Mode, the player
inflicts more damage, but also suffers more. If it looks like you
might lose the battle, you can just move away and wait for your HP to
recover.

Fortunately, we have a genre of games
that is beloved despite its similar lack of gameplay: the MMO. 

In
classic MMO format, the player chooses a target enemy and trades blows automatically, until either the player dies or the enemy dies. This was actually the core concept I used when I started this remake, because it solved many issues:

  • If I made this first person, I wouldn’t need custom attack animations and could tie into the Virtual Hydlide style of gameplay.
  • Because MMO combat-style trading of blows is so similar to the old style, I could keep the stats exactly the same and maintain the original balance.
  • I could even keep the Attack Mode and Defense Mode distinction, and have it function the same.

The other major advantage is that I’d been working on a 3D sprite engine the previous month, and this would allow me to use the original NES sprites in a 3D
world!

Note: The gameplay images in this article use custom sprites to avoid copyright issues. Virtually Super Hydlide Special uses the original NES sprites.

Finally, the sprite engine allowed me
to import maps from a directly from a bitmap. In order to create my
game’s maps, all I needed to do was trace the original maps with
solid colors and shrink the image to a reasonable size. The engine
does the rest.

The actual wold map loaded in
The actual world map my game loads in

Looking back, it really was actually a
pretty good plan. But, you know what they say about the best laid plans…

What Went Horribly Wrong

I Vastly Overestimated My Engine

I’d built my engine for
old-school dungeon crawls. The largest map that I had built was about
30×30. The smallest I could make Hydlide’s world map while keeping
that expansive feel was 83×83. 

At almost triple the tested size, this lead to a long loading
sequence. This is problematic, because the dungeons are not large and
you’ll be loading the world map often. I ended up spending a few days
implementing a streaming map, only to cut the feature later because I
realized the loading screens were a good way to give the player information they needed.

The days I spent making the map stream
were wasted. If I had taken the time to think about things prior to attempting to work through the problem, I’d have saved time and
stress.

The other set of issues came from
modifying the engine to use a looping map. The tiles that I used were very
small and I needed to draw a lot of these to fill a reasonable draw
distance. This lead to visible slowdown as the map tiles looped around.

My solution? I loaded more tiles!

During the loading screen, I loaded
about twice the tiles that I needed to fill the draw distance. This
means that, as you walk, the map is already fully loaded and in
place, but tiles in the distance are loading in real time.

At this point, I modified the system
to load only a few tiles each frame. To the player, it looks like the
map is streaming around seamlessly, but beyond the camera there are
holes in the world where it’s actually being built a little bit at a time.

Overall, the engine worked, but it sure as heck wasn’t as smooth as I had intended. I had wanted my core gameplay to be implemented by Day Seven, but didn’t actually finish until almost a week later.

I Underestimated the Conversion to 3D

Because I put so much time into making the world map work, I didn’t foresee this second major issue until I was well into the project. I have enough experience that I should have seen it coming a mile away.

The dungeons in the original Hydlide are mazes: The Original Dungeon Maps

It was forgivable in the original game, because a bird’s eye view allows you to see the correct paths. But, as a first person game, directly using the dungeons’ maps as I had planned would make things frustrating.

I couldn’t import the levels as I’d planned, and so I needed to hand-make new ones. While creating short and functional maps was not a major problem, it was an unplanned expense.

I Was Overconfident and This Made Me Stupid

Two months earlier, my previous remake project, Ghostbusters Inc., had been amazing from a work standpoint. Everything fell into place, and I ended up implementing nearly every feature I had hoped for, while still working a reasonable schedule.

My last #1GAM project had gone extremely smoothly as well. I completely designed and implemented Tactical Strike Micro in a week. It had used the same engine as Hydlide, and everything worked out well.

I went into this month with good projects on the brain, and I ignored one of my most important tools: planning!

I’m usually a fanatic about taking the time to write down a schedule, plan features and dependencies, and correctly prioritize everything. I’ve seen and often taken part in the stupidity that comes from “winging it”.

On the 13th>, I was still implementing core gameplay features that should have been either implemented or cut by now. Stress was beginning to get to me, and I could feel the developer tunnel vision coming over me. I was working hard, despite having lost sight of the big picture.

Honestly, I wasn’t sure I’d finish on time. Half a month on a small project seems like a long time, but there was a lot that needed to be done, and it wasn’t going well.

I often warn people about the dangers of blind passion, yet this project was a fine reminder that I’m not above it.

The Good

I Didn’t Panic

I’ve worked with myself enough to know that this is an accomplishment. When things go south I usually enter a purely reactive emotional state—highly effective, but misguided. But I didn’t do that here.

On the 13th, I realized that I was in trouble, and I stepped back to review my process. It didn’t take long to see that I was so focused on controlling the steering wheel that I wasn’t watching the road. I was fixing issues without any consideration for how they fit into the final product.

I took the entire day of the 14th off from development to outline a proper plan:

  • Dates by which each part should be ready.
  • A prioritized list of features and bug fixes.
  • Questions that I needed to think about, such as “How will I help guide the player without NPCs?” With this list, I knew what to think about when I wasn’t working.

When the plan was ready, I sat down and relaxed for the rest of the evening. I knew that stress had started to affect my thinking and I needed to clear my head.

Starting on the 15th, my productivity skyrocketed. I accomplished more in the next three days than I had in the previous week.

The Style

I was amazed how good the 2D NES sprites looked in the 3D world. All the enemies, dungeon walls, and terrain tiles are straight from the NES game, yet they stand out and make the game look unique. 

While I’ve designed better games over the years, this one seemed to catch people’s eyes. I actually received a lot of positive feedback on the way the game looks.

My Early Assumptions Were Correct

Thankfully, most of my original assumptions were valid. The combat system worked fine and was reasonably balanced, and even with the flaws, the engine did what I needed it to do.

Despite everything that went poorly, the game is fun.

While I did modify the combat system to be more action-oriented and less of a grind, I had a strong start thanks to the links to the original game.

My Dev Network

While this was a solo project that I built on my own, I didn’t actually do it alone. Many of my friends are experienced game developers and they were an immense help.

The combat redesign came after talking to my friend Josh about the MMO-style combat. He expressed concern that it wouldn’t be exciting enough. As the project continued, I realized that he was right, and that I needed to stray from the original vision.

The same goes for other features ,such as the “fairy guide” I implemented after my friend Rob got lost, or the new attack animations I coded upon his observation that I could just rotate the sprites to decent effect. Even Twitter came to my aid, linking me to information I needed to help guide the player wordlessly.

You cannot underestimate the value of having people to talk to, even on solo projects.

My Biggest Takeaway

Paperwork and scheduling are tedious and rarely accurate, but they are still beneficial.

Taking the time to put your plan on paper will force you to examine the project as a whole. As you break it down into specific features, you’ll see which pieces are reliant on one another so that you can tackle them in an effective order. Then, you can stay in the zone between tasks because you don’t need to switch between details thinking and big picture thinking.

The other nifty advantage is that having a list means that you can add to it during development. If you encounter a bug or feature that should be implemented, you have a place to write it down and stay organized.

I thought I could get away with avoiding the tedium, but I was wrong, No matter how experienced I might be, I’m not immune to mistakes. Pre-production is an important step, no matter how good you think you are.

You can play Virtually Super Hydlide Special Online, or follow me on Twitter for more retro remakes.

Download Bad Game + Bad Game = Good Learning Experience

Build a Grid-Based Puzzle Game Like Minesweeper in Unity: Winning

In the final part of this series, we put the finishing touches on our grid-based Unity puzzle game, and make it playable. By the end of this part, the player will be able to win or lose the game.

Now that you’ve completed the previous tutorials, our game can create a field of tiles, and assign mines randomly to them. We also have a nice light-up effect when the player hovers over a tile with the mouse, and it’s possible to place and remove flags.

Internally, each tile also knows about their neighboring tiles, and can already calculate how many mines are nearby.

Uncovering Tiles

We’ve already added the ability to place flags with a right click. Now, let’s add the ability to uncover tiles with a left click.

In the OnMouseOver() function, where we have the click recognition code, we need to recognize a left click. Adapt the function so that it looks like this:

function OnMouseOver()
{
    if(state == "idle")
    {
        renderer.material = materialLightup;
    
        if (Input.GetMouseButtonDown(0))
            UncoverTile();
    
        if (Input.GetMouseButtonDown(1))
            SetFlag();
    }
    else if(state == "flagged")
    {
        renderer.material = materialLightup;
    
        if (Input.GetMouseButtonDown(1))
            SetFlag();
    }
}

When the left mouse button is pressed, the UncoverTile() function will be called. Make sure that you create this function, so that this won’t cause a bug!

function UncoverTile()
{
    if(!isMined)
    {
        state = "uncovered";
        displayText.renderer.enabled = true;
        renderer.material = materialUncovered;
    }
    else
        Explode();
}

For this to work, we need to introduce a new material.

public var materialUncovered: Material;

Create something that has a different color than the basic tiles—so if your basic tiles are blue, you could choose green for the uncovered state. But don’t use red; we’ll need that later to show that we’ve triggered a mine.

When call that function, the following happens: 

  • First, we check whether the tile is actually mined. 
  • If not, we set the state to uncovered, activate the text display that shows us the number of nearby mines, and set the material to the uncovered material. 
  • Afterwards, the tile cannot be clicked again, and also won’t light up again, which means the passive feedback of tiles reacting to the mouse cursor will only happen on tiles we can actually click.

Before we can try this out, we need to make sure that the material isn’t changed when the mouse cursor exits the tile. For this, adapt the OnMouseExit() function like so:

function OnMouseExit()
{
    if(state == "idle" || state == "flagged")
        renderer.material = materialIdle;
}

This way, the color only gets switched back if the tile has not yet been uncovered.

Try it out! You should be able to uncover tiles. If a tile is mined, though, nothing will happen right now.

Making Empty Tiles Uncover Each Other

This will be a bit tricky. In Minesweeper, when you uncover a tile with no mines
next to, it will uncover all the tiles adjacent to it that also have no mines, and the tiles adjacent to them that have no mines, and so on.

Consider this field:

We don’t actually see the numbers or mines, only regular tiles.

When a tile with zero nearby mines is uncovered, all tiles next to it should automatically be uncovered, too. The uncovered tile then uncovers all neighbors.

These newly uncovered tiles will then check their neighbors, too, and, if there are no mines, uncover them as well.

This will ripple through the field until we reach tiles that actually have mines adjacent to them, where it will stop.

This creates the empty areas we can see in Minesweeper.

To make this work, we need two more functions, UncoverAdjacentTiles() and UncoverTileExternal():

private function UncoverAdjacentTiles()
{
    for(var currentTile: Tile in adjacentTiles)
    {
        //uncover all adjacent nodes with 0 adjacent mines
        if(!currentTile.isMined && currentTile.state == "idle" && currentTile.adjacentMines == 0)
            currentTile.UncoverTile();
        
        //uncover all adjacent nodes with more than 1 adjacent mine, then stop uncovering
        else if(!currentTile.isMined && currentTile.state == "idle" && currentTile.adjacentMines > 0)
            currentTile.UncoverTileExternal();
    }
}

public function UncoverTileExternal()
{
    state = "uncovered";
    displayText.renderer.enabled = true;
    renderer.material = materialUncovered;
}

We also need to make this modification to the UncoverTile() function:

function UncoverTile()
{
    if(!isMined)
    {
        state = "uncovered";
        displayText.renderer.enabled = true;
        renderer.material = materialUncovered;
        
        if(adjacentMines == 0)
            UncoverAdjacentTiles();
    }
}

When we uncover a tile, and there are no mines next to it, we call the UncoverAdjacentTiles() function. This then checks each neighboring tile to see whether it has mines or not. too. If there aren’t any, it uncovers this tile as well, and initiates another round of checking. If there are mines nearby, it only uncovers the tile it is currently at.

Now, try it out. To get good chance of an empty field appearing, create a rather large field with a few mines—say, 81 tiles, with nine tiles per row, and 10 mines in total.

You can actually now play this as a game, except that you cannot trigger mines yet. We’ll add that feature next.

Triggering Mines

When we uncover a tile that is mined, the game stops and the player loses. Additionally, all other mined tiles become visible. For this to happen, we need one more material, for the detonated mine tiles:

public var materialDetonated: Material;

I suggest using something red for this.

Also, we need to add two more functions to handle exploding all of the mines:

function Explode()
{
    state = "detonated";
    renderer.material = materialDetonated;
    
    for (var currentTile: Tile in Grid.tilesMined)
        currentTile.ExplodeExternal();
}

function ExplodeExternal()
{
    state = "detonated";
    renderer.material = materialDetonated;
}

We trigger those methods in the UncoverTile() function:

function UncoverTile()
{
    if(!isMined)
    {
        state = "uncovered";
        displayText.renderer.enabled = true;
        renderer.material = materialUncovered;
        
        if(adjacentMines == 0)
            UncoverAdjacentTiles();
    }
    else
        Explode();
}

If a tile is mined, the tile explodes. The Explode() function then sends an “explode” command to all other tiles with mines, revealing them all.

Winning the Game

The game is won once all tiles with mines have been flagged correctly. At this point, all tiles that are not uncovered are uncovered too. So how do we track that?

Let’s start by adding a state variable to the Grid class, so that we can track which part of the game we are currently in (still playing, lost, or won).

static var state: String = "inGame";

While we’re at it, we can also begin to add a simple GUI, so that we can display necessary information on the screen. Unity comes with its own GUI system which we’ll use for this.

function OnGUI()
{
    GUI.Box(Rect(10,10,100,50), state);
}

This will show us which state we are currently in. We’ll call these states inGame, gameOver, and gameWon.

We can also add checks to the Tile, to make sure we can only interact with the tiles while the current game state is inGame.

In the OnMouseOver() and OnMouseExit functions, move all the existing code into an if block that checks whether Grid.state is currently inGame, like so:

function OnMouseOver()
{
    if(Grid.state == "inGame")
    {
        if(state == "idle")
        {
            renderer.material = materialLightup;
            
            if (Input.GetMouseButtonDown(0))
                UncoverTile();
            
            if (Input.GetMouseButtonDown(1))
                SetFlag();
        }
        else if(state == "flagged")
        {
            renderer.material = materialLightup;
        
            if (Input.GetMouseButtonDown(1))
                SetFlag();
        }
    }
}

function OnMouseExit()
{
    if(Grid.state == "inGame")
    {
        if(state == "idle" || state == "flagged")
            renderer.material = materialIdle;
    }
}

There are actually two ways to check whether the game has been won: we can count how many mines have been marked correctly, or we can check whether all tiles that are not mines have been uncovered. For that, we need the following variables; add them to the Grid class:

static var minesMarkedCorrectly: int = 0;
static var tilesUncovered: int = 0;
static var minesRemaining: int = 0;

Don’t forget to set minesRemaining in the Start() function to numberOfMines, and the other variables to 0. The Start() function should now look like this:

function Start()
{
    CreateTiles();
    
    minesRemaining = numberOfMines;
    minesMarkedCorrectly = 0;
    tilesUncovered = 0;
    
    state = "inGame";
}

The last line sets the state for the game. (This will be important when we want to introduce a “restart” function later.)

We then check for our end-game conditions in the Update() function:

function Update()
{
    if(state == "inGame")
    {
        if((minesRemaining == 0 && minesMarkedCorrectly == numberOfMines) || (tilesUncovered == numberOfTiles - numberOfMines))
            FinishGame();
    }
}

We finish the game by setting the state to gameWon, uncovering all remaining tiles, and flagging all remaining mines:

function FinishGame()
{
    state = "gameWon";
    
    //uncovers remaining fields if all nodes have been placed
    for(var currentTile: Tile in tilesAll)     
        if(currentTile.state == "idle" && !currentTile.isMined)
            currentTile.UncoverTileExternal();
    
    //marks remaining mines if all nodes except the mines have been uncovered
    for(var currentTile: Tile in Grid.tilesMined)    
        if(currentTile.state != "flagged")
            currentTile.SetFlag();
}

For all this to actually work, we need to increment the variables that track our progress at the right spots. Adapt the UncoverTile() function to do that:

function UncoverTile()
{
    if(!isMined)
    {
        state = "uncovered";
        displayText.renderer.enabled = true;
        renderer.material = materialUncovered;
        
        Grid.tilesUncovered += 1;
        
        if(adjacentMines == 0)
            UncoverAdjacentTiles();
    }
    else
        Explode();
}

…as well as the UncoverTileExternal() function:

function UncoverTileExternal()
{
    state = "uncovered";
    displayText.renderer.enabled = true;
    renderer.material = materialUncovered;
    Grid.tilesUncovered += 1;
}

We also need to increment and decrement the minesMarkedCorrectly and minesRemaining variables depending on whether a flag has been set:

function SetFlag()
{
    if(state == "idle")
    {
        state = "flagged";
        displayFlag.renderer.enabled = true;
        Grid.minesRemaining -= 1;
        if(isMined)
            Grid.minesMarkedCorrectly += 1;
    }
    else if(state == "flagged")
    {
        state = "idle";
        displayFlag.renderer.enabled = false;
        Grid.minesRemaining += 1;
        if(isMined)
            Grid.minesMarkedCorrectly -= 1;
    }
}

Losing the Game

In the same way, we need to make it possible to lose a game. We accomplish this via the Explode() function within the tile. 

Simply add this line to the Explode() function:

Grid.state = "gameOver";

Once that line is run, the state of the game is switched to gameOver, and the tiles can no longer be interacted with.

Adding a More Functional GUI

We used the Unity GUI a few steps ago to tell the player which game state they’re currently in. Now we’ll extend it to show some actual messages.

The framework for this looks like the following:

function OnGUI()
{
    if(state == "inGame")
    {
    }
    else if(state == "gameOver")
    {
    
    }
    else if(state == "gameWon")
    {
    
    }
}

Depending on the state, different messages get displayed in the GUI. If the game is lost or won, for example, we can display messages saying so:

function OnGUI()
{
    if(state == "inGame")
    {
    }
    else if(state == "gameOver")
    {
        GUI.Box(Rect(10,10,200,50), "You lose");
    }
    else if(state == "gameWon")
    {
        GUI.Box(Rect(10,10,200,50), "You rock!");
    }
}

We can also show the number of mines found so far, or add a button that reloads the level once the game is over:

function OnGUI()
{
    if(state == "inGame")
    {
        GUI.Box(Rect(10,10,200,50), "Mines left: " + minesRemaining);
    }
    else if(state == "gameOver")
    {
        GUI.Box(Rect(10,10,200,50), "You lose");
    
        if(GUI.Button(Rect(10,70,200,50), "Restart"))
            Restart();
    }
    else if(state == "gameWon")
    {
        GUI.Box(Rect(10,10,200,50), "You rock!");
    
        if(GUI.Button(Rect(10,70,200,50), "Restart"))
            Restart();
    }
}

function Restart()
{
    state = "loading";
    Application.LoadLevel(Application.loadedLevel);
}

You can try it all out in this final build!

Conclusion

That’s it! We have created a simple puzzle game with Unity, which you can use as a basis to create your own. I hope you’ve enjoyed this series; please ask any questions you have in the comments!

Download Build a Grid-Based Puzzle Game Like Minesweeper in Unity: Winning

Projectile Physics Engines: Building a Game World

In What’s in a Projectile Physics Engine, we covered the theory and essential elements of physics engines that can be used to simulate projectile effects in games like Angry Birds. Now, we’ll cement that knowledge with a real example. In this tutorial, I’ll break down the code for a simple physics-based game that I’ve written, so you can see exactly how it works.

For those interested, the example code provided throughout this tutorial uses the Sprite Kit API provided for native iOS games. This API uses an Objective-C wrapped Box2D as the physics simulation engine, but the concepts and their application can be used in any 2D physics engine or world.

You can download the source from the GitHub repo.

Building a Game World

Here is the sample game in action:

The overall concept of the game takes the following form:

  1. A structure of platforms with physics bodies are added to the level, building a tower.
  2. One or more objective objects are placed within the tower, each with a physics body assigned to it.
  3. A firing mechanism shoots a projectile body with an momentary impulse; when the projectile’s body collides with the platforms’ bodies, the simulation takes over and computes the results for us.
  4. If a projectile or a platform touches the objective, it fades from the scene, and the player wins! This collision is detected using the physics bodies, so that the simulation maintains its realism at the point of collision.

Our first use of physics will be to create an edge loop body around our screen’s frame. The following is added to an initializer or -(void)loadLevel method:

//create an edge-loop physics body for the screen, basically creating a "bounds"
self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];

This will keep all of our objects within the frame, so that gravity won’t pull our whole game off the screen!

Adding Objects

Let’s look at adding some physics-enabled sprites to our scene. First, we will look at the code for adding three types of platforms. We will use square, rectangular, and triangular platforms to work with in this simulation.

-(void)createPlatformStructures:(NSArray*)platforms {
    
    for (NSDictionary *platform in platforms) {
        //Grab Info From Dictionay and prepare variables
        int type = [platform[@"platformType"] intValue];
        CGPoint position = CGPointFromString(platform[@"platformPosition"]);
        SKSpriteNode *platSprite;
        platSprite.zPosition = 10;
        //Logic to populate level based on the platform type
        if (type == 1) {
            //Square
            platSprite = [SKSpriteNode spriteNodeWithImageNamed:@"SquarePlatform"]; //create sprite
            platSprite.position = position; //position sprite
            platSprite.name = @"Square";
            CGRect physicsBodyRect = platSprite.frame; //build a rectangle variable based on size
            platSprite.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:physicsBodyRect.size]; //build physics body
            platSprite.physicsBody.categoryBitMask = otherMask; //assign a category mask to the physics body
            platSprite.physicsBody.contactTestBitMask = objectiveMask; //create a contact test mask for physics body contact callbacks
            platSprite.physicsBody.usesPreciseCollisionDetection = YES;
            
        } else if (type == 2) {
            //Rectangle
            platSprite = [SKSpriteNode spriteNodeWithImageNamed:@"RectanglePlatform"]; //create sprite
            platSprite.position = position; //position sprite
            platSprite.name = @"Rectangle";
            CGRect physicsBodyRect = platSprite.frame; //build a rectangle variable based on size
            platSprite.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:physicsBodyRect.size]; //build physics body
            platSprite.physicsBody.categoryBitMask = otherMask; //assign a category mask to the physics body
            platSprite.physicsBody.contactTestBitMask = objectiveMask; //create a contact test mask for physics body contact callbacks
            platSprite.physicsBody.usesPreciseCollisionDetection = YES;
            
        } else if (type == 3) {
            //Triangle
            platSprite = [SKSpriteNode spriteNodeWithImageNamed:@"TrianglePlatform"]; //create sprite
            platSprite.position = position; //position sprite
            platSprite.name = @"Triangle";
            
            //Create a mutable path in the shape of a triangle, using the sprite bounds as a guideline
            CGMutablePathRef physicsPath = CGPathCreateMutable();
            CGPathMoveToPoint(physicsPath, nil, -platSprite.size.width/2, -platSprite.size.height/2);
            CGPathAddLineToPoint(physicsPath, nil, platSprite.size.width/2, -platSprite.size.height/2);
            CGPathAddLineToPoint(physicsPath, nil, 0, platSprite.size.height/2);
            CGPathAddLineToPoint(physicsPath, nil, -platSprite.size.width/2, -platSprite.size.height/2);
            
            platSprite.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:physicsPath]; //build physics body
            platSprite.physicsBody.categoryBitMask = otherMask; //assign a category mask to the physics body
            platSprite.physicsBody.contactTestBitMask = objectiveMask; //create a contact test mask for physics body contact callbacks
            platSprite.physicsBody.usesPreciseCollisionDetection = YES;
            CGPathRelease(physicsPath);//release the path now that we are done with it
            
        }
        
        [self addChild:platSprite];
        
    }
    
}

We’ll get to what all the property declarations mean in a bit. For now, focus on the creation of each body. The square and the rectangular platforms each create their bodies in a one line declaration, using the sprite’s bounding box as the body size. The triangle platform’s body requires drawing a path; this also uses the sprite’s bounding box, but calculates a triangle at the corners and halfway points of the frame.

The objective object, a star, is similarly created, but we will use a circular physics body.

-(void)addObjectives:(NSArray*)objectives {
    
    for (NSDictionary* objective in objectives) {
        
        //Grab the position information from the dictionary provided from the plist
        CGPoint position = CGPointFromString(objective[@"objectivePosition"]);
        
        //create a sprite based on the info from the dictionary above
        SKSpriteNode *objSprite = [SKSpriteNode spriteNodeWithImageNamed:@"star"];
        objSprite.position = position;
        objSprite.name = @"objective";
        
        //Assign a physics body and physic properties to the sprite
        objSprite.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:objSprite.size.width/2];
        objSprite.physicsBody.categoryBitMask = objectiveMask;
        objSprite.physicsBody.contactTestBitMask = otherMask;
        objSprite.physicsBody.usesPreciseCollisionDetection = YES;
        objSprite.physicsBody.affectedByGravity = NO;
        objSprite.physicsBody.allowsRotation = NO;
        
        //add the child to the scene
        [self addChild:objSprite];
        
        //Create an action to make the objective more interesting
        SKAction *turn = [SKAction rotateByAngle:1 duration:1];
        SKAction *repeat = [SKAction repeatActionForever:turn];
        [objSprite runAction:repeat];
    }
    
}

Ready, Set, Fire!

The cannon itself doesn’t need any bodies attached, as it has no need for collision detection. We will simply use it as a starting point for our projectile. 

Here is the method for creating a projectile:

-(void) addProjectile {
    //Create a sprite based on our image, give it a position and name
    projectile = [SKSpriteNode spriteNodeWithImageNamed:@"ball"];
    projectile.position = cannon.position;
    projectile.zPosition = 20;
    projectile.name = @"Projectile";
    
    //Assign a physics body to the sprite
    projectile.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:projectile.size.width/2];
    
    //Assign properties to the physics body (these all exist and have default values upon the creation of the body)
    projectile.physicsBody.restitution = 0.5;
    projectile.physicsBody.density = 5;
    projectile.physicsBody.friction = 1;
    projectile.physicsBody.dynamic = YES;
    projectile.physicsBody.allowsRotation = YES;
    projectile.physicsBody.categoryBitMask = otherMask;
    projectile.physicsBody.contactTestBitMask = objectiveMask;
    projectile.physicsBody.usesPreciseCollisionDetection = YES;
    
    //Add the sprite to the scene, with the physics body attached
    [self addChild:projectile];
    
}

Here we see a more complete declaration of some properties assignable to a physics body. When playing with the sample project later, try altering the restitution, friction, and density of the projectile to see what effects they have on the overall gameplay. (You can find definitions for each property in What’s in a Projectile Physics Engine?)

The next step is to create the code to actually shoot this ball at the target. For this, we’ll apply an impulse to a projectile based on a touch event:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    
    for (UITouch *touch in touches) {
        
        CGPoint location = [touch locationInNode:self];
        NSLog(@"Touched x:%f, y:%f", location.x, location.y);
        
        //Check if there is already a projectile in the scene
        if (!isThereAProjectile) {
            
            //If not, add it
            isThereAProjectile = YES;
            [self addProjectile];
            
            //Create a Vector to use as a 2D force value
            projectileForce = CGVectorMake(18, 18);
        
        
            for (SKSpriteNode *node in self.children){
            
                if ([node.name isEqualToString:@"Projectile"]) {
                    
                    //Apply an impulse to the projectile, overtaking gravity and friction temporarily
                    [node.physicsBody applyImpulse:projectileForce];
                }
            
            }
        }
   
        
    }
}

Another fun alteration to the project might be to play with the impulse vector value. Forces—and therefore impulses—are applied using vectors, giving magnitude and direction to any force value.

Now we have our structure and our objective, and we can shoot at them, but how do we see if we scored a hit?

Collision Course

First, a quick pair of definitions:

  • A contact is used when two bodies touch.
  • A collision is used to prevent two bodies from intersecting.

Contact Listener

So far, the physics engine has been handling contacts and collisions for us. What if we wanted to do something special when two particular objects touch? To start with, we need to tell our game that we want to listen for the contact. We will use a delegate and a declaration to accomplish this. 

We add the following code to the top of the file:

@interface MyScene ()<SKPhysicsContactDelegate>

@end

…and add this statement to the initializer:

self.physicsWorld.contactDelegate = self

This allows us to use the method stub depicted below to listen for contact:

-(void)didBeginContact:(SKPhysicsContact *)contact

{ //code

}

Before we can use this method, though, we need to discuss categories.

Categories

We can assign categories to our various physics bodies, as a property, to sort them into groups. 

Sprite Kit in particular uses bit-wise categories, meaning we are limited to 32 categories in any given scene. I like to define my categories using a static constant declaration like this:

//Create Physics Category Bit-Mask's

static const  uint32_t objectiveMask = 1 << 0;

static const  uint32_t otherMask = 1 << 1;

Note the use of bit-wise operators in the declaration (a discussion on bitwise operators and bit variables is beyond the scope of this tutorial; just know that they are essentially just numbers stored in a very quickly accessed variable, and that you can have 32 maximum).

We assign the categories using the following properties:

platSprite.physicsBody.categoryBitMask = otherMask; //assign a category mask to the physics body
platSprite.physicsBody.contactTestBitMask = objectiveMask; //create a contact test mask for physics body contact callbacks

Doing the same for the other variables in the project, let’s us now complete our contact listener method stub from earlier, and also this discussion!

-(void)didBeginContact:(SKPhysicsContact *)contact
{
    //this is the contact listener method, we give it the contact assignments we care about and then perform actions based on the collision
    
    uint32_t collision = (contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask); //define a collision between two category masks
    if (collision == (otherMask| objectiveMask)) {
        //handle the collision from the above if statement, you can create more if/else statements for more categories
        if (!isGameReseting) {
            
            NSLog(@"You Win!");
            isGameReseting = YES;
            
            //Set up a little action/animation for when an objective is hit
            SKAction *scaleUp = [SKAction scaleTo:1.25 duration:0.5];
            SKAction *tint = [SKAction colorizeWithColor:[UIColor redColor] colorBlendFactor:1 duration:0.5];
            SKAction *blowUp = [SKAction group:@[scaleUp, tint]];
            SKAction *scaleDown = [SKAction scaleTo:0.2 duration:0.75];
            SKAction *fadeOut = [SKAction fadeAlphaTo:0 duration:0.75];
            SKAction *blowDown = [SKAction group:@[scaleDown, fadeOut]];
            SKAction *remove = [SKAction removeFromParent];
            SKAction *sequence = [SKAction sequence:@[blowUp, blowDown, remove]];
            
            //Figure out which of the contact bodies is an objective by checking its name, and then run the action on it
            if ([contact.bodyA.node.name isEqualToString:@"objective"]) {
                    
                [contact.bodyA.node runAction:sequence];
                    
            } else if ([contact.bodyB.node.name isEqualToString:@"objective"]) {
                
                [contact.bodyB.node runAction:sequence];
                
            }
            
            //after a few seconds, restart the level
            [self performSelector:@selector(gameOver) withObject:nil afterDelay:3.0f];
        }

    }
}

Conclusion

I hope that you’ve enjoyed this tutorial! We have learned all about 2D physics and how they can be applied to a 2D projectile game. I hope you now have a better understanding of what you can do to start using physics in your own games, and how physics can lead to some new and fun gameplay. Let me know in the comments below what you think, and if you use anything you’ve learned here today to create projects of your own, I’d love to hear about it. 

A Note on the Example Project

I have included a working example of the code provided in this project as a GitHub repo. The fully commented source code is there for all to use. 

Some minor portions of the working project unrelated to physics were not discussed in this tutorial. For instance, the project is built to be expandable, so the code allows the loading of multiple levels using a property list file to create different platform arrangements and multiple objectives to hit. The game over section, and the code to remove objects and timers, were also not discussed, but are fully commented and available within the project files.

Some ideas for features you could add to expand on the project:

  1. Different types of ammo
  2. Movable and scalable shot direction and magnitude
  3. More types and sizes of platforms
  4. Terrain
  5. Animation and sound effects 

Have fun! Thanks for reading!

Download Projectile Physics Engines: Building a Game World

How to Order Photographic Prints From iPhoto

Digital technology allows the taking of countless photographs for little or no cost; a stark contrast to the expensive, film-based photography of just a couple of decades ago. Yet photos are printed less often than in the past. It’s still possible and, in this tutorial, I’ll show you how to have chosen photos printed professionally and delivered to your door.

Photography, for me, began with a secondhand Zenit camera and a roll of stuff called film that had to be developed before I could see the image I’d just framed. Fast-forward to recent history and now photographs are captured digitally and viewed instantaneously.

Perhaps it’s the ease with which I can rattle off hundreds, if not thousands, of photos that means I rarely look at them after I’ve taken them. In this tutorial I will show you how to produce a custom book highlighting the best of your photography.

Getting Started

For this tutorial you will need:

  • Your best photographs
  • A Mac running OS X
  • iPhoto

For the purposes of this tutorial, I will be using the latest version of iPhoto running on OS X 10.8 Mountain Lion.

If you are running an earlier version of OS X, the outline and principles of the tutorial will be the same with the exception of some of the detail in the iPhoto app itself.

Note, this tutorial assumes that you already use iPhoto to manage your photographs. If you do not, you should import your chosen photographs to iPhoto first.

Select Some Excellent Photographs

Creating photo Events
Creating photo Events

For the purposes of selecting the best photos from which to order prints, I find it useful to create a new Album.  An album is a collection of photos that can come from different Events in the iPhoto library.

To select the photographs:

  • Open iPhoto and go to Events to select an Event from which you wish to select photographs.
  • Select an image by clicking once on it.  If you wish to select more than one image, hold down the Command key and click once on each image required.

Create an Album

Creating a new Album in iPhoto
Creating a new Album in iPhoto
  • Click the Add To icon at the bottom-right of the iPhoto application window
  • Alternatively, navigate to iPhoto > File > New Album
  • Select Album then New Album
  • Enter a name to replace the default untitled album.  I have called mine Prints
  • Return to Events and select photos from other Events in the same way as described above
  • To add photos from other Events, select the photos required
  • Click the Add To icon at the bottom-right of the iPhoto application window
  • Select Album then Prints or whatever you named your Album
  • When you have finished adding photos to the Album, click on the Album, that you created, listed in the sidebar of iPhoto

Review the Photographs

Reviewing the chosen photos
Reviewing the chosen photos

Review the photos that you have selected.  If you have changed your mind and wish to remove a photo, select it by clicking once on it then press the Backspace key.

A pop-up dialogue box will ask Are you sure you want to remove the selected photo form the album? Click Remove Photo to confirm.  

The photos are only removed from the Album that you created; the photos are not deleted from the Events

Select the Photos to Print

In the sidebar of iPhoto, navigate to the Album that you have just created. In my example, I have navigated to the album called Prints.

Selecting All Photos

Selecting all of the photos in the Album
Selecting all of the photos in the Album

You may wish to select all of the photos, in the album, to have printed. If this is the case, you can press Command-A or use the mouse to click and drag a box around all of the photos to select them. 

Personally, I find the keyboard shortcut to be more efficient. Selected photos will be shown each with a yellow border.

Selecting Some Photos

Selecting only some of the photos in the Album
Selecting only some of the photos in the Album

It may be that you do not wish to print all of the photos, in the album, at the present time. That’s fine. To select particular photos hold down the Command key whilst clicking on each desired photo with the mouse. 

Chosen photos will be shown with a yellow border.

Selecting a Single Photo

Selecting a single photo to print
Selecting a single photo to print

This is easy. If you require just one photo from the album, select it by clicking on it. Once selected, the photo will have a yellow border around the edge.

Ordering the Photographic Prints

Ordering the Photographic Prints
Ordering the Photographic Prints

When you are happy that you have selected the photos that you require, click the Share button to reveal a menu. In the menu select Order Prints.

Ordering a Number of Each Photo at a Specific Size

Quick Ordering photo prints
Quick Ordering photo prints

A new screen to order prints will be displayed. The options allow you to swiftly order a quantity of each photo at a chosen size. Alternatively, you can work through each photo in turn selecting the size and the quantity required of each; they don’t all have to be the same size and number ordered if you want to mix it up a bit.

The Quick Order menu allows you to select the size of the photo required. The Up and Down arrows next to the drop down menu enable you to choose the number required.

It is important to note that this will be the same selection across all photos. For example, if you select a 20 x 30 cm photo size with a quantity of 3, you are selecting three of each photo at that size only. 

No variations. 

Ordering Different Numbers and Sizes of Photo

Selecting different sizes and quantities of each photo
Selecting different sizes and quantities of each photo

If you’d like three of the first photo at 20 x 30 cm and only one of the second photo at a different size, the order form allows you to do this.

An added feature is that the price for each size is displayed along with a total that is dependent upon the number that you select. 

The Order Subtotal, at the bottom of the order form, is updated dynamically. This means that you can keep an eye on how much the order for prints will cost.

When you have finished choosing the photo size and the number you require of each, click the blue Buy now button.

Placing the Order

The summary of the order
The summary of the order

A summary of Your Order is displayed along with a thumbnail of each photo that you want printed, the size selected and the number of prints that you want.

Enter the delivery post code in the Ship to: box and click Get Delivery Rates for confirmation of delivery rates.

If you wish to proceed with the order, click the blue Check Out button. You’ll then need to enter your Apple ID, or create one, in order to complete the order.

In my example, the order will ship in 1-3 business days with an estimated delivery of a week to ten days.

Post Card

In this tutorial I have shown you how to create, from scratch, an album of photos using Apple’s iPhoto application. I have shown you how to customise the physical size of the photos to be printed before placing an order for the delivery of the finished, printed photographs.

Photos created with iPhoto look great in frames around your house and make excellent presents for friends and family, alike.

Download How to Order Photographic Prints From iPhoto

What’s in a Projectile Physics Engine?

In this tutorial, we’ll examine the use of physics to simulate projectile effects in games like Angry Birds. We’ll look at the basics of using 2D physics in game world space, such as creating bodies and applying impulses and forces.

Physics Engines

Why use a physics engine? What does it actually do? 

A physics engine helps us do two very important things for our game:

  1. Detect collisions between our in-game objects.
  2. Simulate the forces and resulting motion of our objects from those collisions..

Collision detection: Games wouldn’t much much fun if your character fell through the floor before you could jump, or if, when you hit an enemy with your foot, you fell right through. Collision detection using a physics engine allows for very precise contact listening, and allow interactions between objects to be simulated using forces.

Force simulation: After a collision, what should happen? Game logic could be called, you could bounce, the other game object could bounce, or you could simply move no further. This is all handled behind the scenes, using the calculated forces of the engine. But forces aren’t limited to contact; other forces, such as gravity and impulses, can occur, without objects actually touching. Forces affect in-game actions and the movement of objects, characters, and even the world-space itself.

.

We’ll look at how physics engines work shortly, but first lets look at what engines you may want to use, and why you may decide to use them, based on your particular needs.

Choosing Your Engine

When you first start to think about using physics in your game, you will need to decide how you want to approach the problem, and what your game will require in terms of simulation. You have two options for using physics:

  1. Use an existing physics engine.
  2. Create a custom physics simulation

Using an Existing Physics Engine

Several excellent options exist for predefined and ready-to-use physics engines. One of the most popular choices for 2D games is Box2D; it’s a native C++ written engine, but has wrappers, ports, and extensions that allow it to be used in nearly any 2D platform. Another popular choice is Chipmunk 2D, which is used in several mainstream game engines, like Cocos2D.

Creating a Custom Engine

In some games, using a predefined engine isn’t necessarily the optimal choice. Using a physics engine can cause some unnecessary overhead when its full function isn’t required. In cases like simple platformers or brick-breaker type games—where you don’t need pixel-perfect collision detection or some of the other capabilities of an engine—it may unnecessarily use up resources that could be better spent elsewhere. 

Building your own engine can give you more flexibility over the final product, but it can also make things more complicated if you are dealing with more than a few instances of characters and objects.

The Game Loop

Before discussing the properties and details of a physics simulation, let’s look at how it is called within the loop of your game scene.

The typical game loop will run through the following for each frame, in order:

  1. Input
  2. Update/Game Logic
  3. Simulate Game Physics
  4. Render Screen/Scene

This means that calculating the resulting physics is the last task performed in the loop before the screen is updated. This makes sense, as the point of the simulation is to react to what has happened within the game’s world-space. 

Note that this image shows that physics are simulated during every frame of your game loop. This can result in some large overhead if your simulation gets overly large or complicated. For this reason, it is best to keep game management and calls to the simulation and its listeners limited. 

Fixed Rate vs. Frame Dependent Physics

It makes sense now to discuss two different methods of polling the physics simulation: fixed vs. frame dependent rates. Consider the (void)update: method consistent within most game loops. This loop is called once per frame of the game scene. If your “simulate physics” method is called from (void)update:, your game world physics is going to depend on your frame-rate, and this can lead to some choppy and unrealistic simulations. In iOS, this effect is mitigated by the use of the usesPreciseCollisionDetection Boolean property, but what about in other engines? 

Consider the following code segment:

 CFTimeInterval timeSinceLast = currentTime - self.lastUpdateTimeInterval;
    self.lastUpdateTimeInterval = currentTime;
    if (timeSinceLast > 1) {
        timeSinceLast =  1.0/60.0;
    }

This code is designed to compensate for issues with the delta value for time. Consider a situation where you were playing the game on your phone and got a call: it would help your game for you to reset your delta back to the expected 1/60 (for a 60 fps game). 

This is actually the first step into a discussion on decoupling the physics simulation from the time-step of the (void)update: method. While a modified time interval would certainly aid in a more stable physics simulation call, it doesn’t correct for all situations. To do this, we would need to actually remove the physics simulation call from the game rendering loop, and create a fixed cycle within which it could run. For instance; if your game is meant to run at 60 fps, you set the physics to simulate 60 times per second. This decoupling removes any concerns of rendering issues causing choppy feedback in your physics simulation.

In short, be conscientious in your implementation of physics. If you find yourself using an engine in an environment where you are taxing system resources, consider a fixed step physics simulation to maintain fairness and fidelity.

From Sprite to Physics Body

A sprite is an image rendered to the screen of your game. A sprite has no properties by default within a physics simulation. You can “fake” some of the behaviours of a physical world by using properties of a sprite such as a bounding box and an intersection call, but then you have to write all of the resulting logic yourself. Wouldn’t it be better if the game could handle all of this for us?

In these snippets, we create a sprite:

  SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"image"];
        sprite.position = location;
        [self addChild:sprite];

…and call a collision between two sprites:

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
    if (CGRectIntersectsRect(sprite1.frame, sprite2.frame)) {
        //do something
    }
}

Body Shapes

Physics bodies are “simple” shapes that define the rough size and shape of your sprite, or perhaps define an active area of your sprite. Consider the following:

A physics body is not predefined by the image of your sprite, and is typically invisible within the game. You create the shape dynamically, often by calling a method to either draw the shape that will make up the body, or by using a program to help you draw out and define the body. You then attach the body to the sprite, and gain access to the simulated effects and properties assigned to that body.

You can have multiple physics bodies tied to a single sprite. Take, as an example, a sprite of a hero carrying a sword. It would make sense to create one body for the hero character, and another one for the sword he carries. This would allow you to create game logic based on collisions between different bodies. 

In pseudocode, the logic would look something like this:

//physics logic
-(void)physicsCollisionDidOccur{

switch (collision bitmask) {
case (Player||Sword): //do nothing;
    break;
case (Player||Enemy): //ouch!!;
    break;
case (Sword||Enemy): //do damage!!;
    break;
default: //do nothing;
    break;
}

Relating the Physics Body to the Sprite

Consider the situation of a of a space game, where you have a hero ship and an enemy ship:

You would likely want to make the physics body of the player a little smaller than the base sprite image for two reasons:

Enhanced Visual Collision: When a player collides with an object in your game, by creating this smaller physics body, the sprite images will overlap temporarily at the point of contact, which looks good visually. (Further to this point: when drawing z-values, keep your player’s character at the front of the scene hierarchy.)

User-Perceived Fairness: To try to make your game feel “fair” to the player, keep the collide-able body limited to the bulk of the object, and away from extraneous protrusions like the back fin of the image above. This way, there won’t be any “cheap hits” to annoy the players of your game. Conversely, you usually want the enemy physics body to be at least the size of the base image; if we give our space hero a laser to shoot his enemy, a slightly-too-large enemy body makes it more reasonable for our player to obtain a hit. Also consider this same approach for tiles in a platformer or puzzle game that requires your player to jump from platform to platform. Players are used to a little “grace” in these types of games; extending the physics body a tad will help keep your game reasonably “fair”.

Typical 2D Engine Constraints

There are two main types of physics bodies:

  1. Edge-based bodies
  2. Volume-based bodies

An edge-based body is a static, immovable line that creates a boundary for other bodies to collide with. It has a negative space within it that has no effect on any bodies. A great application of this would be to create a boundary around your screen to contain any bodies within.

A volume-based body has volume and mass, and can be either dynamic or static. Because these bodies have mass, objects bounce off them and they can be affected by force contacts. Volume based bodies can be any of four main shapes:

  1. Circle
  2. Rectangle
  3. Chain
  4. Complex Polygon

There are some constraints to using bodies within your typical 2D physics engine. Here are the two main limitations:

Convex Physics Bodies 

If a shape is convex, it means that no interior angle is less than 180 degrees. 

To be clear, it can be possible to run physics simulations on concave shapes, but the processing cost is so high that it is simply not realistic for 2D, especially when running on a handheld or less powerful device. Concave-like shapes can be constructed by linking together two convex shapes using something called a Static Joint. Joints are another great feature available with 2D engines, but are outside of the scope of this discussion.

Rigid Physics Bodies

When a ball hits a wall, in the “real” world something like this will occur:

Your character’s sprite can undergo this type of transformation, but its physics body cannot. You can control certain properties of the body to affect its “bounciness”, but it cannot actually have a mutable shape. This is known as a Rigid Body, meaning that the body itself cannot be deformed or squished.

Properties of a Physics Body

Let’s have a quick look at what some of the some of the most useful properties available on a typical physics body are:

  1. Restitution is a measure of how “bouncy” an object is. More formally, it’s the measure of how much energy an object retains after it collides with another object.
  2. Density is the measure of how “heavy” an object is. It is used as a relative quality—for instance, a rock would be more dense than a ball, so when the ball hits the rock, it will be affected more heavily.
  3. Friction is the measure of how “slippery” an object is. This is used when one object is sliding along another, and determines how long will it take for it to stop.
  4. If a body is dynamic, then forces imposed upon it by the world and other objects will have an effect; if it is a static body, then they will not.
  5. Rotation is typically a Boolean variable that can be set on a physics body. In certain cases you may want to limit a body and not allow it to rotate, but you want forces to still be applied to that object.

Most engines have more properties available than this, but for the purposes of this discussion, these will be sufficient to get started.

Motion and Momentum

In a simulated physics world, bodies are moved by the application of forces and impulses.

Forces: General forces typically affect bodies more gradually than impulses They are a constant force that is applied over a unit time (like gravity or an engine).

Impulses (Impulse Forces): Impulses are immediately-applied adjustments to a body’s momentum. Impulses are usually applied to a simulation based on user input.

What Next?

Now that you understand the theory, the best way to cement your understanding of projectile physics engines is to build one yourself. Tomorrow, I’ll break down the code for a simple physics-based game that I’ve written, so you can see exactly how it works!

Download What’s in a Projectile Physics Engine?

How to Make a Box Organizer for the Office

Final product image
What You’ll Be Creating

Make this fun and super-easy box organizer, ideal for displaying and storing your craft supplies and desk accessories. 

Supplies

  • Bulldog clips/ binder clips
  • Painter’s tape
  • Acrylic paint
  • Paint brush
  • Wooden boxes in different sizes

1. Create a Design

Apply painter’s tape in a design of your choice on to the outside of the boxes. I’ve kept it geo and simple with a strip of tape across the diagonal of the box. 

2. Paint the Boxes

Step 1

Start painting the outside of the box and leave to dry.

Step 2

Now apply painter’s tape on the backside of the inside of the box in the design of your choice. Again, I’ve chosen to use a simple diagonal line. Paint the inside of the box in your choice of colour.

Step 3

Paint the edges of the box in a complementary colour and set to dry. For a design that pops, try a complementary neon colour. 

Step 4

Repeat steps 1 and 2 with your other boxes. 

3. Paint the Bulldog Clips

Apply a thin coat of paint to each bulldog clip in the same colour as the edge of your boxes. Allow the paint to dry completely before applying the next coat.  

4. Assemble the Box Organizer

Use the bulldog clips to join the boxes together. You can arrange your boxes in any design. Try stacking them on top of each other, or place them in a row on the diagonal and clip them together. 

Organize your Stuff

Well done, your box organizer is now ready for storage!

Use a bunch of boxes to maximize your office to its full storage potential, or pick just a few boxes for small storage. Your new colourful containers will help reduce clutter from building up on the desk.

It’s compact enough for small spaces and provides a place for everything. It’s super-handy for storing craft supplies and over time, you can easily rearrange and add more boxes to suit your needs. 

What do you think of my storage solution for you desk? Do you have any other crafty storage ideas? I’d love to hear them. 

Download How to Make a Box Organizer for the Office

The Freelance Business Funnel (Business)

Filled with Skellie’s clever tips on blogging, freelancing and personal branding, you’ll learn dozens of innovative strategies you can immediately use to create a strong and sustainable freelance business, one that’s able to thrive regardless of the economic climate.

It’s time to earn a living online doing something that makes you happy.

This book was borne out of the question: Why do freelancers spend so much time bidding, cold-emailing and pleading for work, when there is clearly a better way?

While others have written brief articles on the topic of using blogging as the foundation for a freelance business, nobody else has outlined a complete blueprint in book form, sharing everything there is to know.

Written and perfected over six months, this book outlines an easy to follow process for funnelling clients into your freelance business through a blog.

You’ll learn:

  • How to create a popular blog prospective clients will love.
  • How to sell your services to your blog’s visitors.
  • How to optimize your business for success.
  • How to charge your dream rates.
  • How to scale your freelance business. 

Skellie’s Story

I first started freelancing to support myself through university. When I got my first gig, I was excited to be getting paid at all for doing what I loved (writing). I ran a popular blog and had been contacted about doing a series of freelance articles for another blog I respected. This is how it began.

11 months later my business had grown… and grown some more. I found myself staring in disbelief at the balance of my PayPal account. In that month alone, and while still studying full-time, I had earned over $8,000 and was well on my way to a six-figure income that year.

I knew that in many ways I wasn’t a great freelancer. I was too shy to talk to clients on the phone and often submitted work at the very last minute. And yet, this made the reason for my success even clearer. I had stumbled across an incredible system of doing business: The Freelance Business Funnel.

It works regardless of whether you’re a veteran or a newbie.

It works whether you’re full-time or part-time.

It works regardless of your industry, or your skills.

It works regardless of where you live.

It just works.

What’s Inside

Introduction: Why Aren’t Freelancers Filthy Rich?

Freelancers attract solid rates, often upwards of $50 per hour. And yet, why are so many freelancers struggling to live an abundant lifestyle? I believe it’s because of time spent chasing after clients and bidding for jobs, time that could be spent building a business strong enough that great clients find you on auto-pilot. This book will show you how.

Chapter 1: Setting Yourself Up For Business

This chapter outlines the foundations of a strong freelance business. It walks you through creating a blog, a social media presence, and deciding on who you’ll appeal to with your content: clients, or peers.

Chapter 2: The Freelance Business Funnel Explained

Here you’ll learn how to create a popular, thriving blog that is specially designed to appeal to the target market for your services. You’ll learn how the model works and how to adapt the model to your own blog.

Chapter 3: Trust and Targeted Traffic

Learn methods and formulas for creating incredible content designed to draw your target market deeper into your blog. Also, learn how to build trust and a rock-solid reputation in your industry.

Chapter 4: Turning Readers Into Clients

When you have a healthy and thriving blog, the next step is to start funnelling readers into your business. You’ll learn how to properly promote your services to your readership.

Chapter 5: Using Business Launch and Re-Launch Formulas

People are always talking about the importance of product launches, but what about a proper launch for your freelance business? This chapter shows you how to create exciting launches that will fill your client list for months to come.

Chapter 6: Advanced Blog Business Strategies

Get a measurable and profitable return on investment with online advertising for your services. Clever tips that some of the world’s biggest companies still don’t know.

Chapter 7: Scaling Up!

The book finishes with three strategies that your competition simply don’t know about:

  1. How to charge your dream rates.
  2. How to create low-maintenance partnerships you can profit from (without actually doing any work).
  3. Turning your services into a product you can sell in your sleep.

No Fluff

You’re a freelancer, and therefore, time really is money. This is why there is absolutely no fluff in The Freelance Business Funnel. Every page is filled with quick, actionable tips you can use straight away to improve your business and earn more income.

It’s More Affordable Than You Think

Most eBooks that teach you ways to run a business online require a serious investment. $97 for one eBook is considered cheap. And for other products, the price keeps climbing. $199. $247. $499!

This product is different. I want it to be accessible to as many people as possible. If you walked down the aisles of any bookstore you’d never pay $100 or more for a single book. Why should an eBook be different?

The Freelance Business Funnel is just $20 USD if you buy it now.

If you do one single hour of billable work as a result of reading this book, it will have more than paid for itself.

Of course, it’s my hope that the book will help you land thousands of dollars worth of clients, all while doing what you love.

This book shows you how to do work that makes you happy, and earn a great, independent living in the process.

Like all Rockable eBooks, it comes with a 100% Money-back guarantee.

Let’s supercharge your freelance business!

 

Download The Freelance Business Funnel (Business)

Customized Google Map using Google Maps API (Web Development)

This tutorial shows you how to use Google Maps API with jQuery to create unique looking google maps to be embedded in your HTML files. It shows you how to control some map options, how to change the default location marker pin and how to animate it, and finally, how to style your map to match your website feel.

Download Customized Google Map using Google Maps API (Web Development)