游戏编程4_物体移动

下面的代码中,通过将物体的坐标值赋值给了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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值