为什么我的物体的位置没有改变?

时间:2014-12-07 14:46:36

标签: c# unity3d

我目前正在开发基于Unity3D的进化算法。模拟是二维的。一个主题被描绘成汽车,是一个预制件,由3个精灵(2个轮子和车身)和一个CarScript组成。每个精灵都有一个合适的对撞机(BoxCollider2D用于车身,CircleCollider2D用于车轮)。 CarBody也有 两个WheelJoint2D。这些碰撞器的参数由代码改变。

我希望这辆车能够被摧毁,如果它停止移动或更好 - 推进。在游戏窗口,汽车显然正在下坡。问题是,在检查了gameobject的transform.position之后,这个值似乎是不变的。它总是显示SpawnPoint的位置。 SpawnPoint是带有SpawnScript的空GameObject,其片段如下:

public GameObject carprefab; //Set from editor
public Transform[] spawnPoints; //transform of SpawnPoint, just one element. Set from editor.
private void GenerateCar(Chromosome chromosome)
{
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
var instace = (GameObject)Instantiate(carprefab, spawnPoints[spawnPointIndex].position,     spawnPoints[spawnPointIndex].rotation);
    instace.SendMessage("SetChromosome", chromosome);

    foreach (Transform child in instace.transform)
    { //code omitted for clarity, changes some of parameters based on chromosome.

实例化对象有一个CarScript:

 // Update is called once per frame
    void Update()
    {
        if (frames%10 == 0)
            CheckForMoving();
        frames++;
    }
 private void CheckForMoving()
    {
        var pos = gameObject.transform.position; //this is never changing - why?


        var diff = pos - startingPosition; //difference between local position and starting position
        if (CountLength(diff) >= recordLengthYet)
        {
            Debug.Log("It is moving!");
            recordLengthYet = CountLength(diff);
            framesTillLastRecord = 0;
        }
        else
        {
            Debug.Log("It is not moving");
            if (framesTillLastRecord > 4)
                Destroy(gameObject, 0f);
            framesTillLastRecord++;
        }
    }

我尝试通过以下任何方式获得该职位:

var pos = gameObject.transform.position;
var pos = GameObject.FindGameObjectWithTag("player");
var pos = this.transform.position;

问题是 - 我错过了什么,或者为什么这不会改变?我刚刚开始学习Unity,并且以前没有任何类似软件的经验。我也想知道,如果这是正确的方法。

2 个答案:

答案 0 :(得分:2)

几天过去了,没有人上传了正确答案,我设法得到了解决方法。只要它真的很脏,它似乎有效。

我在儿童游戏对象上放置了一个标签,而不是预制件,我正在通过

来确定这个孩子的位置
var pos = GameObject.FindGameObjectWithTag("player");

我不确定,如果这是一个非常好的答案,但我希望有一天有人可能会发现它有用。

答案 1 :(得分:0)

假设您正在使用刚体,那么根据Unity doco,您应该覆盖FixedUpdate()而不是Update()

  

如果启用了MonoBehaviour,则每个固定帧率帧都会调用此函数。在处理Rigidbody时,应该使用FixedUpdate而不是Update。例如,当向刚体添加力时,必须在FixedUpdate内的每个固定帧上应用力,而不是在Update中的每个帧。 - Tell me more...

替换:

 // Update is called once per frame
void Update()
{
    if (frames%10 == 0)
        CheckForMoving();
    frames++;
}

使用:

 // Update is called once per frame
void FixedUpdate()
{
    if (frames%10 == 0)
        CheckForMoving();
    frames++;
}