Argon Assault - Cool Script I Made so Camera follows Player Movement

This took a while, hope some of you find it useful! I noticed the camera rotations during movement between keyframes isn’t great and breaks immersion and decided to make my own CameraPointer script.

There’s a lot of stuff I messed up on originally. I learned at some point that LateUpdate needs to be called to override stuff the animation/timeline does. I tried deleting the rotation property of the animation at first but that didn’t work. At first I also didn’t have any smoothing, just using the previous position to follow the cam pointer which ended up creating very jagged movement.

I ended up smoothing it by taking a position from 50 to 500 frames before and using that as the “previous position” to calculate the delta position from which I get the new angle to point toward. This is essentially the same thing as averaging delta positions from the past 200 frames and using that, except it’s simpler and less computationally expensive.

I’m open to suggestions to optimize this so I don’t have a constantly updating 200-element array. IDK if there’s a way to do this with just one vector3 that represents the position from 200 frames back.

IDK if cinemachine allows you to do this, in any case I didn’t have enough cinemachine experience to do this (just the 2d course).

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraPointer : MonoBehaviour
{
    [SerializeField] float startTimeBuffer = 2;
    [SerializeField] int smoothFactor = 200;
    Vector3 currentPosition;
    Vector3[] previousPositions;
    bool isReadyToPoint = false;

    private void Update()
    {
        if (!isReadyToPoint)
        {
            startTimeBuffer -= Time.deltaTime;
        }
        if (startTimeBuffer <= 0 && !isReadyToPoint)
        {
            isReadyToPoint = true;
            InitializePositions();
        }
    }

    void LateUpdate()
    {
        if(isReadyToPoint)
        {
            AddPreviousPosition(currentPosition);
            currentPosition = transform.position;
            Vector3 positionDelta = currentPosition - previousPositions[0];
            transform.rotation = Quaternion.LookRotation(positionDelta);
        }

    }

    private void InitializePositions()
    {
        currentPosition = transform.position;
        previousPositions = new Vector3[smoothFactor];
        for (int i = 0; i < smoothFactor; i++)
        {
            previousPositions[i] = transform.position;
        }
    }

    private void AddPreviousPosition(Vector3 position)
    {
        for(int i = 0; i < previousPositions.Length - 1; i++)
        {
            previousPositions[i] = previousPositions[i + 1];
        }
        previousPositions[previousPositions.Length - 1] = position;
    }
}
1 Like

I love seeing posts like this. Shows how much work you are putting in! Keep it up!

Privacy & Terms