WindowsMacSoftwareSettingsSecurityProductivityLinuxAndroidPerformanceConfigurationApple All

How to Implement Character Movement in Unity

Edited 4 weeks ago by ExtremeHow Editorial Team

UnityGame DevelopmentAnimation3DProgrammingScriptingC#PhysicsControlsWindowsMacLinux

How to Implement Character Movement in Unity

This content is available in 7 different language

Introduction

Unity is a popular game development platform that allows creators to bring their game ideas to life. One of the fundamental aspects of any game is character movement. Whether it's a simple 2D platformer or a complex 3D world, the way a character moves can have a huge impact on the gameplay experience. This guide is designed to walk you through the basic steps of implementing character movement in Unity. We'll cover different methods, including RigidBody and CharacterController components, scripting basic movement scripts in C#, and tweaking for optimal gameplay feel.

Set up your project

Before you start programming, you'll need to set up a new Unity project. Open the Unity Hub and create a new project. You can choose a 2D or 3D template depending on the type of game you're creating. Name your project and choose a location to save it. Once your project is created, you can begin implementing character movement.

Add a new GameObject to your scene. This will be your character. You can use either a 3D model, a simple shape like a cube or sphere, or a 2D sprite if you're working with a 2D game. For simplicity, we'll assume you're using a basic cube for a 3D character.

Using Rigidbody for motion

The RigidBody component in Unity provides a way to handle physics-based motion. This can include gravity, drag, and collisions. To add a RigidBody to your character, select the GameObject and click Add Component, then find and add RigidBody.

        // C# Script Example for Rigidbody Movement
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
    public float speed = 5f;
    private Rigidbody rb;
    void Start() {
        rb = GetComponent<Rigidbody>();
    }
    void Update() {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
        rb.AddForce(movement * speed);
    }
}
    

This code sets the basic motion using the arrow keys or WASD. The speed variable controls how fast the character moves. The RigidBody component will automatically handle collisions and gravity. Remember to adjust RigidBody settings such as mass and drag to get the motion feel you want.

Using the CharacterController for movement

Unity's CharacterController is another way to implement character movement. This component is non-physics-based, meaning it does not react to forces or torques, but it can still collide with objects. It is often used to achieve smooth, controlled motion for player characters.

Add CharacterController component to your gameobject by selecting it and clicking Add Component, then selecting CharacterController.

        // C# Script Example for CharacterController Movement
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;
    private Vector3 moveDirection = Vector3.zero;
    private CharacterController controller;
    void Start() {
        controller = GetComponent<CharacterController>();
    }
    void Update() {
        if (controller.isGrounded) {
            float moveHorizontal = Input.GetAxis("Horizontal");
            float moveVertical = Input.GetAxis("Vertical");
            moveDirection = new Vector3(moveHorizontal, 0.0f, moveVertical);
            moveDirection = transform.TransformDirection(moveDirection);
            moveDirection *= speed;
            if (Input.GetButton("Jump")) {
                moveDirection.y = jumpSpeed;
            }
        }
        moveDirection.y -= gravity * Time.deltaTime;
        controller.Move(moveDirection * Time.deltaTime);
    }
}
    

In this example, the script is a bit more complex. The CharacterController uses its own Move method, which allows for more sophisticated control. This example involves jumping and uses gravity to keep the character on the ground. You can change the speed, jumpSpeed, and gravity to suit your needs.

Scripting the movement logic

Both the RigidBody and CharacterController methods require scripts to control movement. The scripts provided earlier are starting points, but you may want to expand on these to include more features such as running, crouching, or interacting with the environment.

A useful way to refine motion is to apply acceleration and deceleration, allowing the character to gradually gain or lose speed rather than stopping or starting instantly. Here's a simple way to incorporate acceleration:

        // C# Script Example with Acceleration
public class PlayerMovement : MonoBehaviour {
    public float speed = 6.0f;
    public float acceleration = 5.0f;
    private Vector3 velocity = Vector3.zero;
    private Rigidbody rb;
    void Start() {
        rb = GetComponent<Rigidbody>();
    }
    void Update() {
        float targetSpeed = Input.GetAxis("Vertical") * speed;
        velocity.z = Mathf.MoveTowards(velocity.z, targetSpeed, acceleration * Time.deltaTime);
        Vector3 move = transform.TransformDirection(velocity);
        rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
    }
}
    

This script uses `Mathf.MoveTowards` to smoothly interpolate between current and target motion, creating a more refined and realistic motion experience.

Advanced movement features

After you've implemented the basic movements, you may want to add more advanced features to your character. These can include running, double jumping, and climbing:

Here's how you can implement sprinting:

        // C# Script Example for Sprinting
public class PlayerMovement : MonoBehaviour {
    public float speed = 6.0f;
    public float sprintSpeed = 12.0f;
    public float acceleration = 5.0f;
    private Vector3 velocity = Vector3.zero;
    private Rigidbody rb;
    void Start() {
        rb = GetComponent<Rigidbody>();
    }
    void Update() {
        float currentSpeed = Input.GetKey(KeyCode.LeftShift) ? sprintSpeed : speed;
        float targetSpeed = Input.GetAxis("Vertical") * currentSpeed;
        velocity.z = Mathf.MoveTowards(velocity.z, targetSpeed, acceleration * Time.deltaTime);
        Vector3 move = transform.TransformDirection(velocity);
        rb.velocity = new Vector3(move.x, rb.velocity.y, move.z);
    }
}
    

This script checks if the left shift key is being pressed to determine whether or not to apply a sprint speed.

Tuning and optimization

When developing a game, you will spend a lot of time refining movement. The feel of a character's movement can define the player's experience. Here are some tips for refining movement:

Conclusion

Implementing character movement in Unity is a fundamental skill in game development. Whether you're using physics-based movement with RigidBody or controlled movement with CharacterController, the main thing is to understand the basics and extend with advanced features. Through scripting and fine-tuning movement, you can create a stunning and enjoyable player experience.

If you find anything wrong with the article content, you can


Comments