Camera shaking while following player

Hi,

I have a main camera and a cube. Cube has rigid body and box collider.

Using the following code for camera to follow cube inside Cube script.

            Camera.main.transform.LookAt(transform.position);
	tmps = transform.position;
	tmps.y += 2.0f;
	Camera.main.transform.position = tmps;

But the camera is jittering/shaking while the cube is moving especially when it hits another object.

How to fix it?

Try using Lerp function:

float smooth = 0.95f; //0.01 - super smooth, 1 - super sharp 
GameObject cameraRotationHelper = new GameObject();
cameraRotationHelper.transform.position = Camera.main.transform.position;
cameraRotationHelper.transform.LookAt(transform.position);
Camera.main.transform.rotation = Quaternion.Lerp(Camera.main.transform.rotation, cameraRotationHelper.transform.rotation, smooth);
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, transform.position + new Vector3(0, 2.0f, 0), smooth);

First, you need to put your camera at the same hierarchy level than your cube, not as a child of. Later, you have to move your camera in the same direction as the cube while it’s looking at it. I post you a simple code below…

void followCube(){
          myCameraTransform.LookAt (myCubeTransform.position);
          myCameraTransform.position += myCameraTransform.DIRECTION * speed * Time.deltaTime;

          /**
            * DIRECTION = could be forward, up or right and his negatives values
            * speed = mouvement speed
            */
}

You have to call this method in the Update function and attach the Script to the cube. I hope this help you. Regards.