Skip to content

Instantly share code, notes, and snippets.

@jtenner
Last active May 2, 2016 18:46
Show Gist options
  • Save jtenner/83c8ce681765dfd14f093ab01e0ef3bd to your computer and use it in GitHub Desktop.
Save jtenner/83c8ce681765dfd14f093ab01e0ef3bd to your computer and use it in GitHub Desktop.
import { Part } from 'sidekick-worker';
import { Animation } from 'sidekick-worker-animation';
import { quadInOut } from 'ease-functions';
module.exports = class ExamplePart extends Part {
constructor() {
super();
//setting this.animation = [] opts into the animation engine
this.animation = [];
//store the little circles
this.balls = [];
//keep track of the frame count
this.frame = 0;
}
animationComplete(ball, animation) {
//when an animation is complete, remove the ball from the screen
var index = this.balls.indexOf(ball);
if (index !== -1) {
this.balls.splice(index, 1);
}
}
onPhysics() {
//simplePhysics lifecycle
let position, r, color, ball;
//if the frame count is 11
if (this.frame > 10) {
//subtract 10
this.frame -= 10;
//create the new ball position
position = [
Math.random() * 200 + 100,
Math.random() * 200 + 100
];
//set the ball radius
r = Math.random() * 10 + 10;
//set the ball color
color = [Math.round(255 * Math.random()), Math.round(255 * Math.random()), Math.round(255 * Math.random())];
//add the ball to the queue
this.balls.push(ball = {
position,
r,
color
});
//create an animations
this.animation.push(
new Animation({
obj: ball.position, //target object to animate
prop: 0, //the property [in this case the x property of the ball.position]
frameCount: 60, //how many frames it takes to reach the end
from: position[0], //starting point
to: position[0] - 50 + 100 * Math.random(), //end point
onComplete: (animation) => this.animationComplete(ball, animation), //onComplete function
ease: quadInOut //choose the easing
}),
new Animation({
obj: ball.position,
prop: 1,
frameCount: 60,
from: position[1],
to: position[1] - 50 + 100 * Math.random(),
onComplete: (animation) => this.animationComplete(ball, animation),
ease: quadInOut
})
);
}
//increase the frame count
this.frame += 1;
//serialize the data into an array
var data = [];
for (var i = 0; i < this.balls.length; i++) {
ball = this.balls[i];
data.push(
ball.position[0], //x
ball.position[1], //y
ball.r, //r
ball.color[0], //color
ball.color[1],
ball.color[2]
);
}
this.setData(data); //push the data to the browser
}
onDraw(data, ctx) {
for (var i = 0; i < this.data.length; i += 6) {
ctx.save();
ctx.beginPath();
ctx.arc(this.data[i], this.data[i + 1], this.data[i + 2], 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = `rgb(${this.data[i + 3]},${this.data[i + 4]},${this.data[i + 5]})`;
ctx.fill();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment