• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
7
Question by GreyWolf · Jan 31, 2012 at 06:10 PM · camerapositionlocalshake

Camera shake

Hey guys how can i make a simlpe camera shake that returns 2 its original position after shaking

 function Update() {
  
     if(Shake < 0){
     
      Shake =  0;
       
        } 
 
   if (Shake > 0) {
     
        cam.transform.localPosition = Random.insideUnitSphere * shakeAmount; 
     
             Shake -= Time.deltaTime * decreaseFactor;
 
 
   } else {
     shake = 0.0;
   }
 }
Comment
Add comment · Show 5
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Berenger · Jan 31, 2012 at 07:19 PM 0
Share

For a simple way, try that. For something a little more heavy, might be a little to much if you just want the camera shake : ShakePosition de iTween.

avatar image fafase · Jan 31, 2012 at 07:21 PM 0
Share

You could use a sin function with a damping constant. (Sounds scientic!!!)

Ae^(-kt) cos(wt)

e^(-kt) means e to the power of (-kt). This function will creates a large oscillation depending on you A that will reduce in time to finish to 0. The duration and tilting of your camera depends on the (-kt).

That might not be what you want but if that can lead you somewhere.

avatar image Fattie · Jan 31, 2012 at 07:28 PM 0
Share

You have to save the original position bud. There's no other way.

Your randomisation using the unit sphere is perfect: BUT you have to do "two jiggles" at a time. Always move it using your current system, and then in the new step simply return it to where it was.

Just use parity (i.e. odd/even) to know which you are supposed to do, ok

avatar image insominx · May 17, 2013 at 08:20 PM 0
Share

This blog covers it pretty well: http://unitytipsandtricks.blogspot.com/2013/05/camera-shake.html

avatar image Fattie · Jun 24, 2015 at 05:07 PM 0
Share

For the record it is extremely hard to actually program the physics of hand-held camera shake, "wind" shake, tripod shudder, and other versions of camera shake. Note that in unity you can simply attach a spring to the camera and let physX do the work, no coding required. This would be a winning idea since, uh, you pay $4500 for Unity "since it has a physics engine". So use it. By no means does a "spring on a camera" produce really realistic "camera shake", but it's better than using Perlin Noise. Perlin Noise is sort of ok; the other "solutions" on here are silly.

Getting back to the actual question asked by the OP, conceptually yes you have to save the "original" position (indeed the "base" position, which in any non-trivial system will, of course, be moving. You have to have a whole complicated system representing where the camera is "ideally" and so on.)

11 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by squareorb · Jun 24, 2015 at 10:26 AM

