繁体   English   中英

统一二维字符 controller 上的水平移动力无法正常工作

[英]Force on horizontal movement on unity 2D character controller is not working correctly

C# 字符 Controller

我刚开始使用 unity,我很难将力施加到精灵上。 jump vector 2 变量没问题,但水平移动有问题。 代码不检测键是否被按住,如果你不断地敲击键,它只会向任一侧施加力,然后它会朝一个方向移动。

我不确定我是否不能使用刚体进行水平移动,或者矢量写得不正确。 如果您能回答可能的问题和/或有帮助的解决方案,谢谢。

public float JumpForce;

public float HorizontalForce;

bool  isGrounded = false;

Rigidbody2D RB;

void Start()
{
    RB = GetComponent<Rigidbody2D>();
}

void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    { 
        if(isGrounded == true)
        {
            RB.AddForce(Vector2.up * JumpForce);
            isGrounded = false;
        }
                
    }
    if (Input.GetKeyDown(KeyCode.A))
    {
        RB.AddForce(Vector2.left * HorizontalForce);
    }
    if (Input.GetKeyDown(KeyCode.D))
    {
        RB.AddForce(Vector2.right * HorizontalForce);
    }

}
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.CompareTag("ground")) ;
    {
        if(isGrounded == false)
        {
            isGrounded = true;
        }
    }
}

}

您需要GetButton()而不是GetButtonDown()

GetButtonDown 仅适用于按下按钮的单帧。 只要按住按钮,GetButton 就会返回 true

暂无
暂无

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

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