I’ve written the following code to make a ridigbody2D character jump:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerJump : MonoBehaviour
{
Rigidbody2D rb2d;
private float jumpHeight = 10;
public const string UP = "up";
string jumpState;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
jumpState = UP;
}
else
{
jumpState = null;
}
}
private void FixedUpdate()
{
if (jumpState == UP)
{
rb2d.AddForce(new Vector2(0, jumpHeight), ForceMode2D.Impulse);
}
}
}
Now, it kind of works? Like, the character jumps when I press space but only sometimes. Also, if I move in air the character does a weird Mary Poppins glide and loses a lot of vertical speed. What’s gone wrong?