Created
August 3, 2019 14:39
-
-
Save Ratstail91/0b3b7f8f7321aff873549c5e06cd1a98 to your computer and use it in GitHub Desktop.
My attempt at camera shake - didn't work.
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 System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class CameraController : MonoBehaviour { | |
[SerializeField] | |
GameObject target; | |
[SerializeField] | |
float lerpSpeed = 2f; | |
//shake | |
[SerializeField] | |
int seed = 210795; | |
[SerializeField] | |
float maxOffsetX = 1f; | |
[SerializeField] | |
float maxOffsetY = 1f; | |
[SerializeField] | |
float maxAngle = 10f; | |
float trauma = 0f; | |
//internals | |
Vector3 purePosition; | |
void Start() { | |
purePosition = transform.position; | |
} | |
void Update() { | |
//test | |
if (GamePad.GetState().Pressed(CButton.A)) { | |
AddTrauma(0.5f); | |
} | |
//only continue if the target has been set | |
if (target == null) { | |
return; | |
} | |
//cache the position we want to move to | |
Vector3 targetPosition = target.transform.position; | |
//Interpolate to the target location | |
purePosition = Vector3.Lerp(purePosition, targetPosition, lerpSpeed * Time.deltaTime); | |
//Snap to pixel coordinates | |
Vector3 shaken = Shake(purePosition); | |
shaken.x = Mathf.Round(shaken.x * 100) / 100; | |
shaken.y = Mathf.Round(shaken.y * 100) / 100; | |
shaken.z = transform.position.z; //BUGFIX | |
transform.position = shaken; | |
trauma = Mathf.Clamp(trauma - 0.005f, 0, 1); | |
} | |
void AddTrauma(float amount) { | |
trauma = Mathf.Clamp(trauma + amount, 0, 1); | |
} | |
Vector3 Shake(Vector3 position) { | |
float shake = trauma * trauma; | |
Debug.Log(shake); | |
position.x += maxOffsetX * shake * (Mathf.PerlinNoise(seed * 1, Time.time) - 0.5f); | |
position.y += maxOffsetY * shake * (Mathf.PerlinNoise(seed * 2, Time.time) - 0.5f); | |
transform.rotation = Quaternion.AngleAxis(maxAngle * shake * (Mathf.PerlinNoise(seed * 3, Time.time) - 0.5f), Vector3.forward); | |
Debug.Log(position); | |
return position; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment