Toggle flip on transform y-axis

Viewed 134

I am trying to flip my transform when I flip my character. The part I am trying to flip is a child of the "Player" and I want to flip it on the Y-axis by setting the scale to: -1

void FixedUpdate()
{

    movement.x = Input.GetAxisRaw("Horizontal");
    //rb.MovePosition(rb.position + movement * moveSpeed/2 * Time.deltaTime);
    if (Input.GetKey(KeyCode.LeftShift))
    {
        rb.MovePosition(rb.position + movement * sprintSpeed * Time.fixedDeltaTime);
    }
    else
    {
        rb.MovePosition(rb.position + movement * moveSpeed/2 * Time.fixedDeltaTime);
    }


    if (facingRight == false && movement.x > 0)
    {
        Flip();
        //weaponHolder.localScale = new Vector3(transform.localScale.x, transform.localScale.y * -1, transform.localScale.z);  //Tried here but dont work
    }
    else if (facingRight == true && movement.x < 0)
    {
        Flip();
        //weaponHolder.localScale = new Vector3(transform.localScale.x, transform.localScale.y * -1, transform.localScale.z);  //Tried here but dont work
    }



}



void Flip()
{
    facingRight = !facingRight;
    GetComponent<SpriteRenderer>().flipX = !facingRight;
    childHand = GameObject.Find("Hand");
    childHand.GetComponent<SpriteRenderer>().flipY = !facingRight;

    //weaponHolder.transform.localScale = scaleChange;

    weaponHolder.localScale = new Vector3(transform.localScale.x, transform.localScale.y * -1, transform.localScale.z);  //Tried here but dont work
}

My issue is that it flips it once, but it wont flip back. How do I "toggle" this type of flip back and forth in above provided code? I have tried to flip ony the spriterenderer but that is not a usable solution for the weapon because it holds gameobjects where I instantiate bullets / particle systems etc...

1 Answers

I think you have to keep track of when it is set to -1 scale, and if it is flipped (the scale is -1) then set it back to the normal scale (1). Initialize the flipped var as false.

    bool flipped = false;
    if (flipped){
    weaponHolder.localScale = new Vector3(transform.localScale.x, transform.localScale.y * 1, transform.localScale.z); 
    flipped = false;
    }
    else{
    weaponHolder.localScale = new Vector3(transform.localScale.x, transform.localScale.y * -1, transform.localScale.z); 
    flipped = true
    } 
Related