2017-07-15 36 views
2

我知道這是一個邏輯錯誤,但我有這個程序,我想要顯示50個隨機單詞,這50個單詞應該展開,並且會隨機移動,但是相反,我每幀一次收到50個隨機單詞他們都互相重疊,然後去隨機的地方..我在我的代碼中做錯了什麼?如何使數組中的每個單詞在處理中彼此分開移動?

這裏是我是如何做的:

String [] allWords; 
int index = 0 ; 
float x; 
float y; 


void setup() { 

size (500,500); 
background (255); //background : white 

String [] lines = loadStrings ("alice_just_text.txt"); //imports the 
external file 
String text = join(lines, " "); //make into one long string 
allWords = splitTokens (text, ",.?!:-;:()03 "); //splits it by word 

x = 100; //where they start 
y = 150; 

} 


void draw() { 

background (255); 

for (int i = 0; i < 50; i++) { //produces 50 words 

    x = x + random (-3,3); //makes the words move or shake 
    y = y + random (-3,3); //makes the words move or shake 

    int index = int(random(allWords.length)); //random selector of words 

    textSize (random(10,80)); //random font sizes 
    fill (0); //font color: black 
    textAlign (CENTER,CENTER); 
    text (allWords[index], x, y, width/2, height/2); 
    println(allWords[index]); 
    index++ ; 


} 

} 
+0

你的意思是:x = x + random(-3,3); ?你如何控制可以自由填充的數字? –

+0

這就是他們讓這個詞移動或搖動@VasylLyashkevych –

+0

是的,我認爲你不能編譯你的代碼,並且你使用-3作爲邊界之一。你有沒有考慮過相同的算法?你可以使用:x = x + random.nextInt(3); –

回答

0

你有一對夫婦的問題。

首先,您只有一個xy變量。您需要跟蹤xy變量,而不是每個詞。你可以使用數組,或者更好的是你可以封裝一個位置和一個單詞。 (無恥的自我推銷:我寫了那個教程,但我強烈推薦閱讀它,因爲它包含幾乎所有你想做的事情的例子。)

其次,你需要明確你在做什麼fordraw()函數中循環。特別的是這行的作用:

int index = int(random(allWords.length)); //random selector of words 

這是選擇一個隨機指數,但你這樣做的draw()函數內部for循環中,所以這是發生50次,每秒60次。這可能不是你想要做的。

取而代之,您可能只是想要在setup()函數中生成一次的隨機單詞。您可以通過創建您創建的類的實例並將它們存儲在數組或ArrayList中來實現。

+0

是的,你是如此的樂於助人!並感謝您的所有建議!我在哪裏也可以找到你的教程? –

+0

@Noobprocessor它是我的文章中的[創建類](http://happycoding.io/tutorials/processing/creating-classes)鏈接。 –

+0

哦好吧再次感謝youuu –

相關問題