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

Time:11-30

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

}

CodePudding user response:

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

  • Related