#Script API General
1 messages · Page 17 of 1
What are you trying to do in that event?
Maybe it is working but whats inside is the problem
tried this @knotty plaza
Just in case, you know that worldInitialize only runs once per world load right?
/reload wont make it fire again
Check your content log, maybe it showed up and dissapeared really fast
I see nothing related to it
Uhm figured out what was wrong
is player.getDimension() a valid method
Player has a dimension property
oh
I mean if you wanted you could do world.getDimension(player.dimension.id)
thanks
Well, someone just asked if you could run a script for players in the nether so I wasn’t sure if getting their dimension was a method or not
ah fair
Thats like withdrawing money to deposit to another person's account
Instead of just transfering the money

Hey herobrine what's up
Should I add a delay to run in game commands using worldInitialize?
If your trying to send a message after world Initialize yes, probably a good 5 seconds
To make sure time to see it
If slow device
i managed to do it without chatGPT, did a lot of youtube research 😆 it did take me a while tho. And i added a little of a wave path too
That's pretty cool!
What algorithm are you using?
can you tell me or show me how to do this?
Is your item custom or vanilla?
a lot of math xD
item?
I think you replied to the wrong message before
How ?
In this video, I show you how to create a spider with a procedural galloping animation.
Previous Video:
https://www.youtube.com/watch?v=Hc9x1e85L0w
Source Code:
https://github.com/TheCymaera/minecraft-spider
World Download:
https://www.planetminecraft.com/project/spider-garden/
All my links:
https://heledron.com/links/
Inspired by:
Coding A...
is it mc bedrock feature?
plugin. That's Java Edition, indicated by Block Display Entities
He has the source code in his GitHub (check his main video)
Do you just use the formula for a standard circular motion or add something else?
can you detect if it is raining? and if so can you detect if a player is currently standing in it
Is there a way to get all of the properties on a component? Does JS allow some syntax for this or something?
what is launch_power replacement for projectile shoot?
applyImpulse for entities and items
applyKnockback for the player
that model is amazing tho
👍
Here's an example of how you could do that. Also, keep in mind, the getWeather() method on the Dimension Class is currently in Beta.
import { system, world } from "@minecraft/server";
const overworldDimension = world.getDimension("minecraft:overworld");
system.runInterval(() => {
const isRaining = overworldDimension.getWeather() === "Rain";
for (const player of world.getAllPlayers()) {
const playerDimension = player.dimension;
const isOverworldDimension = playerDimension.id === overworldDimension.id;
if (!isOverworldDimension) continue;
const { x, y, z } = player.location;
const topMostBlock = playerDimension.getTopmostBlock({ x, z });
if (!topMostBlock) continue;
const isStandingInRain = y > topMostBlock.y;
if (isRaining && isStandingInRain) {
world.sendMessage(`${player.name} is standing in Rain.`);
}
}
}, 0.1);
0.1 tick delay?
It's just an example. They're free to alter it for their use-case.
That does work.
It clearly runs 10 times every tick Omniac
Oh, I thought you meant it would error.
lol
guys whats wrong with my code, does world.runCommand() not valid?
server.system.run(function tick() {
for (let player of server.world.getPlayers()) {
managePlayerClanTags(player);
player.nameTag = handlePlayerName(player);
if (player.hasTag("tempestKnight")) {
giveEffect(player, 'strength', 10, 3, true);
giveEffect(player, 'haste', 10, 1, true);
} else if (player.hasTag("flameOni")) {
giveEffect(player, 'fire_resistance', 10, 255, true);
} else if (player.hasTag("forestSpirit")) {
giveEffect(player, 'speed', 10, 1, true);
} else if (player.hasTag("dragonsFang")) {
giveEffect(player, 'resistance', 10, 6, true);
giveEffect(player, 'weakness', 10, 1, true);
if (!player.hasTag("hasWings")) {
player.addTag("hasWings");
player.runCommandAsync(`replaceitem entity @s slot.armor.chest 0 ewings:demon_0 1 0 {"item_lock":{"mode":"lock_in_slot"},"keep_on_death":{}}`);
}
} else {
if (player.hasTag("hasWings")) {
player.removeTag("hasWings");
player.runCommandAsync(`replaceitem entity @s slot.armor.chest 0 air`);
}
}
sidebar(player);
}
if (server.system.currentTick % 200 === 0) {
server.world.sendMessage("sendMessage test");
server.world.runCommand("say runCommand test");
}
// Schedule the next tick
server.system.run(tick);
});
nevermind i resolved it server.world.getDimension('overworld').runCommand()
itemReleaseUse
itemStartUse
itemStopUse
idk
can the charge be canceled?
shrug
would it be possible to combine it with the findClosestBiome/biometype class to make it so that it fires off with actual rain and not snow? or is there an easier way to seperate the two cause im pretty sure the game classifies snow as rain too, as well as identify if the player is in a desert/mesa or not since rain doesnt appear there
How do i get the min and max property value of an enum property?
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
how can i get the owner of projectile that was shot by player using bow
you want to set player as projectile owner?
no i need to give projectile to do smth when hit
wait
oh
nvm i just realized smth
nevermind the nevermind
i still need to track the owner of the projectile and store functions in there
arrow.getComponent('minecraft:projectile').owner```
How do I stop world.beforeEvents.playerInteractWithBlock from firing repeatedly? I'm not using the preview, so I can't use isFirstEvent.
whatcha need beforeEvents for?
Are you trying to do a custom enchantment that can be put on a bow, or just do something for all arrows the player fires?
It might be enough to just lookup the owner in the projectileHitEntity or projectileHitBlock afterEvent
its (mostly) the former
oh wait
yeah it has source property
It needs to be a before event for what I'm doing as I don't want the player placing the block they are using on the target block
Be cancelling the block placement using e.cancel
@shy leaf
so from a glance i think this extends ladder when placed on specific block
Using a ladder on an already placed ladder will extend the ladder down if there is space and a solid block for the ladder to attach to
Like reverse scaffolding
hi, why my json ui don't work on new version
and since its beforeEvents, it can fire multiple times
hmmmmm
So if it was an afterEvent it'd fire once? Only problem then is a ladder might be placed opposite the existing ladder
Script works fine atm, still gotta add the item decrement function but that's all sorted ready to be imported. It's just the rapid fire activation that's a problem. Can place enough ladders from build height to bedrock layer in like 5 seconds lol
The isFirstEvent property just needs to become available outside of the preview
just gotta hope it enters stable
Can't see why it shouldn't. It'd fix so many issues with interactions and item usage
@grave thistle you can try this
Thanks, I'll take a look now
Yeah I have talented friends
** Glide Minigame Flashbacks intensify **
Haven't been able to test it out yet, but based on a bit of research on using Date.now() this looks like it'll fix my issue, thank you!
Sounds like you have a solution, but in general looking into the concepts of debouncing (wait until X time after the last time a function is called) and throttling (limit execution of a function to the first time it gets called in some specified period so that calling it again will do nothing until after some delay) can be pretty helpful
can dynamicproperty store function or code?
yes...
why am i asking this tbh
learn abt eval
mhm...
well, it depends on what variables are scopeable from where it's used
im making custom bow functionalities that can run codes for events like projectileHitEntity and projectileHitBlock
but im not sure what to do to store the functionalities into arrow
or... i could use Date.now() to sync the arrow and event without storing code into arrow
Wait why? I feel like you might be overcomplicating it
could be
I'm heading to bed now, but see if you can take a step back and look at the problem more broadly to try find a simpler solution
my brain is optimized at making the most complicated solution lmao
but yeah projectiles are kinda funky
Yeah like getting the owner and stuff?
Yep nice and easy, you can store it in a dynamic property on the arrow entity (unless they've changed it and it's directly accessible now). What's the other stuff you're trying to do?
... What does "custom bow functionalities" from above entail?
its not just one bow but a whole collection of bows
with abilities? i dunno im just helping with saving an addon from HCF hell
can someone give an example of findClosestBiome
my brain is too small to understand the microsoft doc one
this should help you understand better
Note that the findClosestBiome operation can take some time to complete, so avoid using many of these calls within a particular tick.
just in case
Well, if the event for the arrow is predictable/deterministic i.e. The same bow type fired 3 times will always make the projectile do the same thing, you could simply store a kind of id in a dynamic property on the arrow entity, and when it hits something (in the callback event), check the id and run the appropriate block of code / function
Haha thanks. Yeah I gotta fix my sleep schedule. Goodnight! Let me know if you have any more questions tomorrow.
const { x, y, z } = player.location;
player.dimension.findClosestBiome(x,y,z,"minecraft:plains")
feels so off 😭
looks ok to me
though uh
the pos part should be a vector3
player.dimension.findClosestBiome(player.location,"minecraft:plains")```
this alone should be ok
hmm okay
how would you input an array into it since this doesnt work
player.dimension.findClosestBiome(player.location,${snowBiomeList})```
ooo you should see the other array i have then
let rainBiomeList = ["ocean","deep_ocean","lukewarm_ocean","deep_lukewarm_ocean","warm_ocean","deep_warm_ocean","river","beach","cold_ocean","deep_cold_ocean","forest","flower_forest","birch_forest","birch_forest_mutated","roofed_forest","jungle","jungle_edge","bamboo_jungle","mushroom_island","swampland","plains","sunflower_plains","mangrove_swamp","lush_caves","dripstone_caves","deep_dark"]
no im saying findClosestBiome is very resource heavy
so executing it every 30 seconds would probably be bad
if youre looking for one biome in particular then it should be alright
but doing that for each
doesnt sound great
just trying to decern that when its raining is the biome im in gonna create snow, and if so, nothing happens, only looking for rain. and when getting the weather, Rain is, rain and snow
what
Returns a location of the biome, or undefined if a biome could not be found.```
hmm couldnt i just get that location and detect if the player is standing in it
how are you getting the type of the biome the player is standing at
(genuinely a question)
((i dunno how))
you gotta consider how wide the biome might be
im not sure if the script returns the center of the closest biome
or the location of the closest biome border
well if this is how you say it is and itll give me the location of the biome, i assume i can compare that ouput with the player's current position and if its the same then idk command fire that says hi for now. but like you are saying right now idk where the number it gives me is, i might have to do a range, if the player is at least 50 blocks close

if its the same logic as the locate command it wont be the center of the biome, i was flying around using it earlier and when in the biome i was firing it and it kept taking me to different spots inside the biome
up to 45 blocks away
idk this is way out of my league
e.itemComponentRegistry.registerCustomComponent("evo:voids_edge", {
onUse(e) {
const player = e.source;
const xyz = player.location;
const dimension = player.dimension;
player.startItemCooldown("custom", 20);
player.playSound("mob.enderdragon.flap");
player.runCommandAsync("particle evo:voids_edge_particle ~~~");
let nearbyEntities = dimension.getEntities({
location: xyz,
maxDistance: 10,
excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
});
nearbyEntities = nearbyEntities.filter(entity => entity !== player);
nearbyEntities.forEach(entity => {
entity.runCommandAsync("particle ptg:voids_edge_particle ~~~")
entity.applyKnockback(xyz.x, xyz.z, 1, 0.3);
});
}
});
How to fix apply knock back? I want entity to be pulled to player who use sword
But it don't work. Player only go in positive x direct
idk if im right but i think instead of location you need direction
@shrewd wedge
e.itemComponentRegistry.registerCustomComponent("evo:voids_edge", {
onUse(e) {
const player = e.source;
const xyz = player.location;
const dir = player.getRotation();
const dimension = player.dimension;
player.startItemCooldown("custom", 20);
player.playSound("mob.enderdragon.flap");
player.runCommandAsync("particle evo:voids_edge_particle ~~~");
let nearbyEntities = dimension.getEntities({
location: xyz,
maxDistance: 10,
excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
});
nearbyEntities = nearbyEntities.filter(entity => entity !== player);
nearbyEntities.forEach(entity => {
entity.runCommandAsync("particle ptg:voids_edge_particle ~~~")
entity.applyKnockback(dir.x, dir.y, 1, 0.3);
});
}
});
dw
Hey i test and did not work
Entitys goes out not pull in, how to make it pull in instead
change dir.x to -dir.x
just mess with the values till it works
heyyyoo anyone know what im missing here?
Not able to get a translation.
const message: RawMessage = { translate: 'ts_ml.messaging.toggle_falling_stars'};
It is logging as "ts_ml.messaging.toggle_falling_stars"
remove the spaces around the =
anyone has an algorithm to detect tree
for (let x = WORLD_MIN.x; x < WORLD_MAX.x; x++) {
for (let y = WORLD_MIN.y; y < WORLD_MAX.y; y++) {
for (let z = WORLD_MIN.z; z < WORLD_MAX.z; z++) {
const block = world.getDimension('overworld').getBlock({x: x, y: y, z: z})
if (!block?.isValid()) continue;
if (block.isTree()) world.sendMessage('Found a tree!');
}
}
}
``` 
🗿
wat
I do... see tree? no, turn around... see tree? no. wait. maybe. yes tree over there....
yes
yes
I've looked into throttling and it sounds like a better method than applying properties to an object. However, with what I'm trying to achieve, wouldn't multiple players trying to extend ladders lock other players out of doing the same during the throttle cooldown?
i.e. the throttle lasts for 5 seconds. Player 1 places a ladder triggering the throttle but then player 2 goes to place a ladder 1 second in to the throttle's duration and it doesn't allow the ladder placement
what about storing the duration into player
(i actually just found out about throttling so i have no idea)
don't forget to use try-catch:
try {
for (let x = WORLD_MIN.x; x < WORLD_MAX.x; x++) {
for (let y = WORLD_MIN.y; y < WORLD_MAX.y; y++) {
for (let z = WORLD_MIN.z; z < WORLD_MAX.z; z++) {
const block = world.getDimension('overworld').getBlock({x: x, y: y, z: z})
if (!block?.isValid()) continue;
if (block.isTree()) world.sendMessage('Found a tree!');
}
}
}
} catch (e) {
throw "No tree"
}
I've sorted my problem now thanks to Kira. I've only just learnt about throttling and debouncing and it sounds like a cool way of adding function delays. Not only that, I've only just learnt that functions can be passed as values of a property (still learning js lol, all self taught atm with occasional help from AI when I need something explaining)
got it working, ty
Nice! Well done
just to make sure, can .owner property on projectile component return the owner?
the one im doing rn is very inefficient and i cant redo the code since i dont have access to minecraft rn
Can someone help me resolve a function error? I can't find the problem
the owner property in jayly's script docs doesnt mention about return so i was wondering
im planning to rewrite the code to use entitySpawn + itemReleaseUse afterEvents to store the function id so that i can replace the abomination i made
whats the issue
I think it would be easier to use nameTag, so you can always be sure that you own an entity
dynamic property could work then
"not a function error"
I checked the whole script and I can't understand why this problem is happening...
that would require reviewing the whole code
It's a small code... The runCommand that is bringing the error
@shy leaf
I just can't find what is causing this bug to happen
function arrestEnemy(player) {
const entitiesInView = player.getEntitiesFromViewDirection({ maxDistance: 4 })
if (entitiesInView.length > 0) {
const nearestEnemy = entitiesInView[0]
const playerPos = player.location
const playerRotation = player.getRotation()
const offsetX = 1.5 * Math.sin((playerRotation.y + 90) * (Math.PI / 180))
const offsetZ = 1.5 * Math.cos((playerRotation.y + 90) * (Math.PI / 180))
const newX = playerPos.x + offsetX
const newZ = playerPos.z + offsetZ
const newY = playerPos.y
nearestEnemy.runCommand(`tp @s ${newX} ${newY} ${newZ}`)
}
}
which line is it pointing at?
nearestEnemy gives the error "not a function", but it doesn't make sense
It is pointing to the nearestEnemy.runCommand line
i see the issue
But the problem is not what is inside the command, because when I took it out, it continued with the error
since entitiesInView returns an arrary of it, youd need to do forEach or for loop
So in this case it would be:
for nearestEnemy = entitiesInView[0]
?
This doesn't make sense to me, because in another function it doesn't generate errors, but I'll test it
no
try
for (const e of entitiesInView) {
e.runCommand('say Hello World!');
}```
I see, so in this case the problem is that runCommand cannot call the array
I will test
yeah
Is it possible to cycle through textures for for a block face with permutations that change the texture for a material instance? If that makes any sence
sounds possible
very possible
with block states
Yeah I tried and I'm not really getting anywhere I even had help with it but idk what I did wrong I have a thing open if anyone could help
I know paddles for sure wouldn't work.
Anyone able to help with this?
https://discord.com/channels/523663022053392405/1277805139201232970
Yeah, owner will contain the owner if there is one (which there will be unless an arrow is spawned directly or fired by a dispenser)
You should be able to do it without itemReleaseUse
ty
now im kinda facing another issue
im storing bow's typeid into projectile's dynamic property to determine which function to fire, but im kinda worried if the dynamic property will be nullified since the projectile would be destroyed upon hit
i could use Map for this but i kinda want to preserve it until the projectile dies
Set the property directly onto the arrow
thats what i did
well idk i havent tested it and i might be overthinking but
projectiles are wack
You can’t really do much if their killed before script api gets them
i did check it but doesnt this function by storing data into bow
Ye both
How to remove item stack when use? I try item.amount--; but it say "cannot be less 0 greater 256" in log
would using clear command cause error?
But its mostly relient on the arrow one
hmmmm
Check the amount first if its 0 don’t decrement
what item are you trying at
But if 0 then I have none?
Ye
like a item that drops when players die. It gives effects when use
No I try to remove by 1 when use,
But I have one in hotbar, use and it say cannot be less 0
are you using beforeEvents for itemUse?
No custom component
oh
onUse
its hard to tell without checking the code
This probably happens when you have it on a loop or something like that
Does anybody know the polar Rotation? I'm trying to setup a custom path for an entity using this. I searched on YouTube, I can't seem to find anything useful for what I'm trying to do
It's not
can you post the block of the code
e.itemComponentRegistry.registerCustomComponent("evo:skull", {
onUse(e) {
const player = e.source;
const itemStack = e.itemStack;
const container = player.getComponent("minecraft:inventory").container;
player.runCommandAsync("effect @s regeneration 5 1 true");
player.runCommandAsync("effect @s absorption 5 0 true");
player.startItemCooldown("skull", 20);
itemStack.amount--;
container.setItem(slot, itemStack);
}
});
});
now i see it
It say when use: "item amount cannot be less than 0"
const item = player.getComponent('equippable')?.getEquipment('Mainhand');```
youre trying to get the inventory instead of the item used
Ohh ok thank you
Can't you just use the world event for itemUse?
Also you can set effects to the player via addEffect
Yes
What is difference
Literally nothing tbh
player.addEffect('conduit_power', 2400, {showParticles: false});
It's the same thing
actually, nevermind. since itemUse already gives you itemStack, the code i gave you would be unnecessary
Oh
ok I habe question, if I use clear command, does it clear item you are holding or is random?
Doesn't the clear CMD clear your hotbar?
like if I habe one item in hand, and one in inventory, does it random choose one
it clears your entire inventory unless you define which item by amount
no
I know if I only clear 1 of the item, then will it be random which it clear?
Sorry i haven't touched the cmds in years 😂
It's ok
im pretty sure theres no 'random item clear'
no, sorry hard to explain
ok I habe one item in hand right? And one item in inventory. And I use item in hand. I do clear item of one. Does game choose one in hand, in inventory or is random
That is what I mean
for that? pretty sure it goes in this order
If you want to specify the slot you can do something like this
invComp.setItem(slotId, undefined);
const heldItem = player.getComponent('equippable')?.getEquipmentSlot('Mainhand');```
use this as slot instead
Ohh ok. So I do inventory.setItem(heldItem, itemStack--;)
Uh no the undefined already removed 1
I stand corrected
It clears the slot apperantly
So I'm assuming the whole stack
???
yeah since it reduces itemStack into atoms
you can replace slot in your setItem with the heldItem i gave you
you didnt have slot defined, that could be the issue
Ok I check, thank you
Oh that's true
world.afterEvents.itemCompleteUse.subscribe((eventData) => {
const { itemStack, source } = eventData;
if (itemStack.typeId === "your item typeid") {
source.runCommandAsync(`the command you want to execute`);
};
});```
what do you mean by go down????
It work thank you
Like decrement the item stack how it was ins events
They said on consume so itemCompleteUse fits better here, itemUse will run on just use
that or custom components with onConsume works too
#1067870274894172260
oh ok
the item's amount or the item's durability?
function decreaseItem(itemStack, decreaseAmount) {
itemStack.amount -= decreaseAmount;
return itemStack;
};
// function usage
const inv = player.getComponent('inventory').container;
const newItem = decreaseItem(itemStack, 1);
inv.setItem(player.selectedSlotIndex, newItem);
@shrewd wedge ^
i had a function for decreasing item durability, i just changed it to itemStack.amount
i think you wanted to decrease the amount of the item, not the item's durability...right?
just change the selectedSlotIndex if you dont want to do this with the hand eqquiped item
or wanna do with any inventory item
whatever
How to set a block a sign with a specific text content?
Use this component
https://stirante.com/script/server/1.13.0/classes/BlockSignComponent.html
Documentation for @minecraft/server
That page has a snippet that provides everything you need 👍
i ended up using Map

at least it works perfectly
How would I do a location.dimension.getBlock for the location of for example 0 1 2? Would I use ({x: 0, y: 1, z: 2})?
yeah
Is there an article for set blocks?
setPermutation?
Thank you!
playerInteractWithEntity
Is it possible to use this to stop a player from hitting another player?
👌
If there would be a beforeEvent
As far as I know you can‘t do that, only with editing the player.json
Alright
world.afterEvents.playerInteractWithEntity.subscribe(data => {
const player = data.player;
const entity = data.entity;
console.warn('test')
});
How can you make this work?
Idk you‘d have to ask someone who has a good overview over the documents
It theoretically makes sense but I don‘t know how entity and player are called in that case
There actually seems to be a before event, I just don‘t know if you are able to cancel attacks with that, here‘s more information about it
no
you can prevent damage using entity json but you cant cancel the attack
playerInteractWithEntity is for right clicking so
On mobile it‘s long clicking lol
can you tell the issue
Shouldn't it be running in 11 to 11 position?
Wait how did you open that in your Minecraft tab,
Do you use Android?
its a feature for most phones
Yea
Not on my IPhone 😭
rip
The iPhone is very advanced but for some reason it does not contain some basic features.
iphone isnt advanced tbh
to be fair coding in mobile is frustrating but
all the iphone's """policy""" makes everything harder (at least in my eyes)
though i do recommend getting a phone with high ram if youre getting one someday
so that you dont go insane
In my eyes, the iPhone is a trash
u gotta experiment on it bro
try diff operators like !== or === instead of <= or >= and why are the coords duplicated
How do I system.clearRunInterval();?
its system.clearRun()
system.runInterval() returns a unique id so that you can use it
const interval = system.runInterval(() => {
//code
});
system.clearRun(interval)```
I just wanted to put it into a system.runInterval itself lol
the coordinates displayed are rounded, so technically you're actually at some number between 11 and 10.5, so it shows 11, but your script doesn't
block positions are measured from the NW corner iirc
what do you need it for?
you can
Can the player leave before event cancel player leave?
Is there a player death after event?
ofc not
also there is entityDie afterEvents
Is there a way to cancel a system.runTimeout?
honestly not sure about this one
you can try with the same thing here
yes, use clearRun
is there a way to face a player when using the .teleport notation?
player.teleport(player.location, { facingLocation: anotherPlayer.location })
spawnEntitiesInArea([startX, startY, startZ], [endX, endY, endZ], entitiesToSpawn, entityType);
is it posible to spawn the entity only as an adult?
oh i found another way
player.teleport({ x: -315, y: 138, z: 36 },
{
facingLocation: targetLocationShop
}
);
however thank you
What's the difference between system.run() and system.runJob() ?
system run expect function to run, but runJob expects Generator to execute
Generator? Never heard of that xD
Corutines?
I don't know that either
@beta no more returns preview exp?
@beta returns experimental module from last release, so if stable is released it overwrites
hm
How do i get the location the entity is facing because im trying to recreate the random sheep eating grass then turning it into dirt.
I cant trust this code so much since the location could be on the side of the entity which doesn't make sense at all:
const blockEaten = dim.getBlock({
x: entity.location.x,
y: entity.location.y - 1,
z: entity.location.z + 1
});
blockEaten.setPermutation(
BlockPermutation.resolve('minecraft:dirt')
);
getPlayers is only get online player?
same with getAllPlayers, yes
is it possible to do multi threading?
whichever player entity is executable in the world
i have name
but how can i get just player not name, id or something
would you like to go to dms? i can speak korean
if the player isnt offline, then its not possible to get the Player.prototype
but its possible to manage its ScoreboardIdentity
Ya, there is no native instance for offline players, only accessible are scoreboards that are linked to entities and players
||Player.prototype is always accessible||
ty
btw how do you make add method player.tell? like override the player and add method tell that basically sendMessage but with prefix
Player.prototype.tell = function tell(params){
this.sendMessage(...params); //this is player instance
}
now this is weird
it did get the object normally
but now it just refuses?
Find the bug lol
Lol
Always name your functions. Then it becomes easier to debug.
this does not tell anything lmao
it just tells me "hey im not getting this data"
"over there"
The stack trace is relatively short, so it should be easy to find a start
i ask "why", they reply with " "
What is the anonymous function at ItemsFunctionalities/itemHandler.js on line 186? I'm betting it is an event subscription
yeah its an event
JSON.parse() issue??
no parse is used
i dunno why cuz the event gives an object
and sends the object to other scripts
but it doesnt convert?... object
You are sending the event object to other functions? Minecraft could be garbage collecting it before it can be used
Maybe it could be worthwhile making a shallow copy of the event object. Something like (e) => {const event = {...e};}
gotcha
i think garbage collecting is the issue here, this started once i added some codes for bows

Nah, event data objects are no longer free-ed by native end, so this is not the case here

No longer? I'm curious, when did that change
about 4 months ago
maybe more but not sure
Long enough that I am a bit silly for not having noticed lol
@sharp elbow Not sure which update it was but this is the date of my notice
07/12/2023
lmao
Ah, so about a year ago 😆
yes
BUG SQUASHED
my statics were like
static weapon(id,eventData)```
but i forgot it was supposed to be
```js
static weapon(eventData,id)```
the object was kept sending to id part

Stats (using the api)
Personally, I woouldve done id, data
How to get those?
I made that
I mean how to get the player stats
Those which you can view on player‘s profile
Or are the shown stats for your world only and counted by your system?
If its on scoreboard, then world
if dynamic property, then pack
are dynamic props really per pack?
I did not know that lmao
per pack uuid
regardless of pack version
but i havent tried working two packs same uuid, but diff ver
in that case, global dynamic props would be hella nice
I wouldn’t lol
I don’t think Minecraft likes that
I did it by accident the other night, and it said I applied one pack but it was actually the other one
it chooses the higher version?
Both had the same version
I just copied over one of my packs in its entirety, removed a bunch of stuff & changed the pack name (But forgot to change the UUIDs), and said it added the new pack to the world, but all the stuff in-game was the old pack stuff.
iirc each world caches it's packs so if the version wasn't different, then it wouldn't have updated it
It was a dev pack, however- and I deleted all the world BP json files & the folder for the BP.
pack path was probably still pointing to the old one
i wonder if an addon can access the dynamic properties of another addon?
No
interesting, so i don't have to worry about my addons interfering with other addons of the dp share the same name
no
that's... convenient
I am making a claim system and I am thinking of using dynamicproperty to save the data.
Do you have any other advice?
That works
is there any event to detect when an entity shoots a projectile?
EntitySpawn?
we can detect the entity that spawns it?
projectile have owner property in its "projectile" component
I feel like there should be a shorter route to reach this, but that sounds like it'll work, thanks.
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server-ui
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server-ui
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
@jaunty relicPlease use #debug-playground
ok ^^
I have a function that scans the player's hotbar for an item. How do I check if that item is a block? I'm using if (hotbarItem instanceof Block) { but it's not working
Is it because even though it's a block, it's still technically an item since it's in my inventory
help
mc.world.afterEvents.itemCompleteUse.subscribe((eventData) => {
const { itemStack, source } = eventData;
if (itemStack.typeId === "your item typeid") {
source.runCommandAsync(`the command you want to execute`);
};
});
What are your imports? And did you swap the your item typeid & the command you want to execute parts for your own usage?
yes I changed
Then what’s wrong?
says it doesn't exist
Can you show the actual code you are running in-game, then?
What doesn’t exist? You need to be more specific and tell all the details if you want I someone to assist you
How to make apply knock back go in direction of person who use sword
You mean you want the knockback to send the player away from the sword or closer?
get the user's view direction and apply that to the knockback amounts
Closer. So when player use sword it pull in player and entities
But problem is that if player use sword while looking away, players nearby will be pulled in wrong direction
So when player uses the sword, I want to have it pull nearby entity towards who used
When I use direction sometimes entity pull in wrong direction
In that case, you'd need to get the x & z (and maybe y) vector between the two entities
I try and do player.location and use apply knock back to player who use sword x and z but it not work?
How?
Sorry, it worked, it was another script that was giving conflict and saying it didn't exist
more thanks too
const dx = otherEntity.location.x - source.location.x;
const dy = otherEntity.location.y - source.location.y;
const dz = otherEntity.location.z - source.location.z;
const magnitude = Math.hypot(dx, dy, dz);
otherEntity.applyKnockback(dx / magnitude, dz / magnitude, 1, 1);``` maybe something like the this
You may need to swap the two locations- can't recall if source or otherEntity should be first.
(can also just chuck a negative in front of the dx & dz in the applyKnockback part too)
const kb = {};
Object.keys(player.getViewDirection()).forEach(key => {
kb[key] = -player.getViewDirection()[key];
})
HitEntity.applyKnockback(kb.x , kb.z , 1 , kb.y)
This will send the player near the player
Wouldn't it be better to use Object.entries() instead of recalling the getViewDirection method for every direction?
e.itemComponentRegistry.registerCustomComponent("evo:voids_edge", {
onUse(e) {
const player = e.source;
const xyz = player.location;
const dir = player.getViewDirection();
const dimension = player.dimension;
player.startItemCooldown("custom", 20);
player.playSound("mob.enderdragon.flap");
player.runCommandAsync("particle evo:voids_edge_particle ~~~");
let nearbyEntities = dimension.getEntities({
location: xyz,
maxDistance: 10,
excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
});
nearbyEntities = nearbyEntities.filter(entity => entity !== player);
nearbyEntities.forEach(entity => {
const dx = entity.location.x - xyz.x;
const dy = entity.location.y - xyz.y;
const dz = entity.location.z - xyz.z;
const magnitude = Math.hypot(dx, dy, dz);
entity.applyKnockback(dx / magnitude, dz / magnitude, 1, 1);
entity.runCommandAsync("particle evo:voids_edge_particle ~~~")
});
}
});
Ok this pull nearby entity?
try it and see 
Ok
Is there something I don't know about the percent symbol here? In any other situation, the % will work just fine, but no matter how I try to format it here, the symbol just... doesn't show up.
announced.sendMessage(`Health: ${health + "%"}`)
announced.sendMessage(`Health: ${health} + "%"`)```
Try double percent symbol
Single is used for translation keys in certain strings, and the way the game parses it is a bit goofy
It's my pet peeve that single percent shows up on the item name in the inventory, but it does not in the item name when held- the one above the hotbar
const vDir = Player.getViewDirection()
const kb = {};
Object.entries(vDir).forEach(([key, value]) => {
kb[key] = -value;
})
Now?
ye
How can I do something if a Player uses an Item for x seconds?
Hey, is not work
I'm honestly surprised that worked, thanks
It pull entity away and up not towards
either I'm doing something wrong, or it doesn't work.
I don't think the owner is a value to be returned, only set
Mine doesn’t?
This is what I try
But if player who use sword is not looking at player who got pulled, player gets pulled in other direction
What? How can the player hit someone without looking at him?
It supposed to pull every entity 10 blocks towards the xyz of player who use sword but everything I try does not work
I don't know what I'm doing wrong, the code I use just pull entity up and away not close
const pLoc = player.location
const eLoc = hitEntity.location
const kb = Object.fromEntries(
Object.entries(pLoc).map(([key, value]) => [key, value - eLoc[key]])
)
hitEntity.applyknockback(-kb.x,-kb.z,(Math.abs(kb.x)+math.abs(kb.z)), -kb.y)
This should work
system.runInterval(()=>{
world.getPlayers().forEach(player=>{
const test1 = (player.location.x <= 13 && player.location.x >= -13) && (player.location.z <= 13 && player.location.z >= -13)
player.runCommand(`title @s actionbar ${test1}`)
})});
Shouldn't it work when x is 13 and z is 13?
import { ActionFormData } from "@minecraft/server-ui"
function Ui(player) {
const ui = new ActionFormData()
.title("Form")
.body("")
.button("button1")
.button("button2")
.button("button3");
form.show(player).then((r) => {
if (r.selection === 0){
player.runCommandAsync('say a')
}
}
)
};
function CustomUi(player) {
const customUi = new ActionFormData()
.title("Custom Form")
.body("")
.button("Rewards", "textures/ui/promo_holiday_gift_small")
.button("Shop", "textures/ui/icon_deals")
.button("Ban Tool", "textures/ui/hammer_l")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
form.show(player).then((r) => {
if (r.selection === 0) {
Ui(player);
}
});
};
world.afterEvents.itemUse.subscribe(async (event) => {
const { source, itemStack } = event
switch (itemStack.typeId) {
case "minecraft:compass": ui.show(source); break;
case "minecraft:clock": {
const res = await customUi.show(source);
res.selection //This Is Number Will Be Derived From The "collection_index" property of a button in JSON UI
world.sendMessage(`Button ${res.selection} Has Been Pressed!`)
break
};
}
})```
why am I getting a reference error
I would move this to it's own thread
system.runInterval(() => {
world.getPlayers().forEach(player => {
const { x, z } = player.location
const test1 = Math.abs(x) <= 13 && Math.abs(z) <= 13
player.runCommand(`title @s actionbar ${test1}`)
})
})
This is simpler
hm
just to help avoid it getting lost mostly
also provide the script error
as in the raw error from logs
But send the error 
Ah i see..
You are referencing multiple times unexistant variables
[Scripting][error]-Unhandled promise rejection: ReferenceError: 'customUi' is not defined
[Scripting][error]-Unhandled promise rejection: ReferenceError: 'ui' is not defined
@cold grove
Reference correctly your variables
const ui = new ActionFormData();
//...
form.show(); // 'form'??? Where??
This is what are you doing rn
Also, you cant use local variables outside his function
import { world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
function Ui(player) {
const ui = new ActionFormData()
.title("Form")
.body("")
.button("button1")
.button("button2")
.button("button3");
ui.show(player).then((r) => { // Use 'ui' here instead of 'form'
if (r.canceled) return;
if (r.selection === 0) {
player.runCommandAsync('say a');
}
});
}
function CustomUi(player) {
const customUi = new ActionFormData()
.title("Custom Form")
.body("")
.button("Rewards", "textures/ui/promo_holiday_gift_small")
.button("Shop", "textures/ui/icon_deals")
.button("Ban Tool", "textures/ui/hammer_l")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar")
.button("Skins", "textures/ui/icon_hangar");
customUi.show(player).then((r) => { // Use 'customUi' here instead of 'form'
if (r.canceled) return;
if (r.selection === 0) {
Ui(player);
}
return r.selection; // Return the selected button index
});
}
world.afterEvents.itemUse.subscribe(async (event) => {
const { source, itemStack } = event;
switch (itemStack.typeId) {
case "minecraft:compass":
Ui(source); // Changed from 'ui.show(source)' to 'Ui(source)'
break;
case "minecraft:clock": {
const res = await CustomUi(source); // Changed from 'customUi.show(source)' to 'await CustomUi(source)'
world.sendMessage(`Button ${res} Has Been Pressed!`);
break;
}
}
});
[Scripting][error]-Unhandled promise rejection: TypeError: cannot read property 'selection' of undefined
it works but still shows this error
You can do if (r.canceled) return;
so if the form was canceled (e.g. no button selected but still closed) it'll just stop the code
where in actually?
.show(player).then(r => {
if (r.canceled) return;
...
ok
Both form functions would need that.
I didn't include it since I didn't know what your plan was going forward.
ui.show(player).then((r) => {
if (r.canceled) return;
// Use 'ui' here instead of 'form'
if (r.selection === 0) {
player.runCommandAsync('say a');
}
});
}
ok
I edited my response to include it
does that not imply that r is undefined?
The reason for that is this section of code. The CustomUi function doesn't return anything.
case "minecraft:clock": {
const res = await CustomUi(source); // Changed from 'customUi.show(source)' to 'await CustomUi(source)'
world.sendMessage(`Button ${res.selection} Has Been Pressed!`);
break;
}
That's a valid point
ohh that's the problem section
#1278065220018897159 message
The custom UI function is incomplete anyways, so when they add more functionality to it then they can have it return as needed.
I modified the above to return r.selection to appease the res call in sendMessage
bump
is there a way to add a cooldown for itemUse ?
cooldown as in?
the time you have to wait to use the item again
similar to ender pearls?
world.afterEvents.itemCompleteUse.subscribe((r) =>{
const {source:player, itemStack:item, useDuration:time} = r
switch(item.typeId){
case "minecraft:ender_pearl":
time = 1000
break;
case "minecraft:enchanted_golden_apple":
break;
}
})
yh pretty much what am tryna do
isnt useDuration in ticks? let me check
ItemStack#starCooldown ?
Wait hehe
1st check if item its in cooldow
ItemCooldownComponent#getCooldownTicksRemaining
Run and set cooldown
ItemCooldownComponent#startCooldown
startcooldown is related with cooldown component inside the item
oh really?
yeah
should they be imported?
nah
1st check if item its in cooldow
ItemCooldownComponent#getCooldownTicksRemaining
If its not, run actions and set cooldown
ItemCooldownComponent#startCooldown
getting 'cooldown' component from itemStack can do
not all items have a cooldown
yeah
if youre trying to make a custom cooldown via scripts, try using this
something like this can work
if(player["coolDown"] > Date.now()) return;
player["coolDown"] = Date.now() + 1000;
const cd = <ItemStack>.getComponent(ItemComponentTypes.Cooldown);
if (cd.getCooldownTicksRemaining(<player>) > 0) return;
// Do item action
cd.startCooldown(<player>);
Ah, right
...
whats the best way to deal with error thats thrown for executing code outside the loaded area
its not a big deal but the error kinda bothers me
what function is it and what error is it throwing
thats a bad practice... but, use try {} catch () {}
try {
//code
} catch (e) { console.warn(e) }
thanks
mb
its no problem
#1067535608660107284 message

Lol
oh
let me try
for vanilla ones just use this #1067535608660107284 message
1000 is the cooldown in ms
oh alright
Is there a way to check if a held item is a block?
I haven't really done anything like that previously. However, I believe you can do something like this.
import { BlockTypes } from "@minecraft/server";
// If it's not a block, it will be undefined.
const blockCheck = BlockTypes.get(heldItem.typeId);
how can i get the itemStack from equippable component it if the item breaks or runs out
cuz it returns undefined
i feel like i had a workaround but i kinda forgot
maybe i could add a beforeEvent itemUse to store the item and then give it to functions
system.runInterval(() => {
world.getPlayers().forEach((player) => {
const comp = player.getComponent('equippable');
const head = comp.getEquipment('Head');
if (!head && player._head) console.log('head equip off');
player._head = head;
});
});
hmm i cant really use runInterval
Huh
yeah
You could create a property lastItemType and update it any time you read the itemType for a slot
beforeEvents time
guyy is there anyone know if i use tp command with location is ^^^0.3 so how it looklike in scripts . i meant how location like that look like in scripts
player.teleport({?})
you have to manually code that, here’s my version to see how it works https://jaylydev.github.io/posts/better-mace/#cutscene
.-. ukmmmmm
Yo anyone know how to get the block placed?
(In the playerPlaceBlock beforeEvent)
I haven't touched scripting api in a while and I'm back, lots of cool things are here
But seems they haven't really added a method to get the block being placed
permutationBeingPlaced
The location
You gave me this script in 1.12.0-beta if I recall correctly
import { world, system, Direction } from "@minecraft/server";
const faceOffset = new Map([
[Direction.East, { x: 1, y: 0, z: 0 }], [Direction.West, { x: -1, y: 0, z: 0 }],
[Direction.Up, { x: 0, y: 1, z: 0 }], [Direction.Down, { x: 0, y: -1, z: 0 }],
[Direction.South, { x: 0, y: 0, z: 1 }], [Direction.North, { x: 0, y: 0, z: -1 }],
]);
world.beforeEvents.playerPlaceBlock.subscribe((data) => {
let { player, block, face, permutationToPlace, dimension } = data, item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
let offset = faceOffset.get(face);
let newLocation = { x: block.location.x - offset.x, y: block.location.y - offset.y, z: block.location.z - offset.z}; // new block, but doesn't work
});
I edited it a bit
So here's what I'm tryna do, I'm tryna something like the pc block picking up, when u shift break a block in creative it actually makes a random id and saves the structure name as the ID and puts the ID in the items lore, and yes I tested it, the saving part is fine I can load it using /structure load but, it doesn't seem to override the block I am placing.
Here's the full script:
import { world, system, Direction } from "@minecraft/server";
const faceOffset = new Map([
[Direction.East, { x: 1, y: 0, z: 0 }], [Direction.West, { x: -1, y: 0, z: 0 }],
[Direction.Up, { x: 0, y: 1, z: 0 }], [Direction.Down, { x: 0, y: -1, z: 0 }],
[Direction.South, { x: 0, y: 0, z: 1 }], [Direction.North, { x: 0, y: 0, z: -1 }],
]);
world.beforeEvents.playerPlaceBlock.subscribe((data) => {
let { player, block, face, permutationToPlace, dimension } = data, item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
if (!item || !item.getLore()[0] || !item.getLore()[0].startsWith('ID: ')) return;
let offset = faceOffset.get(face);
let newLocation = { x: block.location.x - offset.x, y: block.location.y - offset.y, z: block.location.z - offset.z};
system.runTimeout(() => {
let itemID = item.getLore()[0].split(' ')[1];
player.dimension.runCommandAsync(`structure load ${itemID} ${Object.values(newLocation).reverse().join(' ')}`);
player.dimension.runCommandAsync(`structure delete ${itemID}`);
}, 2);
});
permutationToPlace should be permutationBeingPlaced, no?
You aren't using it regardless, so it won't throw an error
I didn't use it nor put it their but I decided not to mess with your script and just edit My part.
Also they fixed the issue with the block in the events being the one you're placing on- no need to get the offset now, you can just use the block property from the event 👍
Moyang finally be putting in 50 hours a week
Bruh it still ain't working
It's still putting in the item I'm holding's block and not being overrided by the structure
import { world, system } from "@minecraft/server";
world.beforeEvents.playerPlaceBlock.subscribe((data) => {
let { player, block, face, dimension } = data, item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
if (!item || !item.getLore()[0] || !item.getLore()[0].startsWith('ID: ')) return;
system.runTimeout(() => {
let itemID = item.getLore()[0].split(' ')[1];
player.dimension.runCommandAsync(`structure load ${itemID} ${Object.values(block.location).reverse().join(' ')}`);
player.dimension.runCommandAsync(`structure delete ${itemID}`);
}, 2);
});
What's possibly wrong with this script???
#debug-playground message
Complier says absolutely no problems and even for extra measures I fixed the ts thing of typing face & dimension and never using them
Am I supposed to use afterEvent?.. I'll use it
I think you need to cancel the before event
Can I ask you a question? Why did you do Block.location.reverse() this will do z y x and spawn the structure in a unloaded chunk
Is it just me, the tameable component returns undefined in vanilla entities that can be tamed. But works perfectly on custom entities that can be tamed.
Becuz doing Object.values(vec3) will give you the values z y x and so reversing it will make it x y z again
Welp still doesn't work
Ima use after event
Maybe it'll work
I didn’t know this, but it feels wrong, have you tried to delete reverse and see what happens?
It works lol, not cuz of deleting the reverse. It's cuz it deletes the structure with the placing so if there is a problem with the placing the structure would get deleted anyway and so it never got deleted so I made it send a message before the if (!item || !item.... and after and the after didn't work and so I instantly knew it was a problem with the if statement and I realized the whole problem was with the || !item.getLore()[0].startsWith('ID: ') return; cuz it was supposed to be '§r§5ID: ' not 'ID: '
Anyway thanks for the help yall
Especially herobrine
How would I make it so when I put on a specific armor piece/set it would make my gamertag go away
wdym by "make my gamertag go away"
Make it to where it's no longer visible
you cant
you can just give the player invisibility
to stop showing it
Ok
Then how do I make it so where when wearing a specific piece of armor walking it's like sprinting but only when they're sneaking if that makes any sense
its possible but i dunno how, ive seen it being used in some addons
the only time i've seen this being possible is on the originspe addon by r4isen where if you choose the class "Rogue" your nametag becomes invisible
when you set "nametag" to "" 😔
wait that works?
import { world, system } from "@minecraft/server";
// Function to update player's name tag visibility
function updateNameTagVisibility(player) {
const inventory = player.getComponent("inventory").container;
const helmetSlot = inventory.getItem(103); // Slot 103 is the helmet slot
if (helmetSlot && helmetSlot.typeId === "minecraft:iron_helmet") {
// Player is wearing an iron helmet, hide the name tag
player.nameTag = "";
} else {
// Player is not wearing an iron helmet, show the name tag
player.nameTag = player.name;
}
}
// Run the check periodically
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
updateNameTagVisibility(player);
}
}, 20); // Check every second (20 ticks)
// Listen for item equip events to update immediately when helmet is equipped/unequipped
world.afterEvents.itemUseOn.subscribe((event) => {
const player = event.source;
if (player.typeId === "minecraft:player") {
system.run(() => updateNameTagVisibility(player));
}
});
so this should work?
not that
oh-
no?
I'm pretty sure this works, but I'm not sure whether it would show a tiny bar for a blank space
holy
Why would you need to edit player.json
nametag isn't a component
wizard!!
this might work, just test it out:
import { world, system } from "@minecraft/server";
// Function to update player's name tag visibility
function updateNameTagVisibility(player) {
const inventory = player.getComponent("inventory").container;
const helmetSlot = inventory.getItem(103); // Slot 103 is the helmet slot
if (helmetSlot && helmetSlot.typeId === "minecraft:iron_helmet") {
// Player is wearing an iron helmet, hide the name tag
player.nameTag = "";
} else {
// Player is not wearing an iron helmet, show the name tag
player.nameTag = player.name;
}
}
// Run the check periodically
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
updateNameTagVisibility(player);
}
}, 20); // Check every second (20 ticks)
// Listen for item equip events to update immediately when helmet is equipped/unequipped
world.afterEvents.itemUseOn.subscribe((event) => {
const player = event.source;
if (player.typeId === "minecraft:player") {
system.run(() => updateNameTagVisibility(player));
}
});
Ok ty
so, sneak walking = sprinting?
Ya
thats probably possible, but i have no idea how to do it
Ok
maybe like increase the speed of a player while theyre sneaking?
so when they walk they go faster?
How would I do that
thats a great question
I have no idea
or maybe i do wait
import { world, Player, TicksPerSecond } from "@minecraft/server";
const sprintSpeed = 0.3; // Sprinting speed
const normalSpeed = 0.1; // Walking speed
world.events.tick.subscribe(() => {
for (const player of world.getPlayers()) {
if (player.isSneaking) {
player.setMovementSpeed(sprintSpeed); // Set speed to sprinting speed when sneaking
} else {
player.setMovementSpeed(normalSpeed); // Reset to normal speed when not sneaking
}
}
});
just check if this works
this is generated by chatgpt so i highly doubt if it works
How can I spawn a particle between 10 0 10 and 10 0 15 with spawn particle?
there any way to route a player empty hand block interact to script yet in stable apis? i see block has an on_interact but not seeing a way to route it to a script with a coordinate etc
oh custom components that you register via script api, interesting
tick event 
tick event did exist at one point in time, so it's not inaccurate, just... behind the times.
Wow, thats really great results, its not valid but beter the before tho
if ur looking for ai generated code you should 100% check out claude 3.5 sonnet
that thing is a menace
i think they re using something else like renders
yeah maybe
bingAI works better couse it can look for info in sites, you tell him to get info from microsoft.learn and it will give you the correct info
oh ok, i havent tried that
wow, thats cool
oh wow thats actually kinda impressive
chat GPT is good if you feed it the npm types and can spend time correcting its mistakes
yeah it works fine but you need to specify always to get the info from microsoft learn
I yoted my code in there yesterday and just asked it to optimize it
All it really did was make const variables for things I'm calculating several times
and then replace block.above(1) with block.location.y + 1
wild
Does the script run every game tick or every millisecond?
it's every tick
now if you just slapped a while(true) {} in your code, that will run as fast as possible and crash your game
yes
Ok tysm
system stuff runs once per tick- but world events can fire as many times as they are activated per-tick
e.g. if you break 50 blocks in one second, block break would then fire 50 times
does clearVelocity work on players
nah
it's a thing that let you disable movement or camera rotation
if it's that you want
Resource:
JavaScript Algorithms and Data Structures
Beginner to Advance
https://github.com/trekhleb/javascript-algorithms?tab=readme-ov-file
Al Gore Rhythms!!?!!???!!
Any good method of resuming a custom path system after the player joins the world again?
Why can't I put a DynamicProperty on my itemStack?
well it have to be non-stackable stack
is it non stscksble?
yes
The player.getComponent('minecraft:inventory').container.getItem(player.selectedSlotIndex).getDynamicProperty('balance') is just to replace item because it didn't seem to work
you have to save that item back, bc itemstack is abstract instance
basicly do this steps
- getItem
- set properties
- put item back
Did you ever get it to work? i'm having issues
Oh, yeah
It's a library you have to bundle in your script
do i have to import another module?
i'm not exactly sure what that means
i don't use other scripts often, just mainly @minecraft/server and ui
Do you use something like webpack to bundle your scripts into one file?
Unlike the other @minecraft libraries, @minecraft/math doesn't just contain types. It also contains actual scripts inside of it
its JS module it self, tho, but there is no need to use it
Yeah, I was just showing him that the math library contains stuff that actually does something
Well, ya but module also does something but in the MC directly not in JS
¯_(ツ)_/¯
but ya
Then, why does it even have JS code in it when it can just include types?
Well @minecraft/math is not module but NPM package
I'm aware of that...
thats the different and also reason why you can't import it by default
it doesn't exist in MC
thats utility pkg
Yeah, I know that
If I want to use an NPM package, I have to bundle it along with my scripts
it provides util funcs to use
oh
i was js needing it for the distance calculations
@slim spear this pretty much explains it
this too
||ChatGPT translators|| 
||as a translator i gotta say ChatGPT is alright at it||
||its just that some people depend way too much on it like how they leave their assignment to AIs||
This is true, chatgpt has helped my understanding of JavaScript a lot, but it does get some stuff wrong though. That being said, its usually easy to pick out what is wrong
I've been using chat GPT to help me with a few concepts
can anyone tell me whats wrong with this. its just supposed to change the permutation by using an item and its not changeing it at all
Debug result for [code](#1067535608660107284 message)
Compiler found 0 errors.
ESLint results:
shades.js
1:17 error 'BlockPermutation' is defined but never used @typescript-eslint/no-unused-vars
shit oops
Hi script team, any plan to add cancel these events:
~onAttack
~onBucket
~onDamaged
~onDeath
~onTriggered
~onExplode
~onInteract
~onTargeted
~onTeleport
~onShoot
~onCameraSet
~onItemUse
~onConsume
most of them already has beforeEvents
ok maybe not most
Is there a way that when you press any button the amount will show and increase when you press the second button the amount will increase? Does anyone know how?
Code:
function openForm2(player, tien, values = []) {
let text = ''
const form = new ActionFormData();
form.title("§m§i§n§e§fMINES")
form.body(`${tien}`)
for (let i = 0; i < 25; i++) {
if (!values[i]) values[i] = "gray";
if (!values[i]) text = "???";
}
values.forEach((value) => {
form.button(text, `textures/blocks/glass_${value}`)
})
form.button("§c§l§a§mAbc")
form.show(player).then(rs => {
if (rs.selection <= 24) {
if(abc[rs.selection] == "O") {
win++
if (win === countO) {
player.sendMessage(`Bạn đã win`)
ResetOX()
} else {
values[rs.selection] = "green"
openForm2(player, values)
}
} else {
player.sendMessage(`Lose\n\n${result}`)
ResetOX()
}
}
})
}
wdym "when you press button the amount will increase and show and the second button the amount will incrase"?
Yea
what does this mean?
I want it to increase the amount when the button is pressed
wich button
and what amount you want to increase?
When you press any button like there are 25 buttons, press 1 button it will increase, press 2 button it will increase again
ok but what do you want increase?
Money
in your code there isnt any var that is named money
I have used the part ModalFormData
i give up i cant understande what you re trying to say
You can create money in the section ActionFormData
money += increaseNumber
is that what you mean
That's right
ded

Send a pull request to have it updated.
can you... add colors?
like if I had #fbff00 and #ff0000 can they be combined to get the mix of the two colors?
You need to do some math yourself
myself? no thanks
Well...by that i mean you need to implement it yourself. MC doesnt have any
I'm not even sure if this is really worth doing lol
Whatcha trying to do?
my fan blocks work with my potion soaked sponges to give everything in the same fan column the effects of all of the potion sponges below it
and so my options were
a. have the fan particles inherit the color from the topmost block in the column
b. combine all the colors from the sponges in the column
don't particles use rgba
changing/setting the color isn't my problem
this is how the the beacon beam dose that
what in the world
something like this?
function mixColors(colorsArray) {
let colorsAmount = colorsArray.length - 1;
let result = [0, 0, 0];
for (let i = 0; i <= colorsAmount; i++) {
let w = Math.pow(2, i - 1);
result[0] += w*colorsArray[i][0];
result[1] += w*colorsArray[i][1];
result[2] += w*colorsArray[i][2];
}
return [
Math.round(result[0]/Math.pow(2,colorsAmount)),
Math.round(result[1]/Math.pow(2,colorsAmount)),
Math.round(result[2]/Math.pow(2,colorsAmount))
]
}
damn, particle documentation is also wrong lol
it shows examples saying you can pretty use any format for "color"
but they only work in terms of 0 - 1
can entitys use precise interactions?
no
that would be cool though
e.itemComponentRegistry.registerCustomComponent("evo:bone_crusher", {
onUse(e) {
const player = e.source;
const xyz = player.location;
const dimension = player.dimension;
player.startItemCooldown("custom", 20);
let nearbyEntities = dimension.getEntities({
location: xyz,
maxDistance: 10,
excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
});
nearbyEntities = nearbyEntities.filter(entity => entity !== player);
nearbyEntities.forEach(entity => {
entity.addTag("evo:bone_crusher");
entity.playSound("use.bone_block");
});
}
});
Why did it say "not a function" when I try add tag?
entity.playSound doesn't exist
try dimension.playSound("use.bone_block", entity.location) instead
Oh that only player, haha sorry
Thank you
const player = e.source;
const xyz = player.location;
const dimension = player.dimension;
player.startItemCooldown("custom", 20);
player.playSound("mob.enderdragon.flap");
player.runCommandAsync("particle evo:voids_edge_particle ~~~");
let nearbyEntities = dimension.getEntities({
location: xyz,
maxDistance: 10,
excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
});
nearbyEntities = nearbyEntities.filter(entity => entity !== player);
nearbyEntities.forEach(entity => {
const dx = xyz.x - entity.location.x;
const dz = xyz.z - entity.location.z;
const length = Math.sqrt(dx ** 2 + dz ** 2);
const dx2 = dx / length;
const dz2 = dz / length;
entity.applyKnockback(
-dx,
-dz,
3,
1
);
entity.runCommandAsync("particle evo:voids_edge_particle ~~~");
});
}
});
Does anyone know why entity still get pushed back instead of pull to entity who use sword?
you can input RGB if you divide it by 255
yeah
map.setFloat("variable.colorR", num / 255)```
💀
ended up with this ```js
function getColor(blocks) {
if (blocks.length == 0) return { r: 1, g: 1, b: 1 };
const color = blocks.reduce((acc, block) => {
const potion = potions.find(p => p.id === block[0]);
acc.r += potion.color.r;
acc.g += potion.color.g;
acc.b += potion.color.b;
return acc;
}, { r: 0, g: 0, b: 0 });
color.r /= blocks.length;
color.g /= blocks.length;
color.b /= blocks.length;
return color
}``` Idk what kinda junk is being done with that glass and beacon color, but you really just need to find the average
chatGPT taught me what .reduce was 😔

