A very simple camera shake!

Esteban Ibarra
3 min readApr 25, 2021

Our galaxy shooter now has just about everything it needs to be a pretty cool game except for one thing, Camera Shake! If an asteroid or a ship hits you, having the camera shake at the same time can give the experience that needed flair of excitement!

I decided to keep things as simple as possible, get the camera, and when shaking, choose random positions within a perimeter and when finished, return to its original position.

I created a new script called ShakeCamera and attached it to an empty object called Camerashaker. For some reason, I was having trouble accessing scripts on the main camera, so I figured I’d put the script in an empty and then create a holder for the camera, and it worked out fine.

First I created a handle for the main camera, then a variable to hold the amount of time to shake the camera, and then a variable for how much the camera will deviate from the main area, which as you can see is extremely small, .10 of a unit.

The main running part of the script is mostly concerned with keeping time. It subtracts Time.deltaTime from _timeToShake to bring it ever closer to 0, once it does, the camera is reset and the CameraShake coroutine is told to stop. A protectionary measure is taken that if _timeToShake goes below 0, it will be reset to 0.

There’s an InitiateShake that’s called from the player when the ship is damaged, it’s given a time parameter of around half a second, and that parameter is passed to the local _timeToShake variable. Then the Actual CameraShake routine is called.

Here is the program's meat, if there’s still time allowing, the coroutine halts execution for a small fraction of a second to slow down the illusion of the camera shaking. Without this, the camera would move around randomly, but like a samurai cutting down his foes, it would be so fast, you wouldn’t see it.

Omae wa mō shinde iru

After the wait, random positions are chosen for x and y, assigned to a new variable holding a Vector3 and that’s assigned to the mainCameras transform. This will be repeated over and over until _timeToShake reaches 0.

And that’s all there is to it! Nothing fancy, but it does the job!

--

--