# BoxAccelerator.py

from Processing import *

window(500, 500)

boxes = []
rectMode(CENTER)

class Accelerator:
    def __init__(self, x, y):
        self.x = x          # Position
        self.y = y
        self.vX = 0.0       # Velocity
        self.vY = 0.0
        self.aX = 0.0       # Acceleration
        self.aY = 0.0
        self.targetX = 0.0  # Target position
        self.targetY = 0.0
        self.friction = random(0.9, 1.0)

    def step(self):
        # Accelerate toward target
        self.aX = 0.002 * (self.targetX - self.x)
        self.aY = 0.002 * (self.targetY - self.y)

        # Update velocity and position
        self.vX = self.vX + self.aX
        self.vY = self.vY + self.aY
        self.vX = self.friction*self.vX
        self.vY = self.friction*self.vY
        self.x = self.x + self.vX
        self.y = self.y + self.vY

        # Reset target to mouse
        self.targetX = mouseX()
        self.targetY = mouseY()

    def display(self):
        fill(200)
        pushMatrix()
        translate(self.x, self.y)
        rect(0, 0, 20, 20)
        popMatrix()

# Create a new box and add to the master list
def createBox(o, e):
    x, y = mouseX(), mouseY()
    b = Accelerator(x, y)
    boxes.append( b )

# Draw all boxes
def draw(o, e):
    background(0)
    for b in boxes:
        b.step()
        b.display()

# Create a new box whenever the mouse is clicked
onMousePressed += createBox

# Draw all
frameRate(30)
onLoop += draw
loop()
