0
点赞
收藏
分享

微信扫一扫

unity 几种简单物体移动方式以及它们的区别

修炼之士 2022-02-04 阅读 76

总体来说unity中物体的移动可以分为两大类,分别是物理的和非物理的。

非物理的主要是通过transform组件,具体有两种方法。第一种是

Vector3 v1=new Vector3(0,0,-1f);

transform.position=v1;

直接改变物体位置,也可以在update函数中每次+=一个向量来实现连续移动。

第二种是

    void Update()
    {
        transform.Translate(v1*0.001f);
    }

利用平移矩阵移动。

物理的方法主要是通过rigidbody组件,具体有以下两种

public class enemy : MonoBehaviour
{
    private Rigidbody rb;
    Vector3 direction=new Vector3(0,0,-1f);//方向向量
    float speed = 1.0f;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        rb.velocity = direction*speed;
    }
}

 

public class enemy : MonoBehaviour
{
    private Rigidbody rb;
    Vector3 direction=new Vector3(0,0,-1f);//方向向量
    float force = 1.0f;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        rb.AddForce(direction*force);
    }
}

分别是通过给刚体设定速度和一个力来使物体移动。 

transform.position采用的是世界坐标系,它与unity面板上的位置是不同的,具体见这篇https://blog.csdn.net/qq_43533956/article/details/121945856?spm=1001.2014.3001.5502

而transform.translate()只输入一个参数时默认采用的是自身坐标系。如果要采用世界坐标系,需要在第二形参位置输入space.world。物理方法采用的也都是世界坐标系。

rb.velocity是一个恒定的速度,单位是米每秒,而其他几种写在update中的方法都是每帧执行一次,所以即使是同一电脑由于帧率变化速度也会波动。如果想要不受帧率影响,则需要乘上Time.deltatime即一帧的间隔时间。

rb.AddForce这个方法是对刚体施加力的作用,也就是施加了一个加速度,当然也就不可能是匀速运动了。

举报

相关推荐

0 条评论