I'm working on a downhill racer and I want to have the camera shake to various degrees to convey that the player is getting faster. Right now I have a GameObject called "CameraHolder" which is a parent to the Main Camera.
I have a script attached to the Holder that follows the player, and another script attached to the camera that is meant to shake it within that holder.
CameraHolder Follow Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Camera cam;
public Transform player;
public Vector3 offset;
public float speed = 2f;
public Rigidbody rb;
public float startingFieldOfView = 60f;
void FixedUpdate()
{
float interpolation = speed * Time.deltaTime;
Vector3 cameraPosition = new Vector3(Mathf.Lerp(transform.position.x, player.position.x, interpolation), player.position.y + player.localScale.y + offset.y, player.position.z + -player.localScale.z + offset.z);
// Change of camera FOV depending on the speed of the rigidbody
transform.position = cameraPosition;
cam.fieldOfView = Mathf.Lerp(cam.fieldOfView, startingFieldOfView + (rb.velocity.magnitude / 3), .1f);
CameraShake Script attached to child Main Camera
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraShake : MonoBehaviour
{
public Rigidbody player;
public float shakeThreshold;
public float shakeMagnitude;
private void Update()
{
float x = Random.Range(-shakeMagnitude, shakeMagnitude);
float y = Random.Range(-shakeMagnitude, shakeMagnitude);
if (player.velocity.magnitude >= shakeThreshold)
{
transform.localPosition = new Vector3(x, y, transform.position.z);
}
}
}
I think maybe I misunderstand how localPosition works. I thought that it would move the camera the random amount while moving within the holder, but it does nothing. Am I applying this wrong or is the logic off?
I think using cinemachine will really help you.
To remplace your CameraFollow script you can use a virtual camera with the property Follow, for more information you can go there : https://docs.unity3d.com/Packages/com.unity.cinemachine@2.6/manual/CinemachineSetUpVCam.html
To replace your Camera shake you can check the Noise Property there : https://docs.unity3d.com/Packages/com.unity.cinemachine@2.6/manual/CinemachineVirtualCameraNoise.html
For more information on cinemachine go check the doc here : https://docs.unity3d.com/Packages/com.unity.cinemachine@2.6/manual/CinemachineUsing.html