簡體   English   中英

Unity 2D 操縱桿移動

[英]Unity 2D joystick movement

**嗨,我正在嘗試做一些操縱桿運動,當角色向左移動時,角色精靈會向左翻轉。 它實際上看起來像工作,但事實並非如此。 當角色越過紅線左側時,它向左轉,當它移動到右側時,它向右轉。 那么我該如何解決這個問題? 在此處輸入圖像描述 **我的代碼;

float horizontal;
public float Speed;

public Joystick joystick;
Rigidbody2D rb;
bool facingRight = true;
private void Start()
{
    rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
    
    horizontal = joystick.Horizontal;
    if (horizontal != 0)
    {
        //transform.up = new Vector3(horizontal * Speed, 0, 0);
        transform.Translate(new Vector3(horizontal, 0, 0)*Speed * Time.deltaTime);
        

    }
    if (gameObject.GetComponent<Rigidbody2D>().transform.position.x < 0 && facingRight)  
    {
        flipFace();
    }
    else if (gameObject.GetComponent<Rigidbody2D>().transform.position.x > 0 && !facingRight)
    {
        flipFace();
    }

}

void flipFace()
{
    facingRight = !facingRight; 
    Vector3 tempLocalScale = transform.localScale;
    tempLocalScale.x *= -1; 
    transform.localScale = tempLocalScale; 
}

而不是檢查transform.position.x ,您應該檢查您的移動或輸入。 您可以在速度 > 0 或 < 0 時翻轉Face,這意味着您實際上是在向左還是向右。 檢查速度而不是位置。

它不起作用,因為我沒有使用速度。 角色剛體中沒有速度,所以我像這樣更改了代碼:

if (horizontal != 0)
        {
            //transform.up = new Vector3(horizontal * Speed, 0, 0);
            //transform.Translate(new Vector3(horizontal, 0, 0)*Speed * Time.deltaTime);
            rb.velocity = new Vector3(horizontal * Speed, rb.velocity.y);


        }
        else
        {
            rb.velocity = new Vector3(0, 0, 0);
        }
        if (rb.velocity.x < 0 && facingRight) // < 0 ise sola gidiyor demektir  > 0 is sağa gidiyor demektir
        {
            flipFace();
        }
        else if (rb.velocity.x > 0 && !facingRight)
        {
            flipFace();
        }

在無效更新中使用此代碼

private bool ConFisicas=true;
float horizontal;

void start()   { }


   horizontal = joystick.Horizontal;
    if (ConFisicas)
    {
      


        body.velocity = new Vector2(horizontal, body.velocity.y);
        Debug.Log(horizontal);
        //transform.up = new Vector3(horizontal * speed, 0, 0);
        transform.Translate(new Vector3(horizontal, 0, 0) * speed * Time.deltaTime);

        if (horizontal > 0 || horizontal < 0)
            anim.SetBool("isMove", true);
        else
            anim.SetBool("isMove", false);

    }
    if (facingRight == false && horizontal > 0)
    {
        Flip();

    }
    else if (facingRight == true && horizontal < 0)
    {
        Flip();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM