Uneven movement of 2d sprite

Hi all, my player sprite is not moving properly. It sometimes goes faster/slower than intended and i have no idea why. Below is my code for the player’s movement

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

public class PlayerMovement : MonoBehaviour
{
    public float speed;
    private Rigidbody2D myRigidbody;
    private Vector3 change;
    private Animator animator;

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

    private void Update()
    {
        change = Vector3.zero;
        change.x = Input.GetAxisRaw("Horizontal");
        change.y = Input.GetAxisRaw("Vertical");
        UpdateAnimationAndMove();
      
    }

    void UpdateAnimationAndMove()
    {
        if (change != Vector3.zero)
        {
            MoveCharacter();
            animator.SetFloat("moveX", change.x);
            animator.SetFloat("moveY", change.y);
            animator.SetBool("Moving", true);
        }
        else
        {
            animator.SetBool("Moving", false);
        }
    }
   
    void MoveCharacter()
    {
        myRigidbody.MovePosition(transform.position + change.normalized * speed * Time.deltaTime);
    }
}

The issue is rigidbody.MovePosition. It doesn’t update until FixedUpdate and will only accept the last position entered. Update and FixedUpdate(physics update) are not the same frequency. FixedUpdate is around 50fps or 0.02s, with Update going with vsync or as fast as possible.

My suggestion, grab input in Update like you are, then call UpdateAnimationAndMove() from FixedUpdate instead.

1 Like

Thank you for the suggestion, it worked.

However, could you further elaborate what it means when you said “It doesn’t update until FixedUpdate and will only accept the last position entered”? Thanks in advance

Update and FixedUpdate are not sync’d by default. Update will go with either vsync, which is usually 60fps or unlimited depending on what you have set. So when you call MovePosition in Update it might call Update 2 or more times before FixedUpdate is called. This means that a one of more calls to MovePosition will be overwritten by the last one to be called before FixedUpdate is called. If for some reason things are slowing down and Update is less than 50fps FixedUpdate will be called more often as the system tries to maintain a steady physics update rate, which helps create a more stable physics system.