简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM