在Unity开发中我们难免要使用代码控制角色的移动,现将已知的几种方法总结如下:

一、transform.Translate()

function Translate (translation : Vector3, relativeTo : Space = Space.Self) : void

沿着Translation的方向移动|translation|的距离,其结果将应用到relativeTo坐标系中。如果relativeTo为空(即调用方法Translate(translation:Vector3))或者为Space.Self,则移动结果会应用到自身所在的坐标系中。举个例子:

function Update() {

//导弹相对于战斗机以ShootSpeed 的速度向前运动,Vector3.forward在此时表示导弹的正前方

transform.Translate(Vector3.forward * ShootSpeed * Time.deltaTime, Fighter.transform);

}

再举个例子:

在场景中有一个红球和一个蓝球,红球沿着世界坐标系的z轴正方向匀速运动,蓝球沿着红球坐标系的z轴正向以和红球同样的速度匀速运动。

红球运动脚本RedMove.cs:

using UnityEngine;
using System.Collections;

public class RedMove : MonoBehaviour {

public int MoveSpeed = 10;

// Update is called once per frame
void FixedUpdate () {
        transform.Translate(Vector3.forward * MoveSpeed * Time.deltaTime, Space.World);
}
}

蓝球运动脚本BlueMove.cs:

using UnityEngine;
using System.Collections;

public class BlueMove : MonoBehaviour {

public GameObject RedBall;
    public int MoveSpeed = 10;

// Update is called once per frame
void FixedUpdate () {
        transform.Translate(Vector3.forward * MoveSpeed * Time.deltaTime, RedBall.transform);
}
}

1、我们先让红球的坐标系各轴方向与世界坐标系的各轴方向相同,则红球与蓝球在运动过程中是相对静止的:

2、接着我们将红球绕y轴顺时针旋转90度(即使红球的Transform.Rotation.y = 90),此时红球坐标系的z轴正向和世界坐标系的x轴正向重合,此时运动效果如下:

二、指定速度velocity

这种方法只能适用于刚体,因为velocity是刚体特有的属性。代码如下:

void Start () {
        gameObject.GetComponent<Rigidbody>().velocity = Vector3.forward * MoveSpeed;
}

三、使用rigbody.MovePosition()

public voidMovePosition(Vector3position);

让物体移动到新的位置position。

示例:

void FixedUpdate() {

//让物体向前运动Time.deltaTime距离
        rb.MovePosition(transform.position + transform.forward * Time.deltaTime);
    }

四、Vector3.MoveTowards()

static function MoveTowards(current: Vector3, target: Vector3, maxDistanceDelta: float): Vector3;

该方法一般以以下形式使用:

using UnityEngine;
using System.Collections;

public class YellowMove : MonoBehaviour {

public int MoveSpeed = 10;
    Vector3 target;

void Start () {
        target = new Vector3(20, transform.position.y, 20);
 }
 
 void Update () {
        transform.position = Vector3.MoveTowards(transform.position, target, MoveSpeed * Time.deltaTime);
 }

五、使用lerp()

1、使用Mathf.Lerp()函数

static functionLerp (from : float, to : float,t : float) : float

调用该函数会返回from与to之间的插值(from + to) * t,t在0~1之间。

使用方法如下:

using UnityEngine;
using System.Collections;

public class YellowMove : MonoBehaviour {

public float MoveSpeed = 0.1f;
    Vector3 Target = new Vector3(20, 20, 20);
    
     void Update () {
        gameObject.transform.localPosition = new Vector3(
            Mathf.Lerp(transform.position.x, Target.x, MoveSpeed * Time.deltaTime),
            Mathf.Lerp(transform.position.y, Target.y, MoveSpeed * Time.deltaTime),
            Mathf.Lerp(transform.position.z, Target.z, MoveSpeed * Time.deltaTime));

}

}

2、使用Vector3.Lerp()

public staticVector3Lerp(Vector3a,Vector3b, floatt);

其使用方法与Mathf.Lerp()用法相似。

六、使用SmoothDamp()

1、使用Vector3.SmoothDamp()

static functionSmoothDamp (current : Vector3,target : Vector3,ref currentVelocity : Vector3,smoothTime : float,maxSpeed : float = Mathf.Infinity,deltaTime : float = Time.deltaTime) : Vector3

在大约以smoothTime的时间从current移动到target,其移动的当前速度为currentVelocity,此方法一般用于摄像机的平滑移动。需要注意的是currentVelocity值一般在开始时指定为零向量,每次调用该方法时该方法会自动给currentVelocity赋值。方便起见以Mathf.SmoothDamp()进行如下测试:

using UnityEngine;
using System.Collections;

public class YellowMove : MonoBehaviour {

public float MoveSpeed = 0f;
    float CurrentNum = 0f;
    float TargetNum = 20f;
    float MoveTime = 10f;

void Update () {

Debug.Log("当前数值:" + CurrentNum + ";当前速度:" + MoveSpeed);
        CurrentNum = Mathf.SmoothDamp(CurrentNum, TargetNum, ref MoveSpeed, MoveTime * Time.deltaTime);
    }

}

控制台输出:

Vector3.SmoothDamp()用法如下:

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour{
    public Transform target;
    public float smoothTime = 0.3F;
    private Vector3 velocity = Vector3.zero;

void Update() {

//定义一个目标位置在目标变换的上方并且在后面
       Vector3 targetPosition = target.TransformPoint(new Vector3(0, 5, -10));

//平滑地移动摄像机朝向目标位置
       transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
    }
}

2、使用Mathf.SmoothDamp()

使用方法与Vector3.SmoothDamp()差不多,只是Mathf.SmoothDamp()是对float类型操作,而Vector3.SmoothDamp是对三维向量操作。

七、使用CharacterController组件控制角色移动

Unity使用CharacterController(角色控制器)来控制角色骨骼运动,包括移动、跳跃以及各种动作。CharacterController比较复杂,具体详情请参照博客Unity CharacterController(角色控制器)

八、使用iTween

iTween是Unity3D的一个动画插件,可以让你更加轻松的实现各种动作,iTween实现移动的方式也比较多样,具体的可以参考博客Unity iTween动画库插件

九、使用协程

关于Unity的协程介绍请看博客:Unity协程介绍及使用。

协程和Update方法很类似,不过协程可以在执行切换到下一帧前时局部变量任然会保存,但pdate方法在执行下一帧后局部变量和又重新定义了。既然相似,那么我们就可以像在pdate中没执行一帧改变一次position来那样,在协程中改变position然后再执行下一帧来改变物体的位置让物体运动起来。方法如下:

usingUnityEngine;  
Using System.Collections;  
   
Public class RedMove: MonoBehaviour  
{  
    public Vector3 TargetPosition;  
    public float MoveSpeed;  
   
    Void Start()  
    {  
        StartCoroutine(Move(TargetPosition));  
    }  
   
    IEnumerator Move(Vector3 target)  
    {  
        while(transform.position != target)  
        {  
            transform.position = Vector3.MoveTowards(transform.position, target, MoveSpeed * Time.deltaTime);  
            Yield return 0;  
        }  
    }  
}

unity 移动物体位置的常用方法相关推荐

  1. Unity 控制物体移动的一些方法

    Unity 控制物体移动的一些方法 开坑, 回头慢慢补. 移动方法的总结. 1, 直接+=Vector3 transform.position += Vector3.forward * moveSpe ...

  2. Unity 绘制物体运动轨迹

    unity 物体运动轨迹绘制 ① create empty,命名为LineRender ② 在Assects中新建材质,选择Shader为Sprites/Default,并设置轨迹颜色,如下图: ③ ...

  3. unity 陀螺仪 物体旋转和移动效果

    unity 陀螺仪 物体旋转和移动效果 直接上码 带注释 public class SDKGyroController : MonoBehaviour {//陀螺仪是否存在class GyroGame ...

  4. unity让物体具有高光_具有随机高光的蜂窝导航

    unity让物体具有高光 A few months ago I created a CSS "diamond" mesh navigation; this time, I thou ...

  5. Unity 实现物体破碎效果(转)

    感谢网友分享,原文地址(How to Make an Object Shatter Into Smaller Fragments in Unity),中文翻译地址(Unity实现物体破碎效果) In ...

  6. ue4中在物体上加ui_UE4 物体位置同步相关源码分析浅谈

    前言 多图, 不想在源代码写注释, 不想贴代码块, 看的不清楚 版本4.21混4.22, 区别不大 文章属于旧有文章搬运, 之前在csdn上面 2019.10.27修改一版 物体位置信息同步, 或者说 ...

  7. 【Day27 文献泛读】物体位置与空间关系的心理表征

    阅读文献: 赵民涛. (2006). 物体位置与空间关系的心理表征. 心理科学进展, 14(3), 321-327. 文献链接:物体位置与空间关系的心理表征 摘要 本文从参照框架.朝向特异性.组织结构 ...

  8. unity给物体更改颜色

    unity给物体更改颜色 新建一个你要绑定的物体,如cube,在cube下新建script脚本: using System.Collections; using System.Collections. ...

  9. Unity 给物体加贴图

    如何给物体贴图纸 下载图片 打开Unity 创建物体 导入资源 贴图 新春祝福 下载图片 首先在网上下载几个图片,比如草地: 首先在网上下载下来 打开Unity 然后打开Unity,新建一个项目 创建 ...

  10. Unity某个物体始终朝向相机

    1.Unity某个物体始终朝向相机 Quaternion q = Quaternion.identity;q.SetLookRotation(Camera.main.transform.forward ...

最新文章

  1. educoder 使用线程锁(lock)实现线程同步_性能:Lock的锁之优化
  2. POJ2528 计算可见线段(线段树)
  3. ios找不到信任证书_ios信任苹果企业级应用
  4. WPF DatePicker 默认显示当前时间
  5. 动态规划各类问题分析——LeetCode习题精讲
  6. 驱动程序和应用程序之间的体系结构不匹配_修复Win10上的黑屏问题全攻略,并不高深,一看就会...
  7. 37)智能指针(就是自动delete空间)
  8. openjudge 逆波兰表达式 2694
  9. 6. URL (2)
  10. windows jdk8
  11. 企业级的Java快速开发平台,首选iMatrix平台。
  12. IT人士易犯4大职业病 鼠标手居第一位
  13. python网址编码转换_python实现中文转换url编码的方法
  14. python实现 stft_python scipy signal.stft用法及代码示例
  15. Linux命令之ss命令
  16. 程序员也要学英语——数词攻略
  17. font:12px/1.5 tahoma, arial, \5b8b\4f53, sans-serif详解
  18. 微博做内容和收入来源
  19. 电脑摄像头识别二维码OpenCV程序
  20. 基于百度飞浆平台(EasyDL)设计的人脸识别考勤系统

热门文章

  1. CentOS SSH命令
  2. Windows下使用SSH命令登录Linux服务器
  3. Adobe Photoshop CC2014 安装过程
  4. CPRI vs eCPRI
  5. dbscan聚类python_DBSCAN聚类算法 Python 代码
  6. 帆软单点登录_平台系统单点登录接口
  7. 残差网络resnet网络原理详解
  8. python:对数log 零的处理
  9. 怎么把ppt弄成链接的形式_如何在PPT中插入视频是嵌入而不是将视频文件设为链接...
  10. 深度学习入门资料整理