Skip to content

Instantly share code, notes, and snippets.

@IgnetStudio
Created April 12, 2015 15:50
Show Gist options
  • Save IgnetStudio/474877f3ba3f4f243023 to your computer and use it in GitHub Desktop.
Save IgnetStudio/474877f3ba3f4f243023 to your computer and use it in GitHub Desktop.
Bouncing Balls in sketch.js

Bouncing Balls in sketch.js

A quick demo of balls bouncing off the edges of the container. My first attempt at using sketch.js.

A Pen by Rob Glazebrook on CodePen.

License.

/*
Bouncing Balls by Rob Glazebrook
An update of my earlier Pen which did something similar using DOM elements. This is my first foray into using sketch.js.
*/
var particles = [],
particleCount = 200;
Particle = function(x,y) {
this.x = x;
this.y = y;
this.radius = random(3,30);
this.rgba = 'rgba('+floor(random(0,255))+','+floor(random(0,255))+','+floor(random(0,255))+','+random(.1,.8)+')';
this.vx = random(-2,2);
this.vy = random(-2,2);
// Draw our particle to the canvas.
this.draw = function(ctx) {
ctx.fillStyle = this.rgba;
ctx.beginPath();
ctx.arc(this.x,this.y,this.radius,0,TWO_PI);
ctx.fill();
};
// Update our position.
this.update = function(ctx) {
this.x += this.vx;
this.y += this.vy;
// Bounce off edges.
if(this.x + this.radius > ctx.width) {
this.vx *= -1;
this.x = ctx.width - this.radius;
}
if(this.x - this.radius < 0) {
this.vx *= -1;
this.x = this.radius;
}
if(this.y + this.radius > ctx.height) {
this.vy *= -1;
this.y = ctx.height - this.radius;
}
if(this.y - this.radius < 0) {
this.vy *= -1;
this.y = this.radius;
}
}
};
var sketch = Sketch.create({
setup: function() {
var i = particleCount;
while(i--) {
var p = new Particle(random(0, this.width),random(0, this.height));
particles.push(p);
}
},
update: function() {
var i = particleCount;
while(i--) {
particles[i].update(this);
}
},
draw: function() {
var i = particleCount;
while(i--) {
particles[i].draw(this);
}
}
});
body {
background: #222;
margin: 0;
overflow: hidden;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment