I’m fairly new to unity, and I tried making a 2d platformer game. For some reason, the player only jumps sometimes when I press the spacebar but sometimes it doesn’t. Does anyone have any idea how I can fix this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
private float Move;
public bool isJumping;
public float jump;
public Vector2 boxSize;
public float castDistance;
private Rigidbody2D rb;
public LayerMask groundLayer;
bool grounded;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(speed * Move, rb.velocity.y);
if (Input.GetButtonDown("Jump") && isGrounded())
{
rb.AddForce(new Vector2(rb.velocity.x, jump));
Debug.Log("jump");
}
}
public bool isGrounded()
{
if (Physics2D.BoxCast(transform.position, boxSize, 0, -transform.up, castDistance, groundLayer))
{
return true;
}
else
{
return false;
}
}
private void OnDrawGizmos()
{
Gizmos.DrawWireCube(transform.position - transform.up * castDistance, boxSize);
}
I tried to figure out what was wrong, and I figured out that it had something to do with the ground check true/false but I can’t figure out where.
New contributor
Ethan Yang is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.