How Would I Improve this Simple Player Movement Script?

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public Rigidbody2D rb;

    public float playerSpeed;
    public float jumpHeight;

    private float horizontalInput;
    private bool grounded;

    void Start()
    {
        
    }

    void Update()
    {
        horizontalInput = Input.GetAxisRaw("Horizontal");

        rb.linearVelocity = new Vector2 (horizontalInput * playerSpeed, rb.linearVelocityY);

        if (Input.GetKeyDown(KeyCode.Space) && grounded)
        {
            rb.linearVelocity = Vector2.up * jumpHeight;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            grounded = true;
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            grounded = false;
        }
    }
}

Ignoring things like ‘Cayote Time’ since that is more out of my skill range.

You can improve any piece of code by these two steps:

  • identify the problems it gives you
  • design a fix for those problems and implement it.

Otherwise, randomly improving code is not a thing, especially when done by strangers on the internet.

If it works, it works. Ship it.

Coyote Time Jumping and disconnecting input gathering from input processing:

1 Like