简体   繁体   English

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

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

C# Character Controller C# 字符 Controller

I'm new to using unity and I having difficulty with the force being applied to the sprite.我刚开始使用 unity,我很难将力施加到精灵上。 The jump vector 2 variable is fine but I'm having issue with the horizontal movement. jump vector 2 变量没问题,但水平移动有问题。 The code is not detecting if the key is held down,it will only add force to either side if you constantly tap the key, then it will move in a direction.代码不检测键是否被按住,如果你不断地敲击键,它只会向任一侧施加力,然后它会朝一个方向移动。

I'm not sure if I cant use the rigid body for horizontal movement or the vector is not written correctly.我不确定我是否不能使用刚体进行水平移动,或者矢量写得不正确。 If you could please respond with the possible issues and or solution that would be helpful, thanks.如果您能回答可能的问题和/或有帮助的解决方案,谢谢。

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

} }

You need GetButton() instead of GetButtonDown() .您需要GetButton()而不是GetButtonDown()

GetButtonDown is only true for a single frame, in which the button was pressed. GetButtonDown 仅适用于按下按钮的单帧。 GetButton returns true as long as you hold the button只要按住按钮,GetButton 就会返回 true

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

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