I am learning how to make a 2D game through watching Youtube videos. Currently I am trying to learn to script 2D player movement.
In the given script I am supposed to have limited number of jumps (as much the amount I set) but still I am having infinite jumps.
Please Help !
Link to the video I used as a reference for learning :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterController2D : MonoBehaviour
{
public float speed; //movement speed variable.
public float jumpForce; //at what force you will jump.
private float moveInput; //how to move?
private Rigidbody2D rb;
private bool facingRight = true; //for flipping character side by side when moving.
private bool isGrounded; //is character standing on ground? (ground check required!)
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJump; //extra jumps!
public int extraJumpValue;
void Start()
{
extraJump = extraJumpValue;
rb = GetComponent();
}
void FixedUpdate() //to manage physics related aspects.
{
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround); //is grounded or not?
moveInput = Input.GetAxis(“Horizontal”); //built-in unity input field equivalent to holding left or right keys.
rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
if (facingRight == false && moveInput > 0)
{
Flip();
}
else if(facingRight == true && moveInput < 0)
{
Flip();
}
}
void Update ()
{
if (isGrounded == true)
{
extraJump = extraJumpValue;
}
if (Input.GetKeyDown(KeyCode.UpArrow) && extraJump > 0)
{
rb.velocity = Vector2.up * jumpForce;
extraJump–;
}
else if (Input.GetKeyDown(KeyCode.UpArrow) && extraJump == 0 && isGrounded == true)
{
rb.velocity = Vector2.up * jumpForce;
}
}
void Flip() //flipping character side by side. one of the easy method!
{
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}