2012-11-07 63 views
0

我怎樣才能使用我現在有的對象的代碼,我可以存儲球彈跳次數和顏色(當我添加隨機顏色)和速度。任何指針或提示都會很棒。我是OOP的新手,可能會讓我感到困惑。在此先感謝使用此代碼的對象?處理

float x; 
    float y; 
    float yspeed = 0; 
    float xspeed = 0; 
    float balldiameter = 10; 
    float ballradius = balldiameter/2; 

    void setup() { 
    size (400,400); 
    background (255); 
    fill (0); 
    ellipseMode(CENTER); 
    smooth(); 
    noStroke(); 
    x = random(400); 
    y = 0; 
    } 

    void draw() { 
    mouseChecks(); 
    boundaryChecks(); 
    ballFunctions(); 
    keyFunctions(); 
    } 

    void mouseChecks() { 
    if (mousePressed == true) { 
    x = mouseX; 
    y = mouseY; 
    yspeed = mouseY - pmouseY; 
    xspeed = mouseX - pmouseX; 
    } 
    } 

    void boundaryChecks() { 
    if (y >= height - ballradius) { 
     y = height - ballradius; 
     yspeed = -yspeed/1.15; 
    } 
    if (y <= ballradius) { 
     y = ballradius; 
     yspeed = -yspeed/1.35; 
    } 
    if (x >= width -ballradius) { 
     x = width -ballradius; 
     xspeed = -xspeed/1.10; 
    } 
    if (x <= ballradius) { 
     x = ballradius; 
     xspeed = -xspeed/1.10; 
    } 
    } 

    void ballFunctions() { 
    if (balldiameter < 2) { 
    balldiameter = 2; 
    } 
    if (balldiameter > 400) { 
    balldiameter = 400; 
    } 
    ballradius = balldiameter/2; 
    background(255); //should this be in here? 
    ellipse (x,y,balldiameter,balldiameter); 
    yspeed = yspeed += 1.63; 
    // xspeed = xspeed+=1.63; 
    y = y + yspeed; 
    x = x + xspeed; 
    } 
    void keyFunctions() { 
    if (keyPressed) { 
     if(keyCode == UP) { 
     balldiameter +=1; 
    } 
    if (keyCode == DOWN) { 
     balldiameter -=1; 
     } 
    } 
    } 
+0

我認爲你需要封裝一個函數中的所有內容,並決定你想將哪些對象的部分設置爲變量。爲您想要作爲變量的每個部分創建一個參數。 –

回答

1
你可能會想要做以下


創建
稱爲一個新的文件在該文件中寫:

public class Ball { 
    public float x; 
    public float y; 
    public float yspeed; 
    public float xspeed; 
    public float diameter; 
    public float radius; 

    public Ball(float initial_x, float initial_y, float diam) { 
     this.x = initial_x; 
     this.y = initial_y; 
     this.xspeed = 0; 
     this.yspeed = 0; 
     this.diameter = diam; 
     this.radius = diam/2; 
    } 

    public void move() { 
     // movement stuff here 
    } 
} 

這會給你一個非常基本的Ball類。現在你可以使用這個類在主素描文件像這樣:

Ball my_ball = new Ball(50, 50, 10); 

您可以使用訪問球成員:

my_ball.xspeed; 
my_ball.yspeed; 
my_ball.anything_you_defined_in_ball; 

這將允許你喲商店內的球的所有培訓相關變量的自己的班級。你甚至可以創造超過1

Ball my_ball1 = new Ball(50, 50, 10); 
Ball my_ball2 = new Ball(20, 20, 5); 
+0

爲什麼選擇Ball.ps?它不應該是Ball.pde嗎?還是Ball.java? –

+0

@ v.k。啊,是它的'pde'謝謝,我沒有選擇它。 – Serdalis

0

只是要注意的是,在Proccesing你並不需要創建一個新的文件,該代碼可以去無論是在相同的文件(非常糟糕的做法如下指出)或在IDE的新選項卡中。如果您正在使用Processing IDE,則可以從右側的箭頭菜單中選擇「新選項卡」,它將爲您創建文件。它將有「.pde」擴展名。

+0

這應該是一個評論。將所有課程放在同一個文件中的做法非常糟糕。 IDE中的新選項卡是新文件。 – Serdalis

+1

當時我無法評論......我說一個人不需要,不應該。處理中的原因通常人們對編程都很陌生(就像我一樣),我認爲有時簡單性可能更重要。無論如何,謝謝你指出。我一直在學習。我應該複製並粘貼它作爲評論? –

+0

無論如何,我編輯了答案。 –