简体   繁体   English

transform.position不能在Unity中设置正确的位置?

[英]transform.position not setting correct position in Unity?

I am having this problem that I don't know how to solve, I have a moving object that return to a position if a condition is verified, but it seems like it is working sometimes, but sometimes it is not .. 我遇到了一个我不知道该如何解决的问题,我有一个移动的对象,如果条件经过验证,该对象会返回到某个位置,但有时它似乎在工作,但有时却没有。

Here is my script : 这是我的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MovingDes : MonoBehaviour {
    private float speed = 5f;
    Transform trn;
    //-37.6914
    //62.32123
    // Use this for initialization
    void Start() {
        trn = GetComponent<Transform>();
    }

    // Update is called once per frame
    void Update() {
        transform.Translate(Vector3.back * (speed * Time.deltaTime));
        if(transform.position.z <= -37.6914){
            Vector3 newPosition = new Vector3(17.5f,125.7f,165.32123f);
            trn.position = newPosition;
        }
    }
}

The problem is that I can see in my Unity editor that the position is different from what I have set, and I don't understand from Where those values came from, I did not write them for sure. 问题是,我可以在Unity编辑器中看到位置与设置的位置不同,并且我不知道这些值来自何处,因此我不确定是否将其写入。

在此处输入图片说明

Any help would be much appreciated. 任何帮助将非常感激。

You are moving object with transform.Translate every frame, so immediately after setting up new position, your object is moved again. 您正在通过transform移动对象。平移每一帧,因此在设置新位置后立即重新移动对象。 Notice that in your case trn, and transform, refers to the same Transform component. 注意,在您的情况下,trn和transform指的是相同的Transform组件。

Why don't you change your trn.position= to transform.position= I don't think you need GetComponent<> for transform component of the current gameObject. 为什么不将trn.position=更改为transform.position=我认为您不需要GetComponent<>作为当前gameObject的转换组件。 Or maybe related to relativeTo parameter of .Translate method. 或者可能与.Translate方法的relativeTo参数有关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM