Add basic planet collision
This commit is contained in:
parent
b02675f4fb
commit
09b3df649c
6 changed files with 42 additions and 11 deletions
|
@ -11,9 +11,14 @@ export default class Body {
|
|||
this.mass = mass;
|
||||
}
|
||||
|
||||
tickMotion() {
|
||||
this.x += this.xvel;
|
||||
this.y += this.yvel;
|
||||
}
|
||||
|
||||
tickGravity(bodies) {
|
||||
bodies.forEach(b => {
|
||||
let force = b.mass / this.mass / (distanceTo(b) ** 2) * G;
|
||||
let force = b.mass / this.mass / (this.distanceTo(b) ** 2) * G;
|
||||
let angle = Math.atan2(b.y - this.y, b.x - this.x);
|
||||
this.xvel += Math.cos(angle) * force;
|
||||
this.yvel += Math.sin(angle) * force;
|
||||
|
@ -21,6 +26,18 @@ export default class Body {
|
|||
}
|
||||
|
||||
distanceTo(body) {
|
||||
return Math.sqrt(((body.x - this.x) ** 2) + ((body.y - this.y) ** 2));
|
||||
return Math.max(Math.sqrt(((body.x - this.x) ** 2) +
|
||||
((body.y - this.y) ** 2)), 1);
|
||||
}
|
||||
|
||||
approach(body, distance) {
|
||||
let angle = Math.atan2(body.y - this.y, body.x - this.x);
|
||||
this.x += Math.cos(angle) * distance;
|
||||
this.y += Math.sin(angle) * distance;
|
||||
}
|
||||
|
||||
halt() {
|
||||
this.xvel = 0;
|
||||
this.yvel = 0;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import Module from './module.mjs';
|
||||
import Body from './body.mjs';
|
||||
import * as world from './index.mjs';
|
||||
|
||||
export default class Ship extends Body {
|
||||
constructor(x, y) {
|
||||
|
@ -10,7 +11,9 @@ export default class Ship extends Body {
|
|||
}
|
||||
|
||||
tick() {
|
||||
|
||||
this.tickMotion();
|
||||
this.tickGravity(world.celestials);
|
||||
this.resolveCollisions();
|
||||
}
|
||||
|
||||
addModule(x, y, properties, options) {
|
||||
|
@ -32,4 +35,14 @@ export default class Ship extends Body {
|
|||
[ax + b.x * b.mass, ay + b.y * b.mass], [0, 0])
|
||||
.map(x => x / this.mass);
|
||||
}
|
||||
|
||||
resolveCollisions() {
|
||||
world.celestials.forEach(c => {
|
||||
let dis = this.distanceTo(c);
|
||||
if (dis < c.radius) {
|
||||
this.approach(c, dis - c.radius);
|
||||
this.halt();
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue