- Home /
C# - How to smoothly & slightly move camera while player moves?
Okay, it may sound confusing, but what I want to do is basically when the player starts moving I want the camera to move slightly to catch up. Instead of following it statically, it sort of catches up to it. BTW it is a 2D game
Example: The player moves over to the right, the camera moves over about a fraction after so it seems like the camera is catching up to the player. I don't know how to explain it much further than that. Sorry.
Thanks in advance!
Answer by seandanger · Jul 04, 2014 at 05:54 AM
Unity has an example script for this, called SmoothFollow2D.js, and it's part of the Standard Assets(Mobile) asset package included with Unity.
To load it up, go to the Unity Menu > Assets > Import Package > and select Standard Assets (Mobile). Then, under the Control Setups folder, load the SidescrollSetup.unity scene file.
Now find the Main Camera GameObject in the Hierarchy. With that object selected, you will see the script attached as a component under the Inspector window.
Just in case you or others find it necessary, here's the script in C# format:
public class CSharpSmoothFollow2D : MonoBehaviour
{
public Transform target;
public float smoothTime = 0.3f;
private Transform thisTransform;
private Vector2 velocity;
private void Start()
{
thisTransform = transform;
}
private void Update()
{
Vector3 vec = thisTransform.position;
vec.x = Mathf.SmoothDamp( thisTransform.position.x,
target.position.x, ref velocity.x, smoothTime);
vec.y = Mathf.SmoothDamp( thisTransform.position.y,
target.position.y, ref velocity.y, smoothTime);
thisTransform.position = vec;
}
}
Thanks! But I'm trying to do a top-down game and I don't want to follow it by the Y. but the Z I changed the code but I get an error saying Vector2 doesn't have 'z'
Could there be an alternate with the Z coordinate?
EDIT: I fixed it by changing Vector2 velocity
to a Vector3
Your answer
Follow this Question
Related Questions
Functions via camera rotations... 1 Answer
No Glitch Please ... 1 Answer
C# FP_Camera not following Character Controller 0 Answers
C# locking Main Camera's Rotations 1 Answer
capture image on phone and use it as background of the scene 0 Answers