By a Mario style jump I mean you can tap the jump key and the player will do a little hop and if you hold it they will perform a higher jump. I am new to programming, and I’ve been trying to implement this into my PlayerController2D script for almost a week now.
Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController2D : MonoBehaviour
{
private float movementInputDirection; // Store what direction the player is trying to move in
private int amountOfJumpsLeft;
private bool isFacingRight = true;
private bool isRunning;
private bool isGrounded;
private bool canJump;
private Rigidbody2D rb2d;
private Animator anim;
public int amountOfJumps = 1;
public float movementSpeed = 10f;
public float jumpForce = 16f;
public float groundCheckRadius;
public Transform groundCheck;
public LayerMask whatIsGround;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
amountOfJumpsLeft = amountOfJumps;
}
// Update is called once per frame
void Update()
{
CheckInput();
CheckMovementDirection();
UpdateAnimations();
CheckIfCanJump();
}
private void FixedUpdate()
{
ApplyMovement();
CheckSurroundings();
}
private void CheckSurroundings()
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, groundCheckRadius, whatIsGround);
}
private void CheckIfCanJump()
{
if (isGrounded && rb2d.velocity.y <= 0)
{
amountOfJumpsLeft = amountOfJumps;
}
if (amountOfJumpsLeft <= 0)
{
canJump = false;
}
else
{
canJump = true;
}
}
private void CheckMovementDirection() // Check whether or not the player is facing right and moving right and if it's not the same it will flip the character
{
if (isFacingRight && movementInputDirection < 0)
{
Flip();
}
else if (!isFacingRight && movementInputDirection > 0)
{
Flip();
}
if (rb2d.velocity.x != 0)
{
isRunning = true;
}
else
{
isRunning = false;
}
}
private void UpdateAnimations()
{
anim.SetBool("isRunning", isRunning);
anim.SetBool("isGrounded", isGrounded);
anim.SetFloat("yVelocity", rb2d.velocity.y);
}
private void CheckInput() // Check Input that we are expecting from the player
{
movementInputDirection = Input.GetAxisRaw("Horizontal"); // Based off this input we will apply force to the player
if (Input.GetButtonDown("Jump"))
{
Jump();
}
}
private void Jump()
{
if (canJump)
{
rb2d.velocity = new Vector2(rb2d.velocity.x, jumpForce);
amountOfJumpsLeft--;
}
}
private void ApplyMovement()
{
rb2d.velocity = new Vector2(movementSpeed * movementInputDirection, rb2d.velocity.y);
}
private void Flip()
{
isFacingRight = !isFacingRight;
transform.Rotate(0.0f, 180.0f, 0.0f);
}
private void OnDrawGizmos()
{
Gizmos.DrawWireSphere(groundCheck.position, groundCheckRadius);
}
}