write a character controller for unity 2d in csharp

Here is a basic character controller for Unity 2D in C#:

main.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CharacterController2D : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 5f;

    [SerializeField]
    private float jumpForce = 5f;

    private Rigidbody2D rb;
    private Animator animator;

    private bool isGrounded = false;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
    }

    void Update()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(horizontalInput * moveSpeed, rb.velocity.y);

        if (horizontalInput != 0)
        {
            animator.SetBool("isRunning", true);
        }
        else
        {
            animator.SetBool("isRunning", false);
        }

        if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
        {
            rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
        }
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "Ground")
        {
            isGrounded = true;
        }
    }

    void OnCollisionExit2D(Collision2D col)
    {
        if (col.gameObject.tag == "Ground")
        {
            isGrounded = false;
        }
    }
}
1279 chars
60 lines

This character controller script uses the Rigidbody2D component for movement and the Animator component for animation. The moveSpeed variable controls the character's movement speed, while the jumpForce variable controls the character's jump force.

The Update() function handles movement and animation. The character's velocity is set based on horizontal input from the player using Input.GetAxis("Horizontal"). The character's running animation is controlled by a boolean parameter called isRunning on the Animator component. The OnCollisionEnter2D() and OnCollisionExit2D() functions handle detecting whether the character is grounded or not.

The character can perform a jump by pressing the space bar, but only if the character is currently grounded.

Note that this is a very basic character controller, and you may need to modify this code to fit your specific game requirements.

related categories

gistlibby LogSnag