Skip to content

Instantly share code, notes, and snippets.

@bsparks
Created April 9, 2013 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsparks/5347030 to your computer and use it in GitHub Desktop.
Save bsparks/5347030 to your computer and use it in GitHub Desktop.
ImpactJS Starfield
// starfield.js
ig.module(
'game.starfield'
)
.requires(
'impact.system',
'impact.background-map'
)
.defines(function() {
var colors = ['#fff', '#555', '#f8ceda'];
Starfield = ig.BackgroundMap.extend({
name: 'starfield',
vel: {x: 0, y: 0},
init: function( starCount, settings ) {
starCount = starCount || 250;
this.ctx = ig.system.context;
this.stars = [];
for(var i=0;i<starCount;i++) {
this.stars.push({
x: (Math.random()*ig.system.width).floor(),
y: (Math.random()*ig.system.height).floor(),
color: colors.random()
});
}
ig.merge( this, settings );
ig.log('starfield init', this);
},
draw: function() {
var scale = ig.system.scale;
for(var i=0;i<this.stars.length;i++) {
this.ctx.fillStyle = this.stars[i].color;
this.ctx.fillRect(this.stars[i].x * scale, this.stars[i].y * scale, (Math.random() + 1).floor() * scale, (Math.random() + 1).floor() * scale);
}
},
update: function() {
for(var i=0, len=this.stars.length;i<len;i++) {
this.stars[i].x += this.vel.x * ig.system.tick;
this.stars[i].y += this.vel.y * ig.system.tick;
// clamp stars to viewport
if(this.stars[i].x < 0) {
this.stars[i].x = ig.system.width;
}
if(this.stars[i].x > ig.system.width) {
this.stars[i].x = 0;
}
if(this.stars[i].y < 0) {
this.stars[i].y = ig.system.height;
}
if(this.stars[i].y > ig.system.height) {
this.stars[i].y = 0;
}
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment