forked from bit101/CodingMath
-
Notifications
You must be signed in to change notification settings - Fork 0
/
particle.js
48 lines (40 loc) · 1.15 KB
/
particle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var particle = {
position: null,
velocity: null,
mass: 1,
radius: 0,
bounce: -1,
friction: 1,
create: function(x, y, speed, direction, grav) {
var obj = Object.create(this);
obj.position = vector.create(x, y);
obj.velocity = vector.create(0, 0);
obj.velocity.setLength(speed);
obj.velocity.setAngle(direction);
obj.gravity = vector.create(0, grav || 0);
return obj;
},
accelerate: function(accel) {
this.velocity.addTo(accel);
},
update: function() {
this.velocity.multiplyBy(this.friction);
this.velocity.addTo(this.gravity);
this.position.addTo(this.velocity);
},
angleTo: function(p2) {
return Math.atan2(p2.position.getY() - this.position.getY(), p2.position.getX() - this.position.getX());
},
distanceTo: function(p2) {
var dx = p2.position.getX() - this.position.getX(),
dy = p2.position.getY() - this.position.getY();
return Math.sqrt(dx * dx + dy * dy);
},
gravitateTo: function(p2) {
var grav = vector.create(0, 0),
dist = this.distanceTo(p2);
grav.setLength(p2.mass / (dist * dist));
grav.setAngle(this.angleTo(p2));
this.velocity.addTo(grav);
}
};