Unity简单的物体运动
物体的运动包括位置坐标的改变和旋转。下面是几种运动常见手段的实例。
首先我们先new一个project,创建一个GameObject Cube
然后开始编写脚本
1. 平移
1.1 Transform.position
public class 移动 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
this.transform.position += Vector3.left * Time.deltaTime;
}
}
将该脚本挂载到Cube上,即可产生向左运动的动画效果。
那么这段代码是什么意思呢?首先position是transform中的一个属性,包括x,y,z。x控制物体左右位置,y控制物体上下,z控制物体的远近。Vector3.left是Vector3的一个属性,表示的是3为坐标系中的向左的单位向量,实质和new Vector3(-1, 0, 0)是一个效果。还有right,up,down,forward,back就是类似的意思。Time.deltaTime,按照我的理解,由于unity采用的是离散仿真系统,每一秒被分离成了许多帧,而不同电脑的FTP是不同的,deltaTime就是每一帧所花的时间。所以这一条语句就是说让被挂载的物体每秒向左移动一个单位。
1.2 Transform.translate
public class 移动 : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate(new Vector3(-1, 0, 0) * Time.deltaTime);
}
}
效果同样也是每秒向左移动一个单位
1.3 Vector3.MoveTowards
public class 移动 : MonoBehaviour {
public Transform Target;
public float Speed;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float step = Speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, Target.position, step);
}
}
然后我们在Cube上可以看到出现了Target和Speed需要我们填写
新建一个GameObject的Sphere作为Target,移到和Cube不同的位置,并设置Speed为1,就可以看到Cube以每秒1单位的速度向Target移动,直到位置相同停止。
1.4 Vector3.SmoothDamp
public class 移动 : MonoBehaviour
{
public Transform Target;
public float smoothTime = 0.3F;
private Vector3 velocity = Vector3.zero;
void Update()
{
Vector3 targetPosition = Target.position;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
}
}
这里transform.position参数表示当前位置,targetPosition表示目标位置,ref velocity表示移动速度,
smoothTime表示期望到达目标的时间,其效果与MoveTowards类似
2. 旋转
2.1 Rotate方法
public class 旋转 : MonoBehaviour
{
private void Update()
{
this.transform.Rotate(Vector3.up * 30 * Time.deltaTime);
}
}
Rotate的参数意思是以自身为中心,绕着竖直向上的轴以每秒30°的速度旋转,运行我们就能看到一个Cube在忘情的旋转(卡特哈哈哈哈)
2.2 RotateAround方法
public class 旋转 : MonoBehaviour
{
public Transform target;
private void Update()
{
this.transform.RotateAround(target.position, Vector3.up, 10 * Time.deltaTime);
}
}
设置一个GameObject对象作为target,Cube就会绕着target,以竖直方向为旋转轴,10°每秒的速度旋转(可以思考像地球绕太阳转)
近期会写一篇模拟太阳系的博客,感谢!