繁体   English   中英

C#UNITY 2D尝试在x方向上翻转精灵

[英]C# UNITY 2D trying to flip the sprite in the x direction

我要做的就是当敌人转过身子时,精灵会翻转,下面的代码是我所管理的,但是现在,它仅在方向变化了两次但接近我的方向后才翻转。 请帮忙。

   [HideInInspector]
    public bool facingRight = true;
    public float speed;
    Rigidbody2D rbody;
    public float timer;
    Animator anim;
    public float directionx;

// Use this for initialization

void Start()
    {
        rbody = GetComponent<Rigidbody2D>();

        StartCoroutine(Move(timer));
    }



    IEnumerator Move(float timer)
    {
        while (0 < 1)

        {
            Vector2 targetVelocity = new Vector2(directionx, 0);

            rbody.velocity = targetVelocity * speed;

            yield return new WaitForSeconds(timer);

            facingRight = !facingRight;

            Vector3 theScale = transform.localScale;

            theScale.x *= -1;

            transform.localScale = theScale;

            Vector2 targetVelocity1 = new Vector2(-directionx, 0);

            rbody.velocity = targetVelocity1 * speed;

            yield return new WaitForSeconds(timer);
        }

    }

}

该代码是非常自我说明的,您只需设置一个变量即可知道播放器开始移动的方向(在我的情况下为m_FacingRight ),然后确定何时希望调用flipFunction()发生“翻转”:

private bool m_FacingRight = true;  // For determining which way the player is currently facing.  

private void flipFunction()
{
  // Switch the way the player is labelled as facing.
  m_FacingRight = !m_FacingRight;

  // Multiply the player's x local scale by -1.
  Vector3 theScale = transform.localScale;
  theScale.x *= -1;
  transform.localScale = theScale;    
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM