2016-08-22 59 views
2

我一直在處理一個遊戲,我來到這個問題:我試圖與星飛過去的背景,我有這個類:處理上PVector草圖崩潰設定

public class Star { 
    PVector position; 
    float speed; 

    void draw() { 
    fill(255); 
    ellipse(position.x, position.y, speed, speed); 

    position.x -= speed; 
    } 

    public Star() { 
    speed = random(5); 
    position.set(width+speed,random(height)); 
    } 
} 

我爲明星一個ArrayList名爲星:

ArrayList<Star> stars = new ArrayList<Star>(); 

我調用構造函數中drawBg():

if(random(12) < 1) { 
    stars.add(new Star()); 
} 

但是,當drawBg被調用,它會創建一個新的星(),草圖崩潰,它指向:

position.set(width+speed,random(height)); 

的IDE說:「無法運行草圖」,並在控制檯說:

無法運行草圖(目標虛擬機未能初始化)。有關更多 信息,請閱讀revisions.txt和Help?故障排除。

請幫忙!謝謝!

+0

能否請您提供一個[MCVE],顯示我們你的小品,不只是'Star'其餘類?我們應該能夠複製和粘貼您的代碼以在我們自己的機器上運行它。 –

回答

0

默認情況下,您的position變量是null,這意味着它並沒有指向PVector的實例。

你永遠不初始化變量(使用new關鍵字創建的PVector一個新的實例),所以它仍然null當你在Star構造函數中調用position.set()。這會導致錯誤,因爲您無法調用null變量的函數。

爲了解決這個問題,只需使用new關鍵字創建的PVector一個新實例:

public Star() { 
    speed = random(5); 
    position = new PVector(width+speed,random(height)); 
} 
+0

非常感謝! –