feat: matter collisions
This commit is contained in:
parent
c556c90602
commit
4825bd2494
|
@ -127,12 +127,12 @@ export class World extends AbstractWorld {
|
|||
const newContacts = allContacts.get(entity);
|
||||
for (const contact of newContacts.values()) {
|
||||
if (!oldContacts.has(contact)) {
|
||||
entity.emit('contactStart', contact);
|
||||
entity.emit('collisionStart', contact);
|
||||
}
|
||||
}
|
||||
for (const contact of oldContacts.values()) {
|
||||
if (!newContacts.has(contact)) {
|
||||
entity.emit('contactEnd', contact);
|
||||
entity.emit('collisionEnd', contact);
|
||||
}
|
||||
}
|
||||
entity.body.contacts = newContacts;
|
||||
|
|
|
@ -8,9 +8,23 @@ import { Rectangle } from '../../math';
|
|||
|
||||
export class Body extends AbstractBody {
|
||||
|
||||
static lookupBody(matterBody) {
|
||||
if (this.bodies) {
|
||||
return this.bodies.get(matterBody);
|
||||
}
|
||||
}
|
||||
|
||||
static associateBody(matterBody, avocadoBody) {
|
||||
if (!this.bodies) {
|
||||
this.bodies = new Map();
|
||||
}
|
||||
this.bodies.set(matterBody, avocadoBody);
|
||||
}
|
||||
|
||||
constructor(shape) {
|
||||
super(shape);
|
||||
this.matterBody = this.constructor.bodyFromShape(shape);
|
||||
this.constructor.associateBody(this.matterBody, this);
|
||||
}
|
||||
|
||||
get aabb() {
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import {Engine, World as MatterWorld} from 'matter-js';
|
||||
import {Engine, Events, World as MatterWorld} from 'matter-js';
|
||||
|
||||
import {Body} from './body';
|
||||
import {AbstractWorld} from '../abstract/world';
|
||||
|
@ -17,6 +17,8 @@ export class World extends AbstractWorld {
|
|||
this.engine = Engine.create({
|
||||
world,
|
||||
});
|
||||
this.handleCollisions('collisionStart');
|
||||
this.handleCollisions('collisionEnd');
|
||||
this.lastElapsed = undefined;
|
||||
}
|
||||
|
||||
|
@ -28,6 +30,20 @@ export class World extends AbstractWorld {
|
|||
return new Body(shape);
|
||||
}
|
||||
|
||||
handleCollisions(eventName) {
|
||||
Events.on(this.engine, eventName, (event) => {
|
||||
event.pairs.forEach((pair) => {
|
||||
const {bodyA, bodyB} = pair;
|
||||
const entityA = this.entities.get(Body.lookupBody(bodyA));
|
||||
const entityB = this.entities.get(Body.lookupBody(bodyB));
|
||||
if (entityA && entityB) {
|
||||
entityA.emit(eventName, entityB);
|
||||
entityB.emit(eventName, entityA);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
removeBody(body) {
|
||||
super.removeBody(body);
|
||||
MatterWorld.remove(this.engine.world, body.matterBody);
|
||||
|
|
Loading…
Reference in New Issue
Block a user