Hello,
I am trying to create a smooth camera movement script. I have been able to get the smooth movement that I wanted but the gameobject that the camera follows moves forwards as well as bounces up and down. I only want the camera to follow the gameobject when it is moving forwards and not when the gameobject is bouncing. I am looking for a way to have it where I can restrict the movent of the camera along the x-axis. Here is the script that is on the camera
public Transform target;
public float smoothSpeed = 0.125f;
public Vector3 offset;
private void FixedUpdate()
{
Vector3 desiredPosition = target.position + offset;
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
transform.position = smoothedPosition;
}
If anybody has any suggestions that would be great!
Thanks!
For future reference, there is a Scripting forum that this post would be better suited for. And when posting code, you should use code tags
to make it easier to read.
For the main issue, you should be able to set smoothedPosition.x to any value before you reassign it to transform.position.
smoothedPosition.x = 10f;
One other note, you should avoid using FixedUpdate for (generally speaking) anything except physics-related logic. If your user has a high framerate, then using FixedUpdate will effectively restrict their apparent performance to 50fps (or whatever your fixed timestep is) - even if the game runs at 240fps, the scene will still only appear to change 50 times a second. If they have a low framerate, having a lot of logic in FixedUpdate will cause Unity to have to run that logic multiple times per frame and the low framerate will be more extreme than it needs to be. This is especially true of something like camera movement which logically only needs to be done once per frame. You can multiply in Time.deltaTime to make it respond properly to different framerates (in this case, your “smoothSpeed” would need to be about 50x higher than it is now and then multiplied by Time.deltaTime in order to get a similar movement speed as your current code)
A good rule of thumb is that main game logic goes in Update, physics-related logic goes in FixedUpdate, and logic that only affects visuals (camera movement, FX, UI, etc) should go in LateUpdate so that it’s always responding to the most current state of the game.