2015-05-27 41 views
2

我是Processing的新手,所以請和我一起裸照。我試圖從A點到D點移動一個對象(矩形用於我們的目的)。然而,沿着這條路我想停止不同部分的運動並等待一段時間。翻譯對象,停止並繼續處理

例如,我想從A移動到B,等待5秒,然後從B移動到C,等待2秒鐘。最後,從C移到D.

我試過了幾件事情。首先,我通過給它一個「速度」(xspeed)並將它的位置(xpos)增加xspeed來移動我的對象。然後使用if語句,當它達到100時,我停止了該位置。然後,我計數5秒鐘,然後再次開始運動。然而,由於動議開始超過x位置100,因此if語句不允許我前進。我不知道我是否可以重寫這個if語句。下面是我所做的代碼:

class Pipe { 
    color c; 
    float xpos; 
    float ypos; 
    float xspeed; 
    int time; 

    Pipe(color c_, float xpos_, float ypos_, float xspeed_) { 
    c = c_; 
    xpos = xpos_; 
    ypos = ypos_; 
    xspeed = xspeed_; 
    } 

    void display() { 
    noStroke(); 
    fill(c); 
    rectMode(CENTER); 
    rect(xpos,ypos,10,200); 
    } 


    void pipeMove() { 
    xpos = xpos + xspeed; 
    if (xpos > 100) { 
     xpos = 100; 
     if (millis() > time) { 
     time = millis()+5000; 
     xpos = xpos + xspeed; 
     } 
    } 
    } 
} 

Pipe myPipe1; 
Pipe myPipe2; 

void setup() { 
    size(1500,500); 
    myPipe1 = new Pipe(color(85,85,85),0,height/2,2); 
// myPipe2 = new Pipe(color(85,85,85),-100,height/2,2); 
} 

void draw() { 
    background(255); 
    myPipe1.display(); 
    myPipe1.pipeMove(); 
// myPipe2.display(); 
// myPipe2.pipeMove(); 
} 

我試圖通過使用noLoop(),和循環我班內的位置停止加工自動循環另一種選擇。但是,這不會移動我的對象。看到我的for循環下面的代碼。

class Pipe { 
    color c; 
    float xpos; 
    float ypos; 
    float xspeed; 
    int time; 

    Pipe(color c_, float xpos_, float ypos_, float xspeed_) { 
    c = c_; 
    xpos = xpos_; 
    ypos = ypos_; 
    xspeed = xspeed_; 
    } 

    void display() { 
    noStroke(); 
    fill(c); 
    rectMode(CENTER); 
    rect(xpos,ypos,10,200); 
    } 


    void pipeMove() { 
    for (int i = 0; i<100; i = i+1) { 
    xpos = xpos + i; 
    } 
    } 
} 

任何幫助,方向或指導將不勝感激!

謝謝!

回答

2

我認爲你的第一個方法是正確的。你有第一部分工作,現在你只需要添加其他步驟。解決此問題的一種方法可能是在Pipe類中使用狀態

由此我的意思是,你只需要跟蹤管道當前處於哪一步,然後根據你所在的步驟做正確的事情。要做到這一點最簡單的方法可能是布爾添加到您的Pipe類:

class Pipe { 
    color c; 
    float xpos; 
    float ypos; 
    float xspeed; 
    int time; 

    boolean movingToA = true; 
    boolean waitingAtA = false; 
    boolean movingToB = false; 
    //... 

,然後在pipeMove()功能,只是做了正確的事情取決於你在哪個國家,並更改狀態變化行爲:

void pipeMove() { 

    if (movingToA) { 

     xpos = xpos + xspeed; 

     if (xpos > 100) { 
     xpos = 100; 
     movingToA = false; 
     waitingAtA = true; 
     time = millis(); 
     } 
    } else if (waitingAtA) { 
     if (millis() > time + 5000) { 
     waitingAtA = false; 
     movingToB = true; 
     } 
    } else if (movingToB) { 
     xpos = xpos + xspeed; 

     if (xpos > 200) { 
     xpos = 200; 
     movingToB = false; 
     } 
    } 
    } 
} 

有要作出這裏 - 你可以使用枚舉值,或潛在行動的數據結構,或者參數的行爲,例如一些很明顯的改進。但基本原理是相同的:根據您所處的狀態執行不同的操作,然後更改該狀態以更改行爲。

+0

這很有道理。我要去試試看。謝謝! –