1/** 2 * Soft Body 3 * by Ira Greenberg. 4 * 5 * Softbody dynamics simulation using curveVertex() and curveTightness(). 6 */ 7 8// center point 9float centerX = 0, centerY = 0; 10 11float radius = 45, rotAngle = -90; 12float accelX, accelY; 13float springing = .0009, damping = .98; 14 15//corner nodes 16int nodes = 5; 17float nodeStartX[] = new float[nodes]; 18float nodeStartY[] = new float[nodes]; 19float[]nodeX = new float[nodes]; 20float[]nodeY = new float[nodes]; 21float[]angle = new float[nodes]; 22float[]frequency = new float[nodes]; 23 24// soft-body dynamics 25float organicConstant = 1; 26 27void setup() { 28 size(640, 360); 29 //center shape in window 30 centerX = width/2; 31 centerY = height/2; 32 // iniitalize frequencies for corner nodes 33 for (int i=0; i<nodes; i++){ 34 frequency[i] = random(5, 12); 35 } 36 noStroke(); 37 smooth(); 38 frameRate(30); 39} 40 41void draw() { 42 //fade background 43 fill(0, 100); 44 rect(0,0,width, height); 45 drawShape(); 46 moveShape(); 47} 48 49void drawShape() { 50 // calculate node starting locations 51 for (int i=0; i<nodes; i++){ 52 nodeStartX[i] = centerX+cos(radians(rotAngle))*radius; 53 nodeStartY[i] = centerY+sin(radians(rotAngle))*radius; 54 rotAngle += 360.0/nodes; 55 } 56 57 // draw polygon 58 curveTightness(organicConstant); 59 fill(255); 60 beginShape(); 61 for (int i=0; i<nodes; i++){ 62 curveVertex(nodeX[i], nodeY[i]); 63 } 64 for (int i=0; i<nodes-1; i++){ 65 curveVertex(nodeX[i], nodeY[i]); 66 } 67 endShape(CLOSE); 68} 69 70void moveShape() { 71 //move center point 72 float deltaX = mouseX-centerX; 73 float deltaY = mouseY-centerY; 74 75 // create springing effect 76 deltaX *= springing; 77 deltaY *= springing; 78 accelX += deltaX; 79 accelY += deltaY; 80 81 // move predator's center 82 centerX += accelX; 83 centerY += accelY; 84 85 // slow down springing 86 accelX *= damping; 87 accelY *= damping; 88 89 // change curve tightness 90 organicConstant = 1-((abs(accelX)+abs(accelY))*.1); 91 92 //move nodes 93 for (int i=0; i<nodes; i++){ 94 nodeX[i] = nodeStartX[i]+sin(radians(angle[i]))*(accelX*2); 95 nodeY[i] = nodeStartY[i]+sin(radians(angle[i]))*(accelY*2); 96 angle[i]+=frequency[i]; 97 } 98} 99 100