Your Cart
Loading
how to add camera shake in unity 2d unity 2d camera shake tutorial

How To Add Camera Shake In Unity 2D | Unity Tutorial

How To Add Camera Shake In Unity 2D | Unity Tutorial


In this tutorial, you'll learn how to implement a camera shake effect in Unity 2D to enhance the impact of collisions and add excitement to your game. We'll walk through creating a CameraShake script that applies a dynamic shake effect to the camera, adjusting the intensity and duration of the shake. You'll also see how to trigger this effect in response to collisions with specific objects, giving your game a more polished and engaging feel. Perfect for beginners and seasoned developers alike, this video provides step-by-step instructions and practical examples to help you integrate camera shake into your Unity 2D projects effectively.



WATCH FULL TUTORIAL ON YOUTUBE



CHECK OUR PROJECTS


SUBSCRIBE FOR LATEST OFFERS



=========================================================


3 Unity Projects Only $50 - ON SALE!!!!

https://youtu.be/7mI-fJpXN88


Contact: unitycoderz2022@gmail.com


=========================================================



Scripts:


CameraShake.cs


using UnityEngine;


public class CameraShake : MonoBehaviour

{

  private float shakeDuration = 0f; // Ensure this starts at 0

  public float shakeMagnitude = 0.1f;

  public float dampingSpeed = 1f;


  private Vector3 originalPosition;


  void Awake()

  {

    originalPosition = transform.position;

  }


  void Update()

  {

    if (shakeDuration > 0)

    {

      // Apply shake effect

      transform.position = originalPosition + Random.insideUnitSphere * shakeMagnitude;


      // Decrease shake duration

      shakeDuration -= Time.deltaTime * dampingSpeed;


      // Reset position when duration ends

      if (shakeDuration <= 0)

      {

        shakeDuration = 0f;

        transform.position = originalPosition;

      }

    }

  }


  public void TriggerShake(float duration, float magnitude)

  {

    shakeDuration = duration;

    shakeMagnitude = magnitude;

  }

}


------------------------------------------------------------------------------------------------------------------------------------------


PlayerCollision.cs


using UnityEngine;


public class PlayerCollision : MonoBehaviour

{

  public CameraShake cameraShake;

  public float shakeDuration = 0.2f;

  public float shakeMagnitude = 0.2f;


  void OnCollisionEnter2D(Collision2D collision)

  {

    if (collision.gameObject.CompareTag("Collider"))

    {

      if (collision.relativeVelocity.magnitude > 1) // Adjust threshold if needed

      {

        cameraShake.TriggerShake(shakeDuration, shakeMagnitude);

      }

    }

  }

}





DOWNLOAD CODESTER FILES