找回密码
 立即注册
查看: 291|回复: 0

【unity】移动接口

[复制链接]
发表于 2022-5-27 17:23 | 显示全部楼层 |阅读模式
一、物体移动

总体来说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);

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

}
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-9-22 09:47 , Processed in 0.087227 second(s), 25 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表