简体   繁体   中英

AddForce in Rigidbody2D not working at all

I have been following guides, I have been trudging through dozens of forums, and subsequently, I have been ripping what's left of my hair out!

As you can see in the code, I am trying to use velocity for the movement, and AddForce for the jumping motion. If I use velocity, it jumps super fast and at the maximum, I just don't want this to happen. I want a smooth jump, more realistic, so I saw it said to use AddForce instead. Except.... It doesn't even work at all, he just doesn't jump now... nothing.

I worked with velocity. The code was rb.velocity = jumping * jumpForce;

Like I said, this worked, but it was jumping ridiculously fast and didn't look at all correct.

public class PlayerController : MonoBehaviour
{

    public float speed = 3.0f;
    public float jumpForce = 4.0f;
    public Rigidbody2D rb;
    public Vector2 movement;
    public bool isJumping;
    public Animator animate;
    public Vector2 jumping = new Vector2(0,1);


    // Start is called before the first frame update
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
        //animate = this.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        //animate.SetFloat("Horizontal", Input.GetAxis("Horizontal"));

        movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));


    }
    void FixedUpdate()
    {

        moveCharacter(movement);
        jumpCharacter();


    }

    void moveCharacter(Vector2 direction)
    {
        rb.velocity = direction * speed;

    }

    void jumpCharacter()
    {
        if(Input.GetKey(KeyCode.Space) && !isJumping)
        {
            isJumping = true;

            rb.AddForce(jumping * jumpForce);
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isJumping = false;
            rb.velocity = Vector2.zero;
        }
    }

}

You have Input.GetKey(KeyCode.Space) . Change GetKey to GetKeyDown .

If you are looking for the GetKey the variable will always be true when you are holding down the key. GetKeyDown makes sure that the code can run once each time you push the key down.

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