Skip to content

Instantly share code, notes, and snippets.

@Drumsmasher17
Last active March 25, 2018 14:55
Show Gist options
  • Select an option

  • Save Drumsmasher17/ea5ef1463838eb2d7a99d50001078a8e to your computer and use it in GitHub Desktop.

Select an option

Save Drumsmasher17/ea5ef1463838eb2d7a99d50001078a8e to your computer and use it in GitHub Desktop.
"Camera boom" positioning for a zero-G driving game.
using UnityEngine;
public class BuggyCamFollow : MonoBehaviour
{
public BuggyInfo buggyInfo;
[Header("ReferenceTransforms")]
public Transform buggyTransform;
public Transform cameraBoom;
[Header("CameraPositions")]
public Transform boomCamPos;
public Transform camDirPos;
////Virtual Movement Transforms////
Vector3 virtBoomPos;
Quaternion virtBoomRot;
Vector3 virtCamPos;
Quaternion virtCamLook;
Vector3 _up;
////Smoothed Movement Transforms////
Vector3 smoothedBoomPos;
Quaternion smoothedBoomRot;
Vector3 smoothedCamPos;
Quaternion smoothedCamLook;
////////////////////////////////////
[Header("CurveStuff")]
public bool useCurve;
public AnimationCurve curve;
float posLerpMutliplier = 15f;
float rotLerpMultiplier = 5f;
////Cached Values///////////////////
bool _grounded;
Vector3 _buggyVel;
void FixedUpdate ()
{
_grounded = buggyInfo.GetGroundState();
_buggyVel = buggyInfo.GetVelocity();
////////////////////////////
////////////////////////////
VirtualMovement();
if (useCurve) SmoothingMovement();
FinalActions();
////////////////////////////
////////////////////////////
}
void VirtualMovement()
{
virtBoomPos = buggyTransform.position; //Updates to new position
if (_grounded) _up = buggyTransform.up;
else _up = Vector3.up;
virtBoomRot = Quaternion.LookRotation(_buggyVel.normalized, _up); //Boom looks at the way the buggy is going
virtCamPos = boomCamPos.position;
virtCamLook = Quaternion.LookRotation(camDirPos.position - virtCamPos);
}
void SmoothingMovement()
{
cameraBoom.position = virtBoomPos; //This doesn't need to be smoothed
cameraBoom.rotation = Quaternion.Lerp(cameraBoom.rotation, virtBoomRot, SpeedToLerpRate() * rotLerpMultiplier);
//smoothedCamPos = virtCamPos; //Unsmoothed Version
smoothedCamPos = Vector3.Lerp(smoothedCamPos, virtCamPos, SpeedToLerpRate() * posLerpMutliplier);
smoothedCamLook = virtCamLook;
}
void FinalActions()
{
transform.position = smoothedCamPos;
transform.rotation = smoothedCamLook;
}
float SpeedToLerpRate()
{
return curve.Evaluate(buggyInfo.GetSpeed()) * Time.deltaTime;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment