- Home /
Follow camera: Player jumps on move
I am trying to create a follow camera. I have isolated the problem to the following simple setup:
1) Player object with rigidbody, no gravity, drag 4 and the following simple script
public class playercontrol : MonoBehaviour {
void FixedUpdate () {
if (Input.GetKey (KeyCode.Space)) {
rigidbody.velocity = transform.forward * 20;
}
}
}
2) Camera with the following script
public class cameracontrol : MonoBehaviour {
public GameObject player;
void FixedUpdate () {
transform.position = player.transform.TransformPoint (new Vector3 (0f, 1.5f, -4f));
transform.rotation = player.transform.rotation;
}
}
The intent is to have the camera always placed some distance behind the player. However, when i press the space key the player instantly jumps some distance forward, the camera follows it smoothly thereafter. When i release the space key the player slows down due to drag and, on the screen, it slowly moves backwards the distance that it jumped earlier.
Now, if i change the camera function to Update
instead FixedUpdate
this problem doesn't occur. I understand the difference between Update
and FixedUpdate
, but i dont understand why the player would jump forward even when the camera is simply copying the position directly.
Reading keyboard input inside of FixedUpdate() can result in lost keyboard events, though Get$$anonymous$$ey() likely will be okay. Typically you want camera follow code to be executed in LateUpdate(), and there is no reason why your current code should be executed in FixedUpdate(). I don't know why you see a jump, but it seems to be that you'd want your movement code to ease up to the maximum velocity:
rigidbody.AddForce(someForce * transform.forward);
rigidbody.velocity = Vector3.Clamp$$anonymous$$agnitude(rigidbody.velocity, 20f);
Answer by Mikael-Gyth · Apr 10, 2014 at 07:34 PM
When you apply a force in FixedUpdate the physics calculations are calculated immediately after. If you also move the camera in FixedUpdate the movement of the object have not been calculated yet and as a result the object would have moved when the frame gets rendered. The preferred place to put CameraMovement is in LateUpdate where you can be sure that all movement calculations have been completed. This is better explained here.
This makes sense. So all the engine physics calculations (in this case calculating the translation based on the velocity) happen after FixedUpdate
has been called on all the objects? so my camera is moving to the older position?