问题描述
我在 unity 翻译一个简单的对象时遇到了困难.对象在 3 维世界中移动,但仅在 x 和 z 轴上移动.我正在使用的函数是我的游戏对象变换的 Translate 函数.x 和 z 是我试图移动对象的位置.
I'm having a hard time with unity trying to translate a simple object. The object move in a 3 dimension world but only on the x and z axis. The function I'm using is the Translate function of my transform of my gameobject. x and z are the position I'm trying to move my object.
transform.Translate (( new Vector3(x - transform.position.x ,0,z - transform.position.z)).normalized * Time.deltaTime * speed,Space.World);
所以这就是我正在处理的问题:如果我的计算结果是以下向量:(0,0,-1.0)
,我的对象在错误的方向上缓慢移动.
So here's the problem I'm dealing with : If the result of my calcul is the following Vector : (0,0,-1.0)
, my object move slowly in the wrong direction.
示例:
起始位置(25.16, 1.0, 12.0)
翻译函数后的最终位置:(25.6, 1.0, 12.1)
Starting position (25.16, 1.0, 12.0)
Final position after the translate function : (25.6, 1.0, 12.1)
任何帮助都会帮助我理解这一点.
Any help would be appeciate to help me understand this.
推荐答案
我在我的一个项目中使用此脚本将游戏对象移动到一个点,只需将其附加到您的游戏对象上并在其中输入您的 x 和 yFinPos.
I'm using this script in one of my projects to move an GameObject to a point, just attach it on your game object and enter your x and y in FinPos.
using UnityEngine;
public class MovementAnimation : MonoBehaviour
{
public Vector3 FinPos;
public bool Loop = true;
public int Speed = 1;
private Vector3 StartPos;
private float startTime;
private float lenght;
void Start ()
{
StartPos = this.transform.position;
startTime = Time.time;
lenght = Vector3.Distance(StartPos, FinPos);
}
void Update ()
{
if (this.transform.position == FinPos)
{
if (Loop)
{
this.transform.position = StartPos;
startTime = Time.time;
}
}
else
{
float distance = (Time.time - startTime) * Speed;
this.transform.position = Vector3.Lerp(StartPos, FinPos, distance / lenght);
}
}
}
这篇关于使用 transform.Translate 移动我的对象使它以错误的方式移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!