Unity 2D游戏杆运动

时间:2020-09-04 09:15:47

标签: c# unity3d

**嗨,我正在尝试进行一些操纵杆移动,当角色离开时,角色精灵将“面孔”向左翻转。实际上看起来像在工作,但事实并非如此。字符越过红线的左侧时,它将向左旋转;当字符移动到右侧时,它将向右旋转。那么我该如何解决呢? enter image description here ** 我的代码;

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; 
}

2 个答案:

答案 0 :(得分:0)

您应该检查自己的动向或输入,而不是检查transform.position.x。当速度> 0或<0时,您可以翻转面部,这意味着您实际上是在向左还是向右走。检查速度而不是位置。

答案 1 :(得分:0)

它不起作用,因为我没有使用速度。刚体中没有速度,因此我更改了代码,如下所示:

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();
        }