Recommendation: Instead of Random.Range, try some noise functions. They make the shake less erratic and a bit more realistic. There's a great GDC video about that.
I like that you show both how to start writing your own shake, and then also shows a good assets - but unlike most you also import the asset and shows how to actually use it.
I just want to say thank you... You have helped me out in my programming experience, and I couldn't do any of it without your easy-to-learn explanations. I hope someday to be able to make games as good as you...
DOTween is great for this kind of stuff. Even the free version has some really cool extensions for camera shake, punching out the scale of things to make them "pop". You can "tween" any value you want pretty easily too.
Green Shadow dont listen to this guy, people all over say things like this but you learn so much from these types of videos that you can apply later on
Yeah, totally, perhaps you don't learn quite as much as if you would understand basic stuff, but there is still something to learn here. It's cool to see what you could be able to do and get more familiar with the code syntax. However, it's not good either to just watch these videos if you don't understand the basics.
Kaf3in0 B Yeah that is true, I sounded kind of rude responding to that other guy but you should never be discouraged to watch a video that you dont fully understand. Videos like these used to motivate me to learn and practice more to achieve this type of success.
I have found this comment by sorting all of these comments by the Newest First. You have gotten yourself the award of, "The Newest Comment as of 7-24-2021"
btw the cute way to do this is to put the starting of the coroutine inside of a different function inside of your camera shake object, and just calling that function every time so you dont have to use weird different syntax.
Hello, if for some reason your code is not working, rewrite it like this... this works for me public class CameraShake : MonoBehaviour { // Set up data bool shake = false; float duration; float magnitude; Vector3 originalPos; float elapsed; // Shake the screen public IEnumerator Shake (float duration, float magnitude) { // Setup data for camera to be shaked shake = true; this.duration = duration; this.magnitude = magnitude; yield return 0; } void Update() { // Shake the camera if (shake) { if (elapsed == 0.0f) { Vector3 originalPos = transform.localPosition; // Save the original position } // Every frame, offset the camera's x and y position for duration seconds for duration seconds if (elapsed < duration) { float x = Random.Range(-1, 1f) * magnitude; float y = Random.Range(-1, 1f) * magnitude; transform.localPosition = new Vector3(x, y, originalPos.z); elapsed += Time.deltaTime; } else // Reset data { transform.localPosition = Vector3.zero; shake = false; elapsed = 0.0f; } } } }
Agreed with keeping this self-programmed instead of using an asset, as it's just a few lines of understandable code. The asset only adds dependency to your project. Also since you have a 3D scene and perspective cam, you rather want to randomize camera.rotation than camera.position, because this will effectively pan the whole screen like a "flat image". Randomizing only the position pans objects close to camera much more than farther objects - unless you really want that effect.
If anyone is having an issue like me were the camera went a little too wild I've modified Brackeys script a bit. public IEnumerator Shake (float duration, float magnitude){
Vector3 originalPos = transform.localPosition; float elapsed = 0.0f; while (elapsed < duration) { float x = Random.Range(-1f,1f) * magnitude; float y = Random.Range(-1f,1f) * magnitude; float z = Random.Range(-1f,1f) * magnitude; //transform.localPosition = new Vector3 (x, y, z); transform.localPosition = new Vector3 (originalPos.x + x, originalPos.y + y, originalPos.z + z); elapsed += Time.deltaTime; yield return null; } transform.localPosition = originalPos;
Another tool worth looking at, if you want more control over your camera shake, is Perlin noise. I highly suggest any budding developer to look up camera shaking with Perlin noise, as it has many other applications (procedural world generation, drunken walking, etc).
For anyone whose script is not working nowadays, this works for me using System.Collections; using System.Collections.Generic; using UnityEngine; public class CamShake : MonoBehaviour { public IEnumerator Shake(float duration, float magnitude) { Vector3 originalPos = transform.localPosition; float elapsed = 0.0f; while (elapsed < duration) { float x =Random.Range(-1f, 1f) * magnitude; float y =Random.Range(-1f, 1f) * magnitude; transform.localPosition = new Vector2(originalPos.x + x, originalPos.y + y); elapsed += Time.deltaTime; yield return null;
Hey Brackeys, instead of parenting the camera, you could also set the local position to new Vector3(x + OriginalPos.x, y + OriginalPos.y, OriginalPos.z)
Please do a tutorial where you give us a project that you made but there are a few problems and you have to go fix them. Thanks in advance dude Also congrats on 400k subs
For those who are struggleing to implement this while camera moves: Dont save cameras original position, and instead just return to vector3.zero. That is if your camera is a child to some empty gameobject, and you have camera movement scr on that empty.
@Sicko Put camera inside an emptyObject If you have cameraScript (Responsible for moving camera) make it so this script moves that emptyObject Then if camera shakes it is inside an empty and you dont have to worry about position change hope that was clear :) if not I may do some quick tutorial on my channel
This is sweet and simple, and also really smooth (this goes under the camera game object) void OnPreRender(){ if (sinceShakeTime > 0.0f) { lastPos = Random.insideUnitCircle * shakeIntensity; transform.localPosition = transform.localPosition + lastPos; void OnPostRender(){ if (sinceShakeTime > 0.0f) { transform.localPosition = transform.localPosition - lastPos; sinceShakeTime -= Time.deltaTime;
3:18 Another way to avoid camera snapping instead of adding an empty game object in the Main camera: Simply change transform.localPosition = new Vector3(x, y, originalPos.z); to transform.localPosition += new Vector3(x, y, originalPos.z);
Using Random.insideUnitCircle (returns Vector2 with a random x and y with the value from 0 to 1) instead of getting random value for both x and y is simpler in this case. So simply: Vector2 shake = Random.insideUnitCircle * magnitude; transform.localPosition = new Vector3(shake.x, shake.y, originalPos.z);
Camera Shaker script prevents me from zooming (changing z-value in camera position). Weird thing is that I can't access and disable the script by FindObjectOfType or by make it a public variable in the inspector. It's just not there. Anyone knows a solution?
What I needed screen to shake on sprint What happened creating a camera holder caused sprint to malfunction camera holder caused controls to be swapped camera holder caused controls to flip depending on the direction the player is facing camera holder somehow caused a glitch where sprint couldn't be turned off so the player moved faster and faster until they started passing through solid objects. there were more but my question is How does an empty object cause so many problems?
Great video. I found one problem. Multiple calls to the shake coroutine before it finishes will set originalPos to the current offset position during the interruption (You'll see this when quickly starting the coroutine over and over again before it finishes). You can fix this by setting the originalPos one time outside as a private field or simply ending each shake with Vector3.zero.
I applied this effect when a ball touches a wall in a 2D project and after the camera shake effect the ball does no longer collide with the wall and can pass right through it. Any idea how to fix?
If the rigidbody isn't already set, change the 'collision detection' from discrete to any 'continuous', this will mean it will always be looking for colliders every frame unlike discrete. If you've already done this then i don't what else to tell u :(
Hi! I have a trouble with this shake effect. I need it for my 2D game. I have camera and canvas with background and characters. I set Canvas Render Mode to Screen Space - Camera and applied this code. It works on the Scene screen, i can see correct shake effect but on the Game screen nothing happens. What shall i do, help me pls?
First I wondered why you'd use the old obsolete non-generic enumerators. Then I wondered why you'd always return null and nothing of importance. Finally I realised coroutines uses yielding as a clever hack (yes, it's a hack) to keep a state machine running.
*How to become a good Unity developer:*
Step 1 - Programm everything yourself
Step 2 - Just delete your code and use something from the asset store
As much of a joke that this is, programming things yourself gives you more flexability and control as well as a sense of pride and acomplishment
lol
too real
"good" haha
He gave us both the options bitch.
8:49 best sound effect ever
fart?
I was not prepared for that, and bust out laughing. That was just genuine comedy.
Hahaha, i was expecting a cool effect for real..
Where can I buy this asset? :D
Uniday Studio nn
I was literally scripting my guns in my game and this video gets uploaded right when I needed it.
Can we get a tutorial on how to do that sound effect you used at the end, seems advanced.
yes i hope he do a tutorial
@@-no9039 lmao
@@zlayer2881 sorry i don't understand
I think you may just download an effect and to play it on click you may make a script in c#
@@-no9039 the end sound was spit lola
I already know 99% of the stuff you publish, but for some reason I just love watching your videos
Same here!
I also know most of it, but sometimes, his videos give me a better and easier way to optimize my codes. No knowledge is lost ;)
Same!
Where have you learn ?
Me neither
pro tip: at the beginning of every Brackeys video, freeze it; you'll get a pretty good look at what he looks like high
the real challenge is trying to figure out what he looks like not high
Recommendation: Instead of Random.Range, try some noise functions. They make the shake less erratic and a bit more realistic. There's a great GDC video about that.
The fact that this is one of the only and few camera effects that don't get broken with HDRP deserves an extra comment after 2 years
I like that you show both how to start writing your own shake, and then also shows a good assets - but unlike most you also import the asset and shows how to actually use it.
I just want to say thank you... You have helped me out in my programming experience, and I couldn't do any of it without your easy-to-learn explanations. I hope someday to be able to make games as good as you...
"Go back into unity, there should be no errors"
My Console: ❗️❗️❗️❗️❗️❗️❗️
As of October 2, 2021, I officially no longer like this comment.
Same :D I did a typo though :)
169
HAHHAHA I RUINED IT DONT KILL ME
"; ;" its all it takes
can someone heweeeellllp my console wants to kill itself
Brackeys: "Now we need some sound effects"
Me: Wow! what a complete tutorial!!
Brackeys: *Mouth sounds*
when you made that soundeffect, i felt that
DOTween is great for this kind of stuff. Even the free version has some really cool extensions for camera shake, punching out the scale of things to make them "pop". You can "tween" any value you want pretty easily too.
me as a beginner programmer still watchin his class and arrays videos this looks like magic to me
stannis Barracuda You really shouldn't be watching any of this without base desirably C based language knowledge
Green Shadow dont listen to this guy, people all over say things like this but you learn so much from these types of videos that you can apply later on
Yeah, totally, perhaps you don't learn quite as much as if you would understand basic stuff, but there is still something to learn here. It's cool to see what you could be able to do and get more familiar with the code syntax. However, it's not good either to just watch these videos if you don't understand the basics.
Kaf3in0 B Yeah that is true, I sounded kind of rude responding to that other guy but you should never be discouraged to watch a video that you dont fully understand. Videos like these used to motivate me to learn and practice more to achieve this type of success.
it'll grow on you. Keep learning.
Heeeeeeeey, I started *shaking* because of that pun! Am I part of the joke-class now? 👏
Sykoo NO ! ;)
Just gotta keep trying (and editing your comments) ;)
SYKOO!
I'm shaking my fist every time Sykoo releases another inaccurate video.
yes
8:50 the best sound effect I've ever heard. Gotta download it.
0:46 every mobile game "dev" be like: "yes i need that tutorial, no not the game development part, the ad part"
can i use your sound effect 8:50 for my game ?
Haha, sure! :D
@@Brackeys YEEEET
i wanna use this sound in my video as Fart's sound instead of explosion
I love you. I'm an Egyptian programmer . I learned many at unity because of you
Me: trying to relax listening to the sounds of the forest
*puts on brackeys video instead
I have found this comment by sorting all of these comments by the Newest First. You have gotten yourself the award of, "The Newest Comment as of 7-24-2021"
@@yourfellowgamer487 Thank you, i guess.
The sound effect was awesome! 8:49
btw the cute way to do this is to put the starting of the coroutine inside of a different function inside of your camera shake object, and just calling that function every time so you dont have to use weird different syntax.
And this is guys how the Quarantine started all because of my man Big Brack.
Oh man 8:49 im ready for that sound effects tutorial.
Great tutorial, was looking for a camera shake one :D
Yo your sound effects are so good you should upload them on the Unity Store
That sound effect had me laughing for a bit :D
The asset store camera shake is fine IF you don't ever reset your scene because it fucks the camera
Where can I download that amazing sound effect at the end? Link please
Darknet only
John LaBrie I really hope you are joking
Pls share. I also need it
I NEED!
Fruidacity
That final sound effect Lol ! you're getting better at telling jokes ,,, Thanks man you and your team are awesome !
I miss you, Brackeys ! I hope you and your team are doing well
Hello, if for some reason your code is not working, rewrite it like this... this works for me
public class CameraShake : MonoBehaviour
{
// Set up data
bool shake = false;
float duration;
float magnitude;
Vector3 originalPos;
float elapsed;
// Shake the screen
public IEnumerator Shake (float duration, float magnitude)
{
// Setup data for camera to be shaked
shake = true;
this.duration = duration;
this.magnitude = magnitude;
yield return 0;
}
void Update()
{
// Shake the camera
if (shake)
{
if (elapsed == 0.0f)
{
Vector3 originalPos = transform.localPosition; // Save the original position
}
// Every frame, offset the camera's x and y position for duration seconds for duration seconds
if (elapsed < duration)
{
float x = Random.Range(-1, 1f) * magnitude;
float y = Random.Range(-1, 1f) * magnitude;
transform.localPosition = new Vector3(x, y, originalPos.z);
elapsed += Time.deltaTime;
}
else // Reset data
{
transform.localPosition = Vector3.zero;
shake = false;
elapsed = 0.0f;
}
}
}
}
Agreed with keeping this self-programmed instead of using an asset, as it's just a few lines of understandable code. The asset only adds dependency to your project.
Also since you have a 3D scene and perspective cam, you rather want to randomize camera.rotation than camera.position, because this will effectively pan the whole screen like a "flat image". Randomizing only the position pans objects close to camera much more than farther objects - unless you really want that effect.
Dude nice! This is one of the first times I've seen a practical use of a coroutine. I'm sure there are tons though. Thanks!
I only give you a like because of that awesome Sound Effect :)
It appears that the package EZ Camera Shake is not in the asset store anymore.
Look in the description, there is a GitHub Link to it
If anyone is having an issue like me were the camera went a little too wild I've modified Brackeys script a bit.
public IEnumerator Shake (float duration, float magnitude){
Vector3 originalPos = transform.localPosition;
float elapsed = 0.0f;
while (elapsed < duration) {
float x = Random.Range(-1f,1f) * magnitude;
float y = Random.Range(-1f,1f) * magnitude;
float z = Random.Range(-1f,1f) * magnitude;
//transform.localPosition = new Vector3 (x, y, z);
transform.localPosition = new Vector3 (originalPos.x + x, originalPos.y + y, originalPos.z + z);
elapsed += Time.deltaTime;
yield return null;
}
transform.localPosition = originalPos;
Thank you.
thanks man
Another tool worth looking at, if you want more control over your camera shake, is Perlin noise. I highly suggest any budding developer to look up camera shaking with Perlin noise, as it has many other applications (procedural world generation, drunken walking, etc).
5/5 on the explosion sound at the end! I'm going to use that for explosions in my game now! "Pbfffff"!! Great video like always Brackey's!!
For anyone whose script is not working nowadays, this works for me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamShake : MonoBehaviour
{
public IEnumerator Shake(float duration, float magnitude)
{
Vector3 originalPos = transform.localPosition;
float elapsed = 0.0f;
while (elapsed < duration)
{
float x =Random.Range(-1f, 1f) * magnitude;
float y =Random.Range(-1f, 1f) * magnitude;
transform.localPosition = new Vector2(originalPos.x + x, originalPos.y + y);
elapsed += Time.deltaTime;
yield return null;
}
transform.localPosition = originalPos;
}
}
@Sicko no problem! Glad I could help
The thumbnail is a Besiege screenshot xD (good job DAN)
Hey Brackeys, instead of parenting the camera, you could also set the local position to new Vector3(x + OriginalPos.x, y + OriginalPos.y, OriginalPos.z)
Bruh, thank you so much, that saved me such a hassle. comment was 6 years ago, but still helping out here xd
I can’t explain how much you helped me out
Please do a tutorial where you give us a project that you made but there are a few problems and you have to go fix them.
Thanks in advance dude
Also congrats on 400k subs
8:52 "PPPPFFFFFFF!" Loved the sound effect!
Haha, that sound effect made my day! :D
For those who are struggleing to implement this while camera moves:
Dont save cameras original position, and instead just return to vector3.zero. That is if your camera is a child to some empty gameobject, and you have camera movement scr on that empty.
Thank you
@@GameDevJosh No problem m8
@Sicko
Put camera inside an emptyObject
If you have cameraScript (Responsible for moving camera) make it so this script moves that emptyObject
Then if camera shakes it is inside an empty and you dont have to worry about position change
hope that was clear :)
if not I may do some quick tutorial on my channel
This is sweet and simple, and also really smooth (this goes under the camera game object)
void OnPreRender(){
if (sinceShakeTime > 0.0f) {
lastPos = Random.insideUnitCircle * shakeIntensity;
transform.localPosition = transform.localPosition + lastPos;
void OnPostRender(){
if (sinceShakeTime > 0.0f) {
transform.localPosition = transform.localPosition - lastPos;
sinceShakeTime -= Time.deltaTime;
The EZ CameraShake is awesome! Thanks for the video.
The very awesome part you did is the sound effects. I didn't see that coming.
Awesome camera shake tutorial! 👍🤓🧡
3:18
Another way to avoid camera snapping instead of adding an empty game object in the Main camera:
Simply change transform.localPosition = new Vector3(x, y, originalPos.z);
to transform.localPosition += new Vector3(x, y, originalPos.z);
This is a very epic tutorial, now I can create camera shake easily 👍👍👍
yea
8:50 SFX Approved by the best Minecraft Slime in the world
Your thumbmail looks like the game Besiege!
That's because it's literally a screenshot from the trailer.
how he tries to cover up his jokes is 10x funny then any jokes🤣
If you are into math, you could try making the shake yourself using cos(f*t)*k^-t as a base. k marks how fast the shake will fade out and f frequency
Thanks for the tutorial. All of your tutorials help me a lot!
That sound affect doe. seems really advanced
Using Random.insideUnitCircle (returns Vector2 with a random x and y with the value from 0 to 1) instead of getting random value for both x and y is simpler in this case.
So simply:
Vector2 shake = Random.insideUnitCircle * magnitude;
transform.localPosition = new Vector3(shake.x, shake.y, originalPos.z);
That's what I needed, thanks Brackeys!
this video helped me with an unrelated cause lol, nice vid!
Asset Store Page of EZ Camera Shake: "Unfortunately, EZ Camera Shake is no longer available.
This package has been deprecated from the Asset Store. "
It is open-sourcing on GitHub though ;)
Yes, It's open sourced and here is the link github.com/andersonaddo/EZ-Camera-Shake-Unity
sweet with this plus your menu videos I can make a menu to disable camera shake. That's my favorite setting.
he is always smiling!
I suscribed in the moment that i heard that amazing sound effect
Well, i am learning so much.
We're gonna miss you terribly.
Just use the animation and animate the camera and trigger(or other like bool) when u explode
This camera shake varies depending on your frame rate, and you can only call it once at a time. Guess the asset'll do the job. :-\
he multiplied it with Time.deltaTime , so no it doesnt depend on your framerate.
Dat sound effect dough
You can also use DoTween camera shake. That's the same thing but more comes with it.
You did a good job, really really thanks for providing such an amazing tutorial.
Camera Shaker script prevents me from zooming (changing z-value in camera position). Weird thing is that I can't access and disable the script by FindObjectOfType or by make it a public variable in the inspector. It's just not there. Anyone knows a solution?
Did anyone notice that Yorai Omer, one of the creators of Terraria, is a patreon of brackeys?
bold of you to use a while loop in unity
i wish you were my friend. I would rather learn from you everyday
6:54 when you create something and present it to your friends
Honestly that is so true
Every game must have shakes when collide with something to make the game more dynamic
HAHAHA Best explosion sound effect ever!
only a few special people would know that the thumbnail is from besiege
Rocket league has the best camera shake
Khàléd HàllOuà totally agree
That's because they eat their Wheaties and watch their Brackey's :P
Ambient Relaxation lol :p
Bro force
Good luck trying to use this with Cinemachine or a follow based camera. You'll need to use noise.
Thank you very much for sharing this video! EZCameraShaker seems very useful! :)
best sound FX EVEEEEEEEEEEER!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraShake : MonoBehaviour
{
public IEnumerator Shake (float duration, float magnitude)
{
Vector3 originalPos = transform.localPosition;
float elapsed = 0.0f;
while (elapsed < duration)
{
float x = Random.Range(-1f, 1f) * magnitude;
float y = Random.Range(-1f, 1f) * magnitude;
transform.localPosition = new Vector3(x, y, originalPos.z);
elapsed += Time.deltaTime;
yield return null;
}
transform.localPosition = originalPos;
}
}
thanks
CHAD
I am making a 2d game and want to use this but whenever it shakes the position of camera gets all messed up. How do I fix this?
Cool sound effect jajaja XD, good Job!
What I needed screen to shake on sprint
What happened creating a camera holder caused sprint to malfunction
camera holder caused controls to be swapped
camera holder caused controls to flip depending on the direction the player is facing
camera holder somehow caused a glitch where sprint couldn't be turned off so the player moved faster and faster until they started passing through solid objects.
there were more but my question is
How does an empty object cause so many problems?
Great video. I found one problem. Multiple calls to the shake coroutine before it finishes will set originalPos to the current offset position during the interruption (You'll see this when quickly starting the coroutine over and over again before it finishes). You can fix this by setting the originalPos one time outside as a private field or simply ending each shake with Vector3.zero.
for people that its not working for you ( EZ camera shake ) its not working with cinemachine , this is sad so yea
Great video! Helped me out a lot. Thank you!
there is lots of other ways to do this, you can use local transform with a interval on the camera.
You could make the coroutine public static that way you don't need to put it on a gameobject
I applied this effect when a ball touches a wall in a 2D project and after the camera shake effect the ball does no longer collide with the wall and can pass right through it. Any idea how to fix?
If the rigidbody isn't already set, change the 'collision detection' from discrete to any 'continuous', this will mean it will always be looking for colliders every frame unlike discrete. If you've already done this then i don't what else to tell u :(
@@tssper3488 Thanks for the response! I have already tried that but still the same :(
Really need a tutorial on inAppPurchases. Unity IAP or Unity Ads or AdMob. I don't know how to set it up to monetize my game. Thanks Brackeys!!
For some reason I can only get this to work if the MainCamera is not in the CameraHolder
10/10 sound effects
Hi! I have a trouble with this shake effect. I need it for my 2D game. I have camera and canvas with background and characters. I set Canvas Render Mode to Screen Space - Camera and applied this code. It works on the Scene screen, i can see correct shake effect but on the Game screen nothing happens. What shall i do, help me pls?
First I wondered why you'd use the old obsolete non-generic enumerators.
Then I wondered why you'd always return null and nothing of importance.
Finally I realised coroutines uses yielding as a clever hack (yes, it's a hack) to keep a state machine running.