-
Notifications
You must be signed in to change notification settings - Fork 0
/
boid.py
89 lines (76 loc) · 2.42 KB
/
boid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
from random import random
from math import *
from vector2d import Vector2D
boidSize = 4
boidSpeed = 2
boidAccel = 0.03
class Boid(object):
def __init__(self, x, y):
"""
Create new boid at position x,y
with a random unit velocity
and no acceleration
"""
self.position = Vector2D(x,y)
self.velocity = Vector2D.random2D()
self.acceleration = Vector2D(0,0)
"""
experiment by changing the constants
above
"""
self.size = boidSize
self.maxspeed = boidSpeed
self.maxaccel = boidAccel
#print self.position, self.velocity
def decide(self, boids):
"""
Have each boid decide how to modify its velocity,
based on location, velocity of nearby boids
"""
return
#in this toy example, every boid just wants to circle
theta = radians(90)
self.acceleration = self.velocity.rotate(theta)
self.acceleration.limit(self.maxaccel)
def update(self):
"""
Apply acceleration of current time step
to update velocity an position. Reset acceleration
to zero before next time step
"""
self.velocity += self.acceleration
self.velocity.limit(self.maxspeed)
self.position += self.velocity
self.acceleration *= 0
self.wrap() #keep boid on torroidal screen
def draw(self):
"""
Draw boid as a triangle
pointing in direction of current velocity
at current position
"""
sz = self.size
theta = self.velocity.heading()
fill(252,244,71)
stroke(255)
with pushMatrix():
translate(self.position.x, self.position.y)
rotate(theta)
with beginShape(TRIANGLES):
vertex( sz*2, 0)
vertex(-sz*2,-sz)
vertex(-sz*2, sz)
def wrap(self):
"""
Keep boid on screen by updating position
if boid is travelling off the edge. Wrap
the boid position as if screen were a torus
"""
x = self.position.x
y = self.position.y
sz = self.size
#hey, python's weird floating point mod is useful
if (x < -sz) or (x > width+sz):
self.position.x= self.position.x % width
if (y < -sz) or (y > height+sz):
self.position.y = self.position.y % height