2017-05-30 128 views
0

我是新來處理和修改某人的代碼。除了爲什麼我的精靈會隨機停止之外,我明白了所有這一切。我最終失去了所有似乎是隨機點的運動。任何幫助?處理:精靈移動隨機停止

PImage img; 
sprite player; 
wall[] walls; 

void setup() { 

    size(750, 750); 
    img = loadImage("sprite.png"); 
    player = new sprite(50,300); 
    frameRate(60); 
    smooth(); 

    walls = new wall[3]; 
    walls[0] = new wall(250,0,40,500); 
    walls[1] = new wall(500,250,40,500); 
    walls[2] = new wall(300,200,40,500); 

} 
void draw() { 

    background(255, 255, 255); 
    noStroke(); 

    player.draw(); 
    player.move(walls); 

    for(int i = 0; i < walls.length; i++){ 
    walls[i].draw(); 
    } 

} 

class sprite { 

    float x; 
    float y; 

    sprite(float _x, float _y){ 
    x = _x; 
    y = _y; 
    } 

    void draw(){ 
    image(img,x,y); 
    } 

    void move(wall[] walls){ 

    float possibleX = x; 
    float possibleY = y; 

    if (keyPressed==true) { 

     println(key); 

     if (key=='a') { 
     possibleX= possibleX - 2; 
     } 
     if (key=='d') { 
     possibleX = possibleX + 2; 
     } 
     if (key=='w') { 
     possibleY = possibleY - 2; 
     } 
     if (key=='s') { 
     possibleY = possibleY + 2; 
     } 
    } 

    boolean didCollide = false; 
    for(int i = 0; i < walls.length; i++){ 
     if(possibleX > walls[i].x && possibleX < (walls[i].x + walls[i].w) && possibleY > walls[i].y && possibleY < walls[i].y + walls[i].h){ 
     didCollide = true; 
     } 
    } 

    if(didCollide == false){ 
     x = possibleX; 
     y = possibleY; 
    } 

    } 

} 

class wall { 

    float x; 
    float y; 
    float w; 
    float h; 

    wall(float _x, float _y, float _w, float _h){ 
    x = _x; 
    y = _y; 
    w = _w; 
    h = _h; 
    } 


    void draw(){ 
    fill(0); 
    rect(x,y,w,h); 
    } 

} 
+0

如果你將問題縮小到[mcve],你會有更好的運氣。請注意,這不應該是你的整個草圖。例如,您的問題與繪製圖像無關,因此您不需要這些。把它縮小到一個硬編碼矩形與另一個硬編碼矩形相碰撞。你有沒有嘗試[調試](http://happycoding.io/tutorials/processing/debugging)你的代碼? –

回答

0

問題就出在你的move()功能:

void move(wall [] walls) { 
    ... 
    boolean didCollide = false; 
    for (int i = 0; i < walls.length; i++) { 
     if (possibleX > walls[i].x && possibleX < (walls[i].x + walls[i].w) && ...){ 
      didCollide = true; 
     } 
    } 

    if (didCollide == false) { 
     x = possibleX; 
     y = possibleY; 
    } 

} 

您檢查碰撞,在for循環,這是很好的!然而,你永遠不會解決碰撞(即將人Sprite從牆上移開,使牆不再位於其可能的矩形內),因此人不能再移動,因爲每次調用該函數時,didCollide都會變爲真仍然。

可以通過添加該代碼這個下一次測試:

if (didCollide == false) { 
    ... 
} else { 
    println("I stopped moving."); 
    // could also put collision-resolving code here 
} 

如果你看到,在控制檯,它意味着你碰了壁。

解決衝突是從牆上移動精靈,並在牆上的最近邊緣之間的距離的問題,再加上多一點,這樣你不接觸它仍然像這樣:

// If sprite to the left of the wall, i.e. went too far to the right... 
float diff = walls[i].x - walls[i].w - this.x; 
this.x += diff + 1.0 
... 
// If sprite below the wall, and essentially too high up.... 
float diff = walls[i].y + wall[i].h - this.y; 
this.y += diff + 1.0