Created
March 20, 2015 18:51
-
-
Save jessefreeman/79b07400b474aaf51e9e to your computer and use it in GitHub Desktop.
Simple Unity 2D Camera
This file contains 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 CameraFollow : MonoBehaviour { | |
public GameObject target; | |
public bool lockXAxis; | |
public bool lockYAxis; | |
public bool lockZAxis = true; | |
public bool useBounds = false; | |
public Rect cameraBounds; | |
public float shakeDuration; | |
public float shakeStrength; | |
private bool shakeRunning; | |
private float shakeTimeElapsed = 0; | |
// Update is called once per frame | |
void Update () { | |
if (target != null) | |
{ | |
var pos = transform.position; | |
if (!lockXAxis) | |
pos.x = target.transform.position.x; | |
if (!lockYAxis) | |
pos.y = target.transform.position.y; | |
if (!lockZAxis) | |
pos.z = target.transform.position.z; | |
if (shakeTimeElapsed < shakeDuration && Time.timeScale > 0) | |
{ | |
//TODO need to make this better | |
var distance = Mathf.Round(Random.Range(-shakeStrength, shakeStrength)); | |
pos.x = (int)target.transform.position.x + distance; | |
pos.y = (int)target.transform.position.y + distance; | |
shakeTimeElapsed += Time.deltaTime; | |
var oldFilter = Camera.main.GetComponent<OLDTVFilter>(); | |
oldFilter.noiseMagnetude = .01f * shakeStrength/ 3; | |
} | |
else if (shakeRunning) | |
{ | |
// print("Stop Shake"); | |
shakeRunning = false; | |
var oldFilter = Camera.main.GetComponent<OLDTVFilter>(); | |
oldFilter.noiseMagnetude = 0; | |
} | |
if (useBounds) | |
{ | |
pos.x = (int)Mathf.Round(Mathf.Clamp(pos.x, cameraBounds.x, cameraBounds.width)); | |
pos.y = (int)Mathf.Round(Mathf.Clamp(pos.y, cameraBounds.y, cameraBounds.height)); | |
} | |
transform.position = pos; | |
} | |
} | |
public void Shake(float duration = 1, float strength = 3) | |
{ | |
if (shakeRunning) | |
return; | |
shakeDuration = duration; | |
shakeStrength = strength; | |
shakeRunning = true; | |
shakeTimeElapsed = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment