#Script API General
1 messages Β· Page 9 of 1
Use an event that evaluates a state prior to the mount interaction and to compensate use a system.run to evaluate a verification of the player entity above of the mountable entity on the next tick. He does it in a messy way with the line I mentioned.
What he does not know is that he can use an event that evaluates the state afterwards and that when executing system.run from an event it is not executed in a tick later but in the same tick.
I read it directly in the official documentation. I think it was in the gameplay loop section.
:b speak.
Is my information useful? Admin.
i just figured it out anyways lol, just had some docs issues
b/c ngl theyβre kinda annoying to navigate
You learn to navigate as you play around in it lol.
Also tell me.
You can use https://stirante.com/script/ instead. Way more helpful imo than the official docs
wow, just explored a few things.
man o man... never going back to js, just coding with typescript is too nice to have
LOL
ty btw, never knew how handy it was
It's pretty.
It's a real game changer. Once you understand how to create the types and interfaces you want it makes development so much faster it's crazy.
If you like that typescript has to offer you should look into eslint at some point. In combination with typescript's strict mode it will eliminate 99% of bugs.
What the hell dude?
|| as number ||
ohhh awesome thanks for the heads up/tips!
Welcome to the other side π
th
thx
yeah. parameter types for sure game changer,
using tsc --watch
getting tired of /reload
Welll....dont you still have to do /reload?
yes, just less type errors
i will be doing less is all
sorry for confusion lol
I have a setup that automatically compiles typescript, bundles the code using esbuild and runs /reload every time you save.
I can post it in the next few days if people would use it. I just want to clean it up a bit and add documentation.
oh yeah that would be awesome
Thank you, this fixed my problem π
@wary edge i got it, thanks for helping out π
Nice
can anyone tell me how to detect if player left clicks/right clicks a specific item ?
like i can name the item/add a tag to myself, then i clcik the item and a command is run ?
JS Question Class Constructor
should it be only for the parameters => properties or should it also initialize anything that any of the parameters is related to or do the other properties outside of the constructor get initialized at the same time or if they are listed before the constructor?
that's a huge giraffe
Yes a giraffe π¦
{
"format_version": 2,
"header": {
"name": "Right Click Detection + Custom Click Sounds",
"description": "By TheGwimWeeper",
"uuid": "a936efa2-b925-9169-48f8-807ea620a0a1",
"version": [1, 1, 1],
"min_engine_version": [1, 17, 0]
},
"modules": [
{
"type": "data",
"uuid": "d90c1e39-57a1-9488-85e7-ac0a25c50e37",
"version": "1.0.0-beta"
},
{
"type": "script",
"language": "javascript",
"uuid": "0e365d5e-2fd5-d020-9d06-0de152d6a95b",
"version": "1.0.0-beta",
"entry": "scripts/index.js"
}
],
"metadata": {
"authors": ["TheGwimWeeper"]
},
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.1.0-beta"
}
]
}
can someone add the subpacks line to this please ?
Use the itemUse event
i figured it out :)
can u help with this ?
can you fix it and add the subpacks line if possible ?
"subpacks": [
{
"folder_name": "subpack_1",
"name": "First Subpack",
"memory_tier": 0
},
{
"folder_name": "subpack_2",
"name": "Second Subpack",
"memory_tier": 1
}
]
no inside the code if possible
i tried it but it didnt work
example manifest with subpack:
{
"format_version": 2,
"header": {
"name": "Pack Name",
"description": "Pack Description",
"uuid": "2fc2dd6f-86cb-4370-af70-21490a1ae471",
"version": [1, 0, 0],
"min_engine_version": [1, 13, 0]
},
"modules": [
{
"type": "resources",
"uuid": "f6821b4a-1854-44fc-a8a4-0c2847ffda46",
"version": [1, 0, 0]
}
],
"subpacks": [
{
"folder_name": "subpack_1",
"name": "First Subpack",
"memory_tier": 0
},
{
"folder_name": "subpack_2",
"name": "Second Subpack",
"memory_tier": 1
}
]
}
@chrome flint is editing this possible ?
like adding subpacks in this code ?
yes, by the example i sent, you should be able to do it by yourself
Did I confuse you? LOL... I have this constructorJS constructor(location, qty = 0) { this.startLocation = location; this.blockTypes = Object.keys(MinecraftBlockTypes) .map((k, i) => { return { index: i, key: k, typeId: MinecraftBlockTypes[ k ], name: MinecraftBlockTypes[ k ].split(':')[ 1 ], isAir: false, isLiquid: false, isSolid: true, hasTag: false, tags: [], xyz: { x: 0, y: 0, z: 0 }, y_offset: MinecraftBlockTypes[ k ].includes('cactus') ? 1 : 0, defaultState: {} /* button: facing_direction */ }; }); this.maxBlocks = qty === 0 ? this.blockTypes.length : qty; } //end constructor and I do not think blockTypes belongs in there... but max Blocks needs it to be complete.
experiencing is the best way of learning
oki ill try thanks :)
If blockTypes is a static thing, it's better to define it outside the function
well the location stuff is not, that is dep on where I am (this is just some test I am doing, worked, but I want to make it a class)
But I do think the base part of that can be outside and I can pull it in and add the location stuff...
or it be static
?
in the class
the base part
It definitely can- there's a reason people say to define function calls outside of other function calls..
- bad practice
- looks terrible
- performance
Same deal for constants as you have there
Some cannot be avoided
What function calls.. you mean the Object,keys()
Like, defining functions within functions
wait, then what does in a class
Say, a getScore() within a blockBreak call
same-ish deal to what you have-but the blockBreak is your function method, and your getScore is the constant
Something like that would definitely be better in a outside constant.
I thought the whole point of the class was to bundle it all together... maybe just same file is good enough
I have global constant calls in my class definitions 
How would I check if a block was broken with a pickaxe with a certain enchantment (stable)?
mini example?
outside file?
so not portable
Also check beforeEvent... something should lead to the item used to do it and from there you may be able to get that information
can anyone tell me why this isn't working ??
This addon detects when a player breaks a block and then adds +1 score to their mined scoreboard.
This addon can be used to make level up minigames where players have to mine certain amount of blocks to level up.
Made By TheGwimWeeper.
#minecraft #minecrafttutorial
yesn't
It's just imports from a global constants file I have, nothing special
what is the best way to keep player's modified movement component during a specified time without it being reset to sprinting
runInterval sounds horrifying so im trying to stay away from it
unless its the only way
nvm ig it is the only way
Is getComponent stable? For example: hItem.getComponent("enchantable") doesn't have any other fields when I add a full stop after
getComponent is stable. Stable typings donβt have a map on what class it returns based on specific parameters so it returns nothing. You have to use TS or jsdoc to set return type
How would I do that using js.
/**
* @type {_______}
*/
const component = item.getComponent()
Lol I'm lost. I've had a long break from scripting and addon making.
how can i describe a code using comments?
i dont know how to use those @param etc
those make the code pretty,
so i wanted to use them, to describe my code
but i dont know, how to
Here is a live example:```js
/**
- @param { import("@minecraft/server").Vector3 } locationStart
*/
locationSet (locationStart) {```So when I hover over the param
Part of is is also the settings I changed in vscode and it annotates in TS for me.
Think I need to take a refresher, still confused lol. Why did they have to make it confusing.
It is not that.. it is that there are a lot of tools.. search for what you need, you will find it.
guys how do i make it so that a command is executed when player right click a diamond named test ?
Official documentation for JSDoc.
You mean when they use it? That would be a check for itemUse. From there look and see if you are able to see the name of the item... if you can, that is the route
Have you done other subscribes to events?
i made a block broken counter
this
okay... this page (tho it is preview beta...) https://jaylydev.github.io/scriptapi-docs/preview/classes/_minecraft_server_1_14_0_beta.WorldBeforeEvents.html
This is before. See ItemUse.... travel down that road.... you want to get the itemStack...
imma try it out
some pages have sample code, you have to open them up
itemUse: ItemUseBeforeEventSignal
i gotta use this ?
wait ill send a zip file
this is what im working on
@neat hound
how do i implement the item use into it ?
import { world } from "@minecraft/server";
world.afterEvents.playerBreakBlock.subscribe((data) => {
let { player, block, brokenBlockPermutation } = data;
player.runCommand("/scoreboard players add @s mined 1")
})
can i modify this code somehow ?
like add itemUse: ItemUseBeforeEventSignal into it ?
can you tell how ?
Well I am confused... you want to know if they broke a block with a diamond named test... but you asked about a right click... those are 2 different things
left click hits and breaks.... right click interacts
no the code i sent
it detects when i block is broken
how do i modify it so that it detects player right-clicking a diamond
no, you sent beforeItemUse and UseOn
the stuff I just told you to look up
This is what you sent.... nothing about blocks
use your code to display the nametag of the item to the screen so you know if you can get it.... for breaking block, it can also give you the itemused to break the block, so in that code you can test for the same thing....
and bedtime for me.... good luck
real
One more thing... in VSCode, go to file, settings, open up extensions, scroll down to Typescript....(if you do not have it, not sure what I installed to get it)... but if you do, go thru all the options that say JavaScript.. all kinds of neat things to turn on. After I played with it I had more information than I wanted, but then I got used to it. It keeps me straight.
Now I sleep, nite folks
I'm using bridge. Still can't get the detect silk touch script working...
Need help
Donβt we all
It s not philosophy time π
Ok when i m trying to
world.scoreboard.getObjective
He told me u can't read getObjective of undefined
Even after i wrote :
world?.scoreboard?.getObjective?.(objective)
Maybe beforeevent?
check typo
or any similar variable with the name world
Or actually, confirm where the error comes from
Thefe is no
Maybe you cursor typed getObjective on another place
I think this is not possible an asignation like this
import * as mc from......
const world = mc.world
world.scoreboard = .....
But maybe(????
?
No
/**
* Returns the score of a player in the specified scoreboard objective.
* @param {string} objective - Scoreboard objective.
* @param {Player} player - The player object.
* @returns {number} The player's score or 0 if not found.
*/
function getScore(objective: string, player: Player): number {
try {
return world.scoreboard.getObjective(objective).getScore(player.scoreboardIdentity);
} catch (error) {
return 0;
}
}
/**
* Sets a player's score.
* @param {Player} target - The player object.
* @param {string} objective - Scoreboard objective.
* @param {number} amount - The number to set it to.
* @param {boolean} stack - If true, it will be added instead of set. Default false.
* @returns {number} The score it was set to.
*/
function setScore(target: Player, objective: string, amount: number, stack: boolean = false): number {
const scoreObj = world.scoreboard.getObjective(objective);
if (scoreObj) {
const isParticipant = !!scoreObj.getParticipants().some((participant) => participant.id === target.scoreboardIdentity.id);
if (!isParticipant) {
target.runCommand(`scoreboard players add @s ${objective} 0`);
}
const score = isParticipant ? scoreObj.getScore(target.scoreboardIdentity) : 0;
const result = stack ? score + amount : amount;
scoreObj.setScore(target.scoreboardIdentity, result);
return result;
} else {
return 0;
}
}
ok so im doing skyblock island loading and saving
and when im loading the island it lags the game quite a bit
currently i have a 128x128 island.
and im using 4 structure blocks, (each at 64x64) to load the island
in the image there are 16 32x32 structure blocks
if i change the loading to use the 32x32 structures, would this create less lag?
and introduce priotity loading by loadint the 4 chunks in the centre and then the outside ones.
or split it up even more into 32 structure blocks at 16x16 each
idk, i just need a way to load efficiently without killing the server.
like this.
If the function is not local in the same script where you are calling the function then it means you have it in another script, or you don't have the function at all. If it's in another script you need to export it, then import it to the script where you call the function.
is it possible to make the player to do swing animation when using a custom item
not on specific blocks but use in general
How can i show scoreboard with number beside it ?
Why was the all in EnchantmentSlot removed? And there's still no Mace EnchantmentSlot Enums yet in the latest api
playAnimation
scripting not the best option to play animation
u can do it with json
i dont think swing animation is possible with that
Waiting for a few ticks in between structure loads might help
Not sure about the "all" but you could definitely make a report for "Mace".
okay, not really big of a deal for the devs ithink, but yeah. i'll try to report it later. thanks
import { world } from '@minecraft/server';
import { ActionFormData } from '@minecraft/server-ui';
console.warn("Hello.")
const custom_form = new ActionFormData()
custom_form.title("Map Viewer");
custom_form.body(" ");
custom_form.button("Base")
const meow_form = new ActionFormData()
custom_form.title("Meow Viewer");
custom_form.body(" ");
custom_form.button("Cat")
const ae = world.afterEvents;
ae.itemStartUseOn.subscribe((e) => {
const item = e.itemStack;
const src = e.source;
console.warn(item);
if(item.typeId == "stick") {
custom_form.show(src);
} else if(item.typeId == "clock") {
meow_form.show(src)
}
})```Why it doesn't show the forms? π
Ignore the console.warn, I made them just to test if the script is even running.
i dont have it, how can i solve this
youre using itemStartUseOn
try itemUse?
Oh, lemme try.
im crying about the inconsistency in ;
I'm sorry.
So it does warn the item object but it doesn't show me the form for some reason.
then the form is most likely wrong
shrug!
try adding .then(f => if (f.canceled) console.warn("here 1"))
let me give you an example but its a modal form
function dcConfig(player) {
let form = new ModalFormData()
.title("Dungeons Combat Settings")
.toggle("Toggle Mod\n(You can use compass to open this menu.)", player.getDynamicProperty("dc_state"))
.slider("Camera Distance", 15, 30, 1, player.getDynamicProperty("dc_camdist"))
.slider("Camera Position", 1, 4, 1, player.getDynamicProperty("dc_campos"))
.slider("Camera Lerp", 10, 50, 5, player.getDynamicProperty("dc_camlerp"));
form.show(player).then((response) => {
const { canceled, formValues, cancelationReason } = response;
if (response && canceled && cancelationReason === "UserBusy") {
dcConfig(player);
return;
}
if (canceled) return;
player.setDynamicProperty("dc_state",formValues[0])
player.setDynamicProperty("dc_camdist",formValues[1])
player.setDynamicProperty("dc_campos",formValues[2])
player.setDynamicProperty("dc_camlerp",formValues[3])
if (player.getDynamicProperty("dc_state") == true) {
setcamera(player)
} else {
clearcamera(player)
}
})
}```
this is how i did
no eror? no anything?
Yes.
try to see if your character's auto canceling it
I see I see thanks.
ty thatβs actually so much better
thanks, worked!
Now time to beg for json ui help lol π
I'mma figure out something.
U know json ui is the final boss
Fr fr.
would there be any reasom for someone to have more than one js file in theire manifest stuff
? More than one ?
no
dont think you can do that
then must your script file be named index.js or main.js
or can you change the name
Idk
Why are you attempting to call a function that you do not have in your code? I'm more curious about that one lol
Also, if you scroll above where you first mentioned the function there is some code regarding that function name which you could use to accomplish your goal.
It's written with TS in mind so you would need to clean it up slightly
thats better then what i can do
is it worth learning json ui or paying someone to do it for me?
It is worth it to learn js
id say
90% yes
half of 90% is "learning something is great"
the other half is "i can make something ive dreamed of in minecraft"
It is worth learning.
json ui sounds really worth learning considering there are only few who knows it
but
idk if it pays well
i couldnt even start learning json ui because of how tedius it is
it dose pay well
yeah but like the learning progress counteracts it to me tbh
im just waiting for ore ui to be a thing
same π€·ββοΈ
JSON UI is rewarding if you are good at it and know what you're doing
It sucks cuz you have to relog into the test world, and the miniscule changes to offsets & whatnot are annoying as hell
yeah thats the major thing
its like
making visual blindfolded
and then everytime you finish making, you take the blindfold off
I would kill for a live JSON UI web editor tbh
Yes , we need something like that
We need to wait until someone made it
If u want ur sanity to be well then pay
If u want to be phycopath then learn
- they gonna change it
With ore ui
So
[mini rant]
Just "love" it when you look up a component in the massive list of script components. Just to read an ambiguous piece of text and nothing about how this component would supposedly be written in the script...
context.
This, does help explain what the component would use, but not how it would look as written.
https://stirante.com/script/server/1.11.0/classes/PlayerInteractWithBlockAfterEvent.html#block
It is almost like it could use an example of how the code would look like.
Just like how json files were documented in wikis and they had their code either explained out in full, or have an example to use as a reference.
Which helped a lot for someone learning from scratch.
Like this for example:
https://learn.microsoft.com/en-us/minecraft/creator/reference/content/blockreference/examples/blockjsonfilestructure?view=minecraft-bedrock-stable
The former gives this detached piece of information folks may not know how to apply to a string of code.
The latter is a bit easier to apply like modules without needing to somehow know that "void" means this, or that "arg:" means that something else can be put in its place.
Something like a format guide would help a lot at this rate.
I feel ya bro
use jayly script docs
it explains
Thanks. I'll try. π₯²
Okay I'm making one.
Fuck i can't.
I'm too bad ;(
loll
Good luck with that
function keys(player){
const commmonkey = world.scoreboard.getObjective("ckey").getScores
const rarekey = world.scoreboard.getObjective("rkey").getScores
const epickey = world.scoreboard.getObjective("ekey").getScores
const keys = new ActionFormData()
.title("your crate keys")
.body(`you have\n ${commmonkey} common keys\n ${rarekey} rare keys\n ${epickey} epic keys`)
.button("back")
keys.show(player).then(d => {
if (d.selection === 0) {
main(player)
}
});
}
``` How do i define getScores?
Get score defined by addScore
o
I can actually make one. Only if i understand how Json UI works in the first place π
π
True True.
It honestly feels like a portion of fledgling addon writers have migrated to this section of the script abyss, and those able to write scripts have to deal with clueless folks asking the same questions in roughly the same way.
Which is a bit funny to see, but on a serious note makes me feel bad for bothering folks on where to learn and how it works.
Sorry folks XD
Comes with the territory, I'm afraid π
ikr, few weeks ago I didn't even know what scripts are
we all been there (still are)
Most people don't mind others asking questions, as long as the asker is making a conscious effort to learn themselves.
its surprising how fast a human can learn something if they are focused in it
like how i got to this
in a month
UW
facts me to bru
and i still have the command block badge lol
a day ago I was looking at jayly docs and was like tf?
Anyone can learn it, you just need to β¨ believe β¨
now its all coming to me
I started learning script API without knowing js π
I learnt js to make addons but i never made addons.
I m an atheist
Was going for Lego Movie
Oh
Jk i m not
have you heared of the trip?
feels like im making double decker couches everytime i write something in main.js
my first addon was a script api one
i didn't know shit about the api then
and it is still the second best addon i ever made
I had to learn js to understand script, we are not the same
Both Jayly and Stirante have done a lot of work to provide the help they provide with those API websites. I personally have Jayly's open 24/7.
They do it out of love for the game and for the knowledge. Jayly has added a lot of examples to his, but not to every thing. It is not his job, he does not get paid to do it.
That said, you can find lots of examples in this discord if you search on the key words. If you are not finding what you need, there is a whole community here to help and Jayly is active in this discord., Stirante in the OSS discord.
The trip?
stirante?
What is it about ?
The examples on their websites are ripped straight from the types
bookmarked
Now though I'm good at JS I don't make add-ons much. I do more web dev.
if you see Smokey's links, they are stirante's... looks bascially the same
arabic support for chat
jayly really carried the scripting community
Nice
always has been
Here is a link https://stirante.com/script/server/1.11.0/classes/PlayerInteractWithBlockAfterEvent.html#block
Documentation for @minecraft/server
?
lol
Wth π
I ll be sad if he is not getting paid for it

the rep is good enough ngl but he should be getting paid 100%
Ads exist on his docs site for that; I don't think he expects to get paid, really. Just a hobby for most here.
he is? i think
his website have ads
I have ad blocker π
lol.
there are ads?
I do not see adds anymore... I forgot about those... I wanted to ask him, can I just join or something and pay.... but they have not bothered me lately, so not sure if still there
yes
i ve never seen ads and I don't use adblocker
or my blockers are doing their job
Not on the microsoft docs- on Jayly's docs
maybe after the 100th look up, you get no ads... LOL
ik
ah
There are ads.
Lmao.
i am getting a blank white area instead
πΏ
-# Ladies and gentlemen... WE GOT EM
send link so I can see if ad for me
β
Jayly has been sentenced to 5 years in prison.
indefinitely
He has a perma get out of jail free card with me....
we'll all share the sentence so he gets out quicker
Good idea.
Anything for you Jayly π
we have about 215 members
no ads.... how am I doing it... wow, thankful cause I hate ads.. I'd rather pay membership
should be at least a month
idgaf either way
I ll share it with my pet
I'll share it with all of my fingers.
sukuna?
is that you
π
I ll share with every molecule in my body
flash?
Flash ?
if you don't mind telling how did you tank Jacobs ladder
Whot-
if ykyk
okay when a real q uestion comes... stop all the nonsense....
Script updates wahoo
Yay!
What s new ?
Yayay!
Lmao.
Interaction button ?
The event fires every tick until you released the use button, there's now a property for that so u can filter
Agree
Nice!
Ahh its preview day
I don't do much script API but yay anyways.
and how do you know much about it
PlayerInteractWithBlockBeforeEvent Added property readonly isFirstEvent: boolean to beta. This value will be true if the event was triggered on players initial interaction button press and false if triggered on holding the interaction button
YES
yes
I should not make one yet because ore UI is getting released pretty soon I believe?
idk if ore UI is getting released soon
Who said I know much about it π
I just know how to write js and read documentation.
I'm better at D.js then Minecraft script api.
Ah I see.
will it be done blindfolded like Json UI
This right here (π―).... I personally don't mind helping, as long as I get the vibe they really want to learn. If they are just looking for someone to do it for them, I tend to move on.
whats the best way to load a 128x200x128 structure? π
well yes
So u gotta devide it by 4
the height is more than 64 block
256 if i am not wrong
nice my speciality
creeping crypts exists so its possible
What are crypts ?
its an addon that adds a dungeon with a ridiculous amount of randomly generated rooms
Send link
?
one sec, internet is really slow on my end
Thx
is it normal to get ms spikes of ~140 the first time almost any event subscription is used?
for example, if i have subscribed to the entitydie event, the first time a mob dies i get an ms spike of like 120ms and then all next entities that die die smoothly
140 is a lot
depend on the script
Maybe ur device is low end device
it is
very
can barely play multiplayer
yea i think i shouldve mentioned that
it's ok it only happens the first time an entity dies for example
Idk
Does anyone know the reason for the error?
beforeEvents is read-only
Use afterEvents if u won't need event.cancel
(If that link works for you)
Or use
system.run(()=> {
//Ur code
})
thx
Sus π
"say my name"
my name
πΏ
how do i measure tps?
Ticks per second?
yes
yes
Any idea on how to use system.runJob()?
Hey i have question
I solved it, but the form is not shown
it uses generator functions
look into that
import { system, world } from "@minecraft/server";
// Variables to keep track of ticks and time
let tickCount = 0;
let lastTime = Date.now();
let tps = 0;
let tpsValues = [];
const intervalSeconds = 5; // Interval to calculate TPS
const intervalsToAverage = 12; // Number of intervals to average over (e.g., 12 intervals * 5 seconds = 1 minute)
// Function to calculate TPS
function calculateTPS() {
const currentTime = Date.now();
const elapsedTime = (currentTime - lastTime) / 1000; // Convert milliseconds to seconds
// Calculate TPS
tps = tickCount / elapsedTime;
// Store the TPS value
tpsValues.push(tps);
if (tpsValues.length > intervalsToAverage) {
tpsValues.shift(); // Remove the oldest TPS value to maintain the average window size
}
// Calculate the average TPS
const totalTPS = tpsValues.reduce((sum, value) => sum + value, 0);
const averageTPS = totalTPS / tpsValues.length;
// Print TPS and average TPS to console (or use for other purposes)
console.log(`TPS: ${tps.toFixed(2)}, Average TPS: ${averageTPS.toFixed(2)}`);
// Reset counters
tickCount = 0;
lastTime = currentTime;
}
// Function to increment the tick count
function incrementTickCount() {
tickCount++;
}
// Initialize world events and set up the TPS calculator
world.afterEvents.worldInitialize.subscribe(() => {
// Set an interval to increment the tick count every tick
system.runInterval(incrementTickCount, 1); // 1 tick interval
// Set an interval to calculate TPS every intervalSeconds * 20 ticks
system.runInterval(calculateTPS, intervalSeconds * 20); // 20 ticks per second
});
One of many ways to do it. This script will calculate and display the TPS every 5 seconds but the TPS being shown is the average TPS over the last 1 minute. Basically the first minute will be a process to determine your average and every 5 seconds after that will essentially be your average that's maintained. Make sense? π€ͺ
How will that give u Correct tps ?
Considering latency, ping, hardware, etc, it will be extremely difficult to get an accurate read on TPS. Given the variables which can be problematic to some and maybe not so much to others, you don't have many options.
Issss Minecraft Diagnostic available in the latest stable????
No, it was introduced in 1.21.10 iirc
Can i make a block go from right to left like sand block
Example is on this link: https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_12_0_beta.System.html#runJob
not stable yet tho
how about client <> server latency?
How to prevent baby horse from spawning via
dimension.spawnEntity("horse", location)?
I have no idea lol.
Kill it
Using Entity Spawn event and extra checks
Are you running commands when the event triggers? The first time a command is run in your script there's a pretty big delay most of the time.
Is there a test for block equivalent for scripts that returns the block id of a block at a specific location?
Dimension.getBlock(block location).typeId or something like that, I'm not at home to confirm
import { world, Dimension } from "@minecraft/server";
const player = world.getPlayers()[0];
const block = Dimension.prototype.getBlock.call(player.dimension, player.location).typeId;
console.warn(block);
@ionic kayak
Adjust location as needed.
It can throw if the block is unreachable.
how to access horse equipment
(how to saddle the horse using script)
- equippable > "Body"
- replaceitem command
is the body for saddle or horse armor?
maybe
wtf
Why doesn't kick works? Like I'm using player.runCommand(kick @s) and it just don't kick
I tried using player.name
And world.getdimenson.runcommand too
Tried something my own, but it throws an error saying the dimension canβt be found
What did you try?
Show the code.
Actually let me try something real quick
you're supposed to do world.getDimension() not importing the Dimension class
Have to tell it a specific target.
world.getDimension(player.dimension.id).runCommand(`kick ${player.name}`);
You can call it from a prototype.
player.dimension alrwady returns dimension class.
Wouldn't that be an error tho? It specifically bind the method calls next in that dimension. Calling it from a prototype woudln't technically work
It works. Try and see for yourself.
I will try
if it work, then what dimension it were being called from? maybe Overwolrd as default?
Interesting knowledge from you, i might test it later
The parameter for world.getDimension() requires a string not the Dimension type. It returns the Dimension type.
That's not what I mean.
player.dimension already returns a Dimension instance of where the player's current dimension is.
Doing world.getDimension() and then player.dimension.id is redundant.
Ah, I see.
Valid.
However, given my experience, the kick command tends to run into permission issues unless called from world.
If I remember correctly, you cannot use selector argument on /kick command. Only player names
yes
That is also true.
So this "was" his issue
Yes, which I mentioned.
I think calling runCommand() from the Entity class ignores the target permission.
I know that calling it from the Player Class would sometimes result in a failure when kicking a player, due to permission issues, and logging it via try/catch logic helped to recognize that problem some time ago. So the solution found to help work around that was the example I shared above, albeit being redundant.
I see... well thanks for the knowledge. I'm gona test it later
I knew what the exact reason was back then. I've forgotten now. It's plausible I made a note on it in the commit, back then lol.
It worked, I didn't know you can't kick yourself/owner of the world, thanks man
Welcome
Any idea about how to detect air with getBlockFromRay?
getBlockFromRay({ x: x, y: y, z: z },{ x: 0, y: -1, z: 0 },{ includeTypes: ['minecraft:air'], includePassableBlocks: true }```I try this but dont work
Simply, you check if it returns undefined
then its air
ahh i accidently removed the "summon baby hose" post which was resolved already, this happend for the first time in years sorry to the owner whoever posted that
It doesn't work for what I'm looking to achieve, however, thank you very much.
what's new in interact event
https://discord.com/channels/523663022053392405/1268601041063247955 Feedback post fyi
but what's new
yeah saw that now
nay
on air? That's the neat part, you don't
Can detect on block & entity, that's it
and does the entityHitBlock fire only if the player hits a block
not even some sort of
returning undefined block or anything?

god
damnit
kinda in the name
how do i reset all the items' cooldown at once?
const cooldowns = [
"minecraft:chorusfruit",
"minecraft:ender_pearl",
"minecraft:goat_horn",
"minecraft:shield",
"minecraft:wind_charge"
];
for (const categoryCooldown of cooldowns) {
Player.startItemCooldown(categoryCooldown, 0);
};
huh i can do that? neat
ty
Is it a bad idea to run a replacing item script with no delay? It basically replaces certain items in every players inventory with another item. I can make it so that it will only run for creative players (since the item I'm talking about is only obtainable in creative).
just iterate through cooldown category
What does only triggered on successful interaction in playerInteractWithEntity mean? No longer possible to make an item useable on every mob without modifying every mob?
Edit: sorry for crossposting, ended up asking the same thing in #1268601041063247955
Is there a way to fill an area where the game won't load?
tickingarea command, you should run tickingarea in all the area not loaded
It's not a "bad idea" but you would definitely need to make sure the logic for looping through each player, and their inventory of items is as efficient as you can possibly pull it off to minimize the impact that script may have on your world.
import { system, world, Player, ItemStack, ItemTypes, GameMode, EntityQueryOptions } from "@minecraft/server";
const specificItem = "minecraft:stone"; // Replace with the specific item identifier you want to check for
const replacementItem = "minecraft:diamond"; // Replace with the replacement item identifier
async function checkAndReplaceItems() {
const queryOptions: EntityQueryOptions = {
gameMode: GameMode.creative
};
const players = world.getPlayers(queryOptions);
for (const player of players) {
const inventory = player.getComponent("minecraft:inventory").container;
const size = inventory.size;
for (let i = 0; i < size; i++) {
const item = inventory.getItem(i);
if (item && item.id === specificItem) {
inventory.setItem(i, new ItemStack(ItemTypes.get(replacementItem), item.amount));
}
}
}
// Schedule the function to run again after 20 ticks (1 second)
await new Promise(resolve => system.run(resolve, 20));
checkAndReplaceItems();
}
// Start the loop
checkAndReplaceItems();
Something like this I believe. Not really tested, but it's written up to be asynchronous to help it from jamming up the main thread, allowing other code operations to continue smoothly in your script, should that be applicable.
theres no way to just reset the entire categories, right?
what do you mean? it's seting item cooldown for every registered category to 0
if you have some of your custom cooldowns, just ad to this array
i mean well
im asking cuz there are a bit too much categories 
but thanks anyway, better than nothing
there' s no other way, just add them to this array'
AND for a bit of a type safety, you can add type to this
/**
* @type {readonly srtring[]}
*/
const cooldowns = [
"minecraft:chorusfruit",
"minecraft:ender_pearl",
"minecraft:goat_horn",
"minecraft:shield",
"minecraft:wind_charge"
];
meh im using custom cooldown categories so
you have to add them to this array
there's not really any other solution in API to remove all of these cooldowns
at this point you can build yourself a small API
sounds a bit overkill for one functionality
import { Player } from "@minecraft/server";
/**
* @type {readonly string[]}
*/
const categories = [
"minecraft:chorusfruit",
"minecraft:ender_pearl",
"minecraft:goat_horn",
"minecraft:shield",
"minecraft:wind_charge"
// all these categories
];
class PlayerServer {
static resetItemCooldowns(/** @type {Player} */player) {
for (const cooldownCategory of categories) {
player.startItemCooldown(cooldownCategory, 0);
};
};
};
export { PlayerServer };
to not repeat yourself later
to be more specific the cooldown reset only happens when you use a special item
so
yeah
actually i should do that lol, dont wanna make that one item code in particular to look larger than rest of the code
umm, how do I summon an entity with scripts
whatcha trying?
i tried tickingarea add ~36 ~-1 ~-45 ~45 ~-5 ~45 ddc and then fill ~36 ~-1 ~-45 ~45 ~-5 ~45 grass but still can't fill it
Excuse my absence, my children. I'm studying basic web programming.
Hi boss. I'm hungry
me too
@wheat condor
Very sad.
I want to make my item shoot a projectile
.spawnEntity("entityTypeId", location: vector3)
use shoot method
get the projectile component first
what it gonna be attached to, player(source) or entity()
dimension.spawnEntity("entityTypeId", location: vector3)
thanks but what do you mean by projectile component
Anyone knows where's the docs for Experimental Features toggles and what it means? π
uh
You don't know what is Experimental Features Toggle?
bruhh
There's no way you dont know about tha-
Your the creator of that lumber axe addon right?? I know you
Theyre usually up to date:
Instead of acting like this, maybe give them the link? There are 7 experimental toggles, maybe they want to know all of them
Okay understood sorry
idk what i am doing everytime xp
Internet so slow
Thanks
Adding the ticking area only starts loading the chunks. You have to wait for them to be loaded. If you're using beta API you can use dimension.fillBlocks, which will throw an error if the chunks aren't loaded yet.
You mean every block in the registry? Or do you mean outside loaded chunks?
outside the loaded chunks
so you just afk the player
Last i checked you cant get outside loaded chunks
getBlocks have allowUnloadedChunks parameter
but getBlocks return only positions
you still need to deal with that
what do you mean
so i cant getBlock for the unloaded chunk?
player.dimension.spawnEntity({ identifier: "minecraft:pig" }, location())
do i make an object inside location
and is there a neater way to do this
ticking area
{x:number,y:number,z:number}
so I'm making an object
inside an object
or do I put it into a constant anddo it that way
player.dimension.spawnEntity({ identifier: "minecraft:pig" }, {x:number,y:number,z:number})
thx but can I put it into a const
const spawmEntity = player.dimesion.spawnEntity();
spawnEntity = {...}
Will this work
Heh
bruh what
const entity = player.dimension.spawnEntity({ identifier: "minecraft:pig" }, {x:number,y:number,z:number})
change number to a number
ok, sorry my js knowledge is janky
it is alr
you should take a basic js course
What are you trying to do with that?
I have but its still new to me so I'm polishing my js skills with scripts
me?
Yes
btw spawnEntity is not object it is a function
im trying to make an item shoot a projectile when I rightclick
am I doing it right?
well that only spawns the entity, you need to get the location numbers right
and since you're using an item you might want to spawn it in front of the player
also if I set it to 0, 0, 0 will it spawn on the player or on the world coords
kinda
but you are just spawning it there is a shot function and it is better to spawn it in head location
it spawns it in the dimension coordinates 0,0,0
bruh
no
give me a minute and i will write something for u
okee
ye so you need to get the player's head position
world.afterEvents.itemUse.subscribe(async event => {
const { source, itemStack } = event;
const power = 1
const velocity = Vector3Multiply(source.getViewDirection(), power)
const location = Vector3Add(source.getHeadLocation(), source.getViewDirection())
const arrow = source.dimension.spawnEntity("minecraft:arrow", location)
const projectile = arrow.getComponent('projectile');
projectile.shoot(velocity)
})
function Vector3Add(a, b) {
return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z }
}
function Vector3Multiply(a, b) {
return { x: a.x * b, y: a.y * b, z: a.z * b }
}
thanks so much
whoa this is uhhh...
change the power to change the velocity
also there is a lot of parameters in the projectile component
like gravity and other things
after the projectile const I don't understand anything, lol
the last functions is just to add and multiply vector3 ({x:number,y:number,z:number})
the shot function is a function that receive velocity and shot the projectile accordingly
but why
this why i need to add
Does @minecraft/math contain Vector as well?
the multiply is kinda obvious
nvm
it dose but it is a external library now
check the pined messages
How do I use @minecraft/math
limit?
is there a way to load/generate chunk without needing the player to go to the position
Do I have to include it in the bundled JS file?
Answer to my question: yes
yeah
but there is some vector3 class people coded here
check the pined messages
I just used that NPM package and bundled it how I usually would
Also, can I change gamerules without using commands?
The gamerules fields in World seems to be read-only
lol all your questions end up with nvm
I always end up finding out myself. I don't know why I ask instantly qwq
nope
How to use dimension.fillBlock?
Same
Is there any way to load chunks? Even by using commands
I need this because the function I made requires it when 0 0 isn't loaded due to the location being in the ocean
function getHighestOverworldBlock(x: number, z: number) {
return server.world
.getDimension("overworld")
.getBlockFromRay(
{ x, y: 319, z },
{ x: 0, y: -1, z: 0 },
{ maxDistance: 320 },
)?.block;
}
Tickingarea
Like this?
Ye
Hello, does anyone know how I can get the player's hunger percentage with a script?
Item lore limit is 50 letters, is it possible to increase it?
no
tameable component is undefined on wolf, why?
not possible
oh well, thanks
Would it be possible with commands?
because in wolves' json the tameable component is in their wild component group instead of in "components", and thus gets removed when they get tamed
i... can you rephrase I didn't understand im sorry
only wild wolves have the tameable component
spawned wolves have?
yes
it's not yet tamed so it's wild yet it's still an error
my code
let wolfie = overworld.spawnEntity("minecraft:wolf", player.location);
wolfie.getComponent("minecraft:tameable").tame(player);
console error
... TypeError: cannot read property 'tame' of undefined ..
the wolfie is spawned, yet no tame
try putting system.run around wolfie.getComponent("minecraft:tameable").tame(player);
i mean
let wolfie = overworld.spawnEntity("minecraft:wolf", player.location);
system.run(()=>wolfie.getComponent("minecraft:tameable").tame(player));
oyyy you solved it thanks so much!
np, it's basically because the wild component group of the wolf isn't added instantly
so you delay the taming a little with system.run
ok so basically you can add a ticking area only if the area is currently ticking and there is a limit, so basically if the area is larger than 64x64 blocks you need to teleport you in one side and then add a ticking area then teleport on the other side and add another tickingarea then remove the areas, is s bit complicated becouse there isnt any way to start loading a chunk in bedrock edition without using the player to render it
ohhh ohh i get it now if the component is still being added from component group or something. thank you!
ill make it simpler
if area < 64x64 : fill.
if area > 64x64 : add the firts tickingarea, teleport the player in the remaining part, add the second ticking area,(more area uncovered more tickingareas), fill all the area(if fill is more than the limit just do 2 times fill), remove all ticking areas
if area > ten times 64x64 : add the firts tickingarea, teleport the player in the remaining part, add the second ticking area,(more area uncovered more tickingareas), fill all the area(if fill is more than the limit just do 2 times fill), remove all ticking areas. redo the process for the rest
remember to add like 5 ticks of delay between all the operations to optimize it or the game will crash
or just add a menu with ticks based on the device to make slower (40 ticks) less laggy for mobile players and faster (3 to 5 ticks) for pc players
@hazy nebula
and use scripting to fill
how to i play an animation like the vanilla axe swing when stripping custom logs instead of the awkward place only lol
you make your own π
? im confused why i have to make my own animation when using bonemeal does the item swing thing
hard coded
whats the difference theyre both items
the swing animation is hard coded
right i know that. but why does bonemeal do the swing when in a script and using an axe doesnt
They are two different items
how to add wolf armor to wolf using scripting
Try using ItemEquippableComponent on the wolf entity
"@minecraft/vanilla-data" doesn't need to be in the pack's manifest dependencies, does it?
import { MinecraftItemTypes } from "@minecraft/vanilla-data";
is throwing
[ReferenceError: Module [@minecraft/vanilla-data] not found. Native module error or file not found.]
You need to bundle it
It's not a module technically
bundle it?
tried it equppable is undefined
Maybe make a full post for this one and include your code
you will need to npm it @ your scripts folder to get the download of it. If you are doing JS, may need to make a package.json with {} in it, then run npm init, then npm the vanilla data... then the vanilla data js file isn deep in there, can pull out or reference it.... if ts.... well.. however that works, you still need to get that node-modules folder installed.... I had to deal with this frustration the other day. King and Kiro has to hold my hand thru it.
I suggest running a formatter on the index.js file cause it's ugly-style...
Thanks all
I've also got an entity that looks like this:
"format_version": "1.20.40",
"minecraft:entity": {
"description": {
"identifier": "canopy:probe",
"is_spawnable": false,
"is_summonable": true,
"is_experimental": false,
"properties":{"canopy:light":{"type": "int","range":[0, 15],"default":0}}
},
"components": {
// components
}
}
}```
But things like projectiles and player hits still interact with it. Can I make it even more invisible?
Disable hitbox
#1067869022273667152
Not channel topic
Agree
does adding ticking area on ungenerated chunk makes it generate the chunk?
No, you would need to have a player to generate the world
so i need to teleport the players there?
how about simulated players?
I do not know
simulated players work like players
they can load chunks
how can i add custom armor equip sounds
i could use itemUse event but that wont work when wearing the armor directly in inventory
You can load chunks using ticking areas without having a player at all with BDS. Does that not work the same in the regular game?
Will that generate the terrain?
how about generate
im not sure to understand how to use this
world.beforeEvents.playerInteractWithBlock.subscribe(bruh => {
world.sendMessage("no way")
})
``` can't call it like that
i honestly dont feel major difference between beforeEvents and afterEvents
i can't even use afterEvent
other than using beforeEvents for custom components
idk

