2017-10-19 522 views
0

我正在審閱項目的代碼。如何將對象移動到Unity中的隨機座標?

我想要做的是下面的圖片。 enter image description here

我對這個項目有一些疑問。

作爲一個初學者,我沒有足夠的解釋, 但我會很感激,如果你可以看看它。

這裏有幾個問題:

  1. 我如何創建一個名爲small_star作爲無限期的對象,如在圖片?

  2. 當前,預製的x,y座標值以場景爲中心。 如何以像照片一樣的隨機座標移動物體?當我查看代碼時,我使用Mathf.Cos和Mathf.Sin。它有什麼影響?

我想我應該實現它,但是對我來說編寫代碼太多了。 我是初學者。如果你能給我一個具體的解釋,我會很感激。

+1

您是否嘗試過'Random.Range(minValue(最小值),包括maxValue)'? – Steven

+0

是的,我試過 –

+0

在腳本中添加StarAnimation代碼(出現在圖片右側) –

回答

2

你不提供太多的信息,但是這可能工作

public GameObject small_star; 
public float xMinBoundary; 
public float yMinBoundary; 
public float xMaxBoundary; 
public float yMaxBoundary; 

void MoveSpaceShip(){ 
    float randX = Random.Range (xMinBoundary, xMaxBoundary); 
    float randY = Random.Range (yMinBoundary, yMaxBoundary); 
    Vector2 target = new Vector2 (randX,randY) 
    //Option 1 
    //small_star.transform.Translate(target * Time.deltaTime); 
    //Option 2 
    small_star.transform.position(target) 
} 

您需要適應您的需求

+0

嗯...你需要更多的信息嗎? –

+0

我真的不知道你想如何立即或視覺翻譯的開始。你不想移動GameObject的邊界。這將需要爲Random.Range定義 –