#Script API General
1 messages Β· Page 54 of 1
const durabilityComp = item.getComponent("minecraft:durability");
durabilityComp.damage = 0; // Fully repair the item
this is what i am trying to do
oh so how to change it to write mode?
error
this is line 42
durabilityComp.damage = 0;
^^
I'm so tempted to add an article about readonly and early execution mode on my docs
you should add
is that my docs or someone elses
how do i change the damge
r u setting it back 2 the inventory after u do the damage
i think like
const item = container.getItem() // gets the item
const component = item.getComponent(...) // get component
container.setItem(slot, item) // set it back
You have to set the item back
yeah
ohh
cuz I think it just makes a copied edited version of the item and doesn't actually edit the original
const inventory = player.getComponent("minecraft:inventory").container;
const itemx = inventory.getSlot(player.selectedSlotIndex);
const item = itemx.getItem()
durabilityComp.damage = 0; // Fully repair the item
inventory.setItem(itemx, item)
``` this is what i did
not working
where the getComponent
inventory.setItem(player.selectedSlotIndex, item)
what happens if u do inventory.addItem() but the inventory is full?
i would but im playing tho
fair
ya if i was playing alone then i would creeate new world and test but
is it a realm or smthn?
it return itemStack
let say you have half a stack empty, and you tried to add a stack of the same item.
the function will add half a stack and return the rest
so you will ideally do
const item = container.addItem(...)
if(item) dimension.spawnItem(item, loc)
Is there an event listener to listen to gamerule change ?
gameRuleChange
yes
world.afterEvents.gameRuleChange.subscribe(({ ruleId, value }) => {
});```
Documentation for @minecraft/server


