Attach Collider2D, RigidBody2D, CharacterController2D to player and use Move
Method in FixUpdate. Meanwhile, properties of RigidBody2D: Body Type = Dynamic, Simulated = true, Gravity Scale = 0, Constraints - Freeze Rotation Z = true
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class CharacterController2D : MonoBehaviour
{
#region Move Var
[SerializeField, Tooltip("Max speed, in units per second, that the character moves.")]
float speed = 2;
[SerializeField, Tooltip("Acceleration while grounded.")]
float walkAcceleration = 20f;
[SerializeField, Tooltip("Deacceleration while stopped.")]
float deceleration = 80f;
[SerializeField, Tooltip("Stop when move input smaller than stopThreshold")]
float stopThreshold = 0.1f;
private Rigidbody2D rg;
private Vector2 velocity;
public bool isMoving
{
get { return velocity != Vector2.zero; }
}
#endregion
private void Awake()
{
rg = GetComponent<Rigidbody2D>();
}
public void Move(Vector2 moveInput)
{
// Move Logic
if (moveInput.magnitude >= stopThreshold)
velocity = Vector2.MoveTowards(velocity, speed * moveInput, walkAcceleration * Time.fixedDeltaTime);
else
velocity = Vector2.MoveTowards(velocity, Vector2.zero, deceleration * Time.fixedDeltaTime);
if (velocity.magnitude <= stopThreshold)
velocity = Vector2.zero;
Vector2 curPos = new Vector2(transform.position.x, transform.position.y);
Vector2 nextPos = curPos + velocity * Time.fixedDeltaTime;
rg.MovePosition(nextPos);
}
```