So I’m new to unity, and coding as a whole really, so I’ve been trying to recreate some simple games. This included a 2D platformer, which the left/right movement was pretty easy but my jump is weird. I was able to get the jumping done pretty quickly but I’ve been struggling with having the player only be able to jump on the ground. I thought of something where if your Y velocity was 0, you could jump. Since your Y velocity isn’t changing on the ground, but is when your in the air, you should only be able to jump on the ground. This code led to the player only being able to jump sometimes (seems random when they can jump) and only when standing still. I’ve been trying to fix this for a while now, but I’m stuck. Anyone think they can help? (again, I am new, so I probably will ask a couple of questions lol)
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.UIElements;
public class Movement : MonoBehaviour
{
public Rigidbody2D myRigidBody;
public float speed = 10;
public float jumpHeight = 5;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
// Right movement
if (Input.GetKey(KeyCode.D))
{
myRigidBody.velocityX = speed;
}
if (Input.GetKeyUp(KeyCode.D))
{
myRigidBody.velocity = Vector2.zero;
}
// Left movement
if (Input.GetKey(KeyCode.A))
{
myRigidBody.velocityX = -speed;
}
if (Input.GetKeyUp(KeyCode.A))
{
myRigidBody.velocity = Vector2.zero;
}
// Jump
if (Input.GetKeyDown(KeyCode.W))
{
if (myRigidBody.velocityY == 0)
{
myRigidBody.velocity = Vector2.up * jumpHeight;
}
}
}
}