简体   繁体   中英

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

C# Character Controller

I'm new to using unity and I having difficulty with the force being applied to the sprite. The jump vector 2 variable is fine but I'm having issue with the horizontal movement. 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() .

GetButtonDown is only true for a single frame, in which the button was pressed. GetButton returns true as long as you hold the button

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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