#Script API General
1 messages · Page 5 of 1
Test it against yourself.
It will work
thanks mane
alr
Unless you are working in collaboration with someone else who is designated the tester, you will need to test practically everything yourself. I would suggest, building in the infrastructure to do so.
For myself, I have a whole class module and when I do not want to use it, I use ```JS
export const debug = true;
export const debugMsg = function (msg = "", preFormatting = "") { if (debug && msg) world.sendMessage(${preFormatting}@${system.currentTick}: §cDebug Log:§r ${msg}); };
So for your case, you could list out the tags of a player that spawned in, then add a message in where the tag was found, so that you know your matching is okay. I remember you were concerned about the double quotes in the tag.
yeah i was because for that callback function you would need it however for the tags have quotes in it idk how to list them out
Well. that is a JS thing. Youa are learning yes... so Returns an array.... so... cycle thru it to list what it has. Make your own list tags function, so you can use it anytime. But always check if player is valid...
How many drop down options can a ModalFormData handle?
I need to make the player select from a few hundred options
Don't always give up because someone says something is not possible, unless you know them to be a JS God. yes you can have double-quotes in your tags** and yes you can search and display**
Use this chat command example to extrapolate how you may achieve your goal ```JS
world.beforeEvents.chatSend.subscribe(
(event) => {
const player = event.sender;
if (!(player instanceof Player)) return;
if (player.isOp()) {
if (event.message.toLowerCase() === ":tags") {
event.cancel;
const tags = player.getTags();
player.sendMessage(`\n\nPlayer Tags: ${tags.length}`);
const vipTag = `"rank:§a§lVIP"`;
tags.forEach((tag) => player.sendMessage(`===> ${tag}`));
tags.forEach(tag => { if (tag === vipTag) player.sendMessage(`\n\nSpecial VIP Tag ${tag}§r found`); });
}
if (event.message.toLowerCase() === ":cls") { event.cancel; player.sendMessage("\n".repeat(40)); }
}
}
);``` you can add this, if using beta to test tags. I would suggest if showing this tag to players, that you add §r to the end of VIP, so the last double-quote is not green. Note: test for includes() will not work for some reason. I had another way around it if the === did not work, but it did. Where there is a will, there is a way... remember that, as a programmer. And if it does not exist, create it... (hardcore programmers)
i never knew i could do that bro
thank you alot
its possible to give items with names to players? without structures?
just googled it and || means or? is that true will it work for this
thank you
It is, yes
2 things to explore:
- Players inventory component -> containers
- ItemStack class -> setLore()
There are examples in this link:
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_11_0.ItemStack.html
Exploring the API Classes is a worthwhile activity to help you discover the possiblilites
"if it does not exist, create it" love that line
Also anyone know what to do if when you try loading a gametest it says that it can't find the game test. I have no idea what the issue it.
import { system, world, Player, ItemStack } from '@minecraft/server';
import { ChestFormData } from './extensions/forms.js';
export function removeScore(amount, target, objective) {
if (!(target instanceof Player)) return;
target.runCommand(`scoreboard players remove @s ${objective} ${amount}`);
}
export function getScore(target, objective) {
try {
target.runCommand(`scoreboard players add @s ${objective} 0`);
return world.scoreboard.getObjective(objective).getScore(target);
} catch {
return 0;
}
}
function ChestTest(player) {
const chestui = new ChestFormData('27')
.title('§l§d Pickaxe shop V2')
.button(10, '§l§3Tier 6', ['$50,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/netherite_pickaxe')
.button(11, '§l§bTier 7', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
.button(12, '§l§9Tier 8', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
.button(13, '§l§5Tier 9', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
.button(14, '§l§5Tier 10', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
.button(15, '§l§dTier 11', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
.button(16, '§l§dTier 12', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
.show(player).then(response => {
if (response.canceled) return;
switch(response.selection) {
case 10:
for (const player of world.getAllPlayers()) {
const inv = player.getComponent("inventory").container;
const item = new ItemStack("minecraft:netherite_pickaxe", 1)
const Money = getScore(player, "Money")
if (Money >= 50000) {
removeScore(50000, player, "Money")
item.setLore("Tier 6")
inv.addItem(item)
} else if (Money < 50000) {
player.sendMessage("§l§d HCV KitPvP >> §l§4You do not have enough for a Tier 6 pickaxe")
}
}
break;
keep getting a error could someone help?
I'm prob not the best person for this. But what type of error are you getting? Or what is the error message?
how me summon item
With commands? I think you can only summon entities. But you can give yourself items with /give.
im trying to replace the thing i get from breaking stone
so custom loottable
How do I cancel a callback like a beforeevent? Can I just set a variable equal to the beforeevent?
Native optional type conversion failed, error message
oh nvm i figured it out lol
Line !
which line?
Yes
Might be related to this:
item.setLore("Tier 6");
.setLore() expects a string[] but instead you passed to it a string.
So it should be like this:
item.setLore(["Tier 6"]);
Is it possible to trigger a script file that is outside the script folder?
No
Import ?
What is a dynamic property of the Minecraft server world object?
its a property that last over world loads
Property thag is dynamically saved and persistent across sessions
Yes, perhaps with an absolute path when importing, like in Windows. Otherwise you must use your Main on the outside.
Thats just wrong
It's not associated with any entity, right? It's global.
You cant read anything outside the scripts folder
Its saved to the world
^
It s better to save tags on player's dynamic proprety yep ?
What does the symbol "?" In the TypeScript documentation?
Or they are saved ?
? does a lot of things
Interesting. Have you already tried changing it in the json?
Means , optional parameter
Do you know about TypeScript or am I not still asking about that?
Okay. It's documented on the TypeScript website, right?
The JavaScript engine is limited to within the Scripts folder. Running scripts outside that directory will fail.
? can be used as the ternary operator, an option or null coalescing
Yea
Interesting. Are subfolders still supported?
U can with double dots
What ecmascript version is Minecraft Javascript in?
As long as it's inside the Scripts directory.
2023 i think
they updated it recently
Es6
ofc es6
UwU brilliant
XD
:3
:v I mean physical bookstores. Non-native.
Yes, if it supports esm.
:3
:v Give me ideas to practice and gain experience. I read the complete mdn Mozilla documentation.
but you will need a bundler to make them accesible or just you know 1 random file with the lib in it
I understand, thanks
Try to make snake game and calculator
I'm not a script expert yet, I was wrong.
English or Spanish?
Inside Minecraft, right?
UwU good idea, I'll do it. I'll use the native controls and a block for the rest.
Spanish.
Si te mueves eres goy
:V es ilegal el español. Aquí nos discriminan xD
I used translator XD
I use the integrated one. Keyboard.
Nice
Changing what?
The color of your name would go great with my pfp. Nonetheless, carry on lol.
:v In English everything must always be specified. Spanish uses context a lot.
What?
You are one of the most powerful here, a worthy rival. Ha ha
Now I'm beyond confused
Allright
Language barrier.
does anyone know how to convert the number vars to a vector3 value
like const vector = new Vector3 (num1,num2,num3)
is the idea
how would i achieve this
Vector3 is just an interface
So it be:
{x: blah, y: blah, z: blah}
Oh TS is more beginner friendly then
Toxic senior btw
@gaunt salmon is has a TS debugger inside. Check it out
Your docs are so hard to read
i wonder, which one is much more optimized
multiple lines of .spawnParticle() or a one line of .runCommand() that runs a function with particle commands
spawn particle- run commands are very slow, regardless of what they run.
i see, thank you
functions are faster than runCommands, but only if used outside of runCommands- like inside of an animation controller or whatnot
calling a mcfunction from scripts is... not great
elaborate?
ill just resort to runCommand with functions, much more shorter to write in script
if possible, try to use runCommandAsync
hmm, im curious about the difference
ah, async
async queues until the end of the tick and does not hold up the code.
regular halts code execution until the command has returned a successful/unsuccessful execution- and unsuccessful ones may throw a console error and prevent the code from running further
too dumb of me
yeah its a promise
I despise runCommand
had lag issues on a world, and went to diagnose- 18 runCommands took 16 ms to process.
switched to native methods, and zero problems since.
okay then, ill resort to native methods if possible
#1265218592568246282 if someone can help
I love em.
alr let me try, thank you
how do I use the debug tool?
it depends on what you want to do
hi, could anyone see whats wrong with my script, used to work but i guess they changed the API
its supposed to remove health score from entities when they are hit by my projectiles
dw worked it out
How do i give a item a name?
const item = new ItemStack("minecraft:netherite_pickaxe", 1)
item.setLore(["Tier 6"])
inv.addItem(item).nameTag("Tier 6 pick")
itemStack.nameTag = "item name"
could you show that in js box text format?
const item = new ItemStack("minecraft:netherite_pickaxe", 1)
item.setLore(["Tier 6"])
item.nameTag = "item name"
inv.addItem(item)
thank you alot mane
man*
your wlc
enchant.addEnchantment({ type: "unbreaking", level: 3 })
const enchant = item.getComponent("enchantable")
Did i mess up the syntax of addEnchantment?
define the variable "enchant" first before using it to make changes
const enchant
enchant.addEnch
for (const player of world.getAllPlayers()) {
const inv = player.getComponent("inventory").container;
const item = new ItemStack("minecraft:netherite_pickaxe", 1)
const enchant = item.getComponent("enchantable")
item.setLore(["Tier 6"])
item.nameTag = "§l§3Tier 6"
enchant.addEnchantment({ type: "unbreaking", level: 3 })
inv.addItem(item)
type: new EnchantmentType("unbreaking")
const nPix = new ItemStack("minecraft:netherite_pickaxe")
nPix.setLore(["Tier 6"])
nPix.nameTag = "§l§3Tier 6§r"
const ench = nPix.getComponent("enchantable")
ench.addEnchantment({ type: new EnchantmentType("unbreaking"), level: 1 })
``````js
for (const p of world.getAllPlayers()) {
const inv = p.getComponent("inventory").container
//other code if statements
inv.addItem(nPix)
} ```
player.onScreenDisplay.setActionBar(`${jetpackDurability}`);``` I tried with setTitle it was working but with setActionBar it doesn't work, why ?
U sure there's no RP active that modified the actionbar
There is one but it shouldn't interferring
I'm going to see
It must be that thank u
There's a mistyped in the minecraft fandom wiki, anyone know any accurate as possible enchantment's level table range?
Min: 52
Max: 50
Idk if that's on purpose or mistyped. Not so big deal anyways.
This website and the official Minecraft wiki
Dont use fandom
I just knew rn that I was using fandom the whole time xp, and checked the official wiki
Still 52 - 50
EnchantmentType not defined
import it
with this can i add more then 1 enchant?
make everything look nice
i dont understand the problem lol

i didnt know you could - the amount with world.scoreboard
however thank you
addScore of negative number
alr thanks
guys why is it so weird when I use camera on player its jerky
system.runInterval(() => {
for (let plr of world.getPlayers()) {
let { x, y, z } = plr.location
let scaleValue = player.getComponent("scale").value
plr.camera.setCamera("minecraft:free",
{ location: { x: x, y: y + 5 + scaleValue / 2, z: z },
facingEntity: plr }
)
}
})
set easetype
player.camera.setCamera("minecraft:free",{
easeOptions: {easeTime: player.getDynamicProperty("dc_camlerp")/100, easeType: "Linear"},
location:camlocation,
facingLocation: {x: player.location.x, y: (player.location.y+player.getHeadLocation().y)/2, z: player.location.z }
})```
took it from my code
ah thx now it works
np
Is there away to set the players rotation?
bc this doesn't work
if (plr.getRotation().x <= 0) {
plr.setRotation({ x: 0, y: plr.getRotation().y });
}
I had this solution but its not good if you move
if (plr.getRotation().x <= 0) {
plr.teleport(plr.location, {rotation: {x: 1, y: plr.getRotation().y}})
}
does anyone have a list of all minecraft block that could be import into script?
What do you need it for?
You can do https://stirante.com/script/server/1.14.0-beta.1.21.20-preview.22/classes/BlockTypes.html#getAll
Documentation for @minecraft/server
how...
do i import it?
Just do BlockTypes.getAll() and you'll get an array of of all block ids in the game
What exactly are you trying to do?
Vanilla data is not used
Ik , he must download it
And put it in scripts folder
Somehow
Just import it from minecraft-server
Oh , there is ?
Thats not how modules in scripting api works eheehehe
I didn't know
It s type script module so ._ u need to transpile it
It does for vanilla-data.
- 1000 aura point
ignore the background music, I'm creating a gap filler or something like that
Is there a way to use the player.teleport where you can still move the camera?
Cuz I noticed the camera is forced to a specific location.
const moneyTransfer = (player) => {
const players = [...world.getPlayers()];
const money = getPlayerScore(player, "Money")
new ModalFormData()
.title('Money Transfer')
.dropdown('§o§5 destinatario!', players.map(player => player.name))
.textField(§uEnter The Amount You're Sending!\n§dYour money=§5 (${money}), §o solo numeri)
.show(player)
.then(({ formValues: [dropdown, textField] }) => {
const selectedPlayer = players[dropdown];
const amount = parseInt(textField, 10);
const receiverCurrentMoney = getPlayerScore(selectedPlayer, "Money");
if (selectedPlayer === player) {
player.sendMessage(`§cYou can't select yourself`);
return;
}
if (isNaN(amount) || amount <= 0) {
player.sendMessage(`§cPlease enter a valid positive number`);
return;
}
if (money < amount) {
player.sendMessage(`§cYou don't have enough money`);
return;
}
try {
setPlayerScore(player, money, money - amount);
player.sendMessage(`§aSent §l${selectedPlayer.name} §r§2$${amount}`);
selectedPlayer.sendMessage(`tellraw @s {"rawtext":[{"text":"§l${player.name} §r§aHas Given You §2$${amount}"}]}`);
setPlayerScore(selectedPlayer, "Money", receiverCurrentMoney + amount);
}
});
};
});
there is a syntax error
make hem ride any entity ant tp the entity
setPlayerScore(selectedPlayer, "Money", receiverCurrentMoney + amount);
}
}<--- ); here i dont knnow why
pls help
im happy... i followed the whole enchanting mechanics from the minecraft wiki. Feelsgoodman🫡
i switched to my laptop and need the ChestFormData of Herobrine but cannot fnd it . Could anyone send me its link?
thanks g
isnt there dynamic properties for blocks?
No
💀
wait, how do you add enchantments without using the Enchantment class?
ItemStack.getComponent('enchantable').addEnchantment({ type: new EnchantmentType('unbreaking'), level: 2}) for instance
yep
Are there any script events that can work in spectator mode?
changeDimension?
if i understand your question right, changing dimension should trigger a event
That's good to know. Thanks!
I have the structure saved on the world
many dynamic properties can be laggy? if yes, how can I remove / reset a dynamic property?
set(prop)
but that sets a value, not remove the property from the world
does it...
oh.
thank you
ah
This is running off of onPlayerDestroy
initEvent.blockTypeRegistry.registerCustomComponent('not_enough_adventure:bottom_collision', {
onPlayerDestroy(e) {
e.block.dimension.runCommandAsync("setblock ~-1 ~ ~ air destroy");
},
});
});```
It already has a location
oh shoot
so
I think Im dumb
e.block.dimension.runCommandAsync("setblock ~~-1~ air destroy");
Had to fix that because otherwise it wouldnt be getting the block below it lol
still does not work though
const b = e.block
b.dimension.runCommandAsync(`setblock ${b.x} ${b.y-1} ${b.z} air [] destroy`)
interesting
I thought location was defined since it was running the event from a custom component on the block
Why [] ?
nope, it's running from dimension
empty permutation...
: ) kkk
Vacation and i left my laptop on home 💔
U know u can still try the bad ones to understand how it's "bad"
gg waiting
[Scripting][error]-Unhandled promise rejection: CommandError: Syntax error: Unexpected "0": at "-1083 air >>0<< destroy"
Noice
: ) at least we try
The only reason im even using this command is because you cant set destroy on a block through a script
Using destroy gives out loot
Yeh, which is frustrating
Best thing I could think of lol
oh you want the destroy particles
What are u trying to make
the loot itself
More like cobble from stone instead of stone
So im making a crop thats 2 blocks tall
Instead of giving the top collision loot and doing a whole thing
I have it so that on destroying the top block, set the bottom one to air, but give me the bottom blocks loot
Thanks, works perfectly now thanks to you guys
Oh
About the []
You don't need it at all
just remove it and it still works
Mhm
anybody know why the saddle is given back to the player?Is the saddle considered to be in slot 0 of the entity?Also as you can see in the video for some reason when i try to open the mammoth's inventory it instantly closes...(is that a component issue?)
Prob range of seat issue that closes the inv ui
your seat might be too far away from the entity's feet, maybe
idk thats why im asking here 
@subtle cove do you know about the saddle issue?
is your hitbox small? hmm
uhh, i see 2 saddles from the vid...
well it was from a previous test. I only did have 1 for the mammoth
Dunno what's happening, sorry
alr 😛
Uhm u have a code that moved the items to player's inv...
yes
well nvm i figured out why it was giving me the saddle. The saddle is located in slot 0. Just had to pull slots 1+
wuddahell
idk, I opened a post
#1265531961812717611 message
That s huge asf mammoth
How lazy to make a world edit
[error]-ReferenceError: Native function [Dimension::setBlockType] does not have required privileges
How do I give privileges?
wrap them in system.run()
I had entered the argument format incorrectly. Wait I check.
Okay. But it is already inside a function that is executed by "run". I will give it the privilege to run with an exclusive run.
Lose, tick by tick.
this error appeared when you call a method that "modifies" the world in "beforeEvent" scope
I know
Yes.
system.run push that outside of the scope
I prefer to do it inside another function.
k
Time to test if it works.
UcU then you say what should I place how the structure? I want to place a block in the world after the player places one.
Should I create a function?
I think I already understood. It's because of the scope.
how can I summon a zombie with enchanted armor?
I cant use equippable on entities...
You were right. Events do not need a loop and a block cannot be placed immediately after e. The run helped.
Use loot tables
is there a way to use fillblock but with break?
like make the block break?
with item drop and sound
no you gotta use commands for that
I have a list of them
40 ish
Commands will not be able to handle that 😦
world.structureManager.place(`pshop1`, player.dimension, { ...player.location, y: player.location.y + 2})
const inventory = player.getComponent(`inventory`).container
const item = player.dimension.getBlock({ ...player.location, y: player.location.y + 2 })
inventory.addItem(item)
could someone tell me what i did wrong?
run the commands in runJob
structure name need a namespace ("id:pshop1")
smth like this
world.structureManager.place("id:pshop1"
whats the difference?
so you don't run all the commands at once
yeah
it keeps saying the strucure does not exist
is it a file or what
its saved in the world
does it have to be saved on my storage?
with the id "id:pshop1" ?
world.structureManager.place("id:pshop", player.dimension, { ...player.location, y: player.location.y + 2})
const inventory = player.getComponent(`inventory`).container
const block = player.dimension.getBlock({ ...player.location, y: player.location.y + 2 })
const chest = block.getComponent(`inventory`).container
for (let i = 0; chest.size; i++) {
const item = chest.getItem(i)
if (item) inventory.addItem(item)
}
block.setType(`minecraft:air`)
player.playSound(`note.pling`, { pitch: 2 })
the item is being saved in a chest
i meant the structure
use that instead of "id:pshop1"
alr
place doesnt use strings, it use the structure directly
first get your structure in a variable and then use it in .place
it use both
when I tried didnt work by using the structure identifier directly
weird, I don't know what I did wrong then
oh alr my bad because i thought you didnt need the id before the name
Sadly I need it to run insync to the script...
Lemme try to queue it
not in the preview
just beta API?
huh?
huh?
ill take that as yes (is it "no"? idk anymore)
i don't see why not use beta api
unless it is for marketplace
cuz i dont like having everything to break apart
or have a chance to break apart
not when you use something that you sure will get stable net update
use beta to develop your addon for next update? idk just saying
block.location 🤷♂️
oh yh
honestly i dont like the concept of using beta stuff
unless the stuff im using is bound to break in next update
i accidentally forgot my code was in 1.8.0 one day so i up'd the version to 1.11.0
didnt have any issue

up to you
personally i use what i can
all my addons were using beta api
but with time i will port the all to stable
i have 5 addons they were all beta but now just three of them
How could I detect a specific durability value?
Item -> getcomponent(durability)
Thanks
for (const player of world.getAllPlayers()) {
const Money = getScore(player, "Money")
if (Money >= 400000) {
removeScore(400000, player, "Money")
world.structureManager.place("mystructure:pshop2", player.dimension, { ...player.location, y: player.location.y + 2})
const inventory = player.getComponent(`inventory`).container
const block = player.dimension.getBlock({ ...player.location, y: player.location.y + 2 })
player.playSound(`note.pling`, { pitch: 2 })
player.sendMessage("§l§dHCV KitPvP >> §l§aYou have purchased Tier 7 pickaxe")
} else if (Money < 400000) {
player.sendMessage("§l§dHCV KitPvP >> §l§4You do not have enough for a Tier 7 pickaxe")
}
}
Why when a player buys this i get one aswell
You are doing a for loop for all players in the world, so it will run the code for all players.
how can i do the loop for 1 person
then how can i use player notation without
for (const player of world.getAllPlayers())
What's the context of your code?
am using ur chest ui for my pickaxe shop
Like do you have a player class as a defined variable somewhere?
Consider opening a post for your code
Yeah you have a player variable inside of the UI function already. No need to do a loop over every player unless you want to run code for every player.
Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
did you get it to work? I couldnt find it in the types?
It was posted here so shouldnt it be in 1.2.0-beta?
why isnt it in the types?
how can i get the location infront of the player again?
The most recent ones?
@minecraft/[email protected]
oh, I think @granite badger's thing is outdated
ye
it should be using 1.21.2
npm i @minecraft/[email protected] I still cant find it in the types?
npm i @minecraft/[email protected] (or 1.21.2-stable, both are fine)
this worked
can I even use that tho, I am on v1.21.2?
They're just NPM types, and nothing was added between the versions
but why isnt the uiManager in 1.21.2 types?
dunno
hmm, darknavi question?
It's there in the 1.21.2 types
Can anyone help?
export function removeScore(amount, target, objective) {
if (!(target instanceof Player)) return;
target.runCommand(`scoreboard players remove @s ${objective} ${amount}`);
}
export function getScore(target, objective) {
try {
target.runCommand(`scoreboard players add @s ${objective} 0`);
return world.scoreboard.getObjective(objective).getScore(target);
} catch {
return 0;
}
}
const player = world.getAllPlayers()
const Money = getScore(player, "Money")
Does anyone know why its not picking up the objective?
this means you are making a particular change to the world in the same tick and that is not allowed. you use run to push to next tick.. or runTimeout to push even further.
Very late. I already understood that. Solved.
I was too lazy to scroll down and see if someone explained it fully.
XD
What is it you are having a challange with, regarding getViewDirection() https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_12_0_beta.Player.html#getViewDirection
It is a vector and I believe people may have put vector math classes in the resources... so maybe a discord search for vector or vector3 may bring up information or code snippits or convos from others.
Do you know how the general execution flow is executed?
How it behaves.
not an expert, and some others may have better answers... but as far as event processing... I understand from watching this.. https://www.youtube.com/watch?v=eiC58R16hb8
Learn how the browser event loop, task queue, microtask queue, and Web APIs work together to enable non-blocking, asynchronous JavaScript.
- https://www.patreon.com/LydiaHallie
- https://buymeacoffee.com/lydiahallie
- https://twitter.com/lydiahallie
- https://www.linkedin.com/in/lydia-hallie/
- https://instagram.com/theavocoder
Timestamps:
0:...
It doesn't work for me. I am referring to the default execution flow of the initial Script.
Do we have concurrency in Minecraft script? Without counting events.
Then this may help understand how that works... https://www.youtube.com/watch?v=TlB_eWDSMt4&t=1783s At time mark 53:19 he talks about events and you can see how it can work concurrently . After watching that I understand how the subscribes work. Sorry if I am not getting the jest of your question. I suggest to anyone, watch the whole video..
Learn Node.js basics in 1 hour! ⚡ This beginner-friendly tutorial gets you coding fast.
🚀 Want to master Node.js?
- Check out my complete course: https://mosh.link/nodejs-course
- Subscribe for more awesome content: https://goo.gl/6PYaGF
✋ Stay connected:
- Twitter: https://twitter.com/moshhamedani
- Facebook: https://www.facebook.com/programm...
I think this explains the concurrency....
From top to down
If async
There are two flows at the same time
Which two?
I mean two parallel excutions lines
If there is asynchronous lines in ur code
Oh yes, but "run" is concurrent with the main scope
Yes
They say they add it to the end of the current tick... I read that somewhere
JS is single threaded....
there is no real concurrency
I mean in async functions and code
async stil adds to end of current tick
In JavaScript, "asynchronous" refers to operations that can be executed without blocking the main thread, allowing other operations to continue running while waiting for the asynchronous task to complete. This is particularly important for tasks that might take an indeterminate amount of time, such as fetching data from a server, reading files, or executing timers.
JavaScript handles asynchronous operations using several mechanisms:
-
Callbacks: Functions that are passed as arguments to other functions and are executed after an operation is completed.
-
Promises: Objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises provide
.then()and.catch()methods to handle success and failure cases, respectively. -
Async/Await: A syntactic sugar built on top of Promises that allows writing asynchronous code in a synchronous-looking manner. It uses the
asynckeyword to define an asynchronous function and theawaitkeyword to pause the execution of the function until the Promise is resolved or rejected.
Here's a simple example of each:
Callbacks
function fetchData(callback) {
setTimeout(() => {
callback('Data loaded');
}, 1000);
}
fetchData((data) => {
console.log(data);
});
Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data loaded');
}, 1000);
});
}
fetchData().then((data) => {
console.log(data);
});
Async/Await
async function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data loaded');
}, 1000);
});
}
async function loadData() {
const data = await fetchData();
console.log(data);
}
loadData();
Using these asynchronous methods, JavaScript can perform tasks efficiently without freezing or slowing down the user inte
well that first video I sent, goes over stuff like how this is working... micro tasks and such
thanks chatgpt
#JavaScript #tutorial #course
// synchronous = Executes line by line consecutively in a sequential manner
// Code that waits for an operation to complete.
// asynchronous = Allows multiple operations to be performed
// concurrently without waiting. Doesn't block the execution
// ...
can someone read my thread and reply to it there?
Just made a website where I can see how much lines js I used xD

guys does player.id change in every world?
i saw someone talking about it and saying yes
but im not sure
it does
so its constant in one world?
Yes
where i can find all the emoji like this and copy them? LIKE THIS
you can't see it but that's it
That seems like a #1067869590400544869 question
nop
i dont have any resource pack and i can use it
you mean you want to kniw the unicode
?
wait in my script console.log(message) is referenced to the node.js console
and it doesnt show up in my screen
can someone pls help
Its not a scripting question
oh right
the emoji u see are unicode char which u can copy, game renders it as emoji defined in rp
sorry
nvm
thxx
look into teleport options in the docs
probably entity.teleport(vector3,{dimension:dim})
it's in teleport options
it wants teleport options and not a string
so ..
{}
...
const dim = world.getDimension("minecraft:the_end")
entity.teleport(vector3,{dimension:dim})
it tps me to the overworld
const dim = world.getDimension("minecraft:nether")
let user = message.substring(4).trim(); // THIS VARIABLE OBTAINS WHATEVER THAT IS AFTER THE .HELPOP
if(sender.hasTag('mod')){
system.run(() => {
sender.teleport({x: 0, y:64, z:0}, dim)
})
}
e.cancel = true;
Change the dimension to something other than the overworld. You can decide on the dimension.
you didn't add the options
{dimension: dim}
{dimension:dim}
yeah
np
Teleport Options requires an object with properties that exist, and you defining the properties accordingly. That object is the second parameter of the teleport method.
yeah ty
why do you need that? form?
yeah
i tried placing a portal block on player's feet but it only closes the inventory
you can just wait for the chat to close
nah, i think its not that good looking
and the dimension changer its automatic
depend
but i like your idea tbh
yeah imma send a video when i done with this
When you need that chat window to be closed just send a message to that player instructing them to close the window.
Nah
This is actually not that bad, i dont like that there's a transition like that, but its so fast
nop, its a superflat world
Ah, then it was just stopping the coord at 37 because you accessed the menu.
cuz i flyed xd
Lol
I'm assuming the transition may be longer for certain cases, no?
If it's always super short like that, that's actually a decent way to close menus
yeah bad devices:/
So teleporting a player will close the window huh?
but any way i have a event listener that can show the form as soon as you get into the overworld again
and for less resources i could use the end
between dimensions
Have you tested the same dimension, like using the same coordinates as their current location?
Because if that closes the window then that will be far better than any other method I have seen.
i bet nothing would happend
You should test it really quick lol
mm
👀
From what I can remember, it does not close any windows
Unfortunate
Rip
it doesnt close nothing
Forms, and chat, stay open for that- I had to use closeForms for when teleporting
Can't do anything about chat tho
thats sad
End <=> overworld
u suggest?
I just tell the player to close the chat to continue, and I queue it until it shows the player is no longer busy or hasn't cancelled.
Good idea... maybe a countdown timer too...
That would be nice but mileage varies based on device and ping.
yeah
You could add a timer to cancel it automatically in cases where they may have went afk.
i hope we get chat close function before chatSend get stable
Well.. there may be reasons why chatSend is still beta... so one can hope lol
custom commands?
We already can implement our own custom commands.
I do see custom commands as being registered in world initalize event, similar to how block & custom CCs are currently
maybe they will be like custom component
you register a command with all it parameter
chatSend should be just for messages
Maybe the devs are still scratching their heads over the chat send bug that you found, Visual
Wait, remind me again lol.
what bug is that
It worked
Modifying the message makes the game think you sent the modified message or something along those lines
What chatsend bug?
huh? you can edit the actual message?
Hmm, let me go find it in OSS. If I brought it up then it's probably there.
#879773489601585244 message
that's wired
Just found it haha
Was gonna share it here but you beat me to it.
I remember that issue. Been a while.
Wouldn't be surprised if they are still brainstorming that issue.
On the bright side, the issue seemed to be a rare occurrence. My idea of testing communication with encryption in mind is basically what stumbled across it. An accidental find.
but message property readonly, no?
No it is not.. but that would fix it until they FIX it... and give it to us if they made readonly....
It actually would make sense why they made the events read-only now that you mentioned it lol.
This was discovered before they transitioned to read-only if my memory serves me correctly.
marked as readonly
ah
should test if it is
Oh the after is not readOnly
If they can release it in a way that is just for us to do custome commands that is what we care about
They will probably mess up my ability to accomplish end to end encryption in the process lol
never mind both readonly.. swear I looked for that and now I see it
lol
So who is intercepting chat.. and wtf is MC being used for that needs to be secret
Million dollar question. They never spoke up to me on that matter lol.
The moderation team?
Too many secrets in the world... I don't agree with the encryption thingy... tell them to make a Roblox game that cost a lot to use and they can talk all they want in there...
MAybe the spy network can just make signs to communicate... or name stuff on the anvil...
The encryption was something I did. I was implementing a feature in a project that would allow players to communicate with a form of security because too many hackers were using bots to sniff out data and expose information they had no business exposing.
But anvils are expensive.. so they gotta grind
Yeah, don't want the hackers to know where I hid my diamonds...
Agree to disagree. Players do hold the right to enjoy the game without others attempting to ruin it.
I know I know... but just seems.. like ... If ya gotta do that.. wrong game to play... well the players can be in a discord group and not talk in chat period... LOL if it is that serious
It was just one approach to combating the hackers. I think standing by and allowing the behavior is simply unacceptable and shouldn't be tolerated. Whether it be this game or any other game. The equivalence of that logic could equate to a coworker cheating you out of your paycheck and if you don't like it, then the wrong job to have so go find another job.
No... it is just a matter of where you put the bandaid....
The ability to hack should be fixed...
not encrypt chat
Until it is fixed, which is beyond any of our own echelon, patches are all we have to combat.
.. okay you do that, while I go kick my co-workers azz
Don't be stealing their paycheck, now
I will break fingers or chop off finger tips, see if you have the ability to steal after that.... hehehe... besides that is not a fair comparison in the seriousness of the issue. And would never happen.
Meanwhile, I wonder at peoples attempt to hide meaningless conversations in a game. To me, it means that it will be used to communicate other things that should not be talked about in a game. It is a gateway to... I don't have to say it... but you get the jest.
But to each their own... I do not care, do not play which such people....
Unfortunately, anything made with the intention of serving a good purpose will ultimately be perverted and used for malicious behaviors by others. Life has a way of doing these things because people tend to be wicked by nature.
It's a sad reality.
I do applaud the attempt to do it. Most of us programmers like the challenge of doing the impossible.
Live and learn 😬
The "impossibility" aspect is what made me do it to begin with. I wanted to see if it was feasible.
Had no idea it would trigger the moderators lol.
Maybe you can put the message in a book/quill and deliver it, LOL
Sounds like a resource pack with Little Red Riding Hood sending out baskets to be delivered.
well... put it in their inventory
sometimes when I cancel the event in the beforeEvents it does not work tho
I did wonder why they changed chatSend to read-only, but now I suppose it could have been that bug I reported.
Probably other reasons I'm sure.
Well the account lock is serious and if people know about it, it can be exploited
This is true.
was it the person who sent the message?
what if the world sent the message after captured and canceled, 3rd party, or amor stand?
the message has to make it to the server, post office, in order to be routed.. who is being hacked? sender, receiver, server?
so it is like a pgp/gpg file over the internet... probably... and you did it, cool...
but you have to encrypt on the client, right?
I better stay out of espionage...
I'd have to rummage through the code again, but it used AES encryption and the player.id as the salt for generating the encryption, so as to make it unique and different with each message being sent and received.
What would be a simple way to convert an Entity to a Player? (entityHitEntity event has Entity variable, I want it to be Player for the .name property)
I can think of one reason why it may remain readonly forever.... people can make it look like other people sent a message they did not send. Messages from world or non-players will lead to looking at the code, but messages from players that can be altered. Think of FB responding to people on your behalf
Check if the entity is a player or not...... if (!(hitEntity instance of Player)) return;
Check if the entity is a type of Player. If true, continue, if not, skip. An example could be this:
// Properties from class
const { hitEntity, damagingEntity } = object;
// If not a player entity then ignore
if (!(hitEntity instanceof Player) || !(damagingEntity instanceof Player)) {
return;
}
For that to work, make sure you JS import {Player} from...
Yea, that would be a mess.
^
Alternatively, you can check for typeId = minecraft:player.. I've seen some do that, but I do the instance because I use JDoc and @ts-check
why use instanceof? Is it because of typings?
Yes... if you are not using TS
it helps to avoid errors
after a while it becomes natural to want to use it.
I use instance as well, even though I write code in TS. A number of ways to do it. Just personal preference.
I think I have an old demo video of me encrypting the messages...
Random... Thought
instanceof does pull types, I assume that's why folks use it over checking typeId
Although you could cast types with jsdocs... not nearly as neat
I did not care for TS because a few things are diff and I do not want to compile and not have the JS look like me. I made the VScode show the TS annotations (settings), so my code lets me know when it is not clear or can be typed wrong. That, JDoc and ts-check keep me in line
besides, too many languages right now... I just learned JS a few months ago, and got fluent redoing my regolith filter... and I am supposed to be getting deep into c#... TS was a no go for now.
Been a while since I touched C#. I wrote so many codes in C# for Android applications years ago.
is there a 3rd party lib to emmulate JS? LOL... I am frustrated that so many things I want to do are not as simple as they are in JS
I mean if you want there's probably something out there, where you take pictures of rocks placed on the ground and it translates to valid JS
Lol
apologies about that, didn't really expect mojang would add stuff in a patch release
how to get a random safe-to-spawn location in an area?
how can I create a potion bottle itemStack? since this item only can be obtained with "data"
Use the potioncomponent?
like, getComponent("potion")?
Documentation for @minecraft/server
hmm is there a method for stable api?
There actually is a componentType called "minecraft:potion" but there is no information on how to assign an effect to it
help i'm getting the error
cannot read property 'setItem' of undefined
code:
const inventory = player.getComponent('minecraft:inventory')
inventory.setContainer.setItem(selectedSlotIndex, undefined);
its container, not setContainer
Did you read the docs i sent you...
preview beta api 1.14.0-beta, I cant use it..
thanks
now the error is selectedSlotIndex is undefined
Documentation for @minecraft/server
is it defined?
Womp womp
not yet sorry i thought it was a thing for the inventory
Any other method to assign a data value to an itemStack?
Nope
Or... work on it, perfect it, so it is ready to go when it comes out of beta....
Yes, it looks useful although I don't know if I'm blind, but I only see how to obtain the potion effects and not how to assign it
defined now i just did player.selectedSlotIndex and it worked
i'm in the last part now and i will attempt to get the enchantments of the item! 😄
I see, all the properties are Read Only. Which means, that will come later, I guess
be sure to test when nothing there. Some usage may require to test for existence before you work with.
get to the ItemStack Class
select the getComponent method
click on ItemComponentTypeMap interface
select class = ItemEnchantableComponent
(or go straight there, lol)
I bet there are some methods on that page....
It pays to poke around in the classes and see what is there.. oh the possibilities
hmm im using equippable component instead of itemStack
Well that's fine, that returns an ItemStack class
well, what is equipped is something from ItemStack... you can get to itemstack from there
and if you do not find something in latest, remember to check beta, and then preview.. lots of new stuff commin' .... I think.... probably.. who knows... no one tells me anything
Honestly stable release stuff has calmed down lol
where did i go wrong? 
player.getComponent('inventory').container.getSlot(player.selectedSlotIndex).getItem().getComponent('minecraft:enchantable');
don't mind the one line i wanna get it right first before destructuring
content logs
it can be hard to catch the error if those are all in one place (for me at least)
what is the last error, then look back to one that shows the filename and line number of thise line
Here is what I know, from helping another.. getSlot is not happy if nothing there... use getItem to comfirm there.... where is your if ya gonna need some ifs... or ? thingies
turns out i was just doing something unnecessary, thanks anyways guys 😁
yeah I see.... I had to do a double take on that line
whole middle part... and you may need to check hasComponent. just read the fine print of the methods, if it says it returns undefined... then fine, but if not, it may error if it is not valid.\
okk thank you nikki!!
How do you get entities that arent being loaded? player.dimension.getEntities seems like it doesnt
place a tickingarea
Isnt there a max to ticking areas though?
yes
I need a way that doesn't really have a limit ;-;
Why do u need to get the entity?
I need to be able to find the entity so I can teleport to it from far away
Teleport the player to the entity?
...Then just store the location Vector3 directly in dynamicProperty.
If you mean store the location in the player's dynamicproperties, I have multiple entities I would need to teleport to
And they're based on what the player picks
does the entities move or smth
Nope, could be described as teleporters
Then it's more fitting to rely on dynamicProperty instead of entities as anchor points
You can store an array of Vector3, and then parse it into the interface where the player could pick one. Then use that picked element to teleport
Guess thats what I'm going to have to do
yeah and it should be less head-aching
There's a string limit for dynamicProperty.
I'll probably limit it to only 100 locations per property If you take into account additional data like description or more. (If you have it)
You could chunk the stringified JSON into multiple dynamic properties, and then parse it back later for a larger range.
Man..im going to have to rewrite a bunch of code
how many entities did you use for script
Placing a custom block spawns a custom entity for storing its data and opening a menu associated

Took a while, but I've redone it. Thanks you two
how to recover dynamicproperty since getDynamicProperty is not aparament correct
Wdym its not correct?
getDynamicProperty() exactly?
world.beforeEvents.chatSend.subscribe((eventData) => {
const player = eventData.player;
const message = eventData.message;
//58 const homeLocation = getHome(player)
switch(message) {
case `!home`:
if (homeLocation === undefined) {
player.sendMessage("§cYou have not yet defined your home")
}else {
sender.teleport(homeLocation);
player.sendMessage("§aYou have been teleported to your home successfully")
}
break;
case "!sethome":
if(homeLocation === undefined) {
setHome(player)
player.sendMessage("§aYour home has been successfully set")
}else player.sendMessage("§cYou have already defined your home")
}
})
function setHome(player) {
player.setDynamicProperty("nano:home", player.location);
}
function getHome(player) {
//83 return player.getDynamicProperty("nano:home")
}
const player = eventData.player; this is not correct
The player property in that event is called sender
world.beforeEvents.chatSend.subscribe((data) => {
const sender = data.sender;
const message = data.message
I changed the 3 first line
What s the problem
No worries, because the greatest scripter that ever lived is here
Jk
it’s good by changing the 3 first line the script works
I have a question how to make a home list with dynamic Properties so that you can define more than your home.
What u mean
@somber onyx ?
U mean an array?
I want to make sure that the player can have more home
I am a beginner in the use of dynamic properties
So
U want to put an array inside dynamic properties
if possible yes
@somber onyx
You can use array of Vector3
Then stringify it
And put it in dynamic propreties
@somber onyx
yes I check documentation on internet
Then that s all
Whenever player make new home
Let it push new location to than array
Then stringify it
And setIt in dp
thanks you
Uw
if (item[0] == "!sethome") {
const homeName = item[1]
homeList.push(homeName)
sender.setDynamicProperty(`${homeList}`);
sender.setDynamicProperty(`${homeName}`, sender.location)
sender.sendMessage("§a>>Your home has been successfully set")
}
why it doesn’t work? the data is not recording correctly?
since the message is sent in the chat
How did you string it?
const homeList = JSON.parse(sender.getDynamicProperty("homes") ?? "{}")
homeList[homeName] = sender.location
sender.setDynamicProperty("homes", JSON.stringify(homeList))
!sethome home1
{
"home1": { "x": 1, "y": 1, "z": 1 },
"home2": { "x": 1, "y": 1, "z": 1 }
} ```
Sorry, but where do I put it?
Just this
This is just how it'd look like
oh ok but the my code looks like a ca I know well these not finished but the for me the !sethome does not work
world.beforeEvents.chatSend.subscribe((data) => {
const sender = data.sender;
const message = data.message
const item = message.split(" ")
const homeList = JSON.parse(sender.getDynamicProperty("homes") ?? "{}")
const homeLocation = getHome(sender)
switch(message) {
case "!help":
sender.sendMessage(`§8Here is the list of commands: \n§8/sethome homeName: §7to define a home \n§8/home list / homeName: §7list to get a list of all these home, add to create a new home\n§8/delhome homeName: §7To remove a home`)
break;
case "!home":
sender.sendMessage(">>§cIncomplete command !help")
system.run(() => {
sender.teleport(homeLocation);
sender.sendMessage("§a>>You have been teleported to your home successfully")
})
break;
case "!home list":
sender.sendMessage(`§7>>Here is your home list: ${JSON.stringify(homeList)}`)
break;
case "!delhome":
if (homeLocation === undefined) {
sender.sendMessage("§c>>You do not own any home")
}else {
sender.setDynamicProperty("nano:home", )
sender.sendMessage("§a>>Your home has been deleted successfully")
}
break;
}
if (item[0] == "!sethome") {
const homeName = item[1]
homeList[homeName] = sender.location
sender.setDynamicProperty(JSON.stringify(homeList))
sender.setDynamicProperty(`${homeList}`);
sender.setDynamicProperty(`${homeName}`, sender.location)
sender.sendMessage("§a>>Your home has been successfully set")
}
})
sorry I do my best
It's alr, I'm just too tired atm
just the !sethome for the rest I make myself out of it once I have understood the !sethome
He’s got to be at your house by 8:00?
@somber onyx
world.beforeEvents.chatSend.subscribe((data) => {
const sender = data.sender;
const message = data.message.trim();
const item = message.split(" ");
const command = item[0];
const homeName = item[1];
const homeList = JSON.parse(sender.getDynamicProperty("homes") ?? "{}");
switch (command) {
case "!help":
sender.sendMessage(`§8Here is the list of commands: \n§8/sethome homeName: §7to define a home \n§8/home list / homeName: §7list to get a list of all these homes, add to create a new home\n§8/delhome homeName: §7To remove a home`);
break;
case "!home":
if (homeList[homeName]) {
sender.teleport(homeList[homeName]);
sender.sendMessage("§a>>You have been teleported to your home successfully");
} else {
sender.sendMessage("§c>>Home not found! Use !home list to see available homes.");
}
break;
case "!home list":
sender.sendMessage(`§7>>Here is your home list: ${JSON.stringify(homeList)}`);
break;
case "!delhome":
if (homeList[homeName]) {
delete homeList[homeName];
sender.setDynamicProperty("homes", JSON.stringify(homeList));
sender.sendMessage("§a>>Your home has been deleted successfully");
} else {
sender.sendMessage("§c>>Home not found!");
}
break;
case "!sethome":
if (homeName) {
homeList[homeName] = sender.location;
sender.setDynamicProperty("homes", JSON.stringify(homeList));
sender.sendMessage("§a>>Your home has been successfully set");
} else {
sender.sendMessage("§c>>Please provide a home name.");
}
break;
default:
sender.sendMessage("§c>> list of commas.");
}
});
thank you gas I almost succeeded but you are still certain my problems
how do i use getBlocks so that it returns all the blocks locations that match a specific type
const startLocation = {
x: player.location.x + radius,
y: player.location.y + radius,
z: player.location.z + radius,
}
const endLocation = {
x: player.location.x - radius,
y: player.location.y - radius,
z: player.location.z - radius,
}
const volume = new BlockVolume(startLocation, endLocation)
const blocks = player.dimension.getBlocks(volume, {includeTypes: ['minecraft:air']}, true)
console.warn(blocks[0]) ```this doesnt work
Try [...blocks.getBlockLocationIterator()][0]. Check out https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_12_0_beta.Dimension.html#getBlocks for other usage
ohh yes it works thank you
ok I have a last question how to get only the name of the home?
How are you storing them? Is the home name the key?
Seems to be- you can use Object.entries(homeList) to get all key, value pairs in the object, as an array
Which would return [["a", {x: number, y: number, z: number}], ["b", {x: number, y: number, z: number}]]
Finally
//Made by xGAMEZAx#1241, do not claim this code as yours!
import { world, system, Player } from '@minecraft/server'
import { setTimeout, clearTimeout } from './index'
const combatCooldownMap = new Map();
world.afterEvents.entityHurt.subscribe((ev) => {
const player = ev.damageSource.damagingEntity;
const entity = ev.hurtEntity;
if (entity instanceof Player) {
player.addTag('incombat');
entity.addTag('incombat');
resetCombatCooldown(player);
resetCombatCooldown(entity);
}
});
world.afterEvents.playerSpawn.subscribe((ev) => {
const player = ev.player;
if (ev.initialSpawn) {
const combatCooldown = combatCooldownMap.get(player);
if (player.hasTag('incombat')) {
if (combatCooldown) {
clearTimeout(combatCooldown.timeout);
combatCooldownMap.delete(player);
}
player.removeTag('incombat');
player.kill();
world.sendMessage(`§c§lAntiLog >> §r§e ${player.name} §cdied for getting out in combat!`)
}
} else {
const combatCooldown = combatCooldownMap.get(player);
player.removeTag('incombat');
if (combatCooldown) {
clearTimeout(combatCooldown.timeout);
combatCooldownMap.delete(player);
}
}
});
function resetCombatCooldown(player) {
const combatCooldown = combatCooldownMap.get(player);
if (combatCooldown) {
clearTimeout(combatCooldown.timeout);
}
const timeout = setTimeout(() => {
player.removeTag('incombat');
combatCooldownMap.delete(player);
}, 30000);
combatCooldownMap.set(player, { timeout });
}
system.runInterval(
function scoreBP() {
const players = world.getAllPlayers();
for (let player of players) {
let antilogCooldown = '';
const combatCooldown = combatCooldownMap.get(player);
if (combatCooldown) {
let remainingSeconds = Math.ceil((combatCooldown.timeout._idleStart + combatCooldown.timeout._idleTimeout - Date.now()) / 1000);
antilogCooldown = `§7${remainingSeconds}s`;
}
player.runCommandAsync(`titleraw @s actionbar {"rawtext":[{"text":"§l§eYOUR REALM§r\n\n§fLog Cooldown: ${antilogCooldown}`);
}
}, 1);
Could someone help me with this, because it keep crashing the world am testing this in
you are declaring function scoreBP() every tick
move it outside the runInterval scope and call it from inside
so like this
system.beforeEvents.watchdogTerminate.subscribe(e => e.cancel = true)
that's not at all what i said
Lmao

