// UdK Computational design // Marius Watz 2003 // http://www.evolutionzone.com/udk/ // // UDK03_02_vector_05 // // Use vectors for movement, but use different // speeds depending on the distance between the // points. Vec2D v,v2,D,dir; float direction,speed,minSpeed,maxSpeed; void setup() { size(400,400); background(200,160,0); v=new Vec2D(random(width),random(height)); v2=new Vec2D(random(width),random(height)); D=new Vec2D(); dir=new Vec2D(); direction=random(PI*2); speed=2; minSpeed=0.5; maxSpeed=4; ellipseMode(CENTER_DIAMETER); } void loop() { background(200,160,0); direction+=radians(random(-6,6)); speed+=random(-0.15,0.15); if(speedmaxSpeed) speed=maxSpeed; dir.set(speed,0); dir.rotate(direction); v.add(dir); if(v.x<0) v.x=width; else if(v.x>width) v.x=0; if(v.y<0) v.y=height; else if(v.y>height) v.y=0; D.set(v); D.sub(v2); if(D.length()>100) v2.add(D.x/50, D.y/50); else v2.add(D.x/200,D.y/200); noStroke(); fill(255,0,0); ellipse(v.x, v.y, 10,10); fill(255,255,0); ellipse(v2.x, v2.y, 10,10); } // General vector class for 2D vectors class Vec2D { float x,y; // Constructor with no parameters Vec2D() { x=0; y=0; } Vec2D(float _x,float _y) { x=_x; y=_y; } Vec2D(Vec2D v) { x=v.x; y=v.y; } void set(float _x,float _y) { x=_x; y=_y; } void set(Vec2D v) { x=v.x; y=v.y; } void add(float _x,float _y) { x+=_x; y+=_y; } void add(Vec2D v) { x+=v.x; y+=v.y; } void sub(float _x,float _y) { x-=_x; y-=_y; } void sub(Vec2D v) { x-=v.x; y-=v.y; } void mult(float m) { x*=m; y*=m; } void div(float m) { x/=m; y/=m; } float length() { return sqrt(x*x+y*y); } float angle() { return atan2(y,x); } void normalise() { float l=length(); if(l!=0) { x/=l; y/=l; } } Vec2D tangent() { return new Vec2D(-y,x); } void rotate(float val) { // Due to float not being precise enough, double is used for the calculations double cosval=Math.cos(val); double sinval=Math.sin(val); double tmpx=x*cosval - y*sinval; double tmpy=x*sinval + y*cosval; x=(float)tmpx; y=(float)tmpy; } }