import {compose} from '@avocado/core'; import {StateProperty, Trait} from '@avocado/entity'; const decorate = compose( StateProperty('isCheckingCollisions'), ); export class Collider extends decorate(Trait) { static defaultParams() { return { collidesWithGroups: [ 'default', ], collisionGroup: 'default', isSensor: false, } } static defaultState() { return { isCheckingCollisions: true, } } initialize() { this._collisionGroup = this.params.get('collisionGroup'); this._collidesWithGroups = this.params.get('collidesWithGroups').toJS(); this._isCollidingWith = []; this._isSensor = this.params.get('isSensor'); } destroy() { for (let i = 0; i < this._isCollidingWith.length; i++) { const entity = this._isCollidingWith[i]; entity.emit('collisionEnd', this.entity); } this._isCollidingWith = []; } get collisionGroup() { return this._collisionGroup; } get collidesWithGroups() { return this._collidesWithGroups; } get isCollidingWith() { return this._isCollidingWith; } get isSensor() { return this._isSensor; } listeners() { return { collisionEnd: (other) => { const index = this._isCollidingWith.indexOf(other); if (-1 !== index) { this._isCollidingWith.splice(index, 1); } }, collisionStart: (other) => { const index = this._isCollidingWith.indexOf(other); if (-1 === index) { this._isCollidingWith.push(other); } }, }; } methods() { return { collidesWith: (entity) => { const collisionGroup = entity.collisionGroup(); return -1 !== this._collidesWithGroups.indexOf(collisionGroup); }, }; } }