2D Galaxy Shooter P1: Camera Shake Added!

Gabriel Perez
2 min readMay 2, 2021

--

For today's challenge, I implemented a camera shake!

The challenge is to have the camera shake when the player takes damage.

So I created a camera shake script and attached it to the main camera. We need to create a function in the script so we can call it in the player script.

using System.Collections;
using UnityEngine;
public class CameraShake : MonoBehaviour
{
[Range(0f, 1f)]
[SerializeField] private float _shakeAmount = 0.4f;
[SerializeField] private float _shakeTime = 0f;
public void ActivateCameraShake()
{
StartCoroutine(CameraShakeRoutine());
}
private IEnumerator CameraShakeRoutine()
{
var randomXvalue = Random.value * _shakeAmount * 2;
var randomYvalue = Random.value * _shakeAmount * 2;
var randomXoffset = Random.Range(-randomXvalue, randomXvalue);
var randomYoffset = Random.Range(-randomYvalue, randomYvalue);
var randomPosition = new Vector3(transform.position.x + randomXoffset, transform.position.y + randomYoffset, -10); transform.position = randomPosition; yield return new WaitForSeconds(_shakeTime); transform.position = new Vector3(0, 0, -10);
}
}

It’s a simple script that offsets the x and y positions of the camera. When the function ActivateCameraShake() is called, the coroutine will start the logic.

I created two variables that randomize a value by using Random.value. This will randomize a value from 0 to 1. We times it by the _shakeAmount we can adjust in the inspector by 2.

Since I want the value to take into account negative numbers, I Random.Range the random values and pass them into the new position.

We then assign the new position to the position of the camera. Yield by .015 milliseconds and return the camera position to its starting position.

That is it! A simple script to offset the camera’s position when damaged.

This concludes the Phase 1 framework! Woohoooo! I am heading to the Phase 2 core programming stage where there will be many advanced features to implement!

Thank you for your time!

--

--

Gabriel Perez
Gabriel Perez

Written by Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.

No responses yet