So im trying to implement a momentum. When my Object stops accelerating (Nor X or Y is pressed) it is forced to keep on moving in the inital direction until the base speed is reached. I only got it to work if the object is still able to change its direction. To lock the direction im using a while loop where before entering the loop i grab the prior sign of the transform with:
sign = MathF.Sign(gameObject.transform.localScale.x);
This Code works but im still able to change the direction:
if (!Input.GetKey(KeyCode.X) && !Input.GetKey(KeyCode.Y))
{
sign = MathF.Sign(gameObject.transform.localScale.x);
forwardVelocity += (decelRatePerSec * Time.deltaTime);
forwardVelocity = Mathf.Clamp(forwardVelocity, speed, maxSpeed);
if (forwardVelocity > speed)
{
rb.velocity = new Vector3((forwardVelocity * sign), rb.velocity.y, 0);
}
else
rb.velocity = new Vector3((horizontalInput * forwardVelocity), rb.velocity.y, 0);
}
This Code with a while loop doest work:
if (!Input.GetKey(KeyCode.X) && !Input.GetKey(KeyCode.Y))
{
sign = MathF.Sign(gameObject.transform.localScale.x);
forwardVelocity += (decelRatePerSec * Time.deltaTime);
forwardVelocity = Mathf.Clamp(forwardVelocity, speed, maxSpeed);
if (forwardVelocity > speed)
{
//signCurrent = sign;
while (forwardVelocity > speed)
{
print("Loop Entered");
print("Sign = " + sign);
forwardVelocity += (decelRatePerSec * Time.deltaTime);
forwardVelocity = Mathf.Clamp(forwardVelocity, speed, maxSpeed);
rb.velocity = new Vector3((forwardVelocity * sign), rb.velocity.y, 0);
print("Velocity = " + forwardVelocity);
print("X Vector = " + rb.velocity.x);
}
}
else
rb.velocity = new Vector3((horizontalInput * forwardVelocity), rb.velocity.y, 0);
}
Ive printed all the values and they change accordingly to what im expecting but for some reason the new rb.velocity wont translate to the actual velocity in game. What am im overseeing? Thanks!