Character Running and MovementHow to Setup Colliders and Character Movement in Unity

Author Waldo
Published October 1, 2019

In this video to cover running in a 2D environment for Platformer games.

Video Walkthrough

  • 0:40 - Adding a RigidBody2D and C# Script
  • 1:24 - Defining Controller Input in C#
  • 2:40 - Moving our Character with RigidBody2D.AddForce
  • 3:35 - Adding Animation States to our Character
  • 4:00 - Setting Up Animator Parameters in C#
  • 5:20 - Flipping our Sprite in the Direction we are running
  • 6:50 - Adding EdgeCollider2D
  • 7:50 - Limiting Velocity with Max Speed
  • 9:13 - Using Linear Drag to Stop our Character from running
  • 10:30 - Changing Directions
  • 11:11 - Final Product

Source Code for Player.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour{
    [Header("Horizontal Movement")]
    public float moveSpeed = 10f;
    public Vector2 direction;
    private bool facingRight = true;

    [Header("Components")]
    public Rigidbody2D rb;
    public Animator animator;

    [Header("Physics")]
    public float maxSpeed = 7f;
    public float linearDrag = 4f;

    // Update is called once per frame
    void Update(){
        direction = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
    }
    void FixedUpdate(){
        moveCharacter(direction.x);
        modifyPhysics();
    }
    void moveCharacter(float horizontal){
        rb.AddForce(Vector2.right * horizontal * moveSpeed);

        if((horizontal > 0 && !facingRight) || (horizontal < 0 && facingRight)){
            Flip();
        }
        if(Mathf.Abs(rb.velocity.x) > maxSpeed){
            rb.velocity = new Vector2(Mathf.Sign(rb.velocity.x) * maxSpeed, rb.velocity.y);
        }
        animator.SetFloat("horizontal", Mathf.Abs(rb.velocity.x));
    }
    void modifyPhysics(){
        bool changingDirections = (direction.x > 0 && rb.velocity.x < 0) ||  (direction.x < 0 && rb.velocity.x > 0);

        if(Mathf.Abs(direction.x) < 0.4f || changingDirections){
            rb.drag = linearDrag;
        }else{
            rb.drag = 0f;
        }
    }
    void Flip(){
        facingRight = !facingRight;
        transform.rotation = Quaternion.Euler(0, facingRight ? 0 : 180, 0);
    }
}

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About