Speed exceeds the clamped value by 0.3?
Hello, I'm sorry if this is a simple fix and/or a mess of a script, but I'm very new to C# and Unity. I've been trying to clamp the speed at which my character moves forward between 0 and 4, but it always differs by something like 0.3, causing standstill speed to be -0.3, backwards. Thanks in advance! :)
public GameObject playerCamera;
public GameObject mainPlayer;
float currentSpeed = 0f;
public float accelerationSpeed = 15f;
public float decelerationSpeed = 15f;
public int maximumSpeed = 4;
public int minimumSpeed = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
Debug.Log(currentSpeed);
transform.rotation = Quaternion.Euler(0, playerCamera.GetComponent<MouseLookScript>().currentYRotation, 0);
currentSpeed = Mathf.Clamp(currentSpeed, minimumSpeed, maximumSpeed);
if (Input.GetKey(KeyCode.W))
{
currentSpeed += accelerationSpeed * Time.deltaTime;
transform.position += mainPlayer.transform.forward * currentSpeed * Time.deltaTime;
}
if (!Input.GetKey(KeyCode.W))
{
currentSpeed -= decelerationSpeed * Time.deltaTime;
transform.position += mainPlayer.transform.forward * currentSpeed * Time.deltaTime;
Answer by Ckboyd89 · Apr 06, 2016 at 04:45 PM
In the current state, you are clamping currentSpeed and then modifying it. This results in currentSpeed actually being able to extend beyond the min and max values by (accelerationSpeed Time.deltaTime) or (decelerationSpeed Time.deltaTime).
In order to fix this issue, you'll need to perform the clamp after you have modified the value of currentSpeed. The changed code below should result in the intended functionality:
void FixedUpdate () {
Debug.Log(currentSpeed);
transform.rotation = Quaternion.Euler(0, playerCamera.GetComponent<MouseLookScript>().currentYRotation, 0);
20.
if (Input.GetKey(KeyCode.W))
{
25. currentSpeed += accelerationSpeed * Time.deltaTime;
}
else
30. {
currentSpeed -= decelerationSpeed * Time.deltaTime;
}
currentSpeed = Mathf.Clamp(currentSpeed, minimumSpeed, maximumSpeed);
transform.position += mainPlayer.transform.forward * currentSpeed * Time.deltaTime;
...
Thank you so much for explaining and giving a solution. Your help is very appreciated, Ckboyd89.