123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- 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.absVelocity = new Vec2();
- this.velocity = 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.velocity.y >= 0) {
-
- // Structures are static; just teleport us to the top of them
- if (collider.cStructure) {
- this.velocity.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.velocity.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.velocity.y += this.gravity * dt;
-
- // If we just started riding something, adjust relative absVelocity
- if (!this.prevRelativeTo && this.relativeTo) {
- this.velocity.x = this.absVelocity.x - this.relativeTo.absVelocity.x;
- this.velocity.y = this.absVelocity.y - this.relativeTo.absVelocity.y;
-
- // If we just stopped riding something, adjust relative absVelocity
- } else if (this.prevRelativeTo && !this.relativeTo) {
- this.velocity.x += this.prevRelativeTo.absVelocity.x;
- this.velocity.y += this.prevRelativeTo.absVelocity.y;
- }
-
- // Apply friction
- var fric = this.onGround ? this.groundFriction : this.airFriction;
- var xRatio = 1 / (1 + (dt * fric));
- this.velocity.x *= xRatio;
- }
-
- postUpdate(dt) {
-
- // Update absVelocity
- if (this.relativeTo) {
- this.absVelocity.x = this.velocity.x + this.relativeTo.absVelocity.x;
- this.absVelocity.y = this.velocity.y + this.relativeTo.absVelocity.y;
- } else {
- this.absVelocity.x = this.velocity.x;
- this.absVelocity.y = this.velocity.y;
- }
-
- // Move
- this.entity.bounds.pos.x += this.absVelocity.x * dt;
- this.entity.bounds.pos.y += this.absVelocity.y * dt;
- }
- }
|