i see someone changed his Docs preferences
these are the docs ive been suggesting for awhile now.
Example ?
just create an if statement
I didn't notice
thought you are using jaylys
Ah i see
no
d u have the latest beta version? so i can test it out on multiplayer.
give me a sec to update
E
const inventory = Block.getComponent('inventory').container;
const item = inventory.getItem(2)```
Doesn't work?
I dont know how to possibly come up with a master plan to detect when someone falls
Should work
Unless the block is unloaded
Minatocraft1
send an invite
Do know that i launch a player in the air, i can detect if they start flying with a good'ol elytra or anything easy peasy but when they fall
wait, blocks has an inventory component?
ummm. Yeah? chest, barrel, shulker box?
ah, i thought for custom blocks
I have absolutely no idea what to do because .isJumping flags even if they are holding jump in mid air
So then I'd kill the player if i assume they landed
And .getVelocity() is very helpful but i can't really decide how to use it
just make a map when it detects If the player has already jumped it will set that to true, if they land it will set that to false
Yeah that's hard part
.isOnGround doesn't flag
If you hold the jump button
something went wrong, why is this so freaking HUGE
it works... Fine with me... I used that in my statistics addon
Lower gui texture
Yeah idk i guess my addon isn't very optimized or smth
Ima test out later again
I kinda revamped everything
And split the functionality upon 2 addons
it was -1
i turned it into the smallest one ( -2 ) and it went into the -1 size
i added u
π€·ββοΈ
Reopen mc?
wait a min, i should change one system
this onejs system.runInterval(() => { for (const player of world.getAllPlayers()) { const itemStack = player.getComponent('equippable')?.getEquipment('Head'); if (itemStack?.typeId === 'exe_heads:fisherman_hat') fisherman_hat = true; else fisherman_hat = false; } })
it will set that 'fisherman_hat' into true, when one of the players equips it,
and this works only when one of those players is equipped it if (fisherman_hat === true) if (Math.random() <= 0.1) dimension.runCommandAsync(loot spawn ${x} ${y} ${z} loot "gameplay/fishing") so it will work for anyone who dont equip that fisherman hat
so, the system has to be changed.
specifically this:
world.beforeEvents.entityRemove.subscribe((event) => {
const hook = event.removedEntity;
if (hook.typeId === "minecraft:fishing_hook") {
const loc = hook.location;
const date = Date.now()
const dimension = hook.dimension
const { x, y, z } = hook.location
const id = system.runInterval(() => {
const id2 = system.runTimeout(()=>system.clearRun(id),20)
const items = dimension.getEntities({type:"minecraft:item", location: loc, maxDistance: 2})
for(const item of items){
if(date - (itemSpawnDate.get(item)??0) < 100){
if (fisherman_hat === true) if (Math.random() <= 0.1) dimension.runCommandAsync(`loot spawn ${x} ${y} ${z} loot "gameplay/fishing"`)
system.clearRun(id)
system.clearRun(id2)
return
}
}
});
}
})```@distant tulip this system should detect the owner's equipment, drop the new loot tables when the owner is equipping a fisherman hat.
system.runInterval(() => {
const playerStates = JSON.parse(world.getDynamicProperty('playerStates') || '{}');
for (const player of world.getPlayers()) {
const movementPermission = player.inputPermissions.movementEnabled;
if (!playerStates[player.id]) playerStates[player.id] = { isOnGround: true };
if (movementPermission) {
if (player.isJumping && playerStates[player.id].isOnGround) {
console.error('Jumped');
playerStates[player.id].isOnGround = false;
}
if (player.isOnGround && !playerStates[player.id].isOnGround) playerStates[player.id].isOnGround = true;
}
}
});```
I have this, I'm too lazy to fix some parts
i think i can make it work for the nearest player that is equipping the fisherman hat as a bonus for him, but it will make him get more loot if other players are fishing near him.
Nah it returns undefinied
@untold magnet
import {system, world} from "@minecraft/server";
const hookOwners = new WeakMap();
world.afterEvents.entitySpawn.subscribe((event) => {
const entity = event.entity;
if (entity.typeId !== "minecraft:fishing_hook") return;
const dimension = entity.dimension;
const hRot = entity.getRotation();
const nearbyPlayers = dimension.getEntities({ location: entity.location, maxDistance: 5, type: "minecraft:player" });
for (const player of nearbyPlayers) {
const pRot = player.getRotation();
if (Math.abs(pRot.x + hRot.x)<2 && Math.abs(pRot.y + hRot.y) < 1) {
hookOwners.set(entity, player);
console.warn(player.nameTag);
break;
}
}
});
world.beforeEvents.entityRemove.subscribe((event) => {
const hook = event.removedEntity;
if (hook.typeId !== "minecraft:fishing_hook") return;
const owner = hookOwners.get(hook);
hookOwners.delete(hook);
if (!owner) return;
const { x, y, z } = hook.location;
const hasHat = owner.getComponent("equippable")?.getEquipment("Head")?.typeId === "exe_heads:fisherman_hat"
system.run(()=>{
let found = false
const itemSpawnHandler = world.afterEvents.entitySpawn.subscribe((spawnEvent) => {
const entity = spawnEvent.entity;
if (entity.typeId !== "minecraft:item") return;
const distance = Math.hypot(entity.location.x - x, entity.location.y - y, entity.location.z - z);
if (distance > 3 && !found) return;
found = true
if (hasHat) owner.runCommand(`loot spawn ${x} ${y} ${z} loot "gameplay/fishing"`);
world.afterEvents.entitySpawn.unsubscribe(itemSpawnHandler);
});
system.runTimeout(() => {
world.afterEvents.entitySpawn.unsubscribe(itemSpawnHandler);
},20)
})
});
holy
that looks sick
will it drop the extra loot 100%?
lets test it out and see.
this log is happening at this line const distance = Math.hypot(entity.location.x - x, entity.location.y - y, entity.location.z - z); only when i stand on the hook,
do
const distance = entity.isValid()?Math.hypot(entity.location.x - x, entity.location.y - y, entity.location.z - z):4;
lot of edge cases but i can't think of a better way
but maybe...
@untold magnet
same log
How do I use getViewDirection() and getHeadLocation() to convert tp @s ^2 ^5 ^-9 dynamically?
const distance = entity.isValid()?Math.hypot(entity.location.x - x, entity.location.y - y, entity.location.z - z):0;
alright fixed,
function relativeCoordinates(direction, location, offset){
return {
x: location.x + offset.x * direction.x,
y: location.y + offset.y,
z: location.z + offset.z * direction.z,
}
}
usage:
relativeCoordinates(direction, location, {x:2,y:5,z:-9})
or check this out https://discord.com/channels/523663022053392405/1131984839151714354
thx
what ?
wow minato be helping out everyone
yeah, i suggested a better way when i found out
view direction is z axis if u flip x and y comp of z axis and make one of the comp negative it gives u x axis then z axis cross product x axis gives u y axis
after that u can do this for ^vx ^vy ^vz
location += xaxis * vx + yaxis * vy + zaxis * vz
i created a non cross product method some time ago
@wintry bane
-# and sorry for the misinformation
is there a way to detect player input?
like right clicking
a stable way of course
as long as the block is tangible, yes...
tangible?
like excluding water/lava
is there an alt way for them?
u can use this one if u like, just to see what events triggers simultaneously
this is like an even detector?
sorta, ye
ye nothing get's detected
mhm
I wonder if some found a way around it
how do I know the block I'm looking at?
getBlockFromViewDirection
system.runInterval(()=>{
for (const p of world.getAllPlayers()) {
console.warn(p.getBlockFromViewDirection()?.block?.typeId);
}
})
Doesn't detect water
what does?
Gotta use the parameters for the function

from player's eyes to where ur lookin at, plus includeLiquid, then itll get the 1st block
,
?*
for(const player of world.getAllPlayers()){
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const {player , block} = event;
if(!player || !block) return;
let blocktype = player.getBlockFromViewDirection({includeLiquidBlocks : true}).block.typeId;
if (blocktype === "minecraft:water"){
player.sendMessage("water");
}
})
}
u touched a block not a water
when...
my problem is the spam that happens
oh
if (!event.isFirstEvent || !player || !block) return;
oh firstEvent
ye, they just added that few updates ago
yep ty it's working 
W update
why do you forloop players when the event gives the player?
it was supposed to be for another function
btw what's Ts?
typescript
and it's used for?
typing scripts 
Like javascript, but with stricter rules on what you can type- stops stupid mistakes and helps guide the creator better
Very much so
It's pretty easy to set up and allows for a lot better experience writing code, imo
Yes.
mhm
is it possible to mix it with js?
I have at least 100 lines so far and I'm not sure I have the time to rewrite them
All JavaScript is valid typescript (you just get warnings for type mismatches)
is there a block interact event?
Yes.
is there any examples? i dont have the npm installed
Read the docs.
jesus why do i even ask you
π€· It is useful to just...read the docs as well...you ask for examples and I'm giving you a source to read.
i found another way
Hello smokey
These days bundlers dont care if you mix js and ts
real
wtf
the script randomly stopped working
no errors either
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const {player , block} = event;
if(!event.isFirstEvent ||!player || !block) return;
let blocktype = player.getBlockFromViewDirection({includeLiquidBlocks : true}).block.typeId;
let thirst = JSON.parse(player.getDynamicProperty('thirst') || '{}')
if (blocktype === "minecraft:water"){
thirst.hydration = Math.min(100, thirst.hydration +40);
}
player.setDynamicProperty('thirst', JSON.stringify(thirst));
})```
so i have buttons here, but how can i make them only appear if a certain condition is met? using @valid ice's chestforms also
const form = ...
if(x) form.button(...)
umm, that wouldn't work without an item I guess? Use an item since the time the player can interact with water using a bucket, anything else? No i think
No no it did work
ty
try using itemUseOn
I want it to work with anything tho
you got no choice as I said since players can only interact with water if they interact using bucket
tho I'm not 100% sure
But how did it work?
It actually worked
I just don't know why it's broken
Also that's just wrong
umm, are you looking at water with block behind?
Ye of course
Then you're supporting what I said
^
I'm using a detection of interacting with the block behind the water and detecting that the water is infront of you
water I mean
Ahh
Why is it broken now tho
world.beforeEvents.playerInteractWithBlock.subscribe(ev => {
const { block, player, itemStack } = ev;
const raycast = player.getBlockFromViewDirection({ includeLiquidBlocks: true })?.block;
console.error(raycast?.typeId);
});```
Ain't that the same?
just try it
Ok gemme a min
I missed an s in the includeLiquidBlock
what's your point? lol
nvm my script is working lol
I think there's a problem with the dynamic property
a project
Something like what?
it's kinda obvious lol
making a thirst system
I thought it would be could to have the ability to directly drink water
Hmm
It looks nice
Same, currently im trying to do a Tower Defense just via Script
like a turrets??
Yes
Little "turrets" with mobs on it
Ice Bear is* like a freeze-tower
that's interesting
you have ss?
"ss" ?
^ ??
ScreenShot...
ohhh
Nope, im still working on the structure of the code to make it very perfomant
I need a good sytem for the Enemies path system...
Anyone good ideas?
Hello guys. When I add "minecraft/server-ui" module, it gives me that error: [Scripting][verbose]-Plugin [BEHAVIOR PACK NAME] - promoted [@minecraft/server] from [1.3.0] to [1.16.0] requested by [@minecraft/server-ui - 1.3.0].
use the vanilla ui
I mean for the back end stuff
Like code, not visuals
The Calculation of it
Image you have 1000 Enemies, somehow it needs to be perfomant
so i need a good system
Every enemy follows a path, so they need to walk to the current path-point, and this needs to be perfomant
I can't
neither can my pc lmao
anyone know how i would apply knockback to entities?
entity.applyKnockback(directionX, directionY, horizontalStrength, verticalStrength)
i trie that but it didnt do nun
well nvm now it wants to work lmao
ty
like when doing damage to something
same
I was in the proccess of making one without using scoreboards or anything like that via API calls and turns out damage is stored per-value, meaning Math.random() damage on a entityHitEntity event gives no hit cooldown time lmao
it's so stupid
someone wanted to be able to multiply/divide damage as needed but didn't wanna do scoreboard / rpg style and I was messing with that and discovered it
yeah my code is a mess lmao
for example π
that passive mode shit idek how it works i just made it
You should try to stick with let and const when declaring variables and avoid using var. It's basically legacy code and mostly kept around for backward compatibility.
i use var for after the if's
otherwise it errors
Because you have to declare the variable before the statement with let then use the variable to define it so it's accessible outside the if statement.
let example = false;
if (player.hasTag("idk") {
example = true;
}
console.log(example);
eh it dont matter it works the same idrc
Just trying to teach you some knowledge.
send bp manifest
it's a part of generator functions, used most commonly for filling large areas of blocks at once
ohh, i see
i've used runInterval for generating small terrain, it lags a lot
does job do a better... job?
It splits up the work over multiple ticks, lightening the load on the server
and supports yeild statements so you can choose to split it up as you please
{
"format_version": 2,
"header": {
"name": "PACK NAME",
"description": "This scripts is for practicing",
"uuid": "uuid",
"version": [1, 0, 0],
"min_engine_version": [1, 21, 50]
},
"modules": [
{
"description": "",
"language": "javascript",
"type": "script",
"uuid": "uuid",
"version": [1, 0, 0],
"entry": "scripts/Main.js"
}
],
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.16.0"
},
{
"module_name": "@minecraft/server-ui",
"version": "1.3.0"
},
{
"uuid": "uuid",
"version": [1, 0, 0]
}
],
"metadata": {
"generated_with": {
"blockbench_block_wizard": ["1.2.2"]
}
}
}
ah i see thanks
nvm, it's not actually a problem since the console it says verbose
like success thingy
What does it means? "verbose"
successful to run or successful progress
Hmm, but do you know why is this advice for? What does it mean?
your script doesn't really have a problem, also I think that only shows up when you gui on load option on and selected the type of error to be Verbose
Thanks a lot
please use objects...
ngl. That's looks funny
fuck mentality be like:
is their any way to interact with a dispensor and get if the item being dispensed is bonemeal? im not finding anything yet
I don't think there is.
You could listen to the entitySpawn event and check the item's velocity
If the block in that direction is a dispenser then thats it
hi here. Is it possible to detect the player spawnpoint? like the bed spawn
Yeah. Player.getSpawnPoint()
thank u so much!!
anyone know anti horion crash for bds servers?
world.afterEvents.itemReleaseUse.subscribe(({source: player, itemStack, useDuration}) => {
const hat = player.getComponent('equippable')?.getEquipment('Head')?.typeId === 'exe_heads:fletcher_hat';
if (!hat) return;
if (hat && itemStack?.typeId === 'minecraft:bow' && useDuration <= 0.1) world.sendMessage('Works?');
})```isnt working?
try to console the duration
i will.
console.warn(useDuration)?
71997 is 0.1s
so i should make it like so: if (useDuration <= 71997) {***}
i guess so?
kinda confusing since iirc the docs say that it's based on ticks but 71997 is an hour if my math is correct
look at the logs,
tick-72000 is the start, bows can shoot arrows from tick-71997, so i will use tick-71995
anyways
Ahhh. That's why, I'm confused asf like, what?
Math.floor(Math.min(4) && Math.max(7)) will pick a random number from 4 to 7 ?
player.addEffect('speed', TicksPerSecond * Math(thing), {amplifier: 1})
no.
( showcasing my Math skills )
you used && if I'm correct it will get the second, so the value returns is 7
Math.floor(Math.random() * (7 - 4 + 1)) + 4;```
it will works for addEffect right?
yeah? I mean why not?
it works but,
it should at least give u 3s of speed,
not 0.1s
player.addEffect('speed', TicksPerSecond * Math.floor(Math.random() * (7 - 4 + 1)) + 4, {amplifier: 1})
I assume the TicksPerSecond returns 20 already since it's a built in on the server module
Min time: 3
Max time: 7
its giving me from 0.1s up to 4s as the max value
player.addEffect('speed', 20 * (Math.floor(Math.random() * (7 - 4 + 1)) + 4), { amplifier: 1 });
Not a big difference (I think) since I just added () also make sure you are not looping it since it will obviously generate a new value each time
it works now,
A* maybe?
Ain't an error.
that beat in the mid part is crazy.
TU TU TU TU TU
Fr, I'm vibing to it
there is some components that might help
make the entity target an invisible one either by making it hostile towards it or taming it to it
you can also use go to block thing
guys, I'm starting to be old
A?
A* algorithm
Oh my bad, does some exists like Minato said entity.goToBlock ?
Wait that wouldnt be a good solution because the enemies arent a constant speed (due some slowned by an Ice Tower)
nox have an example in his github for A* algo
Can you send me the Link? Im on phone rn
Thanks
yo
Hey if it works and theres no bugs then thats good enough for me
world.afterEvents.entityHitEntity.subscribe((damagingEntity) => {
const itemStack = damagingEntity.getComponent('equippable').getEquipment("Mainhand")
const itemUsing = itemStack?.typeId == 'bleach:zanpakuto_2'
const score = world.scoreboard.getObjective('z2_charge')
for some reason the 1st line says its not a function
the itemStack one
You're tripping
that part I don't agree
well the world isnt laggy at all even with tons of NPC's and constant code running soo π€·ββοΈ
if you keep insisting that your code works fine do it on large projects cause you'll notice the difference, yes not right now but using objects let and const is way better that vars and using multiple if stamenents
i mean i can screenshare if youd like to see it
i mean wouldnt mind showing the server off + you obv know how to optimize code better so wouldnt mind some tips
anyone pls
like... I already told you how to optimize it π use objects, let and const and less variable calls or if stamenents
send a pic of the content log
bro i have thousands of if statements π
world.afterEvents.entityHitEntity.subscribe(({ damagingEntity, hitEntity }) => {
});```
that's how you destruct
wait but I didnt use it
nvm I'm blind asf
Tho it's still not valid
[Scripting][error]-TypeError: not a function at <anonymous> (main.js:73)

