github上转载下来的(懒得翻墙了)
本页面仅允许已登入成员查看
API
# Code API
You can run javascript when right clicking code blocks and press to code boards.
This is only available to owners of worlds lobbies.
The javascript can interact with the Bloxd.io game api.
Please use [our discord](https://discord.gg/vwMp5y25RX) to report any issues you come across or features you'd like to see added.
## Code Blocks
- World owners can find these by searching in the creative menu
- No need to add `press to code`, this text is only needed for code boards, and will automatically be removed
- If you want to run code without opening the code editor, you can trigger the code block by right clicking an adjacent `press to code` board instead
## Boards
- You can begin a board with `press to code` to run javascript when you right click it.
- Normally you can't edit a code board after placing it, but you can currently work around this by putting a space before `press to code`.
- Boards only allow for a small amount of text, we recommend you use Code Blocks instead, or you can work around this by using multiple boards
## Notes
- Global variable `myId` stores the PlayerID of who is running the code.
- Global variable `thisPos` stores the position of the currently executing code block or press to code board.
- You can use `api.log` or `console.log` for printing and debugging (they do the same thing).
- You can use `Date.now()` instead of `api.now()` if you prefer, both return the time in milliseconds.
- Comments like `/* comment */` work, but comments like `// comment` don't work right now.
## Examples
Code Block to make the player jump:
```ts
f = api.setVelocity(myId, 0, 9, 0)
```
Push the player
```ts
api.applyImpulse(myId, 9, 0, 9)
```
Send an orange message to yourself:
```ts
api.sendMessage(myId, "text", { color: "orange" })
```
Create flying text:
```ts
const speed = 100
api.sendFlyingMiddleMessage(myId, ["Message to display"], speed)
```
Send a message to all players:
```ts
api.broadcastMessage("announcement", { color: "red" })
```
Set player health to 99, and print the old health:
```ts
const oldHealth = api.getHealth(myId)
api.setHealth(myId, 99)
api.log("Old Health:", oldHealth)
```
Define a function to get the player IDs excluding your own ID:
```ts
getOtherIds = () => {
const ids = api.getPlayerIds()
const otherIds = []
for (const id of ids) {
if (id !== myId) {
otherIds.push(id)
}
}
return otherIds
}
```
Use the function above to make other players look like zombies:
```ts
for (const otherId of getOtherIds()) {
api.setPlayerPose(otherId, "zombie")
for (const part of ["head", "body", "legs"]) {
/* Notice the skin texture uses a capital Z */
api.changePlayerIntoSkin(otherId, part, "Zombie")
}
}
```
Make all players look like floating wizards:
```ts
for (const playerId of api.getPlayerIds()) {
api.setPlayerPose(playerId, "driving")
for (const part of ["head", "body", "legs"]) {
/* Notice the skin texture uses a capital W */
api.changePlayerIntoSkin(playerId, part, "Wizard")
}
}
```
## API
Global object `api` has the following methods:
```ts
/**
* Get position of a player / entity.
* @param entityId
*/
getPosition(entityId: EntityId): [number, number, number]
/**
* Set position of a player / entity.
* @param entityId
* @param x Can also be an array, in which case y and z shouldn't be passed
* @param y
* @param z
*/
setPosition(entityId: EntityId, x: number | number[], y?: number, z?: number): void
/**
* Get all the player ids.
*/
getPlayerIds(): PlayerId[]
/**
* Whether a player is currently in the game
*
* @param playerId
*/
playerIsInGame(playerId: PlayerId): boolean
/**
*
* @param playerId
* @returns
*/
playerIsLoggedIn(playerId: PlayerId): boolean
/**
* Returns the party that the player was in when they joined the game. The returned object contains the playerDbIds, as well
* as the playerIds if available, of the party leader and members.
*
* @param playerId
*
* @returns
*/
getPlayerPartyWhenJoined(playerId: PlayerId): PNull<{ playerDbIds: PlayerDbId[] }>
/**
* Get the number of players in the room
*/
getNumPlayers(): number
/**
* Get the co-ordinates of the blocks the player is standing on as a list. For example, if the center of the player is at 0,0,0
* this function will return [[0, -1, 0], [-1, -1, 0], [0, -1, -1], [-1, -1, -1]]
* If the player is just standing on one block, the function would return e.g. [[0, 0, 0]]
* If the player is middair then returns an empty list [].
*
* @param playerId
*/
getBlockCoordinatesPlayerStandingOn(playerId: PlayerId): number[][]
/**
* Get the types of block the player is standing on
* For example, if a player is standing on 4 dirt blocks, this will return ["Dirt", "Dirt", "Dirt", "Dirt"]
* @param playerId
*/
getBlockTypesPlayerStandingOn(playerId: PlayerId): any[]
/**
* Get the up to 12 unit co-ordinates the lifeform is located within
* (A lifeform is modelled as having four corners and can be in up to 3 blocks vertically)
*
* @param lifeformId
* @returns List of x, y, z positions e.g. [[-1, 0, 0], [-1, 1, 0], [-1, 2, 0]]
*/
getUnitCoordinatesLifeformWithin(lifeformId: LifeformId): number[][]
/**
* Show the shop tutorial for a player. Will not be shown if they have ever seen the shop tutorial in your game before.
* @param playerId
*/
showShopTutorial(playerId: PlayerId): void
/**
* Get the current shield of an entity.
* @param entityId
*/
getShieldAmount(entityId: EntityId): number
/**
* Set the current shield of a lifeform.
*
* @param lifeformId
* @param newShieldAmount
*/
setShieldAmount(lifeformId: LifeformId, newShieldAmount: number): void
/**
* Get the current health of an entity.
* @param entityId
*/
getHealth(entityId: PlayerId): number
/**
*
* @param lifeformId
* @param changeAmount Must be an integer. A positive amount will increase the entity's health. A negative amount will decrease the entity's shield first, then their health.
* @param whoDidDamage Optional - If damage done by another player
* @param broadcastLifeformHurt
*
* @return Whether the entity was killed
*/
applyHealthChange(lifeformId: LifeformId, changeAmount: number, whoDidDamage?: LifeformId | { lifeformId: LifeformId; withItem: string }, broadcastLifeformHurt = true): boolean
/**
* Set the current health of an entity.
* If you want to set their health to more than their current max health, the optional increaseMaxHealthIfNeeded must be true.
*
* @param entityId
* @param newHealth Can be null to make the player not have health
* @param whoDidDamage Optional
* @param increaseMaxHealthIfNeeded Optional
*
* @return Whether this change in health killed the player
*/
setHealth(entityId: EntityId, newHealth: PNull<number>, whoDidDamage?: LifeformId | { lifeformId: LifeformId; withItem: string }, increaseMaxHealthIfNeeded = false): boolean
/**
* Make it as if hittingEId hit hitEId
*
* @param hittingEId
* @param hitEId
* @param dirFacing
* @param bodyPartHit
*/
applyMeleeHit(hittingEId: PlayerId, hitEId: PlayerId, dirFacing: number[], bodyPartHit?: PNull<PlayerBodyPart>): void
/**
* Apply damage to a lifeform.
* eId is the player initiating the damage, hitEId is the lifeform being hit.
*
* It is recommended to self-inflict damage when the game code wants to apply damage to a lifeform.
*
* @param eId
* @param hitEId
* @param attemptedDmgAmt
* @param withItem
* @param bodyPartHit
* @param attackDir
* @param showCritParticles
* @param reduceVerticalKbVelocity
* @param broadcastEntityHurt
* @param attackCooldownSettings
* @param hittingSoundOverride
* @param ignoreOtherEntitySettingCanAttack
* @param isTrueDamage
* @param damagerDbId
*
* @returns whether the attack damaged the lifeform
*/
attemptApplyDamage({
eId,
hitEId,
attemptedDmgAmt,
withItem,
bodyPartHit = undefined,
attackDir = undefined,
showCritParticles = false,
reduceVerticalKbVelocity = true,
broadcastEntityHurt = true,
attackCooldownSettings = null,
hittingSoundOverride = null,
ignoreOtherEntitySettingCanAttack = false,
isTrueDamage = false,
damagerDbId = null,
}: PlayerAttemptDamageOtherPlayerOpts): boolean
/**
* Force respawn a player
* @param playerId
* @param respawnPos
*/
forceRespawn(playerId: PlayerId, respawnPos?: number[]): void
/**
* Kill a lifeform.
* @param lifeformId
* @param whoKilled Optional
*/
killLifeform(lifeformId: LifeformId, whoKilled?: LifeformId | { lifeformId: LifeformId; withItem: string }): void
/**
* Gets the player's current killstreak
*
* @param playerId
* @returns
*/
getCurrentKillstreak(playerId: PlayerId): any
/**
* Clears the player's current killstreak
*
* @param playerId
*/
clearKillstreak(playerId: PlayerId): void
/**
* Whether a lifeform is alive or dead (or on the respawn screen, in a player's case).
*
* @param lifeformId
* @returns
*/
isAlive(lifeformId: LifeformId): boolean
/**
* Send a message to everyone
*
* @param message The text contained within the message. Can use `Custom Text Styling`.
* @param style An optional style argument. Can contain values for fontWeight and color of the message.
* style is ignored if message uses custom text styling (i.e. is not a string)
*/
broadcastMessage(message: string | CustomTextStyling, style?: { fontWeight?: number | string; color?: string }): void
/**
* Send a message to a specific player
*
* @param playerId Id of the player
* @param message The text contained within the message. Can use `Custom Text Styling`.
* @param style An optional style argument. Can contain values for fontWeight and color of the message.
* style is ignored if message uses custom text styling (i.e. is not a string)
*/
sendMessage(playerId: PlayerId, message: string | CustomTextStyling, style?: { fontWeight?: number | string; color?: string }): void
/**
* Send a flying middle message to a specific player
*
* @param playerId Id of the player
* @param message The text contained within the message. Can use `Custom Text Styling`.
* @param distanceFromAction The distance from the action that has caused this message to be displayed, this value
* will be used to determine how the message flies across the screen
*/
sendFlyingMiddleMessage(playerId: PlayerId, message: CustomTextStyling, distanceFromAction: number): void
/**
* Play particle effect on all clients, or only on some clients if clientPredictedBy is specified
* @param opts
* @param clientPredictedBy Play only on clients where client with playerId clientPredictedBy
* is not invisible, transparent, or themselves
*/
playParticleEffect(opts: TempParticleSystemOpts, clientPredictedBy: PlayerId = null): void
/**
* Get the in game name of an entity.
* @param entityId
*/
getEntityName(entityId: EntityId): string
/**
* Given the name of a player, get their id
* @param playerName
*/
getPlayerId(playerName: string): PNull<PlayerId>
/**
* Given a player, get their permanent identifier that doesn't change when leaving and re-entering
*
* @param playerId
*/
getPlayerDbId(playerId: PlayerId): PlayerDbId
/**
* Returns null if player not in lobby
*
* @param dbId
*/
getPlayerIdFromDbId(dbId: PlayerDbId): PNull<PlayerId>
kickPlayer(playerId: PlayerId, reason: string): void
/**
* Check if the block at a specific position is in a loaded chunk.
* @param x
* @param y
* @param z
* @return boolean
*/
isBlockInLoadedChunk(x: number, y: number, z: number): boolean
/**
* Get the name of a block.
* @param x could be an array [x, y, z]. If so, the other params shouldn't be passed.
* @param y
* @param z
* @return blockName - will be a name contained in blockMetadata.ts or 'Air'
*/
getBlock(x: number | number[], y?: number, z?: number): BlockName
/**
* Used to get the block id at a specific position.
* Intended only for use in hot code paths - default to getBlock for most use cases
*
* @param x
* @param y
* @param z
*/
getBlockId(x: number, y: number, z: number): BlockId
/**
* Set a block. Valid names are those either contained in blockMetadata.ts or are 'Air'
*
* This function is optimised for setting broad swathes of blocks. For example, if you have a 50x50x50 area you need to turn to air, it will run performantly if you call this in double nested loops.
*
* IF you're only changing a few blocks, you want this to be super snappy for players, AND you're calling this outside of your _tick function, you can use api.setOptimisations(false).
*
* If you want the optimisations for large quantities of blocks later on, then call api.setOptimisations(true) when you're done.
*
*
*
* @param x Can be an array
* @param y Should be blockname if first param is array
* @param z
* @param blockName
*/
setBlock(x: number | number[], y: number | BlockName, z?: number, blockName?: BlockName): void
/**
* Initiate a block change "by the world".
* This ends up calling the onWorldChangeBlock and only makes the change if not prevented by game/plugins.
* initiatorDbId is null if the change was initiated by the game code.
*
* @param initiatorDbId
* @param x
* @param y
* @param z
* @param blockName
*
* @returns "preventChange" if the change was prevented, "preventDrop" if the change was allowed but without dropping any items, and undefined if the change was allowed with an item drop
*/
attemptWorldChangeBlock(initiatorDbId: PNull<PlayerDbId>, x: number, y: number, z: number, blockName: BlockName): "preventChange" | "preventDrop" | void
/**
* Returns whether a block is solid or not.
* E.g. Grass block is solid, while water, ladder and water are not.
* Will be true if the block is unloaded.
*
* @param x
* @param y
* @param z
*/
getBlockSolidity(x: number | number[], y?: number, z?: number): boolean
/**
* Helper function that sets all blocks in a rectangle to a specific block.
*
* @param pos1 array [x, y, z]
* @param pos2 array [x, y, z]
* @param blockName
*/
setBlockRect(pos1: number[], pos2: number[], blockName: BlockName): void
/**
* Create walls by providing two opposite corners of the cuboid
*
*
* @param pos1 array [x, y, z]
* @param pos2 array [x, y, z]
* @param blockName
* @param hasFloor
* @param hasCeiling
*/
setBlockWalls(pos1: number[], pos2: number[], blockName: BlockName, hasFloor = false, hasCeiling = false): void
/**
* Only use this instead of getBlock if you REALLY need the performance (i.e. you are iterating over tens of thousands of blocks)
* ReturnedObject.blockData is a 32x32x32 ndarray of block ids
* (see https://www.npmjs.com/package/ndarray)
* Each block id is a 16-bit number
* The ndarray should only be read from, writing to it will result in desync between the server and client
*
* @param pos The returned chunk contains pos
* @returns null if the chunk is not loaded in a persisted world. ReturnedObject.blockData is an ndarray that can be accessed
* (but modifications have to be saved with resetChunk).
*/
getChunk(pos: number[]): PNull<GameChunk>
/**
* Use this to get a chunk ndarray you can edit and set in resetChunk.
*
* Only use chunk helpers if you REALLY need the performance (i.e. you are iterating over tens of thousands of blocks)
* ReturnedObject.blockData is a 32x32x32 ndarray of air.
* (see https://www.npmjs.com/package/ndarray)
* Each block id is a 16-bit number
*/
getEmptyChunk(): GameChunk
/**
* Splits the block name by '|'. If no meta info, metaInfo is ''
*
* @param blockName
*/
getMetaInfo(blockName: BlockName | null | undefined): ItemMetaInfo
/**
* Get the numeric id of a block used in the ndarrays returned from getChunk
* I.e. chunk.blockData.set(x, y, z, api.blockNameToBlockId("Dirt"))
* or chunk.blockData.get(x, y, z) === api.blockNameToBlockId("Dirt")
*
* @param blockName
* @param allowInvalidBlock Don't throw an error if the block name is invalid. Defaults false.
* If true and name is invalid, returns null
* @returns
*/
blockNameToBlockId(blockName: string, allowInvalidBlock = false): PNull<number>
/**
* Goes from block id to block name. The reverse of blockNameToBlockId
*
* @param blockId
*/
blockIdToBlockName(blockId: BlockId): BlockName
/**
* Get the unique id of the chunk containing pos in the current map
*
* @param pos
*/
blockCoordToChunkId(pos: number[]): string
/**
* Get the co-ordinates of the block in the chunk with the lowest x, y, and z co-ordinates
*
* @param chunkId
*/
chunkIdToBotLeftCoord(chunkId: string): [number, number, number]
/**
* @deprecated - prefer using other UI elements
* (this UI element hasn't been properly thought through in combination with other elements like killfeed, uirequests, etc)
*
* Send a player an icon in the top right corner
*
* @param playerId
* @param icon Can be any icon from font-awesome.
* @param text The text to send.
* @param opts Can include keys duration, width, height, color, iconSizeMult.
*
* Default opts: {
* duration: 8, // seconds
* width: 400px,
* height: 100px,
* color: 'rgb(102, 102, 102)', // must be rgb in this format (hex not supported),
* iconSizeMult: 5,
* textAndIconColor: "white", // can be any colour supported by css (e.g. hex, rgb),
* fontSize: '17px',
* }
*/
sendTopRightHelper(playerId: PlayerId, icon: string, text: string, opts: {
duration?: number
width?: number
height?: number
color?: string
iconSizeMult?: number
textAndIconColor?: string
fontSize?: string
}): void
/**
* Whether the player is on a mobile device or a computer.
* @param playerId
*/
isMobile(playerId: PlayerId): boolean
/**
* Prevent a player from picking up an item. itemId returned by createItemDrop
*
* @param playerId
* @param itemId
*/
setCantPickUpItem(playerId: PlayerId, itemId: EntityId): void
/**
* Delete an item drop by item drop entity ID
*
* @param itemId
*/
deleteItemDrop(itemId: EntityId): void
/**
* Get the metadata about a block or item before stats have been modified by any client options
* (i.e. its entry in either blockMetadata.ts or nonBlockMetadata in itemMetadata.ts)
*
* @param itemName
*/
getInitialItemMetadata(itemName: string): Partial<BlockMetadataItem & NonBlockMetadataItem>
/**
* Get stat info about a block or item
* Either based on a client option for a player: (e.g. `DirtTtb`)
* or its entry in blockMetadata.ts or nonBlockMetadata in itemMetadata.ts if no client option is set.
*
* If null is passed for playerId, this is simply its entry in blockMetadata etc.
*
*
* @param playerId
* @param itemName
* @param stat
*/
getItemStat<K extends keyof AnyMetadataItem>(playerId: PNull<PlayerId>, itemName: string, stat: K): AnyMetadataItem[K]
/**
* Set the direction the player is looking.
*
* @param playerId
* @param direction a vector of the direction to look, format [x, y, z]
*/
setCameraDirection(playerId: PlayerId, direction: number[]): void
/**
* Set a player's opacity
* A simple helper that calls setTargetedPlayerSettingForEveryone
*
* @param playerId
* @param opacity
*/
setPlayerOpacity(playerId: PlayerId, opacity: number): void
/**
* Set the level of viewable opacity by one player on another player
* A simple helper that calls setOtherEntitySetting
*
* @param playerIdWhoViewsOpacityPlayer The player who sees that with opacity
* @param playerIdOfOpacityPlayer The player/player model who is given opacity
* @param opacity
*/
setPlayerOpacityForOnePlayer(playerIdWhoViewsOpacityPlayer: PlayerId, playerIdOfOpacityPlayer: PlayerId, opacity: number): void
/**
* Obtain Date.now() value saved at start of current game tick
*/
now(): number
/**
* Check your game (and, optionally, a entity) is still valid and executing.
* Useful if you're using async functions and await within your game.
* If you use await/async or promises and do not check this, your game could have closed and then the rest of your
* async code executes.
*
* @param entityId
*/
checkValid(entityId?: PNull<EntityId>): boolean
/**
* Let a player change a block at a specific co-ordinate. Useful when client option canChange is false.
* Overrides blockRect and blockType settings, so also useful when you have disallowed changing of a block type with setCantChangeBlockType.
* Using this on 1000s of blocks will cause lag - if that is needed, find a way to use setCanChangeBlockType.
*
* @param playerId
* @param x
* @param y
* @param z
*/
setCanChangeBlock(playerId: PlayerId, x: number, y: number, z: number): void
/**
* Prevents a player from changing a block at a specific co-ordinate. Useful when client option canChange is true.
* Overrides blockRect and blockType settings, so also useful when you have allowed changing of a block type with setCantChangeBlockType.
* Using this on 1000s of blocks will cause lag - if that is needed, find a way to use setCantChangeBlockType.
*
* @param playerId
* @param x
* @param y
* @param z
*/
setCantChangeBlock(playerId: PlayerId, x: number, y: number, z: number): void
/**
* Lets a player Change a block type. Valid names are those contained within blockMetadata.ts and 'Air'
* Less priority than cant change block pos/can change block rect
*
* @param playerId
* @param blockName
*/
setCanChangeBlockType(playerId: PlayerId, blockName: BlockName): void
/**
* Stops a player from Changeing a block type. Valid names are those contained within blockMetadata.ts and 'Air'
* Less priority than can change block pos/can change block rect
*
* @param playerId
* @param blockName
*/
setCantChangeBlockType(playerId: PlayerId, blockName: BlockName): void
/**
* Remove any previous can/cant change block type settings for a player
*
* @param playerId
* @param blockName
*/
resetCanChangeBlockType(playerId: PlayerId, blockName: BlockName): void
/**
* Make it so a player can Change blocks within two points. Coordinates are inclusive. E.g. if [0, 0, 0] is pos1
* and [1, 1, 1] is pos2 then the 8 blocks contained within low and high will be able to be broken.
* Overrides setCantChangeBlockType
*
*
* @param playerId
* @param pos1 Arg as [x, y, z]
* @param pos2 Arg as [x, y, z]
*/
setCanChangeBlockRect(playerId: PlayerId, pos1: number[], pos2: number[]): void
/**
* Make it so a player cant Change blocks within two points. Coordinates are inclusive. E.g. if [0, 0, 0] is pos1
* and [1, 1, 1] is pos2 then the 8 blocks contained within pos1 and pos2 won't be able to be broken.
* Overrides setCanChangeBlockType
*
*
* @param playerId
* @param pos1 Arg as [x, y, z]
* @param pos2 Arg as [x, y, z]
*/
setCantChangeBlockRect(playerId: PlayerId, pos1: number[], pos2: number[]): void
/**
* Remove any previous can/cant change block rect settings for a player
*
* @param playerId
* @param pos1
* @param pos2
*/
resetCanChangeBlockRect(playerId: PlayerId, pos1: number[], pos2: number[]): void
/**
* Allow a player to walk through a type of block. For blocks that are normally solid and not seethrough, the player will experience slight visual glitches while inside the block.
*
*
* @param playerId
* @param blockName
* @param disable If you've enabled a player to walk through a block and want to make the block solid for them again, pass this with true. Otherwise you only need to pass playerId and blockName
*/
setWalkThroughType(playerId: PlayerId, blockName: BlockName, disable = false): void
/**
* Allow a player to walk through (or not walk through) voxels that are located within a given rectangle.
* For blocks that are normally solid and not seethrough, the player will experience slight visual glitches while inside the block.
*
* You could set both pos1 and pos2 to [0, 0, 0] to make only 0, 0, 0 walkthrough, for example.
*
* @param playerId
* @param pos1 The one corner of the cuboid. Format [x, y, z]
* @param pos2 The top right corner of the cuboid. Format [x, y, z]
* @param updateType The type of update. Whether to make a rect solid, or able to be walked through.
* Pass DEFAULT_WALK_THROUGH with a previously passed rect to disable any walkthrough setting for that rect
*
*/
setWalkThroughRect(playerId: PlayerId, pos1: number[], pos2: number[], updateType: WalkThroughType): void
/**
* Give a player an item and a certain amount of that item.
* Returns the amount of item added to the users inventory.
*
* @param playerId
* @param itemName
* @param itemAmount
* @param attributes An optional object for certain types of item. For guns this can contain the shotsLeft field which is the amount of ammo the gun currently has.
*/
giveItem(playerId: PlayerId, itemName: string, itemAmount?: number, attributes?: ItemAttributes): number
/**
* Whether the player has space in their inventory to get new blocks
* @param playerId
*/
inventoryIsFull(playerId: PlayerId): boolean
/**
* Put an item in a specific index. Default hotbar is indexes 0-9
*
* @param playerId
* @param itemSlotIndex 0-indexed
* @param itemName Can be 'Air', in which case itemAmount will be ignored and the slot will be cleared.
* @param itemAmount -1 for infinity. Should not be set, or null, for items that are not stackable.
* @param attributes An optional object for certain types of item. For guns this can contain the shotsLeft field which is the amount of ammo the gun currently has.
* @param tellClient whether to tell client about it - results in desync between client and server if client doesnt locally perform the same action
*/
setItemSlot(playerId: PlayerId, itemSlotIndex: number, itemName: string, itemAmount?: PNull<number>, attributes?: ItemAttributes, tellClient = true): void
/**
* Remove an amount of item from a player's inventory
*
* @param playerId
* @param itemName
* @param amount
*/
removeItemName(playerId: PlayerId, itemName: string, amount: number): void
/**
* Get the item at a specific index
* Returns null if there is no item at that index
* If there is an item, return an object of the format {name: itemName, amount: amountOfItem}
*
* @param playerId
* @param itemSlotIndex
*/
getItemSlot(playerId: PlayerId, itemSlotIndex: number): PNull<InvenItem>
/**
* Whether a player has an item
*
* @param playerId
* @param itemName
* @returns bool
*/
hasItem(playerId: PlayerId, itemName: string): boolean
/**
* The amount of an itemName a player has.
* Returns 0 if the player has none, and a negative number if infinite.
*
* @param playerId
* @param itemName
* @returns number
*/
getInventoryItemAmount(playerId: PlayerId, itemName: string): number
/**
* Clear the players inventory
*
* @param playerId
*/
clearInventory(playerId: PlayerId): void
/**
* Force the player to have the ith inventory slot selected. E.g. newI 0 makes the player have the 0th inventory slot selected
*
* @param playerId
* @param newI integer from 0-9
*/
setSelectedInventorySlotI(playerId: PlayerId, newI: number): void
/**
* Get a player's currently selected inventory slot
* @param playerId
* @returns
*/
getSelectedInventorySlotI(playerId: PlayerId): any
/**
* Get the currently held item of a player
* Returns null if no item is being held
* If an item is held, return an object of the format {name: itemName, amount: amountOfItem}
*
* @param playerId
*/
getHeldItem(playerId: PlayerId): InvenItem
/**
* Get the amount of free slots in a player's inventory.
*
* @param playerId
* @returns number
*/
getInventoryFreeSlotCount(playerId: PlayerId): number
/**
* Checks if a player is able to open a chest at a given location,
* as per the rules laid out by the "onPlayerAttemptOpenChest" game callback.
* Returns true if the player can open the chest, false if they cannot, and void if the chest does not exist.
*
* @param playerId
* @param chestX
* @param chestY
* @param chestZ
*/
canOpenStandardChest(playerId: PlayerId, chestX: number, chestY: number, chestZ: number): boolean | void
/**
* Give a standard chest an item and a certain amount of that item.
* Returns the amount of item added to the chest.
*
* @param chestPos
* @param itemName
* @param itemAmount
* @param playerId The player who is interacting with the chest.
* @param attributes An optional object for certain types of item. For guns this can contain the shotsLeft field which is the amount of ammo the gun currently has.
*/
giveStandardChestItem(chestPos: readonly number[], itemName: string, itemAmount = 1, playerId?: PlayerId, attributes?: ItemAttributes): number
/**
* Get the amount of free slots in a standard chest
*
* @param chestPos
* @returns number
*/
getStandardChestFreeSlotCount(chestPos: number[]): number
/**
* The amount of an itemName a standard chest has.
* Returns 0 if the standard chest has none, and a negative number if infinite.
*
* @param chestPos
* @param itemName
* @returns number
*/
getStandardChestItemAmount(chestPos: number[], itemName: string): number
/**
* Get the item at a chest slot. Null if empty otherwise format {name: itemName, amount: amountOfItem}
*
* @param chestPos
* @param idx
*/
getStandardChestItemSlot(chestPos: number[], idx: number): InvenItem
/**
* Get all the items from a standard chest in order. Use this instead of repetitive calls to getStandardChestItemSlot
*
* @param chestPos
*/
getStandardChestItems(chestPos: number[]): readonly InvenItem[]
/**
*
* @param chestPos
* @param idx 0-indexed
* @param itemName Can be 'Air', in which case itemAmount will be ignored and the slot will be cleared.
* @param itemAmount -1 for infinity. Should not be set, or null, for items that are not stackable.
* @param playerId The player who is interacting with the chest.
* @param attributes An optional object for certain types of item. For guns this can contain the shotsLeft field which is the amount of ammo the gun currently has.
*/
setStandardChestItemSlot(chestPos: readonly number[], idx: number, itemName: string, itemAmount: number = null, playerId?: PlayerId, attributes?: ItemAttributes): void
/**
* Get the item in a player's moonstone chest slot. Null if empty
*
* Moonstone chests are a type of chest where a player accesses the same contents no matter the location of the moonstone chest
*
* @param playerId
* @param idx
*/
getMoonstoneChestItemSlot(playerId: PlayerId, idx: number): InvenItem
/**
* Get all the items from a moonstone chest in order. Use this instead of repetitive calls to getMoonstoneChestItemSlot
*
* Moonstone chests are a type of chest where a player accesses the same contents no matter the location of the moonstone chest
*
* @param playerId
*/
getMoonstoneChestItems(playerId: PlayerId): readonly InvenItem[]
/**
* Moonstone chests are a type of chest where a player accesses the same contents no matter the location of the moonstone chest
*
* @param playerId
* @param idx 0-indexed
* @param itemName Can be 'Air', in which case itemAmount will be ignored and the slot will be cleared.
* @param itemAmount -1 for infinity. Should not be set, or null, for items that are not stackable.
* @param metadata An optional object for certain types of item. For guns this can contain the shotsLeft field which is the amount of ammo the gun currently has.
*/
setMoonstoneChestItemSlot(playerId: PlayerId, idx: number, itemName: string, itemAmount: number = null, metadata?: ItemAttributes): void
/**
* Get the name of the lobby this game is running in.
*/
getLobbyName(): any
/**
* Integer lobby names are public
* @returns boolean
*/
isPublicLobby(): boolean
/**
* Returns if the current lobby the game is running in is special - e.g. a discord guild or dm, or simply a standard lobby
*/
getLobbyType(): LobbyType
/**
* Update the progress bar in the bottom right corner.
* Can be queued.
*
* @param playerId
* @param toFraction The fraction of the progress bar you want to be filled up.
* @param toDuration The time it takes for the bar to reach the given toFraction in ms.
* If this is too low and you queue multiple updates, this toFraction could be skipped. Treat 200ms as a minimum.
*/
progressBarUpdate(playerId: PlayerId, toFraction: number, toDuration = 200): void
/**
* Edit the crafting recipes for a player
*
* @param playerId
* @param itemName
* @param recipesForItem
*/
editItemCraftingRecipes(playerId: PlayerId, itemName: ItemName, recipesForItem: RecipesForItem): void
/**
* Reset the crafting recipes for a given back to its original bloxd state
*
* @param playerId
* @param itemName
*/
resetItemCraftingRecipes(playerId: PlayerId, itemName: string): void
/**
* Check if a position is within a cubic rectangle
*
* @param coordsToCheck
* @param pos1 position of one corner
* @param pos2 position of opposite corner
* @param addOneToMax
*/
isInsideRect(coordsToCheck: number[], pos1: number[], pos2: number[], addOneToMax = false): boolean
/**
* Get the entities in the rect between [minX, minY, minZ] and [maxX, maxY, maxZ]
*
* @param minCoords
* @param maxCoords
* @returns
*/
getEntitiesInRect(minCoords: number[], maxCoords: number[]): EntityId[]
/**
*
* @param entityId
*/
getEntityType(entityId: EntityId): EntityType
/**
* Create a mob herd. A mob herd represents a collection of mobs that move together.
*/
createMobHerd(): MobHerdId
/**
* Try to spawn a mob into the world at a given position. Returns null on failure.
* WARNING: Either the "onPlayerAttemptSpawnMob" or the "onWorldAttemptSpawnMob" game callback will be called
* depending on whether "spawnerId" is provided. Calling this function inside those callbacks risks infinite recursion.
* @param mobType
* @param x
* @param y
* @param z
* @param opts Includes:
* - mobHerdId The ID of this mob's herd. (A mob herd represents a collection of mobs that move together.)
* - spawnerId The ID of the player who tried to spawn this mob.
* - name If set, gives the mob a name that will be displayed as a nametag above their head.
* - playSoundOnSpawn
* - variation
*/
attemptSpawnMob<TMobType extends MobType>(mobType: TMobType, x: number, y: number, z: number, opts?: Partial<{ mobHerdId: MobHerdId; spawnerId: PlayerId; name: string; playSoundOnSpawn: boolean; variation: MobVariation<TMobType> }>): PNull<MobId>
/**
* Dispose of a mob's state and remove them from the world without triggering "on death" flows.
* @param mobId
*/
despawnMob(mobId: MobId): void
/**
* Get the number of mobs in the world.
*/
getNumMobs(): number
/**
* Get the mob IDs of all mobs in the world.
*/
getMobIds(): MobId[]
/**
* Apply an impulse to an entity
*
* @param eId
* @param xImpulse
* @param yImpulse
* @param zImpulse
*/
applyImpulse(eId: EntityId, xImpulse: number, yImpulse: number, zImpulse: number): void
/**
* Set the velocity of an entity
*
* @param eId
* @param x
* @param y
* @param z
*/
setVelocity(eId: EntityId, x: number, y: number, z: number): void
/**
* Set the heading for a server-auth entity.
*
* @param entityId
* @param newHeading
*/
setEntityHeading(entityId: EntityId, newHeading: number): void
/**
* Spin player in kart
* @param playerId
* @param dir direction of spin, 1 for right, -1 for left
* @param durationInTicks the number of ticks it takes to complete a spin
*/
spinKart(playerId: PlayerId, dir: number, durationInTicks: number): void
/**
* Set the amount of an item in an item entity
*
* @param itemId
* @param newAmount
*/
setItemAmount(itemId: EntityId, newAmount: number): void
/**
* Show a message over the shop in the same place that a shop item's onBoughtMessage is shown.
* Displays for a couple seconds before disappearing
* Use case is to show a dynamic message when player buys an item
*
* @param playerId
* @param info
*/
sendOverShopInfo(playerId: PlayerId, info: string | CustomTextStyling): void
/**
* Open the shop UI for a player
*
* @param playerId
* @param toggle Whether to close the shop if it's already open
* @param forceCategory If set, will change the shop to this category
*/
openShop(playerId: PlayerId, toggle = false, forceCategory: string = null): void
/**
* Apply an effect to a player.
* Can be an inbuilt effect E.g. "Speed" (speed boost), "Damage" (damage boost).
* For inbuilt just pass the name of the effect and the functionality is handled in-engine.
* For custom effect, you pass customEffectInfo. The icon can be an icon from "IngameIcons.ts" or a bloxd item name.
* The custom effect onEndCb is an optional helper within which you can undo the effect you applied.
*
* @param playerId
* @param effectName
* @param duration
* @param customEffectInfo (onEndCb will not work for press to code boards and code blocks)
*/
applyEffect(playerId: PlayerId, effectName: string, duration: number | null, customEffectInfo: { icon?: IngameIconName | ItemName; onEndCb?: () => void; displayName?: string | TranslatedText } & Partial<InbuiltEffectInfo>): void
/**
* Get all the effects currently applied to a player
*
* @param playerId
*/
getEffects(playerId: PlayerId): string[]
/**
* Remove an effect from a player.
*
* @param playerId
* @param name
*/
removeEffect(playerId: PlayerId, name: string): void
/**
* Change a part of a player's skin
* @param playerId
* @param partType
* @param selected
*/
changePlayerIntoSkin(playerId: PlayerId, partType: CustomisationPart, selected: string): void
/**
* Remove gamemode-applied skin from a player
* @param playerId
*/
removeAppliedSkin(playerId: PlayerId): void
/**
* Scale node of a player's mesh by 3d vector.
* State from prior calls to this api is lost so if you want to have multiple nodes scaled, pass in all the scales at once.
*
* @param playerId
* @param nodeScales
*/
scalePlayerMeshNodes(playerId: PlayerId, nodeScales: EntityMeshScalingMap): void
/**
* Attach/detach mesh instances to/from an entity
* @param eId
* @param node node to attach to
* @param type if null, detaches mesh from this node
* @param opts
* @param offset
* @param rotation
*/
updateEntityNodeMeshAttachment<MeshType extends MeshEntityType>(eId: EntityId, node: EntityNamedNode, type: PNull<MeshType>, opts?: MeshEntityOpts[MeshType], offset: number[] = [0, 0, 0], rotation = [0, 0, 0]): void
/**
* Set the pose of the player
* @param playerId
* @param pose
*/
setPlayerPose(playerId: PlayerId, pose: PlayerPose): void
/**
* Set physics state of player (vehicle type and tier)
* @param playerId
* @param physicsState
*/
setPlayerPhysicsState(playerId: PlayerId, physicsState: PlayerPhysicsStateData): void
/**
* Get physics state for player
* @param playerId
*/
getPlayerPhysicsState(playerId: PlayerId): PlayerPhysicsStateData
/**
* Add following entity to player
* @param playerId
* @param eId
* @param offset
*/
addFollowingEntityToPlayer(playerId: PlayerId, eId: EntityId, offset?: number[]): void
/**
* Remove following entity from player
* @param playerId
* @param entityEId
*/
removeFollowingEntityFromPlayer(playerId: PlayerId, entityEId: EntityId): void
/**
* Set camera zoom for a player
* @param playerId
* @param zoom
*/
setCameraZoom(playerId: PlayerId, zoom: number): void
/**
*
*
* @param playerId hears the sound
* @param soundName Can also be a prefix. If so, a random sound with that prefix will be played
* @param volume 0-1. If it's too quiet and volume is 1, normalise your sound in audacity
* @param rate The speed of playback. Also affects pitch. 0.5-4. Lower playback = lower pitch
* Good for varying the sound. E.g. item pickup sound has a random rate between 1 and 1.5
* @param posSettings
* {playerIdOrPos: PlayerId | number[], maxHearDist: number, refDistance: number}
* playerIdOrPos: The player the sound originates from, or the position of the sound
* maxHearDist: sound is not played if player is further than this. Default 15
* refDistance: higher means the sound decreases less in volume with distance. Default 3. Hitting is 4. Guns are 10
*
*/
playSound(playerId: PlayerId, soundName: string, volume: number, rate: number, posSettings?: {
playerIdOrPos: PlayerId | number[]
maxHearDist?: number
refDistance?: number
}): void
// See documentation for api.playSound
broadcastSound(soundName: string, volume: number, rate: number, posSettings?: {
playerIdOrPos: PlayerId | number[]
maxHearDist?: number
refDistance?: number
}, exceptPlayerId: PlayerId = null): void
// See documentation for api.playSound
playClientPredictedSound(soundName: string, volume: number, rate: number, posSettings?: {
playerIdOrPos: PlayerId | number[]
maxHearDist?: number
refDistance?: number
}, predictedBy?: PlayerId): void
calcExplosionForce(eId: EntityId, explosionType: ExplosionType, knockbackFactor: number, explosionRadius: number, explosionPos: number[], ignoreProjectiles: boolean): { force: Pos; forceFrac: number; }
/**
* Get the position of a player's target block and the block adjacent to it (e.g. where a block would be placed)
*
*
* Note: This position is a tick ahead of the client's block target info (noa.targetedBlock),
* since the client updates the blocktarget before the entities tick (and since it uses the renderposition of the camera)
*
* This normally doesn't matter but if you are client predicting something based on noa.targetedBlock
* (currently only applicable to in-engine code), you should not verify using this
*
* @param playerId
*/
getPlayerTargetInfo(playerId: PlayerId): { position: Pos; normal: Pos; adjacent: Pos }
/**
* Get the position of a player's camera and the direction (both in Euclidean and spherical coordinates) they are attempting to use an item.
* The camPos has the same limitations described in getPlayerTargetInfo
*
* @param playerId
*/
getPlayerFacingInfo(playerId: PlayerId): { camPos: Pos; dir: Pos; angleDir: AngleDir; moveHeading: number }
/**
* Raycast for a block in the world.
* Given a position and a direction, find the first block that the "ray" hits.
*
* @param fromPos
* @param dirVec
*/
raycastForBlock(fromPos: number[], dirVec: number[]): BlockRaycastResult
/**
* Check whether a player is crouching
*
* @param playerId
*/
isPlayerCrouching(playerId: PlayerId): any
```
## Glossary of Referenced Types
These 'types' can't be referenced by your code, but they help explain some of the parameters in the API.
```ts
type CustomTextStyling = (string | EntityName | TranslatedText | StyledIcon | StyledText)[]
type EntityMeshScalingMap = { [key in "TorsoNode" | "HeadMesh" | "ArmRightMesh" | "ArmLeftMesh" | "LegLeftMesh" | "LegRightMesh"]?: number[] }
type EntityName = {
entityName: string
style?: {
color?: string
colour?: string
}
}
type IngameIconName = "Damage" | "Damage Reduction" | "Speed" | "VoidJump" | "Fist" | "Frozen" | "Hydrated" | "Invisible" | "Jump Boost" | "Poisoned" | "Slowness" | "Weakness" | "Health Regen" | "Haste" | "Heat Resistance" | "Gliding" | "Boating" | "Obsidian Boating" | "Bunny Hop" | "FallDamage" | "Feather Falling"
enum ParticleSystemBlendMode {
// Source color is added to the destination color without alpha affecting the result
OneOne = 0,
// Blend current color and particle color using particle’s alpha
Standard = 1,
// Add current color and particle color multiplied by particle’s alpha
Add,
// Multiply current color with particle color
Multiply,
// Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
MultiplyAdd,
}
type RecipesForItem = {
requires: { items: string[]; amt: number }[]
produces: number
station?: string | string[]
}[]
type StyledIcon = {
icon: string
style?: {
color?: string
colour?: string
fontSize?: string
opacity?: number
}
}
type StyledText = {
str: string | EntityName | TranslatedText
style?: {
color?: string
colour?: string
fontWeight?: string
fontSize?: string
fontStyle?: string
opacity?: number
}
clickableUrl?: string
}
type TempParticleSystemOpts = {
texture: string
minLifeTime: number
maxLifeTime: number
minEmitPower: number
maxEmitPower: number
minSize: number
maxSize: number
gravity: number[]
velocityGradients: {
timeFraction: number
factor: number
factor2: number
}[]
colorGradients: {
timeFraction: number
minColor: [number, number, number, number]
maxColor?: [number, number, number, number]
}[] | {
color: [number, number, number]
}[]
blendMode: ParticleSystemBlendMode
dir1: number[]
dir2: number[]
pos1: number[]
pos2: number[]
manualEmitCount: number
hideDist?: number
}
type TranslatedText = {
translationKey: string
params?: Record<string, string | number | boolean | EntityName>
}
type ItemAttributes = { customDisplayName?: string; customDescription?: string; customAttributes?: Record<string, any> }
```Callbacks
# Callbacks
Players can use World Code in custom worlds get functions they've written to run when game events happen. These special functions are called callbacks. The world code can be viewed by pressing F8 by default. Initially the world code will have this comment, which can be removed:
```text
tick onClose onPlayerJoin onPlayerLeave onPlayerJump onRespawnRequest
playerCommand onPlayerChat onPlayerChangeBlock onPlayerDropItem
onPlayerPickedUpItem onPlayerSelectInventorySlot onBlockStand onPlayerCraft
onPlayerAttemptOpenChest onPlayerOpenedChest onPlayerMoveItemOutOfInventory
onPlayerMoveInvenItem onPlayerMoveItemIntoIdxs onPlayerSwapInvenSlots
onPlayerMoveInvenItemWithAmt onPlayerAttemptAltAction onPlayerAltAction
onPlayerClick onClientOptionUpdated onInventoryUpdated onChestUpdated
onWorldChangeBlock onCreateBloxdMeshEntity onEntityCollision
onPlayerAttemptSpawnMob onWorldAttemptSpawnMob onPlayerSpawnMob
onWorldSpawnMob onMobDespawned onPlayerAttack onPlayerDamagingOtherPlayer
onPlayerDamagingMob onPlayerKilledOtherPlayer onMobKilledPlayer
onPlayerKilledMob onPlayerPotionEffect onPlayerDamagingMeshEntity
onPlayerBreakMeshEntity onPlayerUsedThrowable onPlayerThrowableHitTerrain
onTouchscreenActionButton onTaskClaimed onChunkLoaded onPlayerRequestChunk
onItemDropCreated onPlayerStartChargingItem onPlayerFinishChargingItem
doPeriodicSave
To use a callback, just assign a function to it in the world code!
tick = () => {} or function tick() {}
```
Right now callbacks written by players will have their return values ignored (treated as undefined). The LoadedChunk argument which is normally passed to onChunkLoaded will also always be null.
```ts
/**
* Called every tick, 20 times per second
* @param dt - The time since the last tick in milliseconds
*/
tick: (dt) => {}
/**
* Called when the lobby is shutting down
* @param serverIsShuttingDown - Whether the server is shutting down
*/
onClose: (serverIsShuttingDown) => {}
/**
* Called when a player joins the lobby
* @param playerId - The id of the player that joined
*/
onPlayerJoin: (playerId) => {}
/**
* Called when a player leaves the lobby
* @param playerId - The id of the player that left
* @param serverIsShuttingDown - Whether the server is shutting down
*/
onPlayerLeave: (playerId, serverIsShuttingDown) => {}
/**
* Called when a player jumps
* @param playerId - The id of the player that jumped
*/
onPlayerJump: (playerId) => {}
/**
* Called when a player requests to respawn.
* Optionally return the respawn location. Defaults to [0, 0, 0].
* Return true to handle yourself (good for async,
* but be careful that the player isn't at the place they died,
* as they could pick up their old items or hit the player they were fighting).
* @param playerId - The id of the player that requested to respawn
*/
onRespawnRequest: (playerId) => {}
/**
* Called when a player sends a command
* @param playerId - The id of the player that sent the command
* @param command - The command that the player sent
*/
playerCommand: (playerId, command) => {
return false
}
/**
* Called when a player sends a chat message
* Return false to prevent the broadcast of the message.
* Return CustomTextStyling to add a prefix to message.
* Return for most flexibility: an object where keys are playerIds -
* the value for a playerId being false means that player won't receive the message.
* Otherwise playerId values should be an object with (optional) keys
* prefixContent and chatContent to modify the prefix and the chat.
* @param playerId - The id of the player that sent the message
* @param chatMessage - The message that the player sent
* @param channelName - The name of the channel that the message was sent in
*/
onPlayerChat: (playerId: PlayerId, chatMessage: string, channelName?: string) => {
return true
}
/**
* Called when a player changes a block
* Return "preventChange" to prevent the change.
* If player places block, fromBlock will be Air (and toBlock the block).
* If a player breaks a block, toBlock will be Air.
* Return "preventDrop" to prevent a block item from dropping.
* Return an array to set the dropped item position.
*/
onPlayerChangeBlock: (
playerId: PlayerId, // The id of the player that changed the block
x: number, // The x coordinate of the block that was changed
y: number, // The y coordinate of the block that was changed
z: number, // The z coordinate of the block that was changed
fromBlock: BlockName, // The old block that was replaced
toBlock: BlockName, // The new block that was placed
droppedItem: BlockName | null, // The item that was dropped
fromBlockInfo: MultiBlockInfo, // The info of the old block that was replaced
toBlockInfo: MultiBlockInfo, // The info of the new block that was placed
) => {}
/**
* Called when a player drops an item
* Return "preventDrop" to prevent the player from dropping the item at all.
* Return "allowButNoDroppedItemCreated" to allow discarding items without dropping them.
*/
onPlayerDropItem: (
playerId: PlayerId, // The id of the player that dropped the item
x: number, // The x coordinate of the item that was dropped
y: number, // The y coordinate of the item that was dropped
z: number, // The z coordinate of the item that was dropped
itemName: ItemName, // The name of the item that was dropped
itemAmount: number, // The amount of the item that was dropped
fromIdx: number, // The index of the item that was dropped from the player's inventory
) => {}
/**
* Called when a player picks up an item
* @param playerId - The id of the player that picked up the item
* @param itemName - The name of the item that was picked up
* @param itemAmount - The amount of the item that was picked up
*/
onPlayerPickedUpItem: (playerId: PlayerId, itemName: string, itemAmount: number) => {}
/**
* Called when a player selects a different inventory slot.
* This will be called eventually when you have already set the slot using
* api.setSelectedInventorySlotI so be careful not to cause an infinite loop doing this.
* @param playerId - The id of the player that selected the inventory slot
* @param slotIndex - The index of the inventory slot that was selected
*/
onPlayerSelectInventorySlot: (playerId: PlayerId, slotIndex: number) => {}
/**
* Called when a player stands on a block
*/
onBlockStand: (
playerId: PlayerId, // The id of the player that stood on the block
x: number, // The x coordinate of the block that was stood on
y: number, // The y coordinate of the block that was stood on
z: number, // The z coordinate of the block that was stood on
blockName: BlockName, // The name of the block that was stood on
) => {}
/**
* Called when a player crafts an item
* Return "preventCraft" to prevent a craft from happening
* @param playerId - The id of the player that crafted the item
* @param itemName - The name of the item that was crafted
* @param craftingIdx - The index of the used recipe in the item's recipe list
*/
onPlayerCraft: (playerId: PlayerId, itemName: string, craftingIdx: number) => {}
/**
* Called when a player attempts to open a chest
* Return "preventOpen" to prevent the player from opening the chest
*/
onPlayerAttemptOpenChest: (
playerId: PlayerId, // The id of the player that is attempting to open the chest
x: number, // The x coordinate of the chest that the player is attempting to open
y: number, // The y coordinate of the chest that the player is attempting to open
z: number, // The z coordinate of the chest that the player is attempting to open
isMoonstoneChest: boolean, // Whether the chest is a moonstone chest
) => {}
/**
* Called when a player opens a chest
*/
onPlayerOpenedChest: (
playerId: PlayerId, // The id of the player that opened the chest
x: number, // The x coordinate of the chest that was opened
y: number, // The y coordinate of the chest that was opened
z: number, // The z coordinate of the chest that was opened
isMoonstoneChest: boolean, // Whether the chest is a moonstone chest
) => {}
/**
* Called when a player moves an item out of their inventory
* Return "preventChange" to prevent the movement
*/
onPlayerMoveItemOutOfInventory: (
playerId: PlayerId, // The id of the player moving the item
itemName: string, // The name of the item being moved
itemAmount: number, // The amount of the item being moved
fromIdx: number, // The index which the item is being moved from
movementType: string, // The type of movement that occurred
) => {}
/**
* Called for all types of inventory item movement.
* Certain methods of moving item can result in splitting a stack
* into multiple slots. (e.g. shift-click).
* toStartIdx and toEndIdx provide the min and max idxs moved into.
* Return "preventChange" to prevent item movement.
*/
onPlayerMoveInvenItem: (
playerId: PlayerId, // The id of the player moving the item
fromIdx: number, // The index that the item is being moved from
toStartIdx: number, // The start index that the item is being moved into
toEndIdx: number, // The end index that the item is being moved into
amt: number, // The amount of the item being moved
) => {}
/**
* Called when a player moves an item into an index within a range of inventory slots
* Return "preventChange" to prevent the movement
*/
onPlayerMoveItemIntoIdxs: (
playerId: PlayerId, // The id of the player moving the item
start: number, // The start index of the range
end: number, // The end index of the range
moveIdx: number, // The index of the item being moved
itemAmount: number, // The amount of the item being moved
) => {}
/**
* Return "preventChange" to prevent the swap
* @param playerId - The id of the player swapping the inventory slots
* @param i - The index of the first slot
* @param j - The index of the second slot
*/
onPlayerSwapInvenSlots: (playerId: PlayerId, i: number, j: number) => {}
/**
* Return "preventChange" to prevent the movement
* @param playerId - The id of the player moving the item
* @param i - The index of the first slot
* @param j - The index of the second slot
* @param amt - The amount of the item being moved
*/
onPlayerMoveInvenItemWithAmt: (playerId: PlayerId, i: number, j: number, amt: number) => {}
/**
* Called when player alt actions (right click on pc).
* The co-ordinates will be undefined if there is no targeted block (and block will be "Air")
*/
onPlayerAttemptAltAction: (
playerId: PlayerId, // The id of the player attempting the alt action
x: number, // The x coordinate of the targeted block
y: number, // The y coordinate of the targeted block
z: number, // The z coordinate of the targeted block
block: BlockName, // The name of the targeted block
targetEId: EntityId | null, // The id of the targeted entity
) => {}
/**
* Called when player completes an alt action (right click on pc).
* The co-ordinates will be undefined if there is no targeted block (and block will be "Air")
*/
onPlayerAltAction: (
playerId: PlayerId, // The id of the player completing the alt action
x: number, // The x coordinate of the targeted block
y: number, // The y coordinate of the targeted block
z: number, // The z coordinate of the targeted block
block: BlockName, // The name of the targeted block
targetEId: EntityId | null, // The id of the targeted entity
) => {}
/**
* Called when a player clicks
* Don't have important functionality depending on wasAltClick,
* as it'll always be false for touchscreen players.
*/
onPlayerClick: (
playerId: PlayerId, // The id of the player clicking
wasAltClick: boolean, // Whether the click was an alt click (e.g. right click)
) => {}
/**
* Called when a client option is updated
* @param playerId - The id of the player whose option was updated
* @param option - The option that was updated
* @param value - The new value of the option
*/
onClientOptionUpdated: (playerId: PlayerId, option: ClientOption, value: any) => {}
/**
* Called when a player's inventory is updated
* @param playerId - The id of the player whose inventory was updated
*/
onInventoryUpdated: (playerId: PlayerId) => {}
/**
* Called when a chest is updated by a player
* x, y, z, will be null if isMoonstoneChest is true
*/
onChestUpdated: (
initiatorEId: PlayerId, // The id of the player who updated the chest
isMoonstoneChest: boolean, // Whether the chest is a moonstone chest
x: number | null, // The x coordinate of the chest
y: number | null, // The y coordinate of the chest
z: number | null, // The z coordinate of the chest
) => {}
/**
* Called when a block is changed in the world
* initiatorDbId is null if updated by game code e.g. when a sapling grows
* Return "preventChange" to prevent change
* Return "preventDrop" to prevent a block item from dropping
*/
onWorldChangeBlock: (
x: number, // The x coordinate of the block
y: number, // The y coordinate of the block
z: number, // The z coordinate of the block
fromBlock: BlockName, // The old block that was replaced
toBlock: BlockName, // The new block that was placed
initiatorDbId: string | null, // The id of the player who updated the block
) => {}
/**
* Called when a mesh entity is created
* @param eId - The id of the mesh entity
* @param type - The type of mesh entity
*/
onCreateBloxdMeshEntity: (eId: EntityId, type: string) => {}
/**
* Called when a entity collides with another entity
* @param eId - The id of the entity
* @param otherEId - The id of the other entity
*/
onEntityCollision: (eId: EntityId, otherEId: EntityId) => {}
/**
* Called when a player attempts to spawn a mob, e.g. using a spawn orb.
* Return "preventSpawn" to prevent the mob from spawning.
*/
onPlayerAttemptSpawnMob: (
playerId: PlayerId, // The id of the player
mobType: MobType, // The type of mob
x: number, // The potential x coordinate of the mob
y: number, // The potential y coordinate of the mob
z: number, // The potential z coordinate of the mob
) => {}
/**
* Called when the world attempts to spawn a mob.
* Return "preventSpawn" to prevent the mob from spawning.
* @param mobType - The type of mob
* @param x - The potential x coordinate of the mob
* @param y - The potential y coordinate of the mob
* @param z - The potential z coordinate of the mob
*/
onWorldAttemptSpawnMob: (mobType: MobType, x: number, y: number, z: number) => {}
/**
* Called when a mob is spawned by a player
*/
onPlayerSpawnMob: (
playerId: PlayerId, // The id of the player who spawned the mob
mobId: MobId, // The id of the mob
mobType: MobType, // The type of mob
x: number, // The x coordinate of the mob
y: number, // The y coordinate of the mob
z: number, // The z coordinate of the mob
mobHerdId: MobHerdId, // The herd id of the mob
playSoundOnSpawn: boolean, // Whether to play a sound on spawn
) => {}
/**
* Called when a mob is spawned by the world
*/
onWorldSpawnMob: (
mobId: MobId, // The id of the mob
mobType: MobType, // The type of mob
x: number, // The x coordinate of the mob
y: number, // The y coordinate of the mob
z: number, // The z coordinate of the mob
mobHerdId: MobHerdId, // The herd id of the mob
playSoundOnSpawn: boolean, // Whether to play a sound on spawn
) => {}
/**
* Called when a mob is despawned
* @param mobId - The id of the mob despawned
*/
onMobDespawned: (mobId: MobId) => {}
/**
* Called when a player attacks another player
* @param playerId - The id of the player attacking
*/
onPlayerAttack: (playerId) => {}
/**
* Called when a player is damaging another player
* Return "preventDamage" to prevent damage
* Return number to change damage dealt to that amount
* Sometimes the damager will have left the game (e.g. spikes placer);
* in this case, attackingPlayer will be the damagedPlayer,
* but we pass damagerDbId for use cases where it's important.
*/
onPlayerDamagingOtherPlayer: (
attackingPlayer: PlayerId, // The id of the player attacking
damagedPlayer: PlayerId, // The id of the player being damaged
damageDealt: number, // The amount of damage dealt
withItem: string, // The item used to attack
bodyPartHit: PlayerBodyPart, // The body part hit
damagerDbId: PlayerDbId, // The database id of the player attacking
) => {}
/**
* Called when a player is damaging a mob
*/
onPlayerDamagingMob: (
playerId: PlayerId, // The id of the player damaging the mob
mobId: MobId, // The id of the mob being damaged
damageDealt: number, // The amount of damage dealt
withItem: string, // The item used to attack
) => {}
/**
* Called when a player kills another player
* Return "keepInventory" to not drop the player's inventory
* @param attackingPlayer - The id of the player attacking
* @param killedPlayer - The id of the player killed
* @param damageDealt - The amount of damage dealt
* @param withItem - The item used to attack
*/
onPlayerKilledOtherPlayer: (attackingPlayer, killedPlayer, damageDealt, withItem) => {}
/**
* Called when a mob kills a player
* Return "keepInventory" to not drop the player's inventory
* @param attackingMob - The id of the mob attacking
* @param killedPlayer - The id of the player killed
* @param damageDealt - The amount of damage dealt
* @param withItem - The item used to attack
*/
onMobKilledPlayer: (attackingMob, killedPlayer, damageDealt, withItem) => {}
/**
* Called when a mob kills a player
* Return "preventDrop" to prevent the mob from dropping items
*/
onPlayerKilledMob: (
playerId: PlayerId, // The id of the player killed
mobId: MobId, // The id of the mob that killed the player
damageDealt: number, // The amount of damage dealt
withItem: string, // The item used to attack
) => {}
/**
* Called when a player is affected by a new potion effect
* @param initiatorId - The id of the player who initiated the potion effect
* @param targetId - The id of the player who has started being affected
* @param effectName - The name of the potion effect
*/
onPlayerPotionEffect: (initiatorId, targetId, effectName) => {}
/**
* Called when a player is damaging a mesh entity
*/
onPlayerDamagingMeshEntity: (
playerId: PlayerId, // The id of the player damaging the mesh entity
damagedId: EntityId, // The id of the mesh entity being damaged
damageDealt: number, // The amount of damage dealt
withItem: string, // The item used to attack
) => {}
/**
* Called when a player breaks a mesh entity
* @param playerId - The id of the player breaking the mesh entity
* @param entityId - The id of the mesh entity being broken
*/
onPlayerBreakMeshEntity: (playerId: PlayerId, entityId: EntityId) => {}
/**
* Called when a player uses a throwable item
*/
onPlayerUsedThrowable: (
playerId: PlayerId, // The id of the player using the throwable item
throwableName: ThrowableItem, // The name of the throwable item
thrownEntityId: EntityId, // The id of the projectile created by the player
) => {}
/**
* Called when a player's thrown projectile hits the terrain
*/
onPlayerThrowableHitTerrain: (
playerId: PlayerId, // The id of the player that threw the throwable item
throwableName: ThrowableItem, // The name of the throwable item
thrownEntityId: EntityId, // The id of the entity which hit the terrain
) => {}
/**
* Set client option `touchscreenActionButton` to take effect
* Called when a player presses the touchscreen action button
* Called for both touchDown and touchUp
* @param playerId - The id of the player pressing the touchscreen action button
* @param touchDown - Whether the touchscreen action button was pressed or released
*/
onTouchscreenActionButton: (playerId: PlayerId, touchDown: boolean) => {}
/**
* Called when a player claims a task
* @param playerId - The id of the player claiming the task
* @param taskId - The id of the task being claimed
* @param isPromoTask - Whether the task is a promo task
* @param claimedRewards - The rewards claimed by the player
*/
onTaskClaimed: (playerId, taskId, isPromoTask, claimedRewards) => {}
/**
* Called when a chunk is first loaded
* @param chunkId - The id of the chunk being loaded
* @param chunk - The chunk being loaded, which can be modified by this callback
* @param wasPersistedChunk - Whether the chunk was persisted
*/
onChunkLoaded: (chunkId: string, chunk: LoadedChunk, wasPersistedChunk: boolean) => {}
/**
* Called when a player requests a chunk
*/
onPlayerRequestChunk: (
playerId: PlayerId, // The id of the player requesting the chunk
chunkX: number, // The x coordinate of the chunk being requested
chunkY: number, // The y coordinate of the chunk being requested
chunkZ: number, // The z coordinate of the chunk being requested
chunkId: string, // The id of the chunk being requested
) => {}
/**
* Called when an item drop is created
*/
onItemDropCreated: (
itemEId: EntityId, // The id of the item drop
itemName: string, // The name of the item dropped
itemAmount: number, // The amount dropped
x: number, // The x coordinate of the item drop
y: number, // The y coordinate of the item drop
z: number, // The z coordinate of the item drop
) => {}
/**
* Called when a player starts charging an item
* @param playerId - The id of the player charging the item
* @param itemName - The name of the item being charged
*/
onPlayerStartChargingItem: (playerId: PlayerId, itemName: string) => {}
/**
* Called when a player finishes charging an item
*/
onPlayerFinishChargingItem: (
playerId: PlayerId, // The id of the player charging the item
used: boolean, // Whether the item was used
itemName: string, // The name of the charged item
duration: number, // The duration of the charge
) => {}
/**
* Called every so often.
* You should save custom db values/s3 objects here.
* Persisted items ARE saved on graceful shutdown (e.g. uncaught error, update, etc),
* but this helps prevent large data-loss on non-graceful shutdowns.
*/
doPeriodicSave: () => {}
```SoundNames
# Sound Names
- These are the strings you can give to functions that take a `soundName` as input
- If you want a random similar sound then you can remove the number from the sound name of your choice
- If a sound isn't working then there might be an error in your console explaining why
`beep`
`bow`
`bucketEmpty1`
`bucketEmpty2`
`bucketEmpty3`
`bucketFill1`
`bucketFill2`
`bucketFill3`
`bullet_shell_bounce_general_07`
`bullet_shell_bounce_general_08`
`burp`
`cannonFire1`
`cannonFire2`
`cannonFire3`
`cashRegister`
`caveGolem1`
`caveGolem2`
`caveGolem3`
`caveGolem4`
`chestClose`
`chestOpen`
`cloth1`
`cloth2`
`cloth3`
`cloth4`
`cowMoo1`
`cowMoo2`
`cowMoo3`
`doorClose`
`doorClose2`
`doorOpen-bloxd1`
`doorOpen-bloxd2`
`drink`
`eat1`
`equip_leather1`
`fallsmall`
`glass1`
`glass2`
`glass3`
`grass1`
`grass2`
`grass3`
`grass4`
`gravel1`
`gravel2`
`gravel3`
`gravel4`
`headshot_04`
`headshot_06`
`headshot_08`
`headshot_11`
`hit1`
`hit2`
`hit3`
`hoeTill1`
`hoeTill2`
`hoeTill3`
`hoeTill4`
`pickUp`
`pigOink1`
`pigOink2`
`pigOink3`
`pigOink4`
`pigOink5`
`pistol_cock_01`
`pistol_cock_02`
`pistol_cock_03`
`pistol_cock_06`
`pistol_magazine_load_01`
`pistol_magazine_load_02`
`pistol_magazine_load_03`
`pistol_magazine_unload_01`
`pistol_magazine_unload_02`
`pistol_magazine_unload_03`
`pistol_shot_01`
`pistol_shot_02`
`pistol_shot_03`
`pistol_shot_04`
`pistol_shot_05`
`rifle_cock_01`
`rifle_cock_02`
`rifle_magazine_load_01`
`rifle_magazine_load_02`
`rifle_magazine_load_03`
`rifle_magazine_unload_01`
`rifle_magazine_unload_02`
`rifle_magazine_unload_04`
`rifle_shot_01`
`rifle_shot_02`
`rifle_shot_03`
`rifle_shot_04`
`sand1`
`sand2`
`sand3`
`sand4`
`semiAuto_cock_01`
`semiAuto_cock_02`
`semiAuto_cock_03`
`semiAuto_cock_04`
`semiAuto_cock_05`
`semiAuto_first_shot_01`
`semiAuto_magazine_load_01`
`semiAuto_magazine_load_02`
`semiAuto_magazine_load_03`
`semiAuto_magazine_load_04`
`semiAuto_magazine_load_05`
`semiAuto_magazine_unload_01`
`semiAuto_magazine_unload_02`
`semiAuto_magazine_unload_03`
`semiAuto_magazine_unload_04`
`semiAuto_shot_01`
`semiAuto_shot_02`
`semiAuto_shot_03`
`semiAuto_shot_04`
`semiAuto_shot_05`
`semiAuto_shot_06`
`semiAuto_shot_07`
`semiAuto_shot_08`
`semiAuto_tail_only_shot_01`
`sheepBaa1`
`sheepBaa2`
`sheepBaa3`
`sheepBaa4`
`shotgun_cock_01`
`shotgun_cock_02`
`shotgun_cock_03`
`shotgun_cock_04`
`shotgun_cock_05`
`shotgun_load_bullet_01`
`shotgun_load_bullet_02`
`shotgun_load_bullet_03`
`shotgun_load_bullet_04`
`shotgun_load_bullet_05`
`shotgun_load_bullet_06`
`shotgun_load_bullet_07`
`shotgun_load_bullet_08`
`shotgun_shot_01`
`shotgun_shot_02`
`shotgun_shot_03`
`shotgun_shot_04`
`snow1`
`snow2`
`snow3`
`snow4`
`splash1`
`step_cloth1`
`step_cloth2`
`step_cloth3`
`step_cloth4`
`step_grass1`
`step_grass2`
`step_grass3`
`step_grass4`
`step_grass5`
`step_gravel1`
`step_gravel2`
`step_gravel3`
`step_gravel4`
`step_sand2`
`step_sand3`
`step_sand4`
`step_sand5`
`step_snow1`
`step_snow2`
`step_snow3`
`step_snow4`
`step_stone1`
`step_stone2`
`step_stone3`
`step_stone4`
`step_stone5`
`step_stone6`
`step_wood1`
`step_wood2`
`step_wood3`
`step_wood4`
`step_wood5`
`step_wood6`
`stone1`
`stone2`
`stone3`
`stone4`
`submachine_cock_01`
`submachine_cock_02`
`submachine_cock_03`
`submachine_cock_04`
`submachine_first_shot_01`
`submachine_magazine_load_01`
`submachine_magazine_load_02`
`submachine_magazine_load_03`
`submachine_magazine_load_04`
`submachine_magazine_unload_01`
`submachine_magazine_unload_02`
`submachine_magazine_unload_03`
`submachine_shot_01`
`submachine_shot_02`
`submachine_shot_03`
`submachine_shot_04`
`submachine_shot_05`
`submachine_shot_06`
`submachine_shot_07`
`submachine_shot_08`
`submachine_shot_09`
`submachine_tail_only_shot_01`
`successfulBowHit`
`sweep6`
`trapdoorOpen`
`wood1`
`wood2`
`wood3`
`wood4`
`ZombieGrunt1`
`ZombieGrunt2`
`ZombieGrunt3`
`ZombieHurt1`
`ZombieHurt2`
`ZombieHurt3`
`ZombieHurt4`页面版本: 2, 最后编辑于: 19 Apr 2025 07:39