Currently I am trying to understand some about the physics concepts of unity and therefore I am implementing a simple Character Controller.
I am trying to predict the character position after the next physics update based on the set velocity.
Here is the code I am currently using:
public class MyCustomCharacterController : MonoBehaviour
{
private float moveSpeed = 5.0f;
private Rigidbody rigidbody;
//input constants
private int horizontalMovementDirection;
private int verticalMovementDirection;
// Use this for initialization
void Start()
{
rigidbody = GetComponent<Rigidbody>();
rigidbody.freezeRotation = true;
}
private int getHorizontalMovementDirection()
{
int direction = 0;
if (Input.GetKey(KeyCode.LeftArrow))
{
direction--;
}
if (Input.GetKey(KeyCode.RightArrow))
{
direction++;
}
return direction;
}
private int getVerticalMovementDirection()
{
int direction = 0;
if (Input.GetKey(KeyCode.DownArrow))
{
direction--;
}
if (Input.GetKey(KeyCode.UpArrow))
{
direction++;
}
return direction;
}
private void FixedUpdate()
{
float velX = moveSpeed * getHorizontalMovementDirection();
float velZ = moveSpeed * getVerticalMovementDirection();
Vector3 velocityVector = new Vector3(velX, 0, velZ);
rigidbody.velocity = velocityVector;
Vector3 rbPos = rigidbody.transform.position;
if (velocityVector.x != 0 || velocityVector.y != 0 || velocityVector.z != 0)
{
Debug.Log("curPos: " + rbPos.ToString("F6"));
Debug.Log("vel: " + velocityVector + " - calculated position: " + (rbPos + (velocityVector * Time.fixedDeltaTime)).ToString("F6"));
}
}
// Update is called once per frame
void Update()
{
//save input
horizontalMovementDirection = getHorizontalMovementDirection();
verticalMovementDirection = getVerticalMovementDirection();
}
}
The output I get is like the following:
curPos: (3.000000, 0.524603, 3.000000)
vel: (-5.0, 0.0, 0.0) - calculated position: (2.900000, 0.524603, 3.000000)
curPos: (2.904709, 0.524603, 3.000000)
vel: (-5.0, 0.0, 0.0) - calculated position: (2.804709, 0.524603, 3.000000)
curPos: (2.809418, 0.524603, 3.000000)
vel: (-5.0, 0.0, 0.0) - calculated position: (2.709418, 0.524603, 3.000000)
curPos: (2.714127, 0.524603, 3.000000)
vel: (-5.0, 0.0, 0.0) - calculated position: (2.614127, 0.524603, 3.000000)
curPos: (2.618835, 0.524603, 3.000000)
vel: (-5.0, 0.0, 0.0) - calculated position: (2.518836, 0.524603, 3.000000)
curPos: (2.523544, 0.524603, 3.000000)
vel: (-5.0, 0.0, 0.0) - calculated position: (2.423544, 0.524603, 3.000000)
curPos: (2.428253, 0.524603, 3.000000)
vel: (-5.0, 0.0, 0.0) - calculated position: (2.328253, 0.524603, 3.000000)
As you can see the first prediction is off by 0.004709 and all other calculations are correct (the error from the first calculation is just pulled through to the end)
NOTE: everytime the rigidbody starts moving, after standing still, that error occurs again.
Does anyone know why this happens?
Or am I making an obvious mistake?