Here I found a code that shakes the camera: https://gist.github.com/ftvs/5822103
But how to use it if I want to shake the camera only when a bullet hits something?
In the link you posted there are:
// How long the object should shake for.
public float shake = 0f;
If the shake
variable is set to for example 1 the camera will shake as long as it is greater than one. The code is decreasing the value so that the number you set is equivalent to seconds you want the shake to last.
Then how to shake when bullet hits something? You can add code to the bullet that starts the shaking. This can be done in the collision of the bullet. Use something like this:
public class BulletScript : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
GameObject.Find("Main Camera").GetComponent<CameraShake>().shake = 0.25f;
}
}
For this to work you need the bullet and the counter part to have 2D colliders.
PS. Find
is really slow operation, so you might want to optimize the code by setting pointer to CameraShake into static variable only once in a scene.