Skip to content

Commit 4849358

Browse files
committed
Add Physics#gravitate to calculate gravity
1 parent 3ad606d commit 4849358

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

js/main.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,3 @@ model.scene.push(titan);
4242
view.loop();
4343
physics.loop();
4444
console.log(model);
45-
window.setTimeout(physics.stop, 100);

js/modules/Physics.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,21 @@ export default class Physics {
3838
(obj) => obj.position.add(obj.velocity.copy().scale(Physics.timeScale))
3939
);
4040
}
41+
/**
42+
* Calculate gravitational acceleration between two Celestial instances
43+
* @param {Celestial} m_1 Celestial to apply acceleration to.
44+
* @param {Celestial} m_2 Celestial applying the acceleration.
45+
* @returns {Vector} Gravitational acceleration Vector.
46+
*/
47+
gravitate(m_1, m_2) {
48+
// Vector between m_1 and m_2
49+
const between = m_1.position.vectorTo(m_2.position),
50+
// Distance between m_1 and m_2
51+
r = between.magnitude;
52+
// Make `between` a unit vector
53+
between.magnitude = 1;
54+
return between.scale((Physics.G * m_2.mass) / r ** 2);
55+
}
4156

4257
/*----- Running Methods ----------------------------------------------------*/
4358
/** Calculate physics on a set interval. */

js/modules/Utils.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export class Point {
3737
* @returns {Point} The updated point.
3838
*/
3939
add(addend) {
40-
if(typeof addend === "number"){
40+
if (typeof addend === "number") {
4141
this.x += addend;
4242
this.y += addend;
4343
} else {
@@ -52,7 +52,7 @@ export class Point {
5252
* @returns {Point} The updated point.
5353
*/
5454
subtract(subtrahend) {
55-
if(typeof subtrahend === "number"){
55+
if (typeof subtrahend === "number") {
5656
this.x -= subtrahend;
5757
this.y -= subtrahend;
5858
} else {
@@ -80,7 +80,7 @@ export class Point {
8080
}
8181
/**
8282
* Get a Vector between two points.
83-
* @param {Point} point
83+
* @param {Point} point
8484
* @returns {Vector} A Vector between this Point and another Point.
8585
*/
8686
vectorTo(point) {

0 commit comments

Comments
 (0)