you still should do what i said
any reason why the game somehow thinks I'm using the item on the gravel I'm standing on?
It's only at specific angles as well
you are?
look at the selection box
Are you crouching?
no
wait why is the selection box on the gravel
I'm not looking at it
It should be where my crosshair is
If i had to wager the bridging mechanic
great
alr mane, my bad bro
Could i pay someone to change smth for me
use get block from view?
you need to ask like this
can some one do "...", i am willing to pay for it if anyone is interested
Does it use a specific pov?
I need someone to help change the cps output from sidebar to titleraw(scoreboard), i've tried but failed
Dude just make a post instead of paying for help
Majority of the people on here aren't worth your money
i've tried
hmm ur right but i wanna improve my realm
Just wait for someone to reply
If they reply
Eventually someone will reply
alr thank you guys
imma make a post
I mean, this still doesn't work because getBlockFromViewDirection is inherently garbage and doesn't work with trying to get water
why dose the selection box even show?
is the item a block?
let me see if can do something
eat gravel mojang
const playerLocation = player.location;
const blockFromRay = player.dimension.getBlockFromRay({x:playerLocation.x, y:playerLocation.y + 1.4, z:playerLocation.z}, player.getViewDirection(), {includeLiquidBlocks: true})?.block;
const blockFromRayId = blockFromRay.typeId;
const blockLocation = blockFromRay.location;
const blockFromRayDistance = Math.hypot(playerLocation.x - blockLocation.x, playerLocation.y - blockLocation.y, playerLocation.z - blockLocation.z) <= 7;
const blockId = block.typeId
const blockAboveId = block.above(1).typeId;
world.sendMessage(`fromRayLocation ${JSON.stringify(blockFromRay.location)} fromRayId ${blockFromRay.typeId} distanceFromPlayer ${blockFromRayDistance}`)
if(blockId == 'minecraft:water' || blockId == 'minecraft:flowing_water' || blockAboveId == 'minecraft:water' || blockAboveId == 'minecraft:flowing_water' || (blockFromRayId == 'minecraft:flowing_water' || blockFromRayId == 'minecraft:water' && blockFromRayDistance)) {}
I did it lmao
Dimension.prototype.getBlockFromRay = function(direction, location, maxSteps = 10, stepSize = 0.2) {
for (let step = 0; step < maxSteps; step++) {
location.x += direction.x * stepSize;
location.y += direction.y * stepSize;
location.z += direction.z * stepSize;
const block = this.getBlock(location);
if (block.typeId !== "minecraft:air") {
return block;
}
}
return null;
};
includeLiquidBlocks is a thing?
yes, but it doesn't work how you would expect it to
includeLiquidBlocks means it will consider the liquid block as part of the Ray. HOWEVER, it will not work unless the ray is touching a solid block
there's honestly no reason for the block.typeId and block.above(1).typeId conditionals
getBlockFromRay covers everything
Is there a limit of modifications per tick????
I was looking and in my script it only allows me 1 modification per tick I think. It blocks me from executing a third modification.
whats a "modification"
Place blocks in the world
Can anyone write me a code that makes it say "hello" when I right click on an apple?
you can do ItemUse
I forgot because I haven't dealt with the script for a long time.
world.afterEvents.itemUse.subscribe((e) =>{
const item = e.itemStack
const player = e.source
if(item.typeId == "minecraft:apple"){
player.sendMessage("hello")
}
})
there is a much better way of doing this btw
Isn't import used?
I did it on the fly cuz am working on my own thing rn
import { Player, world, system } from "@minecraft/server";
np
Are the versions of Minecraft server and Minecraft server UI modules important?
What is the difference between 1.0.0 and 1.12.0?
So, using beta or the latest full version?
I made it
Both
Version is always important
Everything I do gets corrupted with every update.
Well, that's the perils of using beta APIs
I assume he just meant "stopped working"
does the fetch api work in behaviour packs for local files?
no
ok
// Script example for ScriptAPI
// Author: Jayly <https://github.com/JaylyDev>
// Project: https://github.com/JaylyDev/ScriptAPI
import { Player, world, system } from "@minecraft/server";
;
//Using map because typescript doesn't support prototype property declaration properly
const clicks = new Map();
world.afterEvents.entityHitBlock.subscribe(function ({ damagingEntity }) {
if (!(damagingEntity instanceof Player))
return;
const clickInfo = { timestamp: Date.now() };
const playerClicks = clicks.get(damagingEntity) || [];
playerClicks.push(clickInfo);
clicks.set(damagingEntity, playerClicks);
});
world.afterEvents.entityHitEntity.subscribe(function ({ damagingEntity }) {
if (!(damagingEntity instanceof Player))
return;
const clickInfo = { timestamp: Date.now() };
const playerClicks = clicks.get(damagingEntity) || [];
playerClicks.push(clickInfo);
clicks.set(damagingEntity, playerClicks);
});
/**
* Get a player's clicks per second
* @param player
* @returns
*/
export function getPlayerCPS(player) {
const currentTime = Date.now();
const playerClicks = clicks.get(player) || [];
const recentClicks = playerClicks.filter(({ timestamp }) => currentTime - 1000 < timestamp);
clicks.set(player, recentClicks);
return recentClicks.length;
}
system.runInterval(() => {
for (const player of world.getPlayers()){
player.onScreenDisplay.setActionBar(`§d§lCps: ${getPlayerCPS(player)}`)
const cps = getPlayerCPS(player);
if(getPlayerCPS(player)>14) {
world.sendMessage(`${player.name} went over the Cps Limit ${getPlayerCPS(player)}`)
player.runCommandAsync(`kick "${player.name}" Cps Limit ${getPlayerCPS(player)}`)
player.playSound('note.bass');
}
// player.runCommandAsync(`scoreboard players set @s cps ${getPlayerCPS(player)}`)
// {"text":"\n • §dCPS§r: "},{"score":{"name":"*","objective":"cps"}}
}
})
;
could someone help me with this, i wanna put the cps counter to scoreboard
use scoreboard manager @glacial widget not running commands async.
why cant i do {dimension: vanilladata.MinecraftDimensionTypes.Overworld} in teleport options tho
Debug result for [code](#1067535608660107284 message)
Compiler found 0 errors.
ESLint results:
<REPL0>.js
40:11 error 'cps' is assigned a value but never used @typescript-eslint/no-unused-vars
Can we have signs with existing data like when you Ctrl + Pick a block it shows +DATA in it?
I'm planning on making something that would generate a pre-filled sign.
i don't think so, maybe place a sign somewhere in the world first edit it destroy it then get its itemstack and place it in the inv
@median stream
import { Player, world } from "@minecraft/server";
world.afterEvents.entityHurt.subscribe(eventData => {
const player = eventData.damageSource;
const entity = eventData.hurtEntity;
if (player instanceof Player) {
player.sendMessage(
"You hurt something, you get a buff");
}
});
anyone know why this isnt working
im new to scripts and don't understand any of this, I'm just picking up bits of code and patching them together
https://stirante.com/script/server/1.14.0-beta.1.21.20-preview.22/classes/EntityHurtAfterEvent.html#damageSource Because damageSource returns an EntityDamageSource object
Documentation for @minecraft/server
I really recommend reading the docs and using an IDE that has intellisense so you can install the type defs
Im on mobile and I don't think there is any IDE like that for mobile
it’s bds only
ik, i wanna use it
but, how would i connect said server to discord?
or some external stuff
anyone got a way to cancel piatons
u could test each button / redstone thats used
well no
idk
isnt there an event
yea but they changed the cancel thing
is there a childish explanation
that’s the most childish explanation
then i need toddler explanation 
goo goo code go bzzzt
youre welcome, thank me later
COURAGE THE COWARDLY DOG
bridge
What are typings anyway?
-# — me with 20% randomized error on world load
For code projection
How can I detect when a custom item has been picked up?
theres no direct way for it iirc
you could either compare inventory or do checks on item entity
Ahh okay, thanks
How to play animation using scripting?
Meow meow thanks.
just question, does playerInteractWithBlock is stable in preview 1.21.20
How to detect player dismounting from a entity?
import { world, system, Player, ItemStack, EquipmentSlot, World, } from '@minecraft/server';
import { ActionFormData, MessageFormData, ModalFormData } from "@minecraft/server-ui";
world.afterEvents.itemUse.subscribe((i) =>{
let player = i.source
const itemStack = i.itemStack
if (itemStack.typeId == "minecraft:heart_of_the_sea") system.run(() => main(player))
function main() {
const form = new ActionFormData()
.title("§l§dModration Menu§r")
.body(" §l§aby Maxis")
.button("§lkick")
.button("§lwarn")
.button("§lmute")
.button(`§cExit Menu`);
form.show(player).then(r => {
if (r.selection == 0) kick(player)
if (r.selection == 1) warn(player)
if (r.selection == 2) mute(player)
})
}
function kick() {
new ModalFormData()
.title("Kick Menu")
.textField("", "Reason for Kick")
.dropdown("Pick a member", player.map(player => player.name), 2)
.submitButton("done")
.show(player).then(r =>{
let input = r.formValues[0]
if (input) {
player.sendMessage(`${player.name} Has kicked a player for ${input}`);
} else {
player.sendMessage(`${player.name} Has kicked a player for no reason.`);
}
})
}
function warn() {
new ModalFormData()
.title("")
.textField("", "Reason for warn" )
.dropdown("Pick a player to warn", player.map(player => player.name), 2)
.submitButton("done")
.show(player).then(r =>{
let input = r.formValues[0]
if (input) {
player.sendMessage(`${player.name} Has warned a player for ${input}`);
} else {
player.sendMessage(`${player.name} Has warned a player for no reason.`);
}
})
}
function mute() {
new ModalFormData()
.title("")
.textField("", "Reason for mute")
.dropdown("Pick a mute", player.map(player => player.name), 2)
.submitButton("done")
.show(player).then(r =>{
let input = r.formValues[0]
if (input) {
player.sendMessage(`${player.name} Has warned a player for ${input}`);
} else {
player.sendMessage(`${player.name} Has warned a player for no reason.`);
}
})
}
})
How does "player" have zero arugments?
please keep function declarations outside of events
just pass in the player as a parameter
oh
I honestly have no idea how events handle variables, but I'm assuming they cannot be used by any functions declared in the same space
take the functions out the world events?
now player is not defined
Is there a way to make custom dimensions?
i think you could try with structureManger
player is a Player class, I am assuming, but you are treating it as both a Player class and an array of Player classes- that is, Player[]
Can't call a .map() on a non-array
you also only need to use system.run to open things like that if it is in a beforeEvent
Hello! is it possible to rename a item through scripts?
yes it is!
get the item componet



