我目前正在開發基於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,並且以前沒有任何類似軟件的經驗。我也想知道,如果這是正確的做法。
'CountLength'?如果你想看看兩點之間有多遠,我認爲你應該使用'Vector3.magnitude'或'Vector3.sqrMagnitude'。您是否嘗試過設置後輸出pos值(debug.log(pos)等)還是您依靠上述調試? – Lefty 2014-12-08 10:14:51
我沒有嘗試輸出值本身,並且pos似乎是常數值,等於SpawnPoint的位置。此外,我稍後將更改代碼以反映您的建議,但我並不知道這些屬性。 – 2014-12-08 11:28:23