@rich kernel are you using the beta apis?
no
There's your answer
oh no
PlayerInteract is in beta APIs

is there any way I can know if the player is interacting with a block (like itemUseOn but with the hand also)?
without beta
I think I need beta for that unfortunately
The class is stable, but thereβs no way to access that class
that's weird
WHY MOJANG
WHY?????
WTF

I recommend using stirante's website, far more easier to understand what is and isn't stable: https://stirante.com/script/
yeah i should unpin microsoft docs off my chrome
so called creators of one of the largest operating system
shameless plug https://jaylydev.github.io/scriptapi-docs/
You should still keep it, just not for scripting
meh i can just leave it open in the tab
also i can do this, right?

wrong reply but its close enough
itemuse triggers when player rights clicks the jtem (eg eat)
and no trigger for wearing the armor itself?
probably not. You probably have to make your own event to listen for that armor in the slot
sounds like runInterval thing
Sounds like it
I have a feeling they def want to add inventory events one day. I bet it's alot of backend work.
yeah
Yeah, just tested it in a random location of a brand new world. I can get any block in a chunk that has never been visited by a player.
I guess I can't be sure if that's proof that it generated the whole chunk though... Might have to try to load the data in a world editor
To my knowledge, the game generates terrain when a player loads it in
"tiny"
All part of the process in learning π€ͺ
its a damn 50/50 chance too
nah
the game will either have mercy and do watchdog
or my phone will run out of memory
and the content log's last words would be Out of Memory
There is logic behind everything... else nothing in the world would work
It would be "out of m.."
Lol, I hope not. Trouble shooting memory leaks can be a daunting task for new/future developers.
Lol
all of my out of memory errors were from not being able to clear runinterval and were related with texts lmao
I've crashed the world more then enough times lmao
how do you guys managed to use up all the script memory
i saw that one block of code, thinking "why did i put this here?
" and removed it
It only allows 250 MB correct?
not even script memory, it was my entire device memory
That's really bad haha

