2D Platformer Controller responsiveness issue
I've been designing some basic controls for a 2D platformer and managed to get the feeling that I've been looking for when moving and jumping, but something is not quite right, it's not very responsive.
Most of the inputs are detected, but a lot of times, for example, the simple action of pressing some key to jump is completely ignored and the player ends up falling when the key was pressed at the right time. I don't consider that I'm developing on a laptop with low specs at all if that matters.
Looking at some other questions it has always been said that input detection should be inside the Update function and that physics related stuff should be on FixedUpdate, however, it has not always been very clear what exactly should be on which function, as far as I understand it should go something like this...right?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed;
public float jumpForce;
public float groundCheckRadius;
public Transform groundCheck;
public LayerMask groundMask;
private float direction;
private bool facingRight;
private bool shouldJump;
private bool isGrounded;
private bool shouldFall;
private SpriteRenderer renderer;
private Rigidbody2D rigidbody;
void Awake() {
this.renderer = GetComponent<SpriteRenderer>();
this.rigidbody = GetComponent<Rigidbody2D>();
}
void Start () {
this.facingRight = true;
this.shouldJump = false;
this.isGrounded = false;
this.shouldFall = false;
}
void Update () {
this.direction = Input.GetAxisRaw("Horizontal");
this.isGrounded = Physics2D.OverlapCircle(this.groundCheck.position, this.groundCheckRadius, this.groundMask);
this.shouldJump = Input.GetKeyDown(KeyCode.S) && this.isGrounded;
if (this.facingRight && this.direction < 0 || !this.facingRight && this.direction > 0)
this.Flip();
if (Input.GetKeyUp(KeyCode.S) && this.rigidbody.velocity.y > 0)
this.shouldFall = true;
}
void FixedUpdate() {
Vector2 velocity = this.rigidbody.velocity;
if (this.shouldFall) {
velocity.y = 0f;
this.shouldFall = false;
}
if (this.shouldJump)
velocity.y = this.jumpForce;
velocity.x = this.speed * this.direction;
this.rigidbody.velocity = velocity;
}
private void Flip() {
this.renderer.flipX = this.facingRight;
this.facingRight = !this.facingRight;
}
}
I'm not sure if I got the idea of Update vs FixedUpdate correctly because of this lack of responsive jumps, and I'm guessing that if I add some more mechanics, later on, those will react the same or worse.
Your answer
Follow this Question
Related Questions
Optimizations: Should I use Update or FixedUpdate? Could you help me optimize rotations? 1 Answer
Physics after build feel different vs In-Editor (Time.deltaTime) 1 Answer
Make FixedUpdate camera be static like in Update? 0 Answers
Programmatically control Unity Game loop to sync with external hardware/software 1 Answer
Need help with my code 0 Answers