簡體   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