Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

vector - moving my object with transform.Translate make it move in wrong way

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);

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.

Example :

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
            }
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...