下面的代码中,通过将物体的坐标值赋值给了pos,然后在pos中修改了z上的值,最后再将修改后的值赋值给了物体的坐标,这样,每一次刷新帧,物体都能往前移动0.1的距离。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleLogic : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Application.targetFrameRate = 60;
}
// Update is called once per frame
void Update()
{
GameObject obj=this.gameObject;
Vector3 pos = obj.transform.position;
pos.z += 0.1f;
obj.transform.position = pos;
}
}
但是,如果像上面这样移动的话,由于帧的更新时间是不固定的,所以势必会造成物体不是匀速运动的情况,如果想要匀速运动的物体,则可以进行如下修改:
从下面的代码中可以看出,设置了一个speed速度,然后利用时间间隔Time.delTime计算出了物体每一帧做匀速运动所需要移动的距离。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleLogic : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Application.targetFrameRate = 60;
}
// Update is called once per frame
void Update()
{
float speed = 5.0f;
float distance = speed * Time.deltaTime;
GameObject obj=this.gameObject;
Vector3 pos = obj.transform.position;
pos.z += distance;
obj.transform.position = pos;
}
}