Skip to content

Instantly share code, notes, and snippets.

@douglasgoodwin
Created January 10, 2018 07:56
Show Gist options
  • Save douglasgoodwin/aad6fe89ec14a55e619cbc0b609a0bec to your computer and use it in GitHub Desktop.
Save douglasgoodwin/aad6fe89ec14a55e619cbc0b609a0bec to your computer and use it in GitHub Desktop.
# Python Flowfield example
# Doug Goodwin
# Example derived from Daniel Shiffman's "Nature of Code"
# http:#natureofcode.com
# Flow Field Following
class FlowField(object):
def __init__(self,r):
# A flow field is a two dimensional array of PVectors
# How large is each "cell" of the flow field
self.resolution = r
# Determine the number of columns and rows based on sketch's width and height
self.cols = width/self.resolution
self.rows = height/self.resolution
# initialize a 2 dimensional matrix of cols x rows
self.field = [[0 for x in range(0,self.rows)] for y in range(0,self.cols)]
# now you can do this: self.field[0][0] = 1
# Reseed noise so we get a new flow field every time
noiseSeed( int(random(10000)) )
xoff = 0
for i in range(0,self.cols):
yoff = 0
for j in range(0,self.rows):
print("i,j:",i,j)
theta = map( noise(xoff,yoff),0,1,0,TWO_PI )
# Polar to cartesian coordinate transformation
# to get the x and y components of the vector
self.field[i][j] = PVector( cos(theta),sin(theta) )
yoff += 0.1
xoff += 0.1
# Renders a vector object 'v' as an arrow and a position 'x,y'
def drawVector(self,v, x, y, scayl):
pushMatrix()
arrowsize = 4
# Translate to position to render vector
translate(x,y)
stroke(0,100)
# Call vector heading function to get direction
# (note that pointing to the right is a heading of 0) and rotate
rotate(v.heading2D())
# Calculate length of vector & scale it to be bigger or smaller if necessary
len = v.mag()*scayl
# Draw three lines to make an arrow
# (draw pointing up since we've rotate to the proper direction)
line(0,0,len,0)
# vector arrows
line(len,0,len-arrowsize,+arrowsize/2)
line(len,0,len-arrowsize,-arrowsize/2)
popMatrix()
def lookup(self,lookup):
column = int(constrain(self.lookup.x/self.resolution,0,self.cols-1));
row = int(constrain(self.lookup.y/self.resolution,0,self.rows-1));
return self.field[column][row].get()
# Draw every vector
def display(self):
for i in range(0,self.cols):
for j in range(0,self.rows):
self.drawVector(self.field[i][j],i*self.resolution,j*self.resolution,self.resolution);
size(900, 600)
# Make a new flow field with "resolution" of 16
f = FlowField(16)
f.display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment