I’m using a rigibody2D on a cube in Unity. I have a constant force been added to slowly increase the speed and couple of ifs to cap it out if max speed is reached. This works but every now and then before fixed update the velocity randomly goes to zero. In addition at the time when it drops to zero it goes to some random numbers for a couple of frames (for example -5.453111E-16)
void FixedUpdate()
{
float horizontalAxis = Input.GetAxis("Horizontal"); //gets horizontal axis
Debug.Log("axis: " + Vector2.right * horizontalAxis * speed);
Debug.Log("velocity.x before addforce: " + rb2d.velocity.x);
rb2d.AddForce(Vector2.right * horizontalAxis * speed); //adds x force based on input and speed property
Debug.Log("velocity.x after addforce: " + rb2d.velocity.x);
//cap out speed to max if more than max (abs)
if(rb2d.velocity.x > maxSpeed)
{
Debug.Log("velocity.x over max: " + rb2d.velocity.x);
rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
Debug.Log("capped velocity.x: " + rb2d.velocity.x);
}
if (rb2d.velocity.x < -maxSpeed)
{
rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
}
}
Image of player components: