unity very high character jump

0

I decided to make a little 2d game in unity before the new year, the question is that when I press jump (upArrow) it's like a rocket, it goes flying and I never see it again, but, why it happens this? This is the code:

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class player_controller: MonoBehaviour {

public float maxSpeed = 5f;
public float speed = 2f;
private Rigidbody2D rb2d;
private Animator anim;
public bool grounded;
public float jumPower = 6.5f;
private bool jump;

// Use this for initialization
void Start () {
    rb2d = GetComponent<Rigidbody2D>();
    anim = GetComponent<Animator>();

}

// Update is called once per frame
void Update () {
    anim.SetFloat("speed", Mathf.Abs(rb2d.velocity.x));
    anim.SetBool("grounded", grounded);

    if (Input.GetKeyDown(KeyCode.UpArrow))
    {
        jump = true;
    }

}

private void FixedUpdate(){
    float h = Input.GetAxis("Horizontal");

    rb2d.AddForce(Vector2.right * speed * h);

    /*  if (rb2d.velocity.x > maxSpeed)
      {
          rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
      }
      if (rb2d.velocity.x < -maxSpeed)
      {
          rb2d.velocity = new Vector2(-maxSpeed, rb2d.velocity.y);
      }*/

    float limitedSpeed = Mathf.Clamp(rb2d.velocity.x, -maxSpeed, maxSpeed);
    rb2d.velocity = new Vector2(limitedSpeed, rb2d.velocity.y);

    if (h > 0.1f)
    {
        transform.localScale = new Vector3(1f, 1f, 1f);
    }

    if (h < -0.1f)
    {
        transform.localScale = new Vector3(-1f, 1f, 1f);
    }

    if (jump)
    {
        rb2d.AddForce(Vector2.up * jumPower, ForceMode2D.Impulse);
    }

    Debug.Log(rb2d.velocity.x);
}

}

everything works fine except for the jump, which instead of jumping is like taking off. Thank you very much for the help

    
asked by Barly Espinal 09.12.2018 в 02:24
source

1 answer

1

Notice that in update when you press UpArrow put a variable in true and then in fixedupdate you do an add force boost while jump is true which is always true since there is no nothing that puts it in false, you should put the method keypressed I think it is, so when you release the w the impulse disappears and you do:

if (Input.GetKeyPressed(KeyCode.UpArrow))
   jump = true;
else
   jump = false;

If I remember correctly, this is an existing method

    
answered by 09.12.2018 / 03:22
source