Need help with Camera follow

Updated on December 16, 2014 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
6 on December 15, 2014

So I am trying to make a smooth follow camera

 public class CameraFollow : MonoBehaviour
 {
 Transform player;
 Transform cam;
 float x = 4f;
 float y = 5f;
 float smoothX;
 float smoothY;
 float velocity = 0;
 public float smoothTime = 0.05f;
 void Awake()
 {
 cam = GetComponent<Transform>();
 player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
 }
 void FixedUpdate()
 {
 smoothX = Mathf.SmoothDamp(cam.position.x, player.position.x, ref velocity, smoothTime, 15f);
 smoothY = Mathf.SmoothDamp(cam.position.y, player.position.y, ref velocity, smoothTime, 15f);
 }
 void LateUpdate()
 {
 cam.position = new Vector3(Mathf.Clamp(smoothX, -x, x), Mathf.Clamp(smoothY, -y, y), -10f);
 }
 }
 

But its behaving weird when I move right or up. For example if I move to the right it seems to follow with some weird offset on the y (if that makes sense :P)
However it works perfect when moving left or down.

Here’s a little demo of it:
https://googledrive.com/host/0Bzct6cQnrUORbmNwTWFSU

Been trying to figure this out for a couple of hours now and getting nowhere 🙁

  • Liked by
Reply
0 on December 16, 2014

Bump for me :/

  • Liked by
Reply
Cancel
0 on December 16, 2014

I think that the problem u have is because you are calculating your smooth dump in fixed update and setting your cam position in LateUpdate, fixed update is not called every frame, its called every couple of frames, try to move your code for smooth dump in the Update or LateUpdate method

  • Liked by
Reply
Cancel
1 on December 16, 2014

I feel like if that was the problem then it would affect all movement, not just the right and up… but will try it.

Master
on December 16, 2014

It moved the same way, but like I suspected it made the movement very shaky. I used fixedupdate because my player is moved with physics.

Show more replies
  • Liked by
Reply
Cancel
0 on December 16, 2014

can you also post the code that moves the player

  • Liked by
Reply
Cancel
0 on December 16, 2014

Actually this has been solved 🙂 the problem was that I used the same velocity float for both the x and y 😛 Thanks anyway 🙂

  • Liked by
Reply
Cancel