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