I really liked this solution for what I'm working on so I thought I'd share the modifications I made. I added the ability to select from the inspector whether you just want to shake position, rotation or both. I also made the intensity and decay values public so they can be set from the inspector as well. And most importantly took the bulk of the code out of the update method and made it a coroutine. This keeps it from checking the shakeIntensity on every single frame whether shaking or not. Cheers!

 using UnityEngine; 
 using System.Collections;
 
 public class ShakeCamera : MonoBehaviour { 
 
     public bool shakePosition;
     public bool shakeRotation;
 
     public float shakeIntensity = 0.5f; 
     public float shakeDecay = 0.02f;
     
     private Vector3 OriginalPos;
     private Quaternion OriginalRot;
 
     private bool isShakeRunning = false;
 
     
     public void DoShake()
     {
         OriginalPos = transform.position;
         OriginalRot = transform.rotation;
 
         StartCoroutine ("ProcessShake");
     }
 
     IEnumerator ProcessShake()
     {
         if (!isShakeRunning) {
             isShakeRunning = true;
             float currentShakeIntensity = shakeIntensity;
 
             while (currentShakeIntensity > 0) {
                 if (shakePosition) {
                     transform.position = OriginalPos + Random.insideUnitSphere * currentShakeIntensity;
                 }
                 if (shakeRotation) {
                     transform.rotation = new Quaternion (OriginalRot.x + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f,
                                                         OriginalRot.y + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f,
                                                         OriginalRot.z + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f,
                                                         OriginalRot.w + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f);
                 }
                 currentShakeIntensity -= shakeDecay;
                 yield return null;
             }
 
             isShakeRunning = false;
         }
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Razzik · Oct 22, 2015 at 08:22 AM

Hi @squareorb Thanks so much for the solution. It works like a charm!

I thought I'd never find a fix for getting a good Camera Shake. Just a quick one though.

Do you know of a method to somehow make only the X Y or Z Axis shake when you shake the position. I've tried converting everything to floats by using the .x/.y/.z parameters on the vector3's but it doesn't seem to work.

Any Suggestions? Thanks again!

Kind Regards,

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Razzik · Oct 22, 2015 at 08:21 AM 0
Share

Hi Guys and @squareorb,

Not to worry. I found a way to do it. Rookie error

Here it is if anyone wants to change the shake direction for any reason and they're not sure how.

 using UnityEngine; 
 using System.Collections;
 
 public class ShakeCamera : $$anonymous$$onoBehaviour { 
     
     public bool shakePosition;
     public bool shakeRotation;
     
     public float shakeIntensity = 0.5f; 
     public float shakeDecay = 0.02f;
     
     private Vector3 OriginalPos;
     private Quaternion OriginalRot;
     
     private bool isShakeRunning = false;
     
 
     public void DoShake()
     {
 
 
         OriginalPos = transform.position;
         OriginalRot = transform.rotation;
         
         StartCoroutine ("ProcessShake");
     }
     
     IEnumerator ProcessShake()
     {
         if (!isShakeRunning) {
             isShakeRunning = true;
             float currentShakeIntensity = shakeIntensity;
             
             while (currentShakeIntensity > 0) {
                 if (shakePosition) {
                     transform.position = new Vector3(Random.insideUnitSphere.x * currentShakeIntensity, transform.position.y ,transform.position.z);
                     // just change the float values of the Vector3 Component to Random.insideUnitSphere.x/y/z where you see fit.
                 }
                 if (shakeRotation) {
                     transform.rotation = new Quaternion (OriginalRot.x + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f,
                                                          OriginalRot.y + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f,
                                                          OriginalRot.z + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f,
                                                          OriginalRot.w + Random.Range (-currentShakeIntensity, currentShakeIntensity) * .2f);
                 }
                 currentShakeIntensity -= shakeDecay;
                 yield return null;
             }
             
             isShakeRunning = false;
         }
     }
 }

As Commented:

// just change the float values of the Vector3 Component to Random.insideUnitSphere.x/y/z where you see fit.

I hope it helps anyone who comes across this.

Thanks again guys.

avatar image
0

Answer by CreativeMatter · Jun 19, 2016 at 05:05 AM

Have a look at this thread

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Mr-Slat · Jul 31, 2018 at 05:17 PM

To anyone still trying to find an answer. Or someone who might want to improve my code here it goes.

This works if you put your camera GameObject as a child of another Transform (this parent Transform holds the true position of the camera while we shake the camera by changing the childs transform position rotation and fov).

First let's define a class for our shake….

 public class CameraShake
 {
     public struct ElementShake
     {
         public float amplitude,
                      frequency;
 
         public ElementShake(float amplitude, float frequency)
         {
             this.amplitude = amplitude;
             this.frequency = frequency;
         }
     }
 
     public float duration,
                  blendInTime,
                  blendOutTime;
     public ElementShake[] rotationShake = new ElementShake[3];
     public ElementShake[] positionShake = new ElementShake[3];
     public ElementShake fieldOfViewShake;
 
     public CameraShake()
         : this(1f, 0.1f, 0.2f)
     {
     }
 
     public CameraShake(float duration, float blendInTime, float blendOutTime)
     {
         this.duration = duration;
         this.blendInTime = blendInTime;
         this.blendOutTime = blendOutTime;
 
 
         for (int i = 0; i < rotationShake.Length; i++)
             rotationShake[i] = new ElementShake(0f, 0f);
         for (int i = 0; i < positionShake.Length; i++)
             rotationShake[i] = new ElementShake(0f, 0f);
 
         fieldOfViewShake = new ElementShake(0f, 0f);
     }
 }


Now lets define our player controller :

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class PlayaController : MonoBehaviour
 {
     internal struct CameraShakeSettings
     {
         public Vector3      pos,
                             initialPosition;
         public Vector3      rot,
                             initialRotation;
         public float        fov,
                             initialFieldOfView;
         public Coroutine    shakeCoroutine;
     }
 
     public Camera mainCamera;
     static PlayaController controller;
     private CameraShakeSettings cameraShakeSettings = new CameraShakeSettings();
 
     private void Awake()
     {
         controller = this;
     }
 
     private void Start()
     {
         cameraShakeSettings.initialPosition = mainCamera.transform.localPosition;
         cameraShakeSettings.initialRotation = mainCamera.transform.localRotation.eulerAngles;
         cameraShakeSettings.initialFieldOfView = mainCamera.fieldOfView;
     }
 
     public static void PlayCameraShake(CameraShake cameraShake, float scale = 1f)
     {
         if (controller == null)
             return;
 
         if (controller.cameraShakeSettings.shakeCoroutine != null)
             controller.StopCoroutine(controller.cameraShakeSettings.shakeCoroutine);
 
         controller.cameraShakeSettings.shakeCoroutine = controller.StartCoroutine(controller.ShakeCamera(cameraShake, scale));
     }
 
     private IEnumerator ShakeCamera(CameraShake cameraShake, float scale)
     {
         float blendScale = 0f;
         float blendInTimer = cameraShake.duration * Mathf.Min(cameraShake.blendInTime, 1f);
         float blendOutTimer = cameraShake.duration * Mathf.Min(cameraShake.blendOutTime, 1f);
         float timer = 0f;
 
         Camera cam = mainCamera;
         Transform t = cam.transform;
 
         while (timer <= cameraShake.duration)
         {
             float blendInScale = Mathf.Clamp01(timer / blendInTimer);
             float blendOutScale = Mathf.Clamp01((cameraShake.duration - timer) / blendOutTimer);
 
             blendScale = scale * blendInScale * blendOutScale;
 
             float blendTime = timer / cameraShake.duration;
 
             cameraShakeSettings.rot.x = (Mathf.Cos(blendTime * cameraShake.rotationShake[0].frequency * Mathf.Rad2Deg) * cameraShake.rotationShake[0].amplitude) * blendScale;
             cameraShakeSettings.rot.y = (Mathf.Cos(blendTime * cameraShake.rotationShake[1].frequency * Mathf.Rad2Deg) * cameraShake.rotationShake[1].amplitude) * blendScale;
             cameraShakeSettings.rot.z = (Mathf.Cos(blendTime * cameraShake.rotationShake[2].frequency * Mathf.Rad2Deg) * cameraShake.rotationShake[2].amplitude) * blendScale;
 
             t.localRotation = Quaternion.Euler(cameraShakeSettings.initialRotation.x + cameraShakeSettings.rot.x,
                                                cameraShakeSettings.initialRotation.y + cameraShakeSettings.rot.y,
                                                cameraShakeSettings.initialRotation.z + cameraShakeSettings.rot.z);
 
             cameraShakeSettings.pos.x = (Mathf.Cos(blendTime * cameraShake.positionShake[0].frequency * Mathf.Rad2Deg) * cameraShake.positionShake[0].amplitude);
             cameraShakeSettings.pos.y = (Mathf.Cos(blendTime * cameraShake.positionShake[1].frequency * Mathf.Rad2Deg) * cameraShake.positionShake[1].amplitude);
             cameraShakeSettings.pos.z = (Mathf.Cos(blendTime * cameraShake.positionShake[2].frequency * Mathf.Rad2Deg) * cameraShake.positionShake[2].amplitude);
 
             t.localPosition = cameraShakeSettings.initialPosition + cameraShakeSettings.pos * blendScale;
 
             cameraShakeSettings.fov = (Mathf.Cos(blendTime * cameraShake.fieldOfViewShake.frequency * Mathf.Deg2Rad) * cameraShake.fieldOfViewShake.amplitude) * blendScale;
 
             cam.fieldOfView = cameraShakeSettings.initialFieldOfView + cameraShakeSettings.fov;
 
             timer += Time.deltaTime;
             yield return null;
         }
 
         t.localRotation = Quaternion.Euler(cameraShakeSettings.initialRotation);
         t.localPosition = cameraShakeSettings.initialPosition;
         cam.fieldOfView = cameraShakeSettings.initialFieldOfView;
     }
 
     private void Update()
     {
         if (Input.GetKeyDown(KeyCode.S))
         {
             CameraShake shake = new CameraShake(1f, 0.5f, 0.5f);
             //Rotation shake On X axis
             shake.rotationShake[0].amplitude = 0.1f;
             shake.rotationShake[0].frequency = 10000;
 
             //Rotation shake ON Y axis
             shake.rotationShake[1].amplitude = 0.1f;
             shake.rotationShake[1].frequency = 10000;
 
             //Rotation shake On Z axis
             shake.rotationShake[2].amplitude = 0.1f;
             shake.rotationShake[2].frequency = 10000;
 
             //Position shake On X axis
             shake.positionShake[0].amplitude = 0.1f;
             shake.positionShake[0].frequency = 10000;
 
             //Position shake On Y axis
             shake.positionShake[1].amplitude = 0.1f;
             shake.positionShake[1].frequency = 10000;
 
             //Position shake On Z axis
             shake.positionShake[2].amplitude = 0.1f;
             shake.positionShake[2].frequency = 10000;
 
             //Field of view shake
             shake.fieldOfViewShake.amplitude = 1f;
             shake.fieldOfViewShake.frequency = 100000;
 
             PlayCameraShake(shake, 0.4f);
         }
     }
 }

You should now be able to Press S and see the camera shake. With this code you can just play the shake from any script by calling the player controller method like this :

PlayaController.PlayCameraShake(cameraShake);

If anybody finds this useful just comment or if you find a bug let me know I'll correct it.

if you can find me a solution to play 2 camera shakes at the same time let me know.

Cheers everybody. Hope this helps.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Mr-Slat · Jul 31, 2018 at 05:24 PM 0
Share

Just some improvement (Not tested yet but it should be fine) :

change this :

float blendInTimer = cameraShake.duration * $$anonymous$$athf.$$anonymous$$in(cameraShake.blendInTime, 1f);

float blendOutTimer = cameraShake.duration * $$anonymous$$athf.$$anonymous$$in(cameraShake.blendOutTime, 1f);

to this :

float blendInTimer = cameraShake.duration * $$anonymous$$athf.Clamp($$anonymous$$athf.$$anonymous$$in(cameraShake.blendInTime, 1f), 0, cameraShake.duration);

float blendOutTimer = cameraShake.duration * $$anonymous$$athf.Clamp($$anonymous$$athf.$$anonymous$$in(cameraShake.blendOutTime, 1f), 0, cameraShake.duration);

avatar image
0

Answer by unity_r5heKATI1ZTDsA · Nov 26, 2018 at 06:27 PM

The snippet in this post works perfectly for me: https://medium.com/@mattThousand/basic-2d-screen-shake-in-unity-9c27b56b516

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • ‹
  • 1
  • 2
  • 3
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Constant camera shake. 1 Answer

How to move camera up and down 1 Answer

Is it possible to shake the camera? 4 Answers

Is there an elegant way of limiting camera's position? 1 Answer

How to freeze the rotation or the position on the camera transform? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges