Set the object to move at a constant speed in Unity

How to set the uniform movement of the object

In Unity, we can Translateadjust the position of the object through the method, but the following usage is a bit problematic.

void Update()
{
    
    
     var location = -0.08f;
     transform.Translate(location, 0, 0);
 }

The effect is as shown in the figure.
insert image description here
As can be seen in the picture, the movement of the small aircraft is obviously not smooth enough, and it feels particularly stuck.
To understand the cause of this problem, we need to understand the concept of FPS first. The full name of FPS is Frames Per Second, which is the number of frames per second. In the above demonstration, I fixed the FPS to 50. The code is as follows.

Application.targetFrameRate = 50;

It means that every 20 milliseconds, a frame of image is refreshed, and every time an image is refreshed, the small plane wants to move 0.8f units to the right. Normally, if the CPU can guarantee that it refreshes every 20 milliseconds when it is determined, it is not a big problem to write, but Although the FPS is set to 50, the CPU calculation will not be accurate to one frame of image every 20 seconds, and there will always be errors. Below is the time to print.
insert image description here
As can be seen in the figure above, there is not a fixed image frame every 20 milliseconds, so the movement of the small plane is not smooth enough. In order to ensure the smooth movement of the small plane, we can write like this.

 void Update()
 {
    
    
      //Debug.Log("查看打印时间"+ Time.deltaTime);
      var location = -0.8f * Time.deltaTime;
      transform.Translate(location, 0, 0);
  }

Multiply the moving distance by the interval time to ensure that the moving distance is short when the interval time is short. The moving distance is not a fixed value, but will change with time. Next look at the effect.
insert image description here
Much smoother than the above movement.

have a wonderful day

おすすめ

転載: blog.csdn.net/u012869793/article/details/125036623