2014-12-07 57 views
1

我目前正在開發基於Unity3D的進化算法。該模擬是二維的。一個主題被描繪成汽車,作爲一個預製件,由3個精靈(2個輪子和身體)和一個CarScript組成。每個精靈都有一個適當的對撞機(用於車身的BoxCollider2D和用於車輪的CircleCollider2D)。 CarBody也有 兩個WheelJoint2D。這些對撞機的參數由代碼改變。爲什麼我的對象的位置不變?

我想要這輛車被摧毀,如果它停止移動或更好 - 推進。在遊戲窗口中,汽車顯然正在下坡。問題是,在檢查遊戲對象的transform.position後,這個值似乎是不變的。它始終顯示SpawnPoint的位置。 SpawnPoint是空的遊戲物體與SpawnScript,該片段是以下:

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,並且以前沒有任何類似軟件的經驗。我也想知道,如果這是正確的做法。

+0

'CountLength'?如果你想看看兩點之間有多遠,我認爲你應該使用'Vector3.magnitude'或'Vector3.sqrMagnitude'。您是否嘗試過設置後輸出pos值(debug.log(pos)等)還是您依靠上述調試? – Lefty 2014-12-08 10:14:51

+0

我沒有嘗試輸出值本身,並且pos似乎是常數值,等於SpawnPoint的位置。此外,我稍後將更改代碼以反映您的建議,但我並不知道這些屬性。 – 2014-12-08 11:28:23

回答

1

幾天過去了,沒有人上傳了正確的答案,我得到了一個解決方法。只要它真的很髒,它似乎工作。

我放在標籤上的兒童遊戲物體,而不是預製,而我通過

var pos = GameObject.FindGameObjectWithTag("player"); 

歌廳這個孩子的位置,我不知道,如果這是真的很好的答案,但我希望有人可能會發現它有用的一天。

0

假設你正在使用的剛體,你應該重寫FixedUpdate()而不是Update()按照統一DOCO:

這個函數被調用每一個固定幀率幀,如果啓用了MonoBehaviour。在處理Rigidbody時,應該使用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++; 
} 
+0

嗯,當然是一個很好的建議,因爲我沒有意識到這一點,我改變了我的代碼。然而,這仍然不能解決我的主要問題,作爲this.transform的不變位置,而GameObject顯然正在移動。 – 2014-12-07 15:19:12

相關問題