Greetings, I’m trying to make my 2D character jump by using AddForce, but i’m having an issue where even if i press the jump key a single time the character will keep flying upwards without going down despite not being in the jumping state anymore (almost as if it’s in a zero-gravity space), i don’t know what the problem exactly is and i would appreciate if anyone would provide some help.
(also just in case you were wondering, i am using a dynamic rigidbody)
public class Movement2D : MonoBehaviour
{
public Rigidbody2D rb;
public float moveSpeed;
[SerializeField] public Vector2 HMove;
public bool isJumping;
public bool jumpSignal;
public float jumpDuration;
public float jumpExtra = 0.5f;
public float jumpForce = 0.4f;
void Awake()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
void Update()
{
HMove = new Vector2(Input.GetAxisRaw("Horizontal"), rb.velocity.y);
if (Input.GetButtonDown("Jump"))
{
jumpSignal = true;
}
else if (Input.GetButtonDown("Jump") == false) jumpSignal = false;
}
void FixedUpdate()
{
Move2D(HMove);
if (jumpSignal == true)
{
Jump();
}
}
void Move2D(Vector2 NavDir)
{
rb.MovePosition((Vector2) transform.position + (NavDir * moveSpeed * (Time.deltaTime)));
}
void Jump()
{
if (!isJumping)
{
isJumping = true;
jumpDuration = Time.time + jumpExtra;
rb.AddForce(new Vector2(0f, jumpForce) * rb.mass, ForceMode2D.Impulse);
print("jumped.");
} else if (isJumping)
{
if (jumpDuration <= Time.time)
isJumping = false;
}
}
}