Home > front end >  Floating when adding Time.deltaTime to movement
Floating when adding Time.deltaTime to movement

Time:10-30

My movement is working fine without Time.deltaTime but when I add it to my player movement I can move left to right fine but I fall slowly and I cant jump

using Newtonsoft.Json.Bson;
using System;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float horSpeed;
    [SerializeField] private float vertSpeed;
    private Rigidbody2D rb;
    private Boolean isJumping;
    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        // we store the initial velocity, which is a struct.
        var v = rb.velocity * Time.deltaTime;

        


        if (Input.GetKey(KeyCode.Space) && !isJumping)
        {
            vf.y = vertSpeed;
            isJumping = true;
        }

        if (Input.GetKey(KeyCode.A))
        {
            vf.x = -horSpeed;
        }
           

        if (Input.GetKey(KeyCode.D))
        {
            vf.x = horSpeed;
        }
           

        if (Input.GetKey(KeyCode.S))
        {
            vf.y = -vertSpeed;
        }
            

        rb.velocity = vf;

        if(Input.GetKey(KeyCode.Escape))
            SceneManager.LoadScene(0);
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        isJumping = false;
    }

}

I've added it to my enemy script and it works fine so im not sure whats different with player movement to using transform.position

CodePudding user response:

Why would you multiply the velocity by Time.deltaTime?

This is used to convert a value from a "certain unit per frame" into a value "certain unit per second".

A velocity already IS a value in units per second.

Linear velocity of the Rigidbody in units per second.

=> It makes no sense to apply Time.deltaTime here at all.


For your X axis movement it doesn't make much difference since you anyway apply that velocity continuously every frame. Here you just would probably want to handle the case where neither left nor right is pressed and set vf.x = 0.

For the Y axis however you apply the jump only once, just to divide it by about 60 (or whatever your frame rate is) right in the next frame => you never give it the chance to fall or jump.


In general you should modify the Rigidbody in FixedUpdate. In your specific case it is fine to do this in Update, it is just redundant work ;)

  • Related