I made script where camera follows the player and camera shaker for effects. But the problem is that camera starts shaking on it's default (0, 0, 0) position. It jumps to that position starts shaking and returns to player. How can I make camera shake on it's current position. Here's my code:
public Transform target;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
private const float _COROUTINE_FREQUENCY = 0.05f;
private Camera _mainCamera;
private Vector3 _initCamPos;
private bool _shaking;
void Start()
{
_mainCamera = Camera.main;
}
void Update()
{
// Define a target position above and behind the target transform
Vector3 targetPosition = target.TransformPoint(new Vector3(0, 0, -10));
// Smoothly move the camera towards that target position
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
if (Bullet.hit && !_shaking){
StartCoroutine(_ShakingCamera());
}
}
public void Shake(){
StartCoroutine(_ShakingCamera());
}
public IEnumerator _ShakingCamera(float magnitude = 0.2f)
{
_shaking = true;
_initCamPos = _mainCamera.transform.position;
float t = 0f, x, y;
while (t < 0.3f)
{
x = Random.Range(-0.35f, 0.35f) * magnitude;
y = Random.Range(-0.35f, 0.35f) * magnitude;
_mainCamera.transform.position = new Vector3(x, y, _initCamPos.z);
t += _COROUTINE_FREQUENCY;
yield return new WaitForSeconds(_COROUTINE_FREQUENCY);
}
_mainCamera.transform.position = _initCamPos;
_shaking = false;
}