【unity】移动接口

一、物体移动

总体来说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这个方法是对刚体施加力的作用,也就是施加了一个加速度,当然也就不可能是匀速运动了。


二、适用于物体按固定路线移动(比如迷宫中的怪物寻路),可以先设置一个组存放这些位置。

public Transform[] wayPoints;//目标点组

private void Update()

{

      if (transform.position != wayPoints[index].position)

      {

          MovePoints();//未到达index位置,继续移动

      }

      else

      {

          index = ++index % wayPoints.Length;//到达index位置,改变index值

      }

}

void MovePoints()

{

    Vector2 temp = Vector2.MoveTowards(transform.position, wayPoints[index].position, speed);

    //从当前位置移至index位置

    GetComponent<Rigidbody2D>().MovePosition(temp);

    //考虑到有可能会做碰撞检测,所以使用刚体的移动方式

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容