I have a character GameObject that you can AddForce to. There is also a script on the camera to follow that character GameObject. When AddForce gets called on the GameObject many times, it starts moving too fast for the camera to keep up. Here is the script for following the character (in Update()):
OriginalX is a variable that just grabs the original Camera x coordinate, as I don’t want the Camera to follow the character in the x coordinate. So is there something I can do to make the Camera keep up with a fast moving object? Or something I can do to the Player script?
Personally I like to use Vector3.Lerp() to bring my camera into alignment with the object I want it to track, either positioning the camera, or positioning the target that I am looking at. This will dynamically adjust the speed at which the camera follows the object, and effectively adjust the lag distance in real time.
This is not the intended purpose of Vector3.Lerp() but it actually works quite nicely.
Essentially what you will be doing is having a preset float variable that determines how snappily your camera will track:
public float CameraSnappiness = 5.0f;
If your camera is at transform.position, and you want the camera to be at Vector3 newPosition (perhaps as calculated by following another object along the x axis, for example), then you would use Vector3.Lerp as follows, in your Update() or FixedUpdate() function:
What this essentially does is increase the rate at which your camera moves the further away the target is. If you make the CameraSnappiness high enough, it should be able to track faster objects.
If you set CameraSnappiness higher than 1.0f / Time.deltaTime, essentially you will lock the camera to the newPosition without any lag or slop, but that sort of defeats the purpose of using Lerp.
That’s an awesome article, mgear - thanks for that!
Unfortunately, Lerp did not work either. The Camera still can’t keep up. If I remove the time.DeltaTime and just use 1f, then it sticks perfectly. Which I suppose is expected.
Is something Updating before something else? It doesn’t make sense why time.DeltaTime is totally messing it up.