Shaking it up – Making your game’s screen shake

Hi everyone,

In this tutorial, I will be showing you my method for making a shaking screen effect in Cocod2D. This is a good effect to add some overall “feeling” to your game. It is like the vibration feature of an xbox controller. It’s not really needed, but adds ambience and “juice” to your games. It immerses the player more deeply into the game.

Here is how I go about doing it. All of the code should be written to affect a CCLayer, in my case, it is called GameWorld.h/.m

In your .h file, you will create three new variables:

@interface GameWorld : CCLayerColor {
BOOL shouldBeShaking;
int shakeLength;
int shakeIntensity;
}

shouldBeShaking is a boolean value that will let us know whether or not to shake the screen.
shakeLength and shakeIntensity will affect how long to shake the screen for and hard to shake the screen.

Now, in your .m file, schedule an update method like so (inside your init method!)

[self scheduleUpdate];

Next, setup that update method somewhere in your code

- (void)update:(ccTime)dt {

}

Before we go on, let me explain how this is going to work. Every frame, we will be checking whether or not shouldBeShaking is true. If it is true, then we will:

  1. offset the layer by some random amount
  2. decrement the shakeTime variable by one
  3. check if shakeTime is 0
  4. if it is, then set shouldBeShaking to false

Now, in code this looks like:

if (shouldBeShaking) {
float x = (arc4random() % shakeIntensity) - 0.5f; //Generate a random x coordinate
float y = (arc4random() % shakeIntensity) - 0.5f; //Do the same for the y coordinate
self.position = ccp(x,y); //Offset the layer's position by x and y
shakeLength--; //Subtract one from the length
if (shakeLength <= 0) { //Have we reached the end?
self.position = ccp(0,0); //Set us back to align with the screen
shouldBeShaking = NO; //Stop shaking
shakeLength = 0; //Reset shakeLength
shakeIntensity = 0; //Reset shakeIntensity
}
}

From there, you just need to set shouldBeShaking to true, set a length, and set an intensity, and your screen will be shaking accordingly.

I usually wrap those three steps up in a helper method to make things more organized.

Hope this tutorial helped someone.

New Programming Languages

I found this rather interesting article on InfoWorld. It goes over some new programming languages that show promise in changing the way developers need to program. It is definitely worth checking out. The article can be found here.

The ones that look the most enticing to me are Fantom, and X10. Let me know which one you think is the best.

Revival

This blog has gotten so much neglect. I am going to start posting regularly about things I am working on programming wise. Hopefully this will make the blog more interesting.
See ya then