When your screen is full of thousands of new intervals... your fkd
my phone UI literally restarted
basically i was making dynamic health bar using nametags and i had to keep track of the entity's health using runInterval
you know the rest
Didnt they add something new to get the top most block?
Top most block of what? To be more specific lol.
Just to get the top most block from a location
Yes they did
Do you know what class its a part of?
Documentation for @minecraft/server
Ah, thank you
Dang that's so much better then previous raycast
Ah, it's preview. Would explain why I couldn't find it lol. I was looking at getBlockAbove with Ray cast options haha.
we can't set damage on custom items?
Wdym?
waht does data-driven items mean?
Means custom items
whatcha trying though
Seems like a #1067869136606220288 questiob
let dura = item.getComponent("durability")
dura.damage = 50;
this is what I got but im not sure if this is what im supposed to do
hmm i could give you the code but its in my tablet rn
and im outside the home
ahh np
brb ill check smth
alr
so damage part represents how much 'damage' the item has gotten
(duh)
but if you were to add damage (or in other words, reduce durability), you need to add values on it
dura.damage += 50 iirc
cant tell if this is how you do cuz i only touched durability component for once
this was it and I also needed to update the item in the mainhand slot
oh right
itemStack

sounds simple to make
can you do it ?
like not vanilla commands
things like !kit
these
both vanilla and custom
wait really ?
but rn no i cant use my tablet rn
can you tell me how to ?
you need to use an event that triggers upon chat send
ok
its in beta API, and make sure to use beforeEvents for it
no sorry i have other stuff to do
oki np
import { world } from "@minecraft/server";
world.beforeEvents.chatSend.subscribe((eventData) => {
const player = eventData.sender;
if (!player.hasTag('Admin')) return;
switch (eventData.message) {
case '!gmc':
eventData.cancel = true;
player.runCommandAsync('gamemode c');
break;
case '!gms':
eventData.cancel = true;
player.runCommandAsync('gamemode s');
break;
default: break;
}
});
where do i add the cooldown in this ?
you could use those
#1067535608660107284 message
can i use scoreboards ?
i dont recommend it
it will be fun π
no
how do i do it ?
trust me
come on i wanna try :)
idl what taht is π
its like scoreboard but without scoreboard
im kinda new to scripting
ok uh let me explain tbis
can u add it in the code if possible ?
like when score "cooldown" hits 0 then a text msg is sent saying you can use the command again
if player tries to use command before then a msg saying "no" is sent
#1067535608660107284 message
i saw but idk how to implement it :(
is it possible to make it so that instead of checking if player has admin tag it checks if player's score is 0 ??
@shy leaf
please for the gods sake dont use scoreboard for scripting
i wanna :(
give me a second then
ok
Anyone benchmerked item dynamic prop so far yet?
I don't think it's possible, hunger component doesn't exist at this moment.
@runic crypt
import { world } from "@minecraft/server";
world.beforeEvents.chatSend.subscribe((eventData) => {
const player = eventData.sender;
const time = Date.now();
if (!player.hasTag('Admin')) return;
if (!(player['cooldown'] > time)) {
switch (eventData.message) {
case '!gmc':
eventData.cancel = true;
player.runCommandAsync('gamemode c');
player['cooldown'] = time + 15000
break;
case '!gms':
eventData.cancel = true;
player.runCommandAsync('gamemode s');
player['cooldown'] = time + 15000
break;
default: break;
}
} else player.sendMessage('Command is in cooldown')
});```
cant guarantee itll work
Β°-Β°
beforeEvents is for running some code "before" the event occurs and canceling the event.
afterEvents is for running some code "after" the event happens.
ye but there are very few beforeEvents
compared to after one
and aside from that
i dont feel the difference
fr. there are less beforeevents compared to aftervents
let dura = item?.getComponent("durability")
dura.damage += 50;
thanks :)
wait
ok
i think i made the chat to cancel regardless of the command
well uhhh
also how do i adjust the time ?
and does it send a msg on how much time is left ?
see the 15000 thing?
yea
its in milliseconds
how do i make it show how much time is left tho ?
you could do
player['cooldown'] - time
itll show in milliseconds so youd need to divide it by 1000
} else player.sendMessage('Command is in cooldown')
Since it's attached on player, u can access that anywhere
here ?
oki i can do that π«‘
player.sendMessage(`Command is in cooldown for ${player['cooldown'] - time}`)
use native methods bruuh player.setGameMode('creative')
im not the one who made the base code
@shy leaf
didn't work :<
β οΈ
no i wanna make daily kits
like i can do !kit
get a kit
but i cant do it for the next 24hrs
is it possible ?
any error?
can you show content logs
also are you sure youre using beta api
Prob the undefined > time
oh wait yeah that
also that since its beforeEvents
if ((player["cooldown"] ??= 0) < time)




