2014-02-12 55 views
1

我想繪製一些形狀,在處理中對每個其他動作作出反應。所以當我移動它們中的一個時,它被連接到草圖中的其他形狀的1或2個。不過,我不希望它是一個靜態的運動,我希望它看起來很自然。移動一個形狀,讓其他人跟着它

我目前唯一的代碼是當你拖動它,但不知道如何聯繫起來的形狀:(幫助其移動的形狀基本繪圖!

float bx; 
float by; 
int boxSize = 75; 
boolean overBox = false; 
boolean locked = false; 
float xOffset = 0.0; 
float yOffset = 0.0; 

void setup() 
{ 
    size(640, 360); 
    bx = width/2.0; 
    by = height/2.0; 
    rectMode(RADIUS); 
} 

void draw() 
{ 
    background(0); 

    // Test if the cursor is over the box 
    if (mouseX > bx-boxSize && mouseX < bx+boxSize && 
     mouseY > by-boxSize && mouseY < by+boxSize) { 
    overBox = true; 
     } 
    // Draw the box 
    rect(bx, by, boxSize, boxSize); 
} 

void mousePressed() { 
    if(overBox) { 
    locked = true; 
    } else { 
    locked = false; 
    } 
    xOffset = mouseX-bx; 
    yOffset = mouseY-by; 
} 

void mouseDragged() { 
    if(locked) { 
    bx = mouseX-xOffset; 
    by = mouseY-yOffset; 
    } 
} 

void mouseReleased() { 
    locked = false; 
} 

我想我需要使用PShape,但我不確定。

回答

0

首先,我建議你使用一個類的形狀,這樣你可以很容易地鏈接它們 我在你的代碼做了一些改變,以獲得某種以下行爲:

class Box{ 
    float bx; 
    float by; 
    int size = 75; 

    Box(float bx, float by){ 
    this.bx = bx; 
    this.by = by; 
    } 

    void drawBox(){ 
    rect(bx, by, size, size); 
    } 

    void moveBox(float x, float y){ 
    bx = bx + x; 
    by = by + y; 
    } 

} 



boolean overBox = false; 
boolean locked = false; 
float xOffset = 0.0; 
float yOffset = 0.0; 
Box box, secondBox, thirdBox; 

void setup() 
{ 
    size(640, 360); 
    box = new Box(width/2.0, height/2.0); 
    secondBox = new Box(100, 100); 
    thirdBox = new Box(500, 300); 
    rectMode(RADIUS); 
} 

void draw() 
{ 
    background(0); 

    // Test if the cursor is over the box 
    if (mouseX > box.bx-box.size && mouseX < box.bx+box.size && 
     mouseY > box.by-box.size && mouseY < box.by+box.size) { 
    overBox = true; 
    box.drawBox(); 
    secondBox.drawBox(); 
    thirdBox.drawBox(); 
    } 

} 

void mousePressed() { 
    if(overBox) { 
    locked = true; 
    } else { 
    locked = false; 
    } 
    xOffset = mouseX-box.bx; 
    yOffset = mouseY-box.by; 
} 

void mouseDragged() { 
    if(locked) { 
    box.bx = mouseX-xOffset; 
    box.by = mouseY-yOffset; 

    deltaMovemente(box, secondBox); 
    deltaMovemente(box, thirdBox); 
    } 
} 

void mouseReleased() { 
    locked = false; 
} 

void deltaMovemente(Box follow, Box box){ 
    float dx = (follow.bx - box.bx)/50; 
    float dy = (follow.by - box.by)/50; 

    box.moveBox(dx, dy); 
} 

希望這可以是有用的。 此致敬禮。