- Home /
Error in the total time needed to translate a GameObject
Hi there,
I'm translating a GameObject one unit length. By the physics formula it should takes one second.
Here's the code
public class Testing : MonoBehaviour
{
[Tooltip("In units per second")]
public Vector2 displacement;
float currentTime;
Stopwatch sw = new Stopwatch();
// Start is called before the first frame update
void Start()
{
currentTime = 0;
sw.Start();
}
// Update is called once per frame
void Update()
{
if (currentTime >= 1.0f)
{
sw.Stop();
UnityEngine.Debug.Log($"Time to translate: {sw.ElapsedMilliseconds}");
return;
}
Vector2 currentPos = transform.position;
var nextPos = currentPos + (displacement * Time.deltaTime);
transform.position = nextPos;
currentTime += Time.deltaTime;
}
}
when currentTime counter reach 1 the GameObject is indeed in the expected position so I thought everything was fine but I added a Stopwatch to measure the time it takes and for my surprise it is 1324 milliseconds.
Can anyone please give me some clue about why is this happening?
Thank you
Answer by RodrigoAbreu · Feb 11, 2021 at 06:31 PM
Maybe, instead of starting your sw on start, start it in the update if currentTime == 0.
void Start()
{
currentTime = 0;
}
// Update is called once per frame
void Update()
{
if (currentTime == 0)
{
sw.Start();
}
if (currentTime >= 1.0f)
{
sw.Stop();
UnityEngine.Debug.Log($"Time to translate: {sw.ElapsedMilliseconds}");
return;
}
Vector2 currentPos = transform.position;
var nextPos = currentPos + (displacement * Time.deltaTime);
transform.position = nextPos;
currentTime += Time.deltaTime;
}
Hi Rodrigo Abreu,
Thank you for your quick response. I tried the changes you recommended me and still the same result.
So I realized that when I click the play button in Unity the game start and for some reason 1 or 2 seconds after the game started it stop for a few milliseconds and then run smoothly.
So I moved the object one unit length and then started to measure the time it takes to move another unit length and effectively the time is in the range of 996 to 1033 milliseconds which is acceptable.
Thank you once again for your help and sorry for the late answer.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Collision reaction not working 2 Answers
Physics2d: one sided edge collider 1 Answer