Home > Enterprise >  Why scripted movement and rotation of sprite gets slow in WebGl build?
Why scripted movement and rotation of sprite gets slow in WebGl build?

Time:12-07

I am a beginner Unity developer. I have created this.

enter image description here

The wizard on the top-right corner comes in from outside the screen when the game starts. Then stops and throws the axe. Which eventually hits the detective and causes him to fall.

The wizard and the axe have their scripts. There is no component attached to the wizard. The axe has a rigidbody (gravity scale set to 0) and a box collider attached.

Script of the wizard:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class WizardMover : MonoBehaviour
{
    public Vector3 move;
 
    // Start is called before the first frame update
    void Start()
    {
       
    }
 
    // Update is called once per frame
    void Update()
    {  
        // Wizard stops at at a specific postion
        if (transform.localPosition.x > 5.79)
        {
            transform.localPosition -= move;
        }
    }
}

And script for the axe:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class AxeFly : MonoBehaviour
{
    public Vector3 move;
    public Vector3 rotate;
 
    // Start is called before the first frame update
    void Start()
    {
       
    }
 
    // Update is called once per frame
    void Update()
    {
        transform.localPosition -= move;
 
        // Axe starts rotating when thrown
        if (transform.localPosition.x < 5.80)
        {
            transform.Rotate(rotate);
        }
    }
}

Everything works as expected when I play this in Unity. But the speed of scripted movement and rotation of both the wizard and the axe gets significantly slow in the WebGL build. Why is this happening?

CodePudding user response:

Your code is frame-rate dependent!

What this means is on a stronger device which can run with higher FPS (frames per second) your Update method is called more often within the same absolute real time as on a weak device with lower FPS.

So of course if you move with a fixed distance more often within the same time the object will in total travel further and vise versa.


For continous animations in Unity you should always use Time.deltaTime

The interval in seconds from the last frame to the current one (Read Only).

(or sometimes even Time.unscaledDeltaTime in cases where you want to ignore the current Time.timeScale)

which basically converts any value from value per frame into a value per second.

transform.localPosition -= move * Time.deltaTime;

and

transform.Rotate(rotate * Time.deltaTime);

adjust the move and rotate accordingly to the expected absolute value per second.

  • Related