- Home /
Camera shake, everything disappear from screen except canvas.
I made camera shake script and when I use it on button everything except canvas disappear from screen (game is continue to go). I make 2d game and in game view option I set 9:14 (I tried with different views and there is same problem). Here is my code:
using UnityEngine; using System.Collections;
public class CameraShake : MonoBehaviour {
public Camera mainCam;
float shakeAmount = 0.2f;
void Awake() {
if (mainCam == null) {
mainCam = Camera.main;
}
}
void Update() {
if (Input.GetKeyDown(KeyCode.T)) {
Shake(0.1f, 0.1f);
}
}
public void Shake (float amt, float length) {
shakeAmount = amt;
InvokeRepeating("BeginShake", 0.01f, 0);
Invoke("StopShake", length);
}
void BeginShake() {
if (shakeAmount > 0) {
Vector3 camPos = mainCam.transform.position;
float offsetX = Random.value * shakeAmount * 2 - shakeAmount;
float offsetY = Random.value * shakeAmount * 2 - shakeAmount;
camPos.x += offsetX;
camPos.y += offsetY;
mainCam.transform.position = camPos;
}
}
void StopShake()
{
CancelInvoke("BeginShake");
mainCam.transform.position = Vector3.zero;
}
}
I set Camera as empty game object and MainCamera as child. Script is attached on child object.
Answer by Joe_DaBurca · Oct 26, 2017 at 07:34 PM
I have the same problem, can someone tell me if this was resolved?
Answer by minh23520000 · Feb 15, 2018 at 06:01 AM
In the Function StopShake(), try to change the last line of code into mainCam.transform.localPosition = Vector3.zero; and see what happens. If you change the localPosition into Zero, now the child object will have the same position with the parent object, which should be working. Hope that helps =))
Answer by thomasfriday · Jul 14, 2021 at 09:16 AM
Here's a short Youtube video that covers exactly how to code a screen shake effect: https://youtu.be/BQGTdRhGmE4

Your answer
Follow this Question
Related Questions
Camera Shake Effect (Constant)? 4 Answers
Camera Effects binoculars 2 Answers
Smooth dizzy camera shake. 0 Answers
Cinemachine Noise Messes Up Isometric Z as Y Tilemap 1 Answer
Camera shake 11 Answers