Programming: Smoothest Player Movement in Unity

I did a little research to find the best player movement in Unity.

I wanted to find the smoothest and one that works with colliders.

Out of the different ways of moving a player. Like Lerping Translate or Move to. I found Add Force on a rigid body to yield the best results.

Here’s the script and a video showing the fluid movement of the player with acceleration and deacceleration.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float accleration;
    [SerializeField] private float deccleration;
    [SerializeField] private float maxSpeed;

    private Rigidbody2D rb2d;
    private PlayerActions actions;
    private Vector2 moveDirection;

    void Awake()
    {
        rb2d = GetComponent<Rigidbody2D>();
        actions = new PlayerActions();
    }
    void Update()
    {
        MoveDirection();
    }

    void FixedUpdate()
    {
        MovePlayer();
    }

    private void MovePlayer()
    {
        if (moveDirection != Vector2.zero)
        {
            rb2d.AddForce(moveDirection * accleration, ForceMode2D.Force);
            if (rb2d.velocity.magnitude > maxSpeed)
            {
                rb2d.velocity = rb2d.velocity.normalized * maxSpeed;
            }
        }
        else
        {
            rb2d.AddForce(rb2d.velocity * -deccleration, ForceMode2D.Force);
        }
    }

    private void MoveDirection()
    {
        moveDirection = actions.Movement.Moves.ReadValue<Vector2>().normalized;
    }
    
    
    private void OnEnable()
    {
        actions.Enable();
    }
        
    private void OnDisable()
    {
        actions.Disable();
    }
}

The script for Player input uses Unity’s new Input System. But you can adapt to for any user based input even 3D space.


These are the videos that helped me find the best solution.

https://youtu.be/EMhTROG0nAw?si=r4pYSJBrjh2S0H9h

https://youtu.be/JOiEz9fnc5Y?si=_6Aip4atSmy7iQSX

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments