12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- import {Trait} from "../Entity.js";
- import Vec2 from "../Vec2.js";
-
- export default class TPhysics extends Trait {
- constructor(entity) {
- super(entity, "physics");
-
- this.gravity = 40;
- this.groundFriction = 6;
- this.airFriction = 2;
-
- this.velocity = new Vec2();
- this.relVelocity = new Vec2();
-
- this.onGround = false;
- this.prevRelativeTo = null;
- this.relativeTo = null;
- }
-
- update(dt) {
- let collider = this.entity.t.collider;
-
- this.prevRelativeTo = this.relativeTo;
- this.relativeTo = null;
- this.onGround = false;
-
- if (
- this.entity.has("collider") &&
- collider.collides &&
- this.relVelocity.y >= 0) {
-
- // Structures are static; just teleport us to the top of them
- if (collider.cStructure) {
- this.relVelocity.y = 0;
- this.entity.bounds.bottom = collider.cStructure.top;
- this.onGround = true;
-
- // If we're colliding with an entity, and that entity is
- // a platform, teleport us to the top of them.
- } else if (collider.cEntity.has("platform")) {
- this.relVelocity.y = 0;
- this.entity.bounds.bottom = collider.cEntity.bounds.top;
- this.onGround = true;
-
- if (collider.cEntity.has("physics")) {
- let cPhys = collider.cEntity.t.physics;
- this.relativeTo = cPhys;
- }
- }
- }
-
- if (!this.onGround)
- this.relVelocity.y += this.gravity * dt;
-
- // If we just started riding something, adjust relative velocity
- if (!this.prevRelativeTo && this.relativeTo) {
- this.relVelocity.x = this.velocity.x - this.relativeTo.velocity.x;
- this.relVelocity.y = this.velocity.y - this.relativeTo.velocity.y;
-
- // If we just stopped riding something, adjust relative velocity
- } else if (this.prevRelativeTo && !this.relativeTo) {
- this.relVelocity.x = this.velocity.x + this.relativeTo.velocity.x;
- this.relVelocity.y = this.velocity.y + this.relativeTo.velocity.y;
- }
-
- // Apply friction
- var fric = this.onGround ? this.groundFriction : this.airFriction;
- var xRatio = 1 / (1 + (dt * fric));
- this.relVelocity.x *= xRatio;
-
- // Update velocity
- if (this.relativeTo) {
- this.velocity.x = this.relVelocity.x + this.relativeTo.velocity.x;
- this.velocity.y = this.relVelocity.y + this.relativeTo.velocity.y;
- } else {
- this.velocity.x = this.relVelocity.x;
- this.velocity.y = this.relVelocity.y;
- }
- }
-
- postUpdate(dt) {
- this.entity.bounds.pos.x += this.velocity.x * dt;
- this.entity.bounds.pos.y += this.velocity.y * dt;
- }
- }
|