'How can I refactor my 2d unity movement script to resolve the behavioral issues I have?

Below is the code I've written for my 2D movement:

void HandleInput()
{
    float verticalMoveAmount = Input.GetAxis("Vertical") * playerSpeed * Time.deltaTime;
    float horizontalMoveAmount = Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;

    if (facingRight)
    {
        transform.Translate(horizontalMoveAmount, verticalMoveAmount, 0);
    }
    else
    {
        transform.Translate(-horizontalMoveAmount, verticalMoveAmount, 0);
    }

    if (horizontalMoveAmount > 0 && !facingRight)
    {
        Flip();
    }
    else if (horizontalMoveAmount < 0 && facingRight)
    {
        Flip();
    }

    if (Input.GetKeyDown(KeyCode.Space) && hasBall)
    {
        Shoot();
    }   
}

void Flip()
{
    facingRight = !facingRight;
    transform.Rotate(0f, 180f, 0f);
}

I have the below problems though:

  1. I have a Cinemachine virtual camera following the player around. However, whenever the player changes direction they vanish from the camera view. I think this is something to do with the Flip(), but I don't know why or how to fix it.
  2. The if statement for if facingRight where I have to use negative movement on the horizontal axis, this feels like a really poor way to handle it, but if I don't do that I can't move left when the player changes directions to the left. Is there a better way I can do this?

Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source