forked from JaylyDev/ScriptAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
63 lines (54 loc) · 1.85 KB
/
index.js
File metadata and controls
63 lines (54 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Script example for ScriptAPI
// Author: Jayly#1397 <Jayly Discord>
// Project: https://github.com/JaylyDev/ScriptAPI
import { EntityHealthComponent, EntityHurtAfterEvent, world } from "@minecraft/server";
/**
* @typedef EntityDeathCallback
* @property {(arg: EntityHurtAfterEvent) => void} callback
* @property {import("@minecraft/server").EntityEventOptions} options
*/
/**
* @type {EntityDeathCallback[]}
*/
const callbacks = [];
// backend
world.afterEvents.entityHurt.subscribe((event) => {
const { hurtEntity } = event;
if (!hurtEntity) return;
const health = hurtEntity.getComponent(EntityHealthComponent.componentId);
if (health.currentValue > 0) return;
for (const callback of callbacks) {
const { entities, entityTypes } = callback.options;
if (entities instanceof Array && !entities?.includes(hurtEntity)) break;
if (entityTypes instanceof Array && !entityTypes?.includes(hurtEntity.typeId)) break;
callback.callback(event);
};
});
/**
* Manages callbacks that are connected to when an entity dies.
*/
class EntityDeathEventSignal {
/**
* @remarks
* Adds a callback that will be called when an entity dies.
* @param {(arg: EntityHurtAfterEvent) => void} callback
* @param {import("@minecraft/server").EntityEventOptions} options
* @returns {(arg: EntityHurtAfterEvent) => void}
*/
subscribe(callback, options = {}) {
callbacks.push({ options, callback });
return callback;
};
/**
* @remarks
* Removes a callback from being called when an entity dies.
* @param {(arg: EntityHurtAfterEvent) => void} callback
* @throws This function can throw errors.
*/
unsubscribe(callback) {
const index = callbacks.findIndex((value) => value.callback === callback);
callbacks.splice(index);
};
}
const entityDeath = new EntityDeathEventSignal();
export { entityDeath, EntityDeathEventSignal };