Created
May 30, 2017 09:33
-
-
Save buijldert/4dafe41566812f120f6e925ad5e474bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class CameraShake : MonoBehaviour { | |
private bool _isShaking = false; | |
[SerializeField]private float _shakeDuration = 0.25f; | |
[SerializeField]private float _originalXPos = 0f; | |
[SerializeField]private float _originalYPos = 0f; | |
[SerializeField]private float _shakeIntensity = 0.5f; | |
private float _offsetXPos; //set to _originalXpos +/- _shakeIntensity | |
private float _offsetYPos; //set to _originalYPos +/- _shakeIntensity | |
// Use this for initialization | |
void Start () | |
{ | |
_offsetXPos = _originalXPos + _shakeIntensity; | |
_offsetYPos = _originalXPos - _shakeIntensity; | |
} | |
// Update is called once per frame | |
void Update () | |
{ | |
CheckForShake(); | |
} | |
//start duration of the shake and shake itself | |
public void Shake() | |
{ | |
_isShaking = true; | |
StartCoroutine(CameraShaking()); | |
} | |
//check if camera should be shaking, if yes, starts shaking | |
void CheckForShake() | |
{ | |
if (_isShaking) | |
{ | |
gameObject.transform.position = new Vector2(Random.Range(_originalXPos, _offsetXPos), Random.Range(_originalYPos, _offsetYPos)); | |
} | |
else | |
{ | |
gameObject.transform.position = new Vector2(_originalXPos , _originalYPos); | |
} | |
} | |
//duration of the shake | |
IEnumerator CameraShaking() | |
{ | |
yield return new WaitForSeconds(_shakeDuration); | |
_isShaking = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment