Camera Shake

I’m having trouble resetting my camera after using a camera shake script on collision

	public void ScreenShake(bool dead){
  
	if(shakeTimer > 0){
		shakeTimer = 16;
		if(dead)
			shakeTimer = 30;
        Debug.Log("shakeTimer" + shakeTimer);
	}
	else
		StartCoroutine(ScreenShakeRoutine(dead));
}

public void StopShaking()
{
	stopShake = true;
}

public IEnumerator ScreenShakeRoutine(bool dead){
	shakeTimer = 16;
	if(dead)
		shakeTimer = 30;
	Vector3 originalCamPos = myCamera.localPosition;
	while(shakeTimer > 0)
	{
		if (stopShake)
		{
			stopShake = false;
			yield break;
		}
		
		if(shakeTimer % 2 ==0)
			myCamera.localPosition = originalCamPos;
		else
			myCamera.Translate(Random.Range(-0.2f, 0.2f),Random.Range(-0.2f, 0.2f),0);
		shakeTimer--;
		yield return new WaitForSeconds(0.04f);
	}
    myCamera.localPosition = originalCamPos;

}

When I do not call stopShake() the camera does not return to its original position, but the position but stays at the position of the camera when it originally started shaking.

When I do call stopShake() the camera returns to its original position, but it does not screen shake anymore even if I set screen shake to be false on restart.

One clean way to do it is to start maintain the camera’s original position, say Vector3 originalPos = …
Then make sure every frame you calculate the shake offset and add it to the original pos. That way, you always know where to come back to. Then to make sure it returns to its starting point, decay the offset value closer and closer to 0 as it gets closer to the time you want to stop the shake. This blog covers it in more detail with some nice visuals: Camera Shake.

I’m using this script. Work perfectly for camshake.
Not so complicated either.

	bool flip;

	float yPos;
	float shakeAmount = 1;

	public Transform myCam;

	void Update()
	{
		if(Input.GetKeyDown(KeyCode.Space)) StartCoroutine ("CamShake");
	}

	IEnumerator CamShake ()
	{
		yPos = shakeAmount;

		while (Mathf.Abs(yPos) > 0.01f ) 
		{
			yPos = Mathf.Abs (yPos) - 0.1f;

			if (flip) yPos *= -1;

			flip = !flip;

			//Tripple setup thingo!
			Vector3 tempPos = myCam.localPosition;
			tempPos.y = yPos;
			myCam.localPosition = tempPos;

			yield return null;
		}
	}

In your code, you could add myCamera.localPosition = originalCamPos before yield break.

If you put your object under a parent that sets the world position, you can offset the localPosition to give it shake and when your offset goes to zero your object will return to the neutral position.

Please don’t use random values to cause camera shake! Use a continuous function like perlin noise or sine to get smooth movement.

Here’s a script ShakeIn2D that can shake objects or camera as shown in these videos.

Here’s a short Youtube video that covers exactly how to code a screen shake effect: How to Code a Screen Shake Effect | Unity Tutorial - YouTube


screen shake