Game Development Reference
In-Depth Information
// The particle distance is 120 pixels from the left and 70 pixels
// from the top
var position = new Vec2(120, 70),
// and in one second the particle moves
// 10 pixels to the right and -5 pixels down (5 pixels up).
velocity = new Vec2(10, -5),
particle = new Particle(position, velocity);
// 60 times per second
window.setInterval(function(){
var time_passed = 1.0/60,
movement_right = particle.velocity.x * time_passed,
movement_down = particle.velocity.y * time_passed;
particle.position.x += movement_right;
particle.position.y += movement_down;
}, 1000/60);
setInterval
requestAnimationFrame
Note I use
for simplicity, in practice using
is a
better idea.
This code moves the particle velocity.x pixels per second to the right and velocity.y pixels per second
downwards. As you can see, writing code like that is quite tedious. By adding some operations—like
addition and multiplication—to the vector, we can make this code a lot simpler.
Vec2.prototype = {
muls: function(n) { return new Vec2(this.x*n, this.y*n); },
imuls: function(n) { this.x *= n; this.y *= n; return this; },
mul: function(v) { return new Vec2(this.x*v.x, this.y*v.y); },
imul: function(v) { this.x *= v.x; this.y *= v.y; return this; },
divs: function(n) { return new Vec2(this.x/n, this.y/n); },
div: function(v) { return new Vec2(this.x/v.x, this.y/v.y); },
adds: function(n) { return new Vec2(this.x+n, this.y+n); },
iadds: function(s) { this.x+=s; this.y+=s; return this; },
add: function(v) { return new Vec2(this.x+v.x, this.y+v.y); },
iadd: function(v) { this.x+=v.x; this.y+=v.y; return this;},
subs: function(n) { return new Vec2(this.x-n, this.y-n); },
isubs: function(s) { this.x-=s; this.y-=s; return this;},
sub: function(v) { return new Vec2(this.x-v.x, this.y-v.y); },
isub: function(v) { this.x-=v.x; this.y-=v.y; return this;},
set: function(x, y) {this.x = x; this.y = y;}
};
Search WWH ::




Custom Search