How to measure or assign Movement Speed ?

Hi guys,

I am working on a 2D Game and I would like to measure or assign a Movement Speed for the character, any ideas how can I get this done?

My goal is to have a value that represent the speed of the character and be able to modify the value depending on the character.

Here is the code i am using:

public class Player_Movement : MonoBehaviour
{
    private BoxCollider2D boxCollider;
    private Vector3 moveDelta;
    private RaycastHit2D hit;
    // Test Speed
    public float MoveSpeed = 3.0f;
    private void Start()
    {
        boxCollider = GetComponent<BoxCollider2D>();
    }
    private void FixedUpdate()
    {
        float x = Input.GetAxisRaw("Horizontal");
        float y = Input.GetAxisRaw("Vertical");
     
        // Reset MoveDelta
        moveDelta = new Vector3(x,y,0);
        // Swap sprite direction, wether you are going right or left
        if (moveDelta.x < 0)
            transform.localScale = Vector3.one;
        else if (moveDelta.x > 0)
            transform.localScale = new Vector3(-1, 1, 1);
        // Make sure you can move in this direction by casting a box there first, if the box returns null we are free to move
        hit = Physics2D.BoxCast(transform.position,boxCollider.size, 0, new Vector2(0, moveDelta.y), Mathf.Abs(moveDelta.y * Time.deltaTime), LayerMask.GetMask("Player","Blocking"));
        if(hit.collider == null)
        {
            // Make this thing move
            transform.Translate(0, moveDelta.y * Time.deltaTime, 0);
        }
        hit = Physics2D.BoxCast(transform.position, boxCollider.size, 0, new Vector2(moveDelta.x, 0), Mathf.Abs(moveDelta.x * Time.deltaTime), LayerMask.GetMask("Player", "Blocking"));
        if (hit.collider == null)
        {
            // Make this thing move
            transform.Translate(moveDelta.x * Time.deltaTime, 0, 0);
        }

First, please use [ code = CSharp ] tags above to make it more readable.

Second, It looks like your movement per frame is the moveDelta vector multiplied by time.deltaTime. Whenever you multiply by Time.deltaTime you are adjusting for the per-frame amount. So that means that in 1 second, it will move by the amount of moveDelta, hence moveDelta is your speed per second. So if you want to adjust this based on a value that is adjustable per character, just add a public float and multiply your moveDelta by it.

...
transform.Translate (moveDetla.x * maxSpeed * Time.deltaTime, 0, 0)```
1 Like

Thanks Barskey, it did work out!