Skip to content

Instantly share code, notes, and snippets.

@kurtbrose
Created February 26, 2014 08:33
Show Gist options
  • Select an option

  • Save kurtbrose/9225842 to your computer and use it in GitHub Desktop.

Select an option

Save kurtbrose/9225842 to your computer and use it in GitHub Desktop.
working on pyglet stuff for having a dynamic set of 2d nodes
'''
Two main jobs:
1- calculate the desired position
2- accelerate towards that position
Several acceleration profiles:
"spring" acceleration -- acceleration proportional to displacement from ideal
"rocket" acceleration -- max acceleration to mid point, followed by max de-celleration
At any given time, the window will be "anchored" to one element.
This element will be arbitrarily assigned to the center of the window.
Other elements will arrange themselves around the central one.
'''
import collections
import random
import pyglet
window = pyglet.window.Window()
class MetaNode(object):
image = pyglet.image.ImageData(10, 10, 'RGBA', '\x80\x80\xFF\x80'*100)
batch = pyglet.graphics.Batch()
def __init__(self, approach=None):
self.approach = approach or spring
self.sprite = pyglet.sprite.Sprite(img=self.image, batch=self.batch)
self.velocity = Vector(0, 0)
self.target_pos = Vector(0, 0)
@property
def pos(self):
return Vector(self.sprite.x, self.sprite.y)
@pos.setter
def pos(self, val):
self.sprite.x, self.sprite.y = val
def update(self, dt):
self.velocity = self.approach(self.pos, self.target_pos, self.velocity, dt)
self.pos = self.pos + self.velocity
def spring(src_pos, dst_pos, cur_vel, scale=1.0):
'''
this "spring" will follow a very smooth path,
accelerating in proportion to the displacement from ideal
'''
return cur_vel + scale * (dst_pos - src_pos)
def rocket(src_pos, dst_pos, cur_val, scale=1.0):
'''
this "rocket" will follow the shortest-time path,
accelerating at the maximum rate at all time
'''
# should we be accelerating or de-cellerating?
# motion can be split into x-component and y-component
cur_vel
class Vector(collections.namedtuple("vec2d", "x y")):
def __add__(self, other):
return Vector(self.x + other[0], self.y + other[1])
def __sub__(self, other):
return Vector(self.x - other[0], self.y - other[1])
def __mul__(self, factor):
return Vector(self.x * factor, self.y * factor)
__rmul__ = __mul__
nodes = [MetaNode() for i in range(20)]
for n in nodes:
n.target_pos = Vector(random.randint(0, window.width - 1), random.randint(0, window.height - 1))
def update(dt):
for n in nodes:
n.update(dt)
@window.event
def on_draw():
window.clear()
MetaNode.batch.draw()
pyglet.clock.schedule_interval(update, 1/60.0)
if __name__ == "__main__":
pyglet.app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment