UNPKG

@occultus/entity-api

Version:

Star Tenon entity api and utils

94 lines (92 loc) 2.67 kB
import { Block, DataDrivenEntityTriggerAfterEvent, Dimension, PlayerInteractWithBlockAfterEvent, system, Vector3, world, } from "@minecraft/server"; import { BlockEntity } from "./BlockEntity"; import { BlockEntityData } from "../interface/BlockEntityData.js"; /** * 设置一个带有方块实体的方块 * * @see BlockEntity * @example * new BlockWithEntity("minecraft:stone", "starock:stone"); */ export class BlockWithEntity { /** * @param blockId 方块的 ID * @param entityId 方块实体的 ID */ constructor( readonly blockId: string, readonly entityId: string, readonly tickEventName?: string ) { this.eventListener(); } private eventListener() { world.afterEvents.playerPlaceBlock.subscribe((arg) => { if (arg.block.typeId === this.blockId) { this.placeEntity(arg.dimension, arg.block.location); } }); world.beforeEvents.playerBreakBlock.subscribe((arg) => { if (arg.block.typeId === this.blockId) { const data = this.getBlockEntityData(arg.block); system.run(() => { if (data) BlockEntity.destory(data); }); } }); world.afterEvents.playerInteractWithBlock.subscribe((arg) => { if (arg.block.typeId === this.blockId) { this.onInteract(arg); } }); if (this.tickEventName) { world.afterEvents.dataDrivenEntityTrigger.subscribe((arg) => { if ( arg.entity.typeId === this.entityId && arg.eventId === this.tickEventName ) { this.onTick(arg); } }); } } /** * 获取方块实体的数据 * @param block 要获取方块实体的方块 * @returns 获取到的方块实体 */ getBlockEntityData(block: Block): BlockEntityData | undefined { const { dimension, location } = block; const entity = dimension.getEntities({ location: location, type: this.entityId, })[0]; return BlockEntity.getData(entity); } /** * 放置一个方块实体 * @param dimension 要放置实体的维度 * @param location 要放置实体的位置 * @returns */ placeEntity(dimension: Dimension, location: Vector3) { const entity = dimension.spawnEntity(this.entityId, location); entity.setDynamicProperty("starock:blockEntityLocation", location); entity.setDynamicProperty("starock:blockEntityId", entity.id); return entity; } onInteract(event: PlayerInteractWithBlockAfterEvent) { return; } onTick(event: DataDrivenEntityTriggerAfterEvent) { return; } }