My player runs too fast

Hi,

If I include runSpeed (even at very low values) my player runs left and right way too fast. If I omit runSpeed he runs too slow. How can I fix this?

Here is the relevant PlayerMovement.cs code:

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

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] float runSpeed = 0.00001f;
    [SerializeField] float jumpSpeed = 5f;

    Vector2 moveInput;
    Rigidbody2D myRigidbody;
    Animator myAnimator;
    CapsuleCollider2D playerCollider;
    bool playerHasHorizontalSpeed;

    void Start()
    {
        myRigidbody = GetComponent<Rigidbody2D>();
        myAnimator = GetComponent<Animator>();
        playerCollider = GetComponent<CapsuleCollider2D>();
    }

    void Update()
    {
        playerHasHorizontalSpeed = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;
        Run();
        FlipSprite();
    }

    void OnMove(InputValue value)
    {
        moveInput = value.Get<Vector2>();
    }

    void OnJump(InputValue value)
    {
        if(playerCollider.IsTouchingLayers(LayerMask.GetMask("Ground")) && value.isPressed)
        {
            myRigidbody.velocity += new Vector2 (0f, jumpSpeed);
        }
    }

    void Run()
    {
        Vector2 playerVelocity = new Vector2 (moveInput.x * runSpeed, myRigidbody.velocity.y);
        myRigidbody.velocity = playerVelocity;

        myAnimator.SetBool("isRunning", playerHasHorizontalSpeed);
    }

    void FlipSprite()
    {

        if(playerHasHorizontalSpeed)
        {
            transform.localScale = new Vector2 (Mathf.Sign(myRigidbody.velocity.x), 1f);
        }
    }
}

Edit: Updated to include all class code.

Thanks

This can’t be the only relevant code because I just ran this and the ‘player’ is hardly moving at all with those values. Where does moveInput come from? Where is Run() called from?


Edit
What is the value of runSpeed in the inspector? I suspect it’s a rather high value. You cannot change serialized values in the code once they’ve been set in the inspector. Unity has saved the inspector value and is overriding whatever is in code with that value

Thank you for your response:

  • I’ve updated my question to include all code in the class
  • runSpeed is 30 in the inspector

Edit: I changed the code and inspector runSpeed to 5 and the player speed is much better. Next time I’ll remember to reset the inspector values to match the code!

Thanks

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

Privacy & Terms