A key will not respond
In a platform game I am making, I programmed the player to jump assuming the up arrow is pressed and the bool "onGround" is equal to true. Sometimes it inexplicably works even when onGround equals true. So I had "Jump" printed to the console every time I pressed up arrow. When onGround equaled true, and I pressed the up arrow, occasionally it would, regardlessly, not work. Please help!
Code:
public float speed;
public float jumpForce;
Rigidbody2D rb;
public GroundCheck groundCheck;
Animator anim;
SpriteRenderer spriteRend;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
spriteRend = GetComponent<SpriteRenderer>();
}
void FixedUpdate()
{
anim.SetFloat("Velocity", rb.velocity.y);
anim.SetFloat("Speed", Mathf.Abs(rb.velocity.x));
if (Input.GetKeyDown(KeyCode.UpArrow)&&groundCheck.onGround)
{
rb.velocity = new Vector2(0, 0);
rb.AddForce(jumpForce * Vector2.up, ForceMode2D.Impulse);
anim.SetBool("IsJumping", true);
Debug.Log("jump");
}
if (Input.GetKey(KeyCode.RightArrow))
{
rb.velocity = new Vector2(+speed, rb.velocity.y);
transform.localScale = new Vector3(1, 1, 1);
}
else if (Input.GetKey(KeyCode.LeftArrow))
{
rb.velocity = new Vector2(-speed, rb.velocity.y);
transform.localScale = new Vector3(-1,1,1);
}
else
{
rb.velocity = new Vector2(0, rb.velocity.y);
}
}
public void StopJumpAnim()
{
anim.SetBool("IsJumping", false);
}
Answer by rage_co · Aug 16, 2021 at 04:25 AM
The problem is that, while continous inputs like checking if a key is being held down are totally fine in fixed update, One time Functions like checking if a key is pressed (GetKeyDown)..are better in Update as it can result in input loss in fixedupdate, it's totally healthy to Move your jump command to the update method along with all the physics is it, because it's a one time run so you don't need to worry about them adding up if the framerates are high
Your answer
Follow this Question
Related Questions
How do I make a ball bounce in a circle? 0 Answers
Menu object not responding 0 Answers
Level Start error :/ 1 Answer
Sound in Unity is not working! WHY? 0 Answers
Unity 2017 or 5.6 Doesn't work after install. Editor is broken. 0 Answers