Unity中transform与Rigidbody两种运动方式的比较

Transform组件是Unity中每个Gameobject必须包含的组件,它控制着物体的位移、旋转、缩放。
这里写图片描述
在Unity中,物体的运动是通过改变物体的Position(在世界空间坐标transform的位置)。

Transform.Translate

1、相对坐标系移动

(1) public void Translate(Vector3 translation, Space relativeTo = Space.Self);<br>
(2) public void Translate(float x, float y, float z, Space relativeTo = Space.Self);

这是一种相对坐标系移动。参数translation为移动向量,包括方向和大小,参数relativeTo为参考坐标系空间。当relativeTo设置为空或者为Space.Self,表面该物体沿着自己本地坐标进行运动。当设置为Space.World,表面它的参考坐标为世界坐标系。 该方法可以将物体从当前位置,移动到指定位置,并且可以选择参照的坐标系。 当需要进行坐标系转换时,可以考虑使用该方法。事例代码如下:

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
        transform.Translate(Vector3.forward * Time.deltaTime);
        transform.Translate(Vector3.up * Time.deltaTime, Space.World);
transform.Translate(0, 0, Time.deltaTime);
        transform.Translate(0, Time.deltaTime, 0, Space.World);

    }
}


2、相对其他物体移动
1public void Translate(Vector3 translation, Transform relativeTo);
(2public void Translate(float x, float y, float z, Transform relativeTo);

参数translation为移动向量,包括方向和大小,参数relativeTo为移动参考物体,默认为Space.World。它是使物体沿着relativeTo的坐标系中移动向量translation。如果relativeTo为空,则相对坐标系为世界坐标系。

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Update() {
 transform.Translate(Vector3.right*Time.deltaTime,Camera.main.transform);
transform.Translate(Time.deltaTime, 0, 0, Camera.main.transform);
    }
}




Rigidbody.velocity


Rigidbody组件用于模拟物体的物理状态,比如通过增加物体的受力来模拟真实的物理效果。Velocity是刚体的一个属性,用来设置刚体的速度值。设置刚体速度可以让物体运动并且忽略静摩擦力。

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Rigidbody rb;
    void Start() {
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate() {
        if (Input.GetButtonDown("Jump"))
            rb.velocity = new Vector3(0, 10, 0);

    }
}




参考资料:

《Unity》API解析,陈泉宏,人民邮电出版社
http://gad.qq.com/article/detail/28791
http://blog.csdn.net/myarrow/article/details/45846567
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html

猜你喜欢

转载自blog.csdn.net/ONEMOOC/article/details/79488033