sonmar
sonmar

Reputation: 1

When I use Time.deltaTime, it stops my function from working

in my code whene I want to move a character from right or left, the code works but unfortunately after 2 seconds the character stops and when I used Time.deltaTime, my character no longer moves. Do you have any ideas? the console displays messages well

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

public class MoveUpDown : MonoBehaviour
{
    private Rigidbody2D rb;
    public float moveSpeed;

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

    public void MoveRight()
    {
        rb.velocity = Vector2.right * moveSpeed * Time.deltaTime;
        Debug.Log("il vas a droite");
    }

    public void MoveLeft()
    {
        rb.velocity = Vector2.right * -moveSpeed * Time.deltaTime;
    }

    public void StopMoving()
    {
        rb.velocity = Vector2.zero;
        Debug.Log("il bouge plus");
    }

   
}

Upvotes: 0

Views: 67

Answers (1)

gurur
gurur

Reputation: 13

Try it without the Time.deltaTime.

You're directly assigning the velocity to some value so you don't need the Time.deltaTime.

if you want to gradually add some velocity to an object inside the update function that's when you need the Time.deltaTime.

for Example;

    private void Update()
    {
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            rb.velocity = Vector2.left * moveSpeed * Time.deltaTime;
        }
    }

also you can check this thread;

https://forum.unity.com/threads/velocity-time-deltatime.91518/

Upvotes: 1

Related Questions