humus-old/common/combat/damaging.trait.js

102 lines
2.0 KiB
JavaScript

import * as I from 'immutable';
import {Trait} from '@avocado/entity';
import {AFFINITY_PHYSICAL} from './constants';
export class Damaging extends Trait {
static defaultParams() {
return {
damagingSound: '',
damageSpecs: [],
};
}
static type() {
return 'damaging';
}
constructor(entity, params, state) {
super(entity, params, state);
this._collidingWith = [];
this._doesNotDamage = [];
const damageSpecsJSON = this.params.damageSpecs;
this._damageSpecs = damageSpecsJSON.map((damageSpec) => {
return {
affinity: AFFINITY_PHYSICAL,
lock: 0.1,
power: 0,
variance: 0.2,
...damageSpec,
};
});
this._damagingSound = this.params.damagingSound;
}
doesNotDamageEntity(entity) {
return -1 !== this._doesNotDamage.indexOf(entity);
}
get damageSpecs() {
return this._damageSpecs;
}
get damagingSound() {
return this._damagingSound;
}
tryDamagingEntity(entity) {
if (this.doesNotDamageEntity(entity)) {
return;
}
if (entity.is('vulnerable')) {
if (!entity.isInvulnerable) {
entity.takeDamageFrom(this.entity);
}
}
}
listeners() {
const listeners = {};
if (AVOCADO_SERVER) {
listeners.collisionStart = (other) => {
this.tryDamagingEntity(other);
};
}
return listeners;
}
methods() {
return {
setDoesDamage: (entity) => {
const index = this._doesNotDamage.indexOf(entity);
if (-1 !== index) {
this._doesNotDamage.splice(index, 1);
}
},
setDoesNotDamage: (entity) => {
if (-1 === this._doesNotDamage.indexOf(entity)) {
this._doesNotDamage.push(entity);
}
},
};
}
tick(elapsed) {
if (AVOCADO_SERVER) {
if (this.entity.is('collider')) {
const isCollidingWith = this.entity.isCollidingWith;
for (let i = 0; i < isCollidingWith.length; i++) {
this.tryDamagingEntity(isCollidingWith[i]);
}
}
}
}
}