Skip to content

Commit

Permalink
Update the sample to remove constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
eonarheim committed Nov 30, 2023
1 parent 8065a1f commit 01dfc46
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 3 deletions.
9 changes: 8 additions & 1 deletion src/block.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Actor, ActorArgs, CollisionType, Vector } from "excalibur";
import { Actor, ActorArgs, CollisionType, Observable, RemovedComponent, Vector } from "excalibur";
import { MatterJsBodyComponent } from "./matterjs-body.component";
import { MatterJsConstraintComponent } from "./matterjs-constraint.component";

Expand All @@ -22,4 +22,11 @@ export class Block extends Actor {
bodyB: this.matterJs.matterJsBody
}));
}

removeConstraints() {
const component = this.get(MatterJsConstraintComponent)
if (component) {
this.removeComponent(component, true);
}
}
}
8 changes: 7 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CollisionType, Color, DisplayMode, Engine, Random, Vector, vec } from "excalibur";
import { CollisionType, Color, DisplayMode, Engine, Random, Vector, vec, Input } from "excalibur";
import { MatterJsSystem } from "./matterjs.system";
import { Block } from "./block";

Expand Down Expand Up @@ -48,4 +48,10 @@ game.input.pointers.primary.on('down', evt => {
game.add(newBlock);
});

game.input.keyboard.on('press', (evt) => {
if (evt.key === Input.Keys.D) {
constrainedBlock.removeConstraints();
}
})

game.start();
7 changes: 6 additions & 1 deletion src/matterjs-constraint.component.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { Component } from "excalibur";
import { Component, Entity, Observable } from "excalibur";
import * as Matter from 'matter-js';


export class MatterJsConstraintComponent extends Component<'matterjs.constraint'> {
public readonly type = 'matterjs.constraint' as const;
constraint: Matter.Constraint;
removed$ = new Observable<MatterJsConstraintComponent>();

constructor(public constraintDef: Matter.IConstraintDefinition) {
super();
this.constraint = Matter.Constraint.create(constraintDef)
}

onRemove(previousOwner: Entity): void {
this.removed$.notifyAll(this);
}

}
3 changes: 3 additions & 0 deletions src/matterjs.system.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ export class MatterJsSystem extends System<MatterJsBodyComponent | TransformComp
const matterJsConstraint = msg.data.get(MatterJsConstraintComponent);
if (matterJsConstraint) {
Matter.Composite.add(this.matterEngine.world, matterJsConstraint.constraint);
matterJsConstraint.removed$.subscribe(() => {
Matter.World.remove(this.matterEngine.world, matterJsConstraint.constraint);
});
}
}
}
Expand Down

0 comments on commit 01dfc46

Please sign in to comment.