2d-physics-engine
Version:
A lightweight, flexible 2D physics engine with ECS architecture, built with TypeScript
112 lines • 3.09 kB
JavaScript
import { Vector2 } from '../math/Vector2';
import { Component } from './Component.abstract';
export class Rigidbody extends Component {
constructor(options) {
super();
Object.defineProperty(this, "componentId", {
enumerable: true,
configurable: true,
writable: true,
value: Symbol('Rigidbody')
});
Object.defineProperty(this, "velocity", {
enumerable: true,
configurable: true,
writable: true,
value: new Vector2()
});
Object.defineProperty(this, "angularVelocity", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "forces", {
enumerable: true,
configurable: true,
writable: true,
value: new Vector2()
});
Object.defineProperty(this, "torque", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "mass", {
enumerable: true,
configurable: true,
writable: true,
value: 1
});
Object.defineProperty(this, "inertia", {
enumerable: true,
configurable: true,
writable: true,
value: this.mass * 0.5
});
Object.defineProperty(this, "restitution", {
enumerable: true,
configurable: true,
writable: true,
value: 1
});
Object.defineProperty(this, "friction", {
enumerable: true,
configurable: true,
writable: true,
value: 0.1
});
this.mass = options?.mass || this.mass;
this.restitution = options?.restitution || this.restitution;
this.friction = options?.friction || this.friction;
}
update() { }
// Getters and setters for state
getVelocity() {
return this.velocity.clone();
}
setVelocity(velocity) {
this.velocity = velocity.clone();
}
getAngularVelocity() {
return this.angularVelocity;
}
setAngularVelocity(angularVelocity) {
this.angularVelocity = angularVelocity;
}
getMass() {
return this.mass;
}
getInverseMass() {
return this.mass > 0 ? 1 / this.mass : 0;
}
getInertia() {
return this.inertia;
}
// Force accumulation
getAccumulatedForces() {
return this.forces.clone();
}
getTorque() {
return this.torque;
}
addForce(force) {
this.forces = this.forces.add(force);
}
addTorque(torque) {
this.torque += torque;
}
clearForces() {
this.forces = new Vector2();
this.torque = 0;
}
// Material properties
getRestitution() {
return this.restitution;
}
getFriction() {
return this.friction;
}
}
//# sourceMappingURL=Rigidbody.component.js.map