well then the entity isnt defined
damagingEntity.damagingEntity.getCompo...
its reffering to this
const itemStack = damagingEntity.getComponent('equippable').getEquipment("Mainhand")
world.afterEvents.entityHurt.subscribe((data) => {
const hitEntity = data.hurtEntity
const attacker = data.damageSource.damagingEntity
const cause = data.damageSource.cause
const { x, y, z } = hitEntity.location
})
``` i use this, use it if you want
yippie
OH
SO THAT WHY IT BROKE
?
forgot to readd data
uh
it was working before but modified it
that's why use short names like ev or e
oh how i love errors
world.afterEvents.entityHitEntity.subscribe(ev => {
const { damagingEntity, hitEntity } = ev;
});
world.afterEvents.entityHitEntity.subscribe(({ damagingEntity, hitEntity }) => {
});```
was doing that before but changed it
from what library can I import Vector3 from? I need the class itself to build prototypes on
forgot why
it's not a class, it's a typescript interface
I dunno which one you mean since I made two scrips there lmfao
1st one
if you're using ts you can do this for types
class Vector implements Vector3 {}
then changed it to 2nd
DAYUM
ah okay, that's why I can't find it
send your script in my dms
π
-# or here just choose lmfao
join vc so i can show
-# I don't vc... I'm scared π
brehhhh
wait how u can make too many ifs more compact
I'll joined VC but I won't talk lol
use switch or make a map
Tho it always depends what you are doing
will chack them ty
for an inventory shorthand like entity.inventory, should it return the container property or just the actual inventory component itself?
Inventory.
I was thinking the same thing since the user may want other properties but I know that it's also most commonly used for getting items so that's why I wasn't sure
anyone have a function to turn vector3 to rotation
Madlad has a math library in #1067535712372654091
thanks
Well that's lame. Was working on block that works like nylium and that's the only thing g I can't do lol
hmm,
Minato should be scripting leader
nah, i have a habit of trying to help even if i don't know shit
Trying is always better than not even try
(Sorry for my bad English)
sup budd, ( i need a little bit of help )
dimension.spawnItem(new ItemStack(wools.forEach(itemStack), 1), loc); this should spawn one item from the IDs in the index right?
Nope
const wools = ['id', 'id2'];
***
dimension.spawnItem(new ItemStack(wools.forEach(itemStack), 1), loc);```for a better view
Dimension.spawnItem(new ItemStack(wools[parseInt(Math.random * wools.lenght)]))
parse int seems really unnecessary when you can just do math.round or floor.
Math.random() * wools.lenght ?
Just a method itβs the same
Preferences.
Random picks an item from the array
Math random returns a random number between 0-1
ik
Yeah I just forgot ()
hi
is there a way to smoothly move the player from point A to point B
i tried teleport by a small distance but it locks the camera, also the whole journey is nothing but smooth
If the player themselves must move, I would try having them ride an entity, then teleport/push that entity.
Otherwise I would look into using the /camera command or its API equivalent.
Camera doesnt work right?
Since its override the player camera
Well yea, that's the idea. That solution would be ideal if you don't care about the player's camera (that is, you need the player's view to move smoothly, for e.g. a cutscene)
You were not very specific what this was for, so I'm only offering general solutions.
applyknockback also work. in the video i am moving the player by a small knockback in an interval until he reach the hook
dimension.spawnItem(new ItemStack(wools[parseInt(Math.random() * wools.lenght)], 1), loc);
This means that wools isnβt an id of an item
Thatβs up to you to edit wools
const wools = ['minecraft:black_wool', 'minecraft:blue_wool', 'minecraft:brown_wool', 'minecraft:cyan_wool', 'minecraft:gray_wool', 'minecraft:green_wool', 'minecraft:light_blue_wool', 'minecraft:light_gray_wool', 'minecraft:lime_wool', 'minecraft:magenta_wool', 'minecraft:orange_wool', 'minecraft:pink_wool', 'minecraft:purple_wool', 'minecraft:red_wool', 'minecraft:white_wool', 'minecraft:yellow_wool'];
Length, not lenght
( i didn't write it, @-carchi77 he did)
And I'm telling you your mistake.
@wary edge i just copied it from his message :v
And I'm telling you what to fix.
can I make custom enchants? like with a book and stuff
nope.
guys why it throws an error can't getProperty on entity.
I'm using projectileHitEntity I have this
const type = projectile?.getProperty('coddy:type') ?? 'poke_ball'
okay thank you! also is there anyway to make it where a block was broken another is placed?
import { world, ItemStack } from "@minecraft/server"
world.beforeEvents.playerBreakBlock.subscribe(event => {
if (event.block.typeId == "minecraft:wheat") {
event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ detect ~~~ air 0 setblock ~~~ wheat");
event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ give @p wheat 1");
event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ kill @s");
}
}
)```
I have this but it spawns wheat 1 block in the air and doesnt always replant
Check the location of the block broken and spawn it at that location
thank you
import { world, ItemStack } from "@minecraft/server"
world.beforeEvents.playerBreakBlock.subscribe(event => {
if (event.block.typeId == "minecraft:wheat") {
let block = event.block;
let player = event.player;
let location = block.location;
event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ setblock ${location.x} ${location.y} ${location.z} wheat");
event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ give @p wheat 1");
event.player?.runCommandAsync("execute @s ~~~ execute @e[c=1,type=item,name=\"Wheat\"] ~~~ kill @s");
}
}
)```
reason for this?
change "..." to `...`
and not '...'
where with my commands?
my commands work with the "." its just the ${location.x}
etc
world.afterEvents.itemUse.subscribe(({ itemStack, source }) => {
if (itemStack.typeId !== "minecraft:chest_minecart" || source.typeId !== "minecraft:player") return;
const itemComp = itemStack.getComponent("minecraft:display_name");
if (!itemComp) return;
const itemName = itemComp.data;
switch (itemName) {
case "test":
source.sendMessage("test");
break;
}
});
whats wrong
- Don't use AI if ever
- it's
itemStack.nameTagit returns undefined if the item is not read at all.
guys.
world.afterEvents.projectileHitEntity.subscribe(ev => {
const { source, projectile } = ev
cosnt hitEntity = ev.getEntityHit()?.entity;
cosnt type = projectile?.getProperty('coddy:type') ?? 'poke_ball';
});```
it throws an error that I can't get the property
Because the projectilr is already gone.
oh yeah, I'm fuckin stupid. I'll just make that it doesn't destroy on hit
thanks smokey
Is it possible to add dynamic properties to blocks like chests, barrels and doors?
you could store a dynamic property on that location specifically, but not on blocks as far as I was aware of
close enough, thanks
How would I do this?
the name is the location as what he/she said
world.setDynamicProperty(Object.values(block.location).join(','), <value>)
the object value will return x,y,z I'm just too lazy to manually show the seperation one
That works it's up to you
thank you, I was waiting for some method, but thank you!
how to show text above the hotbar, just like when you hold an item?
How do I check if the chest placed by the player has connected to another chest?
It was a sample to give you the idea, i just misstyped
Is it necessary to have all the functions in the entry file?
no.
why would it be
you can have functions in any file, just import it to the entry or a file thats imported to it already.
what?
you just need to import it to the entry so it can work.
Yep that's what I meant to ask
It has to be imported
where is the world initialise before event on the Microsoft docs
I can't find it
bruh I'm mad confused
Use this from now on https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.WorldBeforeEvents.html#worldinitialize
ok thanks but why was it removed from the Microsoft docs?
is it getting removed or sum
Suggestion for @minor wren
Description
This script checks whether a player has the hack "Nuker" enabled through the use of block break event.
Credits
These scripts were written by iBlqzed
a web app that have types auto complete
Description
Gets chat ranks from a player and display in chat when player messages.
Credits
These scripts were written by Smell of curry
Description
Gets chat ranks from a player and display in chat when player messages.
Credits
These scripts were written by Smell of curry
how to reduce this delay?
Which event do you use?
before events, playerInteractWithBlock
Minecraft needs Perfomance upates.. even Java run better on 120 FPS with 80+ Mods
client side desync
you can't fix it
Isnt it because Minecraft Scripts are capped (or running on..) 20 TPS but the Game can do more
Doesn't mcbe have something like this natively?
could be, but i had a similar problem where the door stay open in client and the server say it is closed
hmm okay
@inland merlin had the same thing, i thing he solved it with a tp away from the door
-# Will we have client-side scripting someday? π’
That could make some errors if some client side would be desynced
smart
someone here know how to use minecraft/server-net?
-.-
:)
I dont think that's possible
yes it is
ive seen server that do that
and a random here told me is possible
It's not possible to use only the API's. You need other resources beyond just the API.
exposing players IP is not a very good idea
damn who created such a good editor!
...
ohh its using VSCode under the hood
i dont trust chat gpt
then dont
lol
AI is dump asf, but it helps writing meanless documentations so its kind useful for that
or for searchnig and explaining things
he wrote me a working code
recently cht gpt only gave me working code idk how and why
but i appreciate it
He can search in the internet now
so he can take a look over the docs
and writing you working code
oh nice
but i just use him for math
wait i want to test deep seek
ChatGPT is a tool. Not a magic wand. How you communicate with it will determine the results it returns to you. It's also designed to learn about you as you communicate with it. So the more you use it the more it becomes familiarized with what your intentions are.
or for god code structures (because i write with OOP)
How to get a player's velocity?
const velocity = player.getVelocity();
player.getVelocity(): Vector3
lol, it is just monaco editor
(which is the VSCode editor)
i know
idk why auto complete don't work with some stuff tho
like getComponent functions
The mapping is not in stable
oh
thanks it is showing now
it is possible to detect when the player killed a mob, but i have no idea how,
i think by using the entityDie component, right?
Woah what are you using for that page format? Is that VSC?
limit of records dynamic properties per minute concerns only one entity or all
yeah, just pushed the page to github btw
you can try it out
https://minato-mba.github.io/web-apps/web-editor.html
A simple web-based code editor for Minecraft Bedrock Edition scripting with real-time autocomplete, module version management.

world.afterEvents.entityDie.subscribe(({damageSource,deadEntity:victim})=> {
const source = damageSource.damagingEntity;
if (!source) return;
if (source.typeId == 'minecraft:player' && source.hasTag('goldRush')) {
const victimLocation = victim.location;
const goldItem = new ItemStack('minecraft:gold_ingot', 1);
source.dimension.spawnItem(goldItem,victimLocation);
}
});
right now, i am trying to detect the deadEntity family type
i think via getComponent('type_family')
Well, it's dead so it's removed.
what I'm trying to do:
detecting if the player killed a monster type of entities, so i have to use beforrEvent right?
victim.getComponent('minecraft:type_family')?.hasTypeFamily('monster');
ya i see
i didnt know that was a thing xD
but i have to use beforrEvent so i can detect it before it dies
maybe use entity remove event
it have a before event
Why do you need to detect it before death?
the family type, detecting if i am killing a monster or not.
Wouldn't you use the entityHit?
oh how that works
too much unnecessary work ig
lemme see if it works first.
try the matches method instead
fetched the types files and included them from the site cache using monaco addExtraLib function
entity.matches({families: ['family']})
?
:D
was that the death event?
world.afterEvents.entityDie.subscribe(({ deadEntity: eEntity, damageSource }) => {
const source = damageSource.damagingEntity;
if (source?.typeId !== 'minecraft:player') return;
const hat = source.getComponent('equippable')?.getEquipment('Head')?.typeId === 'exe_heads:witch_hat';
if (!hat) return;
const monster = eEntity.getComponent('type_family')?.hasTypeFamily('monster');
if (monster) world.sendMessage('Work?');
});;```
OH sweet
make it so the player teleports bac behind the door if he passes through while it's locked
offtopic
That's still off topic lol.
There's Google.
Do you know the playerPlaceBlock event? How do I check if I placed a chest, and if that chest connected to another, forming a double chest?
Hmm :
Idea 1 : i think there type id for connected chests
Idea 2 : using runTimeout
I don't think so
You'll need to check the neighbouring block.
What if the neighbour block was connected already?
but then I would have to check if the neighboring chest is not already connected
would the connecting chest increase the inventory slot size? depending on how that works and when the event fires you could use that
Make a logic to detect if two chests places to each others
what does container.size return for double chest?
In the same pov
is that I need the location of the second chest
you wouldn't need the location of the second chest, if that's what your asking
if you're saying you need it to be returned though that's a different thing
a chest next to a chest don't mean they are connected
Yeah make :-: dynamic proprety , and put inside it object like that :
let object =
{ location : block.location , direction : "east or , west , north ,or south" } ;
Then make ur logic compare between faces and location of two chests
And that s it...
If there was no easy way to do it...
could false-fire if there's three consecutive chests in a a row all oriented the same way
And add logic to remove the detected ones
that is not enough
you can't check for connected chest, i looked into this for a while
i even fired a ray in the middle of the two sides hoping to get a result but it passed through them
"the logic"?
._. code i mean
how
Add a counter there ,_,
I just presented a case where it could false-fire? literally the image above
what's the plan if someone places a chest in the middle of the two like I did?
I can't understand kiro
there is no way to check that a chest is connected since that is stored in the block entity which we don't have access to
._. , i think i must write the code , to make my idea more clear
uh sure you do you pal
yeah
Yeah ik :-:
oh, I had forgotten about that
.__. maybe i m bad in explaing things
But i m sure i can write correct code the detect this
container.size does work
well no it doesn't because you still could have cases where it false fires
how are we all getting stumped by connected chests lmao
I imagine a double chest would still have a container size of 27 slots for both chests. Each chest holds its own inventory, it only merges the two in the UI
Hmm :-: let's use our brains
What is the special thing about connected chests
That make it easy for us to detect it
makes sense since the content is separated when you break one of the sides
Watch Minecraft and millions of other Minecraft videos captured using Medal.
world.afterEvents.playerPlaceBlock.subscribe(({player, block})=>{
if (block.typeId !== "minecraft:chest") return
const inventory = block.getComponent(`inventory`).container
console.log(inventory.size)
})
Would you look at that, I was wrong
just send it
the blocks share the same tile entity
Ok
I'm pretty sure there's no way to 100% accurately detect it through API
like getting the secondary chests' location
what are the cases?
if a player places the chests like I do in the video and the right side is checked first instead of the left it would "technically" be a double chest since they both have container sizes of 54 but aren't connected
actually maybe not if you stored them as a connected chest in a dynamic property
you mean marking that location as single chest?
kinda, gimme a minute to make code for this because now I'm invested lmao
imagine creating a property for every placed chest...
kiro made a chunk loader that store location of every block that need to be loaded
β οΈ he didn't work tho
dear God lmao
just stop, kiro
you have already helped a lot
discord to mc chat?
I like the idea, I'll research it
it's with discord.js and minecraft protocol bots, they're pretty fun to make for the first time
so i don't need to host a url to receive discord messages and send them to the mc dedicated server?
I suppose you could use PlayerPlaceBlockAfterEvent and PlayerInteractWithBlockBeforeEvent to determine if a freshly placed chest connects with an existing chest.
you could do this, yeah
Does anyone know how to import this?
const r = 1; //radius to check for blocks, adjust it until it make sense
const targetBlock = "minecraft:gold_block"; //block to detect
const soundEffect = "random.orb"; //sound to play
const objective = "pacman" // Tu scoreboard
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const { x, y, z } = player.location;
for (let dx = -r; dx <= r; dx++) {
for (let dy = -r; dy <= r; dy++) {
for (let dz = -r; dz <= r; dz++) {
const block = player.dimension.getBlock({ x: x + dx, y: y + dy, z: z + dz });
if (block && block.typeId == targetBlock) {
player.playSound(soundEffect)
world.scoreboard.getObjective(objective).addScore(player, 1)
player.runCommand(`setblock ${block.x} ${block.y} ${block.z} air destroy`)
}
}
}
}
}
}, 0);```
but you could also do it the other way I was talking about
I can't understand difficult words, or I just don't know what protocol bots are
it's a node.js project that someone made to allow actual bots that can read/write game packets to be loaded into realms/dedicated servers
may i see the github?
anyway back to the chests
I found a solution
Watch Minecraft and millions of other Minecraft videos captured using Medal.
const connectedChests = new Map()
//using maps so I don't have to clear a bunch of dynamic properties after this
world.afterEvents.playerPlaceBlock.subscribe(({player, block})=>{
if (block.typeId !== "minecraft:chest") return
const inventorySize = block.getComponent(`inventory`).container.size
const surroundingBlocks = [block.east(),block.west(),block.north(),block.south()]
for (const otherBlock of surroundingBlocks){
if (otherBlock?.typeId !== "minecraft:chest" || connectedChests.get(otherBlock) !== undefined) continue
const blockSize = block.getComponent(`inventory`).container.size
if (blockSize == 27 || blockSize !== inventorySize) continue
connectedChests.set(otherBlock, block)
connectedChests.set(block, otherBlock)
break
}
const connectedChest = connectedChests.get(block)
if (connectedChest !== undefined){
console.log(`chest at ${JSON.stringify(block.location)} is connected to chest at ${JSON.stringify(connectedChest.location)}`)
}
})
you could probably optimize that further but that seemed to work every time I used it
Where is connectedChests defined?
there isn't really any edge case
huh, we basically got the same code with different steps, yours is more thorough for visuals though by far
I'm working on a solution that requires no storage
:-:
ping me in it when you have it, I'm invested in this now
I was working on it too
It's gonna be chunky though
._.
:-bruh i m dumb:
._. there is better logic for all of this
Ok ,
Let s detect the two block beside it from west and south and east and north
you need to add "minecraft:cardinal_direction" check btw
that's a component? mannnn I wish I knew that
I can't just use npm modules in my addon, right?
direction state
What s that ?
is a block state
._. and ?
I think you can check the value using <block>.permutation.getState("minecraft:cardinal_direction")
:-: i mean i don't know what it used for
to check chest direction and avoiding another edge case
@drowsy scaffold
my approach
function getDoubleChest(block) {
if (block.typeId !== "minecraft:chest") return undefined;
const inventory = block.getComponent("minecraft:inventory")?.container;
if (!inventory || inventory.size !== 54) return undefined;
const direction = block.permutation.getState("minecraft:cardinal_direction");
if (!direction) return undefined;
const checkDirs = direction === "north" || direction === "south"
? ["east", "west"]
: ["north", "south"];
for (const dir of checkDirs) {
const neighbor = block[dir]();
if (neighbor?.typeId === "minecraft:chest") {
const neighborDir = neighbor.permutation.getState("minecraft:cardinal_direction");
const neighborInventory = neighbor.getComponent("minecraft:inventory")?.container;
if (neighborDir === direction && neighborInventory?.size === 54) {
return [block, neighbor];
}
}
}
return undefined;
}
How does it perform in this situation, with placing the chest in the middle of these two?
Depends on orientation too, be sure to try all four cardinal directions
Unless, is that covered by north and east appearing first in checkDirs?
That is pretty straightforward. I was trying to perform the checks in BeforeEvent, before the placed chest could merge
actually...
that is the only edge case in my function
if one of the tow chest is double chest, it will fail
Hmmm a question
ask
ez fix, just walk along the chests until you find a non double chest
or a diff block
yeah, working on it
just have to visualize it for my brain lol
Ok i found a way
It s pretty simple
And no one can guess it
._. let s count the number or east and west chests
what if it just keep going
And if the number of continuative chests is odd or even
In both directions:-:
And we will know if it s connected or not
If number of west is even and number of east is even = there is chest
If one of them if false there is not
What do u think ? @distant tulip
How do we set a Block to an ID again? I forget
chests can be in line without connecting
._.
setType
,_, the same direction
yeah?
They face the same direction and must be chest type and continuative
If u mean commands :-: we cannot detect that , but better than nothing right ?
Cursed asf
kinda
What is in the picture?
6 chests
I thought this was not possible in Bedrock without cheats?
pistons
Ah, I see
Swear you were a mod
Yeah that s innormal
I thought shifting place disabled connectedness on BE as well?
I was, at one time
I see
But i think my idea will work to detecting players
Wait u can disable connecting by shifting!!!!!?!!!
only on java
Quick, help me think of edge cases
Oh god :-:
Should update my parity site then.
place it in the gap
Instructions relatively unclear, I hope I followed them
Seems to be good
Here's my file
@drowsy scaffold
Some of the JSDoc is a bit behind what I implemented ("left and right" became "first and second")
I got a bit lazy at the end and hardcoded the placeAbove conditions
@umbral dune got a potential solution for you
seem solid
this is solid, you used no additional storage and still accurately counted it out. Nice
Now the question is if someone can write it to be shorter π
what happen if only one side of the chest is loaded π
Not sure. I did not account for LocationInUnloadedChunkErrors
That s great
that
throw Error("Sanity condition");
lol
Theoretically that error should never be thrown, but you never know
Explain me how ur logic works :-:
unless you look into the 4th dimension
yeah that player rotation is confusing me
It maps the player's y-rotation to the corresponding facing_direction of the chest.
2 means the chest faces north; thus the player must be facing somewhere south (-45..45)
3 means the chest faces south; thus the player must be facing somewhere north (-180..-135, or 135..180)
4 means the chest faces west; thus the player must be facing somewhere east (-135..-45)
5 means the chest faces east; thus the player must be facing somewhere west (45..135)
._.
i mean yeah, but how that help, and why not just get chest dir
The chest does not exist at this time. All of this logic is performed before the chest is placed
rotationToFacing determines what the to-be-placed chest's rotation will be
.____. my brain hurts
use permutationBeingPlaced?
Ah, that's a thing? My typings did not suggest that
yeah, also permutation == permutation2, work so no need for get state
nvm, you are using get state for other things
Hmmm
Before the chest is placed:
- Find the Block where the chest will be (119).
const ToBeChest = arg.block[DirMap[arg.blockFace]]();
- This uses a mapping of BlockFace types to a method that grabs the adjacent face, then performs that method on the block.
- The result is essentially the space where the chest will be after this function ends.
- Find the facing_direction state of the chest that will be placed (120).
const FacingDir = rotationToFacing(arg.player.getRotation().y);
- This uses a function that returns either 2, 3, 4, or 5 depending on the rotations specified earlier. This matches the values that a chest's facing_direction state can take on.
- Find the blocks to the left and to the right of the chest (121).
const {First, Second} = getFirstAndSecond(ToBeChest, FacingDir);
- Based on the facing_direction state of the chest, grab the Blocks to the "left" and "right" of the chest. North is prioritized over South, and East is prioritized over West.
- Determine if the blocks to the left and right are chests that have not yet been connected (123, 124).
const FirstValid = isConnectableChest(First, FacingDir);
const SecondValid = isConnectableChest(Second, FacingDir);
- A block is considered to be a connectable chest if: The block is a chest; it faces the same direction as the first chest; and it has an inventory, and its inventory has 27 slots.
- Determine which of the blocks to the side the original chest will connect to.
if(FirstValid && !SecondValid) {
placeAbove(ToBeChest), placeAbove(First);
}
if(SecondValid && !FirstValid) {
placeAbove(ToBeChest), placeAbove(Second);
}
if(FirstValid && SecondValid) {
placeAbove(ToBeChest), placeAbove(First);
}
- If both the left and right blocks are valid, then we pick the first, which will be the North or East block.
Elisah , just put a bomb here and left :-:
Wait a min
Double chest
Inventory = ?
I mena double chest slots
54
Both chests in a Double Chest arrangement have an inventory size of 54
Same there. If you grabbed the "inventory" component of one block in a Double Chest arrangement, it would report 54 slots
U can detect that with script api ?
Nice
What about one chest ?
A single chest on its own would be 27 slots
Sure ?
Ok i think i find the solution._.
._.
I ll make a code smaller than yr .___.
Hihihi
What makes this challenging is Bedrock does not expose its connection type as a block state. If we could read this, it would be much simpler
I see
And I just realized my typing in JSDoc on CardinalLeft was obtuse
could have just done this haha
Question
Shoot
It is predictive. Based on what we know of chest connection rules, I wrote functions to predict what would happen
It may have been. In a sense, this does detect it, but through prediction
I might not be understanding your question fully either
:-: i mean what they ll use ur code for
To make another event of detecting if chest connected
Or ._.
Another thing
Oh, that I have no idea. I tried to write it generically enough so anyone could adapt it
Oh
For example, this could be used to prevent players from making double-chests
That s nice
I think it's kinda pointless actually, lol
Hahaha, I found an edge case where it fails @distant tulip
damn, lol
@distant tulip can u try it ?
the extend i took to fix mine is just stupid
sure
Ok one min
import { world } from "@minecraft/server";
world.afterEvents.playerPlaceBlock.subscribe(({ block }) => {
let current_b = block;
if (block.type !== "minecraft:chest") return;
let EastConnected = (
current_b.east().permutation.getState("facing_direction") == current_b.permutation.getState("facing_direction") &&
current_b.east().getComponent("inventory").container.size == 27 &&
current_b.east().type == "minecraft:chest"
) ? true : false;
let WestConnected = (
current_b.west().permutation.getState("facing_direction") == current_b.permutation.getState("facing_direction") &&
current_b.west().getComponent("inventory").container.size == 27 &&
current_b.west().type == "minecraft:chest"
) ? true : false;
if (EastConnected || WestConnected) {
world.sendMessage("there is a connected chest");
}
});
._. what do u think :-:
If the container size comparison is !== 27 (i.e. == 54) then I suppose it would return true.
changed that and nothing
πthe double chest problem optimization is incredible
._.
Idk :-: if the problem is detecting if chest is connected anymore or not
:-: i can't even debug my code .___.
If the facing direction of both the block and its adjacent block matches, the adjacent block has 54 slots, and the adjacent block is a chest, that is technically the criteria for a chest connecting.
here i saved the first slot form the origin block
set that slot to an item with random id
checked for that item in other chests
set the original item back π
._.
What it lacks is detecting if the placed chest has connected to the adjacent chest. That is, the single chest being placed here will also result in a true value
._. u told me single chest slots are 27
And if we get Inventory components of that double chest we will get 54
Yep ?
Logically, if everything is same direction and the east or west blocks are chests
And slots ._. are 27 , it forces it to be connected
Yes. By the time a function in PlayerPlaceBlockAfterEvent is called, the placed chest will have already merged with another block; so if the placed chest is connected, it will report 54
Only if.... ,_, there are commands that makes no chest sticks to another
Oh β οΈ
That needs before event then
Lol ._.
I thought so too
Yay :-: i breaked the rule i made the best chest detector ;-; yay
You gave it a fair shot. Now try with BeforeEvent!

