Home > database >  Should I put Time.deltaTime into this code and if so how should I do it?
Should I put Time.deltaTime into this code and if so how should I do it?

Time:10-30

Im not sure weather or not to use Time.deltaTime I think it would be good to implement it but im not sure how to, I've already tried but I've messed something up

using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float horSpeed;
    [SerializeField] private float vertSpeed;
    private Rigidbody2D rb;
    private bool isJumping;

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

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

        


        if (Input.GetKey(KeyCode.Space) && !isJumping)
        {
            v.y = vertSpeed * Time.deltaTime;
            isJumping = true;
        }

        if (Input.GetKey(KeyCode.A))
            v.x = -horSpeed * Time.deltaTime;

        if (Input.GetKey(KeyCode.D))
            v.x = horSpeed * Time.deltaTime;

        if (Input.GetKey(KeyCode.S))
            v.y = -vertSpeed * Time.deltaTime;

        rb.velocity = v;

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

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

}

When I tried to add it my character just moved extremely slow

CodePudding user response:

Increase The speed of both vertSpeed and horSpeed or u can use rb.AddForce()

CodePudding user response:

Multiplying your input vectors with Time.DeltaTime makes it frame rate independent.

CodePudding user response:

Try my code. It has no jumping and requires rigidbody and collider2D. I make it for 2d RPG game.

public float speed = 2f;
private Rigidbody2D rb;
private Vector2 moveDelta;
//Inputs
private float x;
private float y;

private void Start()
{
    rb = GetComponent<Rigidbody2D>();      
}


private void FixedUpdate()
{
    //Reset V3
    x = Input.GetAxisRaw("Horizontal");
    y = Input.GetAxisRaw("Vertical");
    moveDelta = new Vector2(x, y);        

    //Facing Toward Mouse
    float dir = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).normalized.x;

    //Rigidbody
    rb.velocity = moveDelta * speed * Time.fixedDeltaTime;

    //Swap side of the sprite
    if(dir > 0)
    {
        transform.localScale = Vector3.one;
    }else if (dir < 0)
    {
        transform.localScale = new Vector3(-1, 1, 1);
    }
}
  • Related