Skip to content

Instantly share code, notes, and snippets.

@mamadDev
Last active January 25, 2021 01:37
Show Gist options
  • Save mamadDev/a02d19966626020e2d2c060d57339adc to your computer and use it in GitHub Desktop.
Save mamadDev/a02d19966626020e2d2c060d57339adc to your computer and use it in GitHub Desktop.
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
[Tooltip("Player transform to follow")]
[SerializeField] private Transform player;
[Tooltip("Distance between camera position to Player transform")]
[SerializeField] private float distance = 10;
[Tooltip("Height of camera position from Player transform")]
[SerializeField] private float height = 5;
[Tooltip("Camera offset rotation to the Player")]
[SerializeField] private Vector3 lookOffset = new Vector3(0,1,0);
float cameraSpeed = 100;
float rotSpeed = 100;
void FixedUpdate ()
{
if(player)
{
//get the initialize look position and add with player position
Vector3 lookPosition = player.position + lookOffset;
//get the distance between the player and the camera transform
Vector3 relativePos = lookPosition - transform.position;
//Get rotation angle of the relativePos
Quaternion rot = Quaternion.LookRotation(relativePos);
//Interpolate between the rotation angle
transform.rotation = Quaternion.Slerp(this.transform.rotation, rot, Time.deltaTime * rotSpeed * 0.1f);
//Get the target position minus or pplus will result to camera facing front or rear
Vector3 targetPos = player.transform.position + (player.transform.up * height) - (player.transform.forward * distance);
//Interpolates the previous position to taarget position
this.transform.position = Vector3.Lerp(this.transform.position, targetPos, Time.deltaTime * cameraSpeed * 0.1f);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment