Game Development, Monogame

Screen / Camera Shake in Monogame

So any time I spend working on my game(s) during the week, I’m trying to move it forward with features, gameplay or whatnot. But on the weekends, I like to polish stuff up and add little effects or fun things that while not necessarily important to the game, add that extra bit of pizzazz that I’m looking for. This weekend I wanted to add something when the player died the screen would shake like a great impact. Here’s a quick video of my game with the finished effect.

I like the effect but it’s one of those things that might not necessarily make it to the final release. Code to do so was really pretty simple (and written pretty quickly so if you see improvements that could be made, by all means let me know. (I also can’t take complete credit for this code as I stole some pseudocode from, http://bit.ly/2aqGzee)

In my main Draw method:

      Vector2 offset = new Vector2(0,0);
      if (shakeViewport)
      {
        offset = new Vector2((float)(Math.Sin(shakeStartAngle) * shakeRadius), (float)(Math.Cos(shakeStartAngle) * shakeRadius));
        shakeRadius -= 0.25f;
        shakeStartAngle += (150 + rand.Next(60));
        if (gameTime.TotalGameTime.TotalSeconds - shakeStart.TotalSeconds > 2 || shakeRadius <= 0)
        {
          shakeViewport = false;
        }
      }

When I want to trigger a shake (on death of player), I set the shakeViewport flag, which is a property on my main game object. All I’m trying to do is change the offset of the draw viewport by random amount in a random direction for a limited amount of time. The shake radius also helps to dampen the shake as the frames progress.

Once I’ve got the offset calculated, I simply add a transform matrix to all my spriteBatch.Begin calls as follows:

spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.Additive,null,null,null,null,Matrix.CreateTranslation(offset.X, offset.Y, 0));

pretty simple effect that fits well for those big impacts.

Advertisements