Camera looks to be teleporting

Hi,

I’m trying to have my camera move downwards in an increasing velocity, and have it follow the character if it falls faster than the current velocity. My issue is that the character looks to be teleporting instead of falling, and I think it’s the camera that causes this to happen since the player is falling through normal gravity.

This is my camera script:

public class CameraFollow : MonoBehaviour {
    [SerializeField] Rigidbody2D rb;
 
    float speed = 2f;
    float threshold = 2.5f;
    bool updateSpeed = true;

    void Start() {
        StartCoroutine("UpdateSpeed");
    }

    void Update() {
        if(rb.transform.position.y < transform.position.y - threshold) {
            transform.Translate(new Vector3(0, (rb.transform.position.y - transform.position.y) * 10 * Time.deltaTime, 0));
        } else {
            transform.Translate(new Vector3(0, -speed * Time.deltaTime, 0));
        }
    }

    IEnumerator UpdateSpeed() {
        while(updateSpeed) {
            if(speed <= 3) {
                speed += 0.05f;
            } else if(speed <= 5) {
                speed += 0.025f;
            } else if(speed <= 7) {
                speed += 0.0125f;
            } else {
                updateSpeed = false;
            }

            yield return new WaitForSeconds(0.5f);
        }
    }
}

Any idea how I can fix this, or how I can improve the script?

Thanks in advance! :slight_smile:

Camera stuff is difficult to get right… really good camera is really difficult.

In 2021 you might want to consider just installing Cinemachine (Unity package) and using that.

1 Like

Haha yeah, I see. But is it bad pratice to call Translate in the Update method? Is there perhaps a better way to have the camera move towards a specific position every frame?

Nothing wrong with that at all.

Well for one, lines like 14 and 16 above are hard to reason about.

Why not instead rewrite them to calculate a temporary variable with how much you want to move it, then read the position out of the transform, add it, and write it back?

That approach gives you at least two new places to put a Debug.Log() statement in and find out what is happening in realtime.

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

1 Like