Hi everyone. I am trying to add screen shake on a collision.

Hi everyone. I followed the unity space shooter tutorial but have changed into a side scroller and I am trying to add features. I am stuck on camera shake. If anyone could direct me or help me implement it when the bullet hits the object I would be grateful. I am also trying to add point display at the origin of the explosion when the object is hit but that is a secondary issue. Thanks

using UnityEngine;
using System.Collections;

public class DestroyByContactAlt : MonoBehaviour

{
    public GameObject explosion;
    public GameObject explosionAlt;
    public GameObject playerExplosion;
    public int scoreValue;
    //public TextGenerator killText;
    private GameController gameController;



    void Start()
    {
        GameObject gameControllerObject = GameObject.FindWithTag("GameController");
        if (gameControllerObject != null)
        {
            gameController = gameControllerObject.GetComponent<GameController>();
        }
        if (gameController == null)
        {
            Debug.Log("Cannot find 'GameController' script");
        }
    }



    void OnTriggerEnter(Collider other)
        
        {     
       
        if (other.tag == "Boundary")
        {
            return;
        }
        Instantiate(explosion, transform.position, transform.rotation);
        Instantiate(explosionAlt, transform.position, transform.rotation);
        //Instantiate (killText, transform.position, transform.rotation);

    
       
        if (other.tag == "Player")
        {
            Instantiate(playerExplosion, other.transform.position, other.transform.rotation);

            gameController.GameOver();
        }
        gameController.AddScore(scoreValue);
        Destroy(other.gameObject);
        Destroy(gameObject);
    }
   

}

Not sure how your project is set up but the easiest way to screen-shake is to have a coroutine and adjust the offset of the camera from where it is supposed to be for a short period of frames after the impact you care about.

Some things to keep in mind:

  • you probably only want one shake active at a time (either stop the first one or else prevent more than one from starting)
  • record the position of the camera before the shaking so you can restore it at the end
  • a little bit of shaking goes a long way
  • a series of random shakes starting large and getting smaller is a good way to go

Another way is to have the camera actually be one game object “below” (i.e. parented to) the object that it presently sits on. That way you can just adjust the transform.localPosition of the child object to get the shaking, then set it back to Vector3.zero when you want it to restore to normal offset from the parent.

1 Like

This is solved?