How can I create a player movement script in Unity?

Hello everyone,

I’m relatively new to Unity and game development in general, and I’m currently working on a 2D platformer game. I want to create a player movement script that allows the character to move horizontally and jump. I’ve been trying to figure it out on my own, but I’m facing some difficulties.

Could someone please guide me on how to create a basic player movement script in Unity? I would greatly appreciate it if you could provide some example code or step-by-step instructions.

Thank you in advance!
Best regards,

You can use a RigidBody to make a character controller

Here is an example script:

public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float jumpForce = 5f;
    
    private Rigidbody2D rb;
    private bool isJumping = false;
    
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    
    private void Update()
    {
        float moveX = Input.GetAxis("Horizontal");
        
        // Move the player horizontally
        rb.velocity = new Vector2(moveX * moveSpeed, rb.velocity.y);
        
        // Jumping
        if (Input.GetButtonDown("Jump") && !isJumping)
        {
            rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
            isJumping = true;
        }
    }
    
    private void OnCollisionEnter2D(Collision2D collision)
    {
        // Check if the player is touching the ground
        if (collision.gameObject.CompareTag("Ground"))
        {
            isJumping = false;
        }
    }
}

Please try it and tell me if it works.