So I have a player movement script that is supposed to allow the player to double jump by counting the number of times the space bar is pressed. It was working a couple versions early, but now has just randomly stopped working. No idea why it randomly stopped working.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float jumpPower = 2f;
[SerializeField]
public bool isGrounded = true;
[SerializeField]
private LayerMask groundLayer, waterLayer;
private int numSpacePress = 0;
private Rigidbody2D rb;
// Ground Checker Stuff
public Transform groundChecker;
public float groundCheckRadius = 0.1f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && isGrounded && numSpacePress < 2)
{
numSpacePress++;
Debug.Log("Num spaces pressed = " + numSpacePress);
rb.velocity = new Vector2(rb.velocity.x, jumpPower);
if (numSpacePress >= 2)
{
isGrounded = false;
}
}
Collider2D[] hits = Physics2D.OverlapCircleAll(groundChecker.position, groundCheckRadius);
foreach (Collider2D hit in hits)
{
if (hit.gameObject != gameObject)
{
Debug.Log("Hit = " + hit.gameObject.name);
if (((1 << hit.GetComponent<Collider2D>().gameObject.layer) & groundLayer) != 0)
{
isGrounded = true;
numSpacePress = 0;
}
}
}
}
}
What's Happening Gif, clearly in the gif I am pressing space twice, but it is only printing the number of spaces pressed by one. If the player is on the ground the number of spaces pressed is reset, but the gif also shows that the player is not touching the ground. Why is the space bar not being registered when pressed?
What was happening was a hit was occurring just after the space bar was pressed, which reset the variable counting the number of spaces pressed.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float jumpPower = 2f;
[SerializeField]
public bool isGrounded = true;
[SerializeField]
private LayerMask groundLayer, waterLayer;
private int numSpacePress = 0;
private Rigidbody2D rb;
// Ground Checker Stuff
public Transform groundChecker;
public float groundCheckRadius = 0.1f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Collider2D[] hits = Physics2D.OverlapCircleAll(groundChecker.position, groundCheckRadius);
foreach (Collider2D hit in hits)
{
if (hit.gameObject != gameObject)
{
Debug.Log("Hit = " + hit.gameObject.name);
if (((1 << hit.GetComponent<Collider2D>().gameObject.layer) & groundLayer) != 0)
{
isGrounded = true;
numSpacePress = 0;
}
}
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded && numSpacePress < 2)
{
numSpacePress++;
Debug.Log("Num spaces pressed = " + numSpacePress);
rb.velocity = new Vector2(rb.velocity.x, jumpPower);
if (numSpacePress >= 2)
{
isGrounded = false;
}
}
}
}