
在本教程中,3D天堂将介绍如何在运行时在Unity3D中转换游戏对象,因为在玩游戏的过程中,由于各种原因,总是需要转换游戏对象,在这里,将看到平移或移动游戏对象的不同方式。
转换方法
此方法将在给定方向上平移游戏对象。
public void Translate(Vector3 translation, Space relativeTo = Space.Self);
脚本:
using UnityEngine;
public class TranslateBehaviour : MonoBehaviour
{
float speed;
void Update()
{
// translate object in a direction relative to its transform
gameObject.transform.Translate(Vector3.right * Time.deltaTime * speed);
}
}
使用Space.World参数在世界空间中平移对象。
gameObject.transform.Translate(Vector3.right * Time.deltaTime * speed, Space.World);
如图所示:

转换走向的方法
此方法有助于将游戏对象从一个点转换到另一个点。
脚本:
using UnityEngine;
public class TranslateBehaviour : MonoBehaviour
{
public float speed;
public Transform Target;
void Update()
{
// step size for each call
float step = Time.deltaTime * speed;
// translate from current position to target position
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, Target.position, step);
}
}
如图所示:

使用LERP方法
LERP方法允许在两点之间进行线性插值,LERP在源到达目标位置时提供平滑过渡。
// Interpolates between point a and b with interpolant t
// Value of t will be clamped between 0 to 1
// when t ill be 0.5 will return the mid position between point a and b
public static Vector3 Lerp(Vector3 a, Vector3 b, float t);
脚本如下:
using UnityEngine;
public class TranslateBehaviour : MonoBehaviour
{
public float speed = 0.01f;
public Transform Target;
private float tValue = 0.0f;
void Update()
{
tValue += Time.deltaTime * speed;
transform.position = Vector3.Lerp(transform.position, Target.position, tValue);
}
}
如图所示:

…
以上是3D天堂关于如何在unity中转换游戏对象的全部内容,如果你有任何反馈,请随时在本页面下方留言。