【发布时间】:2014-11-25 06:11:00
【问题描述】:
如何在 Unity 4.6 中使用 C# 代码将图像从位置 A 移动/动画/翻译/补间到位置 B?
假设 Image 是一个 GameObject,所以它可能是一个 Button 或其他任何东西。 必须有一个单行字,对吧?我已经在谷歌上搜索了一段时间,但我所看到的所有开箱即用的东西都是在 Update 中完成的,我坚信在 Update 中完成的东西并不是一种快速编写脚本的方法。
【问题讨论】:
如何在 Unity 4.6 中使用 C# 代码将图像从位置 A 移动/动画/翻译/补间到位置 B?
假设 Image 是一个 GameObject,所以它可能是一个 Button 或其他任何东西。 必须有一个单行字,对吧?我已经在谷歌上搜索了一段时间,但我所看到的所有开箱即用的东西都是在 Update 中完成的,我坚信在 Update 中完成的东西并不是一种快速编写脚本的方法。
【问题讨论】:
maZZZu 的方法可以,但是,如果你不想使用更新功能,你可以像这样使用 IEnumerator/Coroutine……
//Target object that we want to move to
public Transform target;
//Time you want it to take before it reaches the object
public float moveDuration = 1.0f;
void Start ()
{
//Start a coroutine (needed to call a method that returns an IEnumerator
StartCoroutine (Tween (target.position));
}
//IEnumerator return method that takes in the targets position
IEnumerator Tween (Vector3 targetPosition)
{
//Obtain the previous position (original position) of the gameobject this script is attached to
Vector3 previousPosition = gameObject.transform.position;
//Create a time variable
float time = 0.0f;
do
{
//Add the deltaTime to the time variable
time += Time.deltaTime;
//Lerp the gameobject's position that this script is attached to. Lerp takes in the original position, target position and the time to execute it in
gameObject.transform.position = Vector3.Lerp (previousPosition, targetPosition, time / moveDuration);
yield return 0;
//Do the Lerp function while to time is less than the move duration.
} while (time < moveDuration);
}
这个脚本需要附加到您想要移动的游戏对象上。然后,您需要在场景中创建另一个 GameObject 作为您的目标……
代码已注释,但如果您需要澄清某些内容,请在此处发表评论。
【讨论】:
如果你想自己做这个动作,你可以使用这样的东西:
public Vector3 targetPosition = new Vector3(100, 0, 0);
public float speed = 10.0f;
public float threshold = 0.5f;
void Update () {
Vector3 direction = targetPosition - transform.position;
if(direction.magnitude > threshold){
direction.Normalize();
transform.position = transform.position + direction * speed * Time.deltaTime;
}else{
// Without this game object jumps around target and never settles
transform.position = targetPosition;
}
}
或者您可以下载例如DOTween 包并启动补间:
public Vector3 targetPosition = new Vector3(100, 0, 0);
public float tweenTime = 10.0f;
void Start () {
DOTween.Init(false, false, LogBehaviour.Default);
transform.DOMove(targetPosition, tweenTime);
}
【讨论】: