2019-04-08 15:20:28 -05:00
|
|
|
import {compose} from '@avocado/core';
|
2019-04-14 20:21:52 -05:00
|
|
|
import {StateProperty, Trait} from '@avocado/entity';
|
2019-04-08 15:20:28 -05:00
|
|
|
|
|
|
|
const decorate = compose(
|
|
|
|
StateProperty('isCheckingCollisions'),
|
|
|
|
);
|
|
|
|
|
|
|
|
export class Collider extends decorate(Trait) {
|
|
|
|
|
|
|
|
static defaultParams() {
|
|
|
|
return {
|
|
|
|
collidesWithGroups: [
|
|
|
|
'default',
|
|
|
|
],
|
|
|
|
collisionGroup: 'default',
|
2019-04-19 02:52:39 -05:00
|
|
|
isSensor: false,
|
2019-04-08 15:20:28 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
static defaultState() {
|
|
|
|
return {
|
|
|
|
isCheckingCollisions: true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
initialize() {
|
|
|
|
this._collisionGroup = this.params.get('collisionGroup');
|
|
|
|
this._collidesWithGroups = this.params.get('collidesWithGroups').toJS();
|
2019-05-01 17:34:24 -05:00
|
|
|
this._isCollidingWith = [];
|
2019-04-19 02:52:39 -05:00
|
|
|
this._isSensor = this.params.get('isSensor');
|
2019-04-08 15:20:28 -05:00
|
|
|
}
|
|
|
|
|
2019-04-30 18:22:02 -05:00
|
|
|
destroy() {
|
2019-05-01 17:34:24 -05:00
|
|
|
for (let i = 0; i < this._isCollidingWith.length; i++) {
|
|
|
|
const entity = this._isCollidingWith[i];
|
|
|
|
entity.emit('collisionEnd', this.entity);
|
|
|
|
}
|
|
|
|
this._isCollidingWith = [];
|
2019-04-30 18:22:02 -05:00
|
|
|
}
|
|
|
|
|
2019-04-08 15:20:28 -05:00
|
|
|
get collisionGroup() {
|
|
|
|
return this._collisionGroup;
|
|
|
|
}
|
|
|
|
|
|
|
|
get collidesWithGroups() {
|
|
|
|
return this._collidesWithGroups;
|
|
|
|
}
|
|
|
|
|
2019-04-19 12:06:56 -05:00
|
|
|
get isCollidingWith() {
|
|
|
|
return this._isCollidingWith;
|
|
|
|
}
|
|
|
|
|
2019-04-19 02:52:39 -05:00
|
|
|
get isSensor() {
|
|
|
|
return this._isSensor;
|
|
|
|
}
|
|
|
|
|
2019-04-19 12:06:56 -05:00
|
|
|
listeners() {
|
|
|
|
return {
|
|
|
|
|
|
|
|
collisionEnd: (other) => {
|
2019-05-01 17:34:24 -05:00
|
|
|
const index = this._isCollidingWith.indexOf(other);
|
|
|
|
if (-1 !== index) {
|
|
|
|
this._isCollidingWith.splice(index, 1);
|
|
|
|
}
|
2019-04-19 12:06:56 -05:00
|
|
|
},
|
|
|
|
|
|
|
|
collisionStart: (other) => {
|
2019-05-01 17:34:24 -05:00
|
|
|
const index = this._isCollidingWith.indexOf(other);
|
|
|
|
if (-1 === index) {
|
|
|
|
this._isCollidingWith.push(other);
|
|
|
|
}
|
2019-04-19 12:06:56 -05:00
|
|
|
},
|
|
|
|
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-04-08 15:20:28 -05:00
|
|
|
methods() {
|
|
|
|
return {
|
|
|
|
|
|
|
|
collidesWith: (entity) => {
|
|
|
|
const collisionGroup = entity.collisionGroup();
|
|
|
|
return -1 !== this._collidesWithGroups.indexOf(collisionGroup);
|
|
|
|
},
|
|
|
|
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|