i am making a script in unity c#, that needs to accelerate or deccelerate the player so he smoothly moves towards a direction. I somewhat got it working, but it ended up having some flaws that i couldn't fix.
The exact behaviour i need from this is: A vector3 speed value that is increased every frame with an acceleration value towards a direction vector3.
It needs to recognise when it is slowing down, and then use a decceleration value instead of the acceleration value to slow down.
It needs to be targeting a speed, so it will not accelerate beyond that speed, and if that speed changes while moving, it needs to deccelerate / accelerate to the new speed.
As i said, i tried making it, but got stuck, heres the code i used:
private void Move()
{
if (targetDirection.x > 0)
{
currentSpeedX = Mathf.Min(currentSpeedX + acceleration, targetSpeed);
}
else if (currentSpeedX > 0)
{
currentSpeedX = Mathf.Max(currentSpeedX - decceleration, 0f);
}
if (targetDirection.x < 0)
{
currentSpeedX = Mathf.Max(currentSpeedX - acceleration, -targetSpeed);
}
else if (currentSpeedX < 0)
{
currentSpeedX = Mathf.Min(currentSpeedX + decceleration, 0f);
}
if (targetDirection.z > 0)
{
currentSpeedZ = Mathf.Min(currentSpeedZ + acceleration, targetSpeed);
}
else if (currentSpeedZ > 0)
{
currentSpeedZ = Mathf.Max(currentSpeedZ - decceleration, 0f);
}
if (targetDirection.z < 0)
{
currentSpeedZ = Mathf.Max(currentSpeedZ - acceleration, -targetSpeed);
}
else if (currentSpeedZ < 0)
{
currentSpeedZ = Mathf.Min(currentSpeedZ + decceleration, 0f);
}
Vector3 moveDirection = new Vector3(currentSpeedX, 0, currentSpeedZ);
currentSpeedX = Mathf.Clamp(moveDirection.x, -Mathf.Abs(moveDirection.normalized.x), Mathf.Abs(moveDirection.normalized.x));
currentSpeedZ = Mathf.Clamp(moveDirection.z, -Mathf.Abs(moveDirection.normalized.z), Mathf.Abs(moveDirection.normalized.z));
rb.MovePosition(rb.position + new Vector3(currentSpeedX, 0f, currentSpeedZ) * targetSpeed * Time.fixedDeltaTime);
}
The problems i ended up having with this is:
It's locked to 8 directions. Changing speed limit while moving to a lower speed, accelerates down instead of deccelerates.
So, if someone could help me understand why this code is not working, or give me another aproach to this problem, i'd be grateful.