Movement behaviour is unexpected

I’m not really sure what’s happening, this is my current code:

public class Player : MonoBehaviour
{
    [Header("Player Movement")]
    [SerializeField] float moveSpeed = 10f;

    //Cached references
    Rigidbody2D playerRigidBody;
    Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        playerRigidBody = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        Run();
        FlipSprite();
    }

    public void Run()
    {
        float deltaX = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
        Vector2 playerVelocity = new Vector2(deltaX, playerRigidBody.velocity.y);
        playerRigidBody.velocity = playerVelocity;   
    }

    private void FlipSprite()
    {
        bool playerHasHorizontalSpeed = Mathf.Abs(playerRigidBody.velocity.x) > Mathf.Epsilon;
        if (playerHasHorizontalSpeed)
        {
            transform.localScale = new Vector2(Mathf.Sign(playerRigidBody.velocity.x), 1f);
        }
    }
}

But using the moveSpeed as 10, it gets EXTREMELY slow, barely visible, so for properly testing I set it to 200. Other issue, is that the sprite moving on the screen is extremely laggy, you can see it moving, and then losing speed and then moving again.

Not sure what to do in this case!

Hi Galiza,

Try to remove Time.deltaTime from the float deltaX line.

Did this fix it?


See also:

Yes, it did! Thank you so very much!

But then my question is, how could I make it frame rate independent?

It already is framerate independent. See the description in the API. :slight_smile:

Oh, nice! Thank you so very much for the fast response!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms