Creating a camera-shake feature for my space shooter

Michael Kline
2 min readApr 13, 2021

I think it would be cool if my game had some sort of visual effect when the player takes damage. A camera shake could do the trick here, and I have an idea about how to do it.

I only want a slight movement of the camera, maybe only within .5 units in any direction. What I want to do is randomly generate a series of x and y coordinates and then move the camera from one point to the next in sequence. This SHOULD give the illusion of a shaking camera.

I created a script called CameraController to handle all of this logic and attached it to the main camera. I created a Vector3 variable to hold a reference to the origin position of the camera so we can set back to that after shaking. A public method called CameraShake will handle the logic and populate two arrays with random values, one each for x and y-values. CameraShake will be called from the Player object when it takes damage.

CameraController.cs

I made a coroutine to do the actual movement of the camera, as I want a small delay between moving to each point to give it the visual effect. It takes both arrays as arguments and uses a for-loop to iterate through each set of coordinates and move the camera, then waits for .05 seconds. At the end, it sets the position back to the origin.

CameraController.cs
Shakecam engage

One small bug I noticed early on was that the background was stationary and did not move along with the camera. I fixed this by making the background object a child of the main camera, that way they move iN-sync now. Bye-bye-bye.

--

--