Home > Back-end >  Unity3d, script for moving along x-axis
Unity3d, script for moving along x-axis

Time:07-17

I have written a script for moving by X-axis. It is called from another script in Update() if Input.GetKeyDown("left") (there is an object of this class).

But why does it work with different speed in build and in editor? Does it depend on Time.deltaTime?

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

public class MoveToSpecifiedAbscissa : MonoBehaviour
{
    [SerializeField] private float AbscissaOfTheDestinantion;
    [SerializeField] private int Frequency;
    [SerializeField] private float Waiting;
    private float DisplacementByAbscissa;
    private bool IsMovingNow = false;

    public float GetTimeOfTheMoving()
    {
        return Waiting * (float)(Frequency);
    }

    public bool GetBoolVariableWhichSaysIfItIsMovingNow()
    {
        return IsMovingNow;
    }

    public void SetAbscissaOfTheDestinantion(float AbscissaToSave)
    {
        AbscissaOfTheDestinantion = AbscissaToSave;
    }

    private void Start()
    {
        DisplacementByAbscissa = AbscissaOfTheDestinantion - transform.position.x;
    }

    private IEnumerator MoveAbstractly(int frequency, float waiting)
    {
        IsMovingNow = true;
        for (int i = 0; i < frequency; i  )
        {
            transform.position  = new Vector3(DisplacementByAbscissa * (1 / (float)(frequency)), 0, 0);
            yield return new WaitForSeconds(waiting);
        }
        IsMovingNow = false;
        StopCoroutine(MoveAbstractly(frequency, waiting));
    }

    public void Move()
    {
        StartCoroutine(MoveAbstractly(Frequency, Waiting));
    }
}

CodePudding user response:

This could be because you use Update() in the other script, which is called more or less depending on the current FrameRate. (Update is called once every new frame) You could try calling your Movement via FixedUpdate() instead since it will be called frequently and does not depend on the FrameRate. I hope that fixes your problem! :)

CodePudding user response:

It is always safe to use time delta in transformations. As Pretzl already mentioned if you are calling the Move method from another script's Update method you will be calling the Move method based on the current framerate that will lead to speed deviations of the object on different runtimes.

By the way maybe there are small deviations in time when calling method WaitForSeconds(). When program waits for next iteration in the coroutine I guess you should be calculating the difference based on time delta. It will be safe.

  • Related