AxOn
AxOn

Reputation: 101

Camera follows object a little wrong (it trembles, twitches) How to do it smoothly?

I use LookAt(target) function:

public class cub : MonoBehaviour {
    public float range = 5f, moveSpeed = 30f, turnSpeed = 150f;
    public Transform target;

    void Update(){
        if (Input.GetKey(KeyCode.UpArrow))
            transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
        if (Input.GetKey(KeyCode.DownArrow))
            transform.Translate(-Vector3.forward * moveSpeed * Time.deltaTime);
        if (Input.GetKey(KeyCode.LeftArrow))
            transform.Rotate(Vector3.up * -turnSpeed * Time.deltaTime);
        if (Input.GetKey(KeyCode.RightArrow))
            transform.Rotate(Vector3.up * turnSpeed * Time.deltaTime);
    }
}

public class cubeCamera : MonoBehaviour {
    public Transform target; 
	void Update () {
        transform.LookAt(target);
        transform.position = new Vector3(target.position.x, target.position.y + 6, target.position.z - 25);
	}
}

I change position of camera from got position cub, it's not right I think. for example like that, I need following object absolutely smoothly

Upvotes: 0

Views: 78

Answers (1)

Koby Duck
Koby Duck

Reputation: 1138

transform.position = new Vector3(target.position.x, target.position.y + 6, target.position.z - 25);

Is the source of the problem. Here you move the object a fixed amount of units each update, seemingly relying on there being 60 updates/sec. The "twitching"(also called jitter) is due to variable framerate. Games on modern hardware don't run at precisely 60fps(might be 59 in one frame, 61 in another, etc). Framerate fluctuates a lot depending on what the game and the rest of the system are doing.

It can look something like this:

  • 16.667ms
  • 19ms
  • 25ms
  • 16.667ms
  • 18ms
  • 19ms

After enough frames take longer than 16.667ms(~60fps), you'll notice twitching/jittering. The solution is to make changes framerate independent. The simplest way to do that is to multiply the units(6 and 25 in your case) by Time.deltaTime. This changes your computations from units/frame to units/sec, independent of framerate.

Upvotes: 2

Related Questions