- Home /
Why my variable istn't always used?
Hi, I'm trying to make my character able to jump and have a problem. Not always when I press space my character jumps, so I have added Debug.Log to check is it registered the button is pressed, and it is. So at the moment I have no idea what's wrong.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public float moveSpeed;
public float jumpForce;
public int extraJumps = 1;
private float horizontalDirection;
private bool onGround;
private bool isJumping = false;
public LayerMask GroundMask;
public Transform feet;
Rigidbody2D rb;
CircleCollider2D circle;
void Start()
{
rb = GetComponent<Rigidbody2D>();
circle = GetComponent<CircleCollider2D>();
}
void Move()
{
horizontalDirection = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(horizontalDirection,0)*moveSpeed;
if(onGround)
extraJumps = 1;
}
void Jump()
{
if(isJumping)
{
Debug.Log("up");
rb.velocity = Vector2.up * jumpForce;
}
}
void JumpDetection()
{
isJumping = Input.GetKeyDown(KeyCode.Space);
if(isJumping)
Debug.Log("Space pressed");
}
bool GroundCheck()
{
return onGround = Physics2D.OverlapCircle(feet.position,0.1f,GroundMask);
}
void FixedUpdate()
{
Move();
Jump();
}
void Update()
{
JumpDetection();
}
}
Answer by KarMa_PlaYzz · Jul 09, 2021 at 08:25 AM
What probably is happening is that FixedUpdate and Update are sometimes out of sync.
Instead, have the bool work as a flag:
void Jump()
{
if(isJumping)
{
Debug.Log("up");
rb.velocity = Vector2.up * jumpForce;
//Disable isJumping here
isJumping = false;
}
}
void JumpDetection()
{
//Enable isJumping here
if(Input.GetKeyDown(KeyCode.Space))
isJumping = true;
}
Answer by Mrpxl · Jul 09, 2021 at 08:29 AM
You never set isJumping
to false so it won't reset. I suggest you call Jump() function when you detect the spacebar press. FixedUpdate() is called at the beginning of the new frame whereas Update() is called later, resulting in your jump being executed the next frame after your key press
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Jumping on moving platforms problem c# 1 Answer
How can I change jump direction? 1 Answer