drakeerv
drakeerv

Reputation: 303

How can you move by how fast the frame rate is in unity?

So I have some code for movement in my unity 3d game like:

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

public class FPSMovement : MonoBehaviour
{
    [SerializeField] float speed;
    [SerializeField] float sprintMultiplier = 1.5f;

    Rigidbody rb;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        float x = Input.GetAxisRaw("Horizontal");
        float z = Input.GetAxisRaw("Vertical");

        Vector3 moveBy = transform.right * x + transform.forward * z;

        float actualSpeed = speed;

        if (Input.GetKey(KeyCode.LeftShift)) {
            actualSpeed *= sprintMultiplier;
        }
        
        rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime);
    }
}

But when the frame rate is lower you move faster then when the framerate is higher. I can't find a answer on how to fix it. I can attach a video if it is necessary. Thanks.

Upvotes: 1

Views: 1009

Answers (1)

ChilliPenguin
ChilliPenguin

Reputation: 715

You have Time.deltaTime, in rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime); which is the time between frames. Since lower fps causes more time between frames, it will increase your speed. This is used to make the player travel for same amount of time under different fps.

Upvotes: 2

Related Questions