Created
July 28, 2011 22:35
-
-
Save bengolder/1112736 to your computer and use it in GitHub Desktop.
Grasshopper Boids Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from Rhino.Geometry import Point3d, Vector3d, Curve | |
# inputs | |
# numBoids | |
# switch | |
# boundingBox | |
class Boid(): | |
radius = 5.0 | |
def __init__(self, initialPosition, initialHeading): | |
self.position = initialPosition | |
self.heading = initialHeading | |
self.trail = [initialPosition] | |
def move(self): | |
"""Updates boid position based on heading.""" | |
self.position = Point3d.Add( self.position, self.heading ) | |
self.trail.append( self.position ) | |
def findDirection(self, allBoids): | |
"""Filters self out of others and | |
Updates heading based on other boids.""" | |
others = allBoids[:] | |
others.remove(self) | |
neighbors = [] | |
for other in others: | |
distance = self.position.DistanceTo( other.position ) | |
if distance < self.radius: | |
neighbors.append(other) | |
if neighbors: | |
self.align(neighbors) | |
self.cohere(neighbors) | |
def align(self, others): | |
headings = [other.heading for other in others] | |
uberVector = Vector3d(0.0,0.0,0.0) | |
for heading in headings: | |
uberVector = Vector3d.Add( uberVector, heading ) | |
self.heading = Vector3d.Divide( uberVector, uberVector.Length ) | |
def cohere(self, others): | |
centerPoint = others.pop(0).position | |
for other in others: | |
centerPoint = Point3d.Add( centerPoint, other.position ) | |
centerPoint = Point3d.Divide( centerPoint, len(others) - 1 ) | |
direction = Point3d.Subtract( centerPoint, self.position ) | |
direction = Vector3d.Divide( direction, direction.Length ) | |
self.heading = Vector3d.Add( direction, self.heading ) | |
boids = [] | |
if initialPoints: | |
# initial state | |
# create random points | |
for point in initialPoints: | |
heading = Vector3d( Point3d.Multiply( point, -1 ) ) | |
boid = Boid( point, heading ) | |
boids.append( boid ) | |
if switch and numSteps: | |
print 'go boids!' | |
# for loop | |
for i in range(int(numSteps)): | |
# evaluate boids | |
for boid in boids: | |
boid.findDirection( boids ) | |
# move boids | |
for boid in boids: | |
boid.move() | |
trails = [] | |
for boid in boids: | |
trails.append(Curve.CreateControlPointCurve( boid.trail, 3)) | |
points = [boid.position for boid in boids] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment