简体   繁体   中英

How to write a proper jump script at unity2d? rigidbody.addforce doesnt work

Okay, so i am creating a simple platformer and i am struggling to make player game object jump. The problem is, when i press space, my gameobject just teleports up and then falls down and it doesn't look like a jump at all. As i know, it is supposed to simulate an impulse and i should be able to see the object moving up but i dont.

void Update () 
{
    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        rigidbody2d.AddForce(Vector2.up * 50f, ForceMode2D.Impulse);
    }

}

Also, I tried to copy code from a couple of tutorials where it worked just fine but it doesn't worked out for me.

As @bolkay commented you could change rigidbody's velocity, however if you got problems with this i thing you should follow unity's suggestion and not modify it directly and maybe start manipulating velocity when you got more skills. docs for velocity: https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html

that said, jump with velocity:

rb.velocity=rb.velocity+transform.up*jumpPower; //easier to predict
rb.velocity= transform.velocity*transform.up*jumpPower
rb.velocity= new vector2(rigidbody2d.velocity.x,jumpPower);//erases your rb's previous y velocity

I think your problem is in force you are applying(the code seems ok) try to declare a float and play with its value at runtime. Also check your rb's propreties in inspector.

You can try use this solution:

rigidbody2d.AddForce(Vector2.up * 50f, ForceMode2D.Force);

I changed the ForceMode2D.Impulse to ForceMode2D.Force , maybe it will work. I met this problem too -- fly up and cannot get down XD

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