#Script API General
1 messages · Page 8 of 1
i need to
let item = itemStack.clone();
item.nameTag = "New name";
smth.setItem(item)
Oh it s an object
Was it a ContainerSlot?
hmmm no not actually it's just a container
ctnr.setItem(slotIndex, item)
ah yes right
but this tho?
it just doesn't upate if i just assign
Cus it's not ContainerSlot, it's just ItemStack
Assigning on ItemStack would need the cntnr.setItem(slotIndex, itemStack)
ohhh cool, now i get to save bunch of lines of code thanks!
//ContainerSlot
const cSlot = cntr.getSlot(slotIndex)
if (cSlot.hasItem()) {
cSlot.amount += 2 //item changed
cSlot.nameTag = cSlot.typeId //item changed
//no need for setItem
//changing component stuff like enchantments would be different
const item = cSlot.getItem()
const ench = Item.getComponent("enchantable")
ench.addEnchantment({ type: new EnchantmentType("mending"), level: 1})
cSlot.setItem(item)//item changed
} ``````js
//ItemStack
let slotIndex = 16
const item = cntnr.getItem(slotIndex)
if (item) {
item.nameTag = item.typeId
item.amount *= 3
const ench = Item.getComponent("enchantable")
ench.addEnchantment({ type: new EnchantmentType("mending"), level: 1})
cntnr.setItem(slotIndex, item) //item changed
} ```
whats difference in Save to memory and save to disk in structure blocks
and do i need to use save to disk to use the structure manager?
Disk is temporary for that world session, if I recall correctly.
Memory saves to the world DB
tried still getting the error
._what ?
@wary edge sorry i meant to ask this #1070606638525980753 message
here. I am trying to do it with scripts. or maybe an Effect?
TP it in place?
With runInterval?
good idea
i know damage is read only in entity hurt event but is it possible to edit it? i was thinking something like damage = 0
No
alright, thanks
well is there another way where i can half the damage dealt to the player instead of healing/giving back half the health back?
Hey what could i do for size? of an entity.
I noticed entity.setRotation() in the docs, but couldnt fiund size
You cant change the scale as far as i know
maybe overwriting player entity file with a property, and change scale when property changes?
Yeah
You can do that. I'm not on my computer but a component group which targets "minecraft:scale" should allow you to modify that scale.
in EntityQueryOptions for getEntities in dimension class, does maxDistance and/or closest, farthest, etc work if location is not defined?
something like this
const entities = player.dimension.getEntities({
maxDistance: 10,
closest: 5,
families: [ 'mob' ]
});
entities.forEach(entity => {
...
});
Yes
does the location fallback to player.location in player.dimension then?
i could test it but i cant open minecraft rn
What ?
Yes
neato
Ofc
world.structureManager.place("island", player.dimension, {
x: (slot*1000)+61,
y: 31,
z: (slot*1000)+59
}, {
animationMode: StructureAnimationMode.Layers,
animationSeconds: 2,
})```how come it says structure doesnt exist when i can load it ingame through the chat?
Does any one know how to make a structure generator
I want to use barrels as containers
namespace?
huh
@devout dune
In player.json just add something like this as a component.
"components": {
"minecraft:scale": {
"value": 1.5 // set to whatever you want
}
}
Then in your script here is an example on how to change it.
system.run(() => {
const player = world.getPlayers()[0];
const scale = player.getComponent("scale").value;
if (scale > 0) {
// This cannot be edited in read-only mode
player.getComponent("scale").value = 0;
}
});
wheres the namespace
the structure is saved to memory on the world
if thats what your asking
hmmmmm
through the structure block
no i was asking if you did put the namespace on the structure's id
like how you put minecraft:
What is ur structure name ?
island
Is in in structures file in ur behaviour pack?
yea, it defaults to minecraft: if it doesnt have one
which is probably why it doesnt work
the script is trying to run mystructure:island
so
mystructure:island?
Yes
ah yes it works now
ok nvm i thought i was tripping
I want structure generator._.
ok then make one
So
In script resources
I saw someone that used barrels as containers
Using mcstructure
huh
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]
doing minecraft damage gonna be fun :)
how to catch and cancel fatal damage?
Can't do that with Script yet
oh no how about player.json?
Can i detect when player uses command or command block get used ?
Like :
/tag
Or idk
u sure it's itemStack?.typeId
Not possible for now
Sad
/scriptevent, yes
Not even with chatsend ?
Sad
Is it possible to get the equipped armor of an armor stand?
Have u tried it?
Yes
Tried equippable and inventory and it returns underfined
Then no... 🙄
The inventory component returns undefined.
Wait let me try again
No
Use "equippable"
Component
Same thing, returns undefined
Show me ur code
const armorStands = world.getDimension("overworld").getEntities({type: "minecraft:armor_stand"})
for (const armorStand of armorStands) {
const equippable = armorStand.getComponent("minecraft:equippable");
const bootsArmor = equippable.getEquipment(EquipmentSlot.Feet)
console.warn(bootsArmor.typeId)
}
something like this
remove minecraft:
world.sendMessage(armorStand.getComponents().map(c=>c.typeId).join('\n'))
still not working
this one also shows undefined error for c
for (const armorStand of armorStands) {
console.warn(armorStand.typeId) // I'm sure armor stand exists
world.sendMessage(armorStand.getComponents().map(c=>c.typeId).join('\n'))
}
Ohh, type_family and health are the only components readable ig?
It only sends message for those comps
That not beta, right?
Yeah
Mhm
How can i add colors to an objective on display
addObjective(objId, displayName)
No i mean
I just add
" | " + "§3green"
To the second argument
And i get this error
[Scripting][error]-TypeError: Native type conversion failed. Interface property ['objective'] expected type: ScoreboardObjective (failed parsing interface to Function argument [1]) at teleportToTeam (forbiddenAreas.js:118)
at <anonymous> (forbiddenAreas.js:61)
Why is that ?
ScoreboardObjective, not objective string
Huh ?
addObjective( "something" , colors[color] + color)
That s how i got it
colors[color] and color are both strings
world.scoreboard.addObjective(objId, display)
Yes i did that
Whats on this line?
This
how would i add a property/method to a prototype?
like entity.myPrototype.action(1)
How did you set the display?
setObjectiveAtDisplay("BelowName") , {objective : "something"})
The "objective" property should be a Socreboard Objective
Oh yeah i see
its getObjective there
world.scoreboard.addObjective("idString", "§pColored")
const scoreboardObjective = world.scoreboard.getObjective("idString")
world.scoreboard.setObjectiveAtDisplaySlot(DisplaySlotId.Sidebar, {objective: scoreboardObjective})
like this
i tried that but it acted like a method or smth, basically like entity.myPrototype(1) im not sure what it's called
Search "Proxy"
How do I reduce the durability of an item? Without losing your current enchantments.
ah i see thank you
When you use it, do not mention the prototype, it is not necessary. Just use it from the object, Javascript does the search in the prototype chain.
If you want to add to the prototype during creation there are also ways.
what kind of ways?
Hmm ?
Bro , use prototype
@misty pivot
Because it used like that :
entity.urMethod()
@misty pivot
mb, i was away earlier
What are u trying to do ?
Make new method or proprety
Into an entity?
Or player
yeah pretty much, but like i can add another method to that method
similar to how you can put dimension after entity
Ah
It s possible
Just ur function must return an object
That s all
U mean
player.method().method2()
@misty pivot
yeah
Then use something like
something like this?
Entity.prototype.method1 = {
function() {
return function method2() {
...
}
}
}```
Not exactly
something like this?
Entity.prototype.method1 = {
function() {
return { method2 : function() {
...
} }
}
}```
ah i see
Put it in prototype, so u can use it in any player or entity
can i declare the functions outside it because if i where to have a ton of methods it would look like a mess
alright thanks, also do you think it's more efficient than using classes? because i usually do something like class(player, /*a ton of properties*/)
jsdocs?
Yes
It is
- Player is a class by itself
well i declare a class then i convert it to an object and put it in events (like world events and such) and to declare the player in the class i put the player in it
.d.ts is a magical thing :3
Why ?
Used to declare types for js code
Oh yeah

is ts used more than js for scripting?
What happens inside that class ?
It s just a js with typing
functions and stuff, it's my way of organizing things
.ts needs to be compiled to .js to run within minecraft
Yeah it better to use prototype in this one
What s difference between
.d.ts , .ts
extend prototype is pretty poggers ngl
Wait ,
.d.ts is used to declare types for regular use in .js scripts- think of a .d.ts like a large jdoc file
.ts is it's own language based off .js, and must be compiled.
.d.ts doesn't do anything but provide autocompletion & intellisense in the editor
Oh
That s cool
So it s like ts file that s compatible with js
It s for notations
Like with this-
I get autocompletion for inventory component, and a custom message to tell me what's happening
I don't get it
yes
So u are happy because u changed the documentation that is there so u can understand it easily
It does nothing in-game itself
Only used for the editor and ease of use for the coding
I never mentioned the game here ☠️
Alright
Alright that s cool too , i hope u are happy with it : )
I was just thinking in using it
"YOU CANNOT USE A string | number | boolean | undefined FOR A NUMBER TYPE YOU IDIOT"
But ngl it just used for big projects
(I really should use it tbh)
There is no reason to use it in an add-on
How is that possible ☠️
There is number already
I just cannot be bothered to change my scripts
ah, but it could be the others as well
That's what ts does
stricter rules than a prison warden
It catches stupid mistakes
U are laterally telling an ordinary programming language rules ☠️
How to make your entity knockback mobs with resistance
UsIng script api ?
apply the same force but the opposite direction of the knockback/attacker's location
or if you mean entities just use minecraft:knockback_resistance
He can use
entityHitEntity event too
And how do you make mob walk backwards when the target is near
erm, are you sure you're in the right channel?
Maybe check ranged mobs .json
also ocelot.json
Hey guys. How many characters are allowed in a textField description?
You cannot return a function declared on the same line. It must be expressed or previously declared, I think.
lmao you are so delayed, but yeah kiro taught me that i could make it return objects
How do I add custom components to items?
Also functions. Without needing the object.
Although this is not to learn Javascript. Here is to get my question answered.
How do I add custom components to items?
Not possible right now
I don't want to read the component.
I think 255
I knew it. Although the documentation said yes xD.
Can I change the durability of an item in the inventory?
I think this is the allowed number of buttons in ActionFormData.
How do I place the component in the json?
Please correct the documentation, the last word appears in plural.
mb mb, it is actually plural
Then you are wrong. It does not work.
and must be 1.20.80+ format
yep
world.beforeEvents.worldInitialize.subscribe((e) => {
// Custom for block
e.blockComponentRegistry.register.CustomComponent("ur:custom_comp" , {
// An example
onPlace(e) {
//Ur code
}
})
}
Formatting is always a pain in many jsons.
I know. I know everything else.
If I'm not mistaken, you might have to use 1.20.80 because iirc that doesn't work
It s too limited tho : T
I mean- It's supposed to be a replacement for Block/Item events so
Replacement for my precious events
imo it allows for way more
Why they are lazy
XD don't use 1.21.0
Js dosen't bite pplz
I don't think they are lazy
also, i tested custom components in a server, it doesn't seem to work :/
32k bit probably
but be careful it can crush your game
i can confirm but i learned this from something else and not textField
How strange, the icon component is failing me when updating the format version.
Are u sure ?
yeah just tested it with 2000 char
and this happened to me twice because of miscalculation 
Do you have HCF enabled?
:v ?
Trying to use the "minecraft:custom_components" component with both Beta APIs and HCF enabled will cause issues
Holiday Creator Features
Bruh, this means I have to use body in ActionFormData.
:0
I'll see.
why is that?
Are u writing the bible ☠️
AH, NO WONDER IT DIDN'T WORK IN THE SERVER, thanks for the info
Scam.
15000 char
yep thats what happened to me, but with nametags instead
Lol. I'll do something similar to the chat.
Don't worry, the toggle has been removed in 1.21.20 so all you need to do is wait for stable release
Bruuuh. Not this.
I mean this
the filed name?
It actually works for me, only now the icon fails xD
That happens because of conflicting schemas xD
I will make a Clans Add-on
same thing
Nice, what is the maximum?
it start to lag but let me see
those are 10 000 char
Ah wait
I don't think I need this number. 💀
(both of these work) ```json
{
"minecraft:icon": "reforged:copper_pickaxe"
}
or
```json
{
"minecraft:icon": {
"textures": {
"default": "reforged:copper_pickaxe"
}
}
}
😦 what is the current scheme? I already get a scheme error.
Fuck Mojang.
alr
I did not understand
alright
They had to change it to make trimming possible for custom items
How do I reduce the durability? Without losing the current state of the object.
There is no point in increasing the damage of the durability component.
Oh, well then I'll use it, Thx
And where were they notified of the change?
TnT I should check.
.
why?
I've been doing it using the durability component in Scripting
The damage property of the durability component on itemStack objects.
And how? It does not work.
you need to set the item
You'd have to set the item back
with equippable.setEquipment or slot.setItem
:'v And it doesn't remove the enchantments or anything?
Nope
TnT okey
iirc if you use container.getSlot it should update without having to set it back
slots dont let you get components, only ItemStacks
I thought they always did, huh
you can change amount though
Do the Source properties of the events return only one entity? They don't return a player?
An entity can be a player
Can be any entity also
So a Source type entity can return a type player?
Mhm
you can check with
if (source instanceof Player) {
// source is player
}
:'v I'll have to verify it on my own then.
but instanceof gives automatic type stuff so i find it better
import player
import Player
yes you need to
Vrom vrom
Recommend movies.
anyone know whats the diffrence b.w getPlayers() vs getAllPlayers() without query
Yes
Probably not in this channel.. #off-topic is the right place.
One returns a player and the other a list of all players.
One receives a filter parameter and the other nothing.
There shouldn't be any difference
yea why do we even have 2
Yes, the Source is player type.
Because, u want to specify player
Idk only players who has some tags
Included
Filter function.
Yes. That's why the "?" sign.
Yes
I cannot get this to workjs import { MinecraftEntityTypes } from "@minecraft/vanilla-data";if I do not have it, MinecraftEntityTypes is undefined, if I do have it and TRY to throw in the dependency, it says ```
[Scripting][error]-Plugin [§cPreview§r: §6Beta§r: Test Space BP - 1.0.0] - failed to create context.
[Scripting][error]-Plugin [§cPreview§r: §6Beta§r: Test Space BP] - module [§cPreview§r: §6Beta§r: Test Space BP - 1.0.0] depends on unknown module [@minecraft/vanilla-data - 1.21.20].
[Scripting][error]-Plugin [§cPreview§r: §6Beta§r: Test Space BP - 1.0.0] - run failed, no runtime or context available.
That will probably change in v2
Did u turn it to js ?
hmm
Just getPlayers() used for filtering the player
To not have to filter inside the function and to be able to do it outside in a better way with the list.
With iterators.
You might have to use absolute paths or TypeScript though you need to install the package using NPM
getAllPlayers() give u all players that are connected to that world
And so does getPlayers()
That is, download the package directly and place it where it should go.
Yes
Transpile the ts to js
Their question was why do we have two despite them doing the same thing excluding queries
Oh
We even have an iterator:
Yeah , they just can make the queries inside getAllPlayers()
Instead of making two methods
That s a dumb thing
That s weird
I code in js
what are you talkin about ? have you seen the signatures of both
- getPlayers(option?): Player[]
- getAllPlayers(): Player[]
I don't think that's being used anywhere LOL
vanilla-data needs to be compiled to js
It already has a bundled JS file ready inside the package
The auto completion is working, maybe because I have the npm? download it from where
:v in my defense we are screwed.
XD I think the same haha.
Download NodeJs, it has npm inside.
What are u talking about :T
I have npm
I, who am in cel, would only translate those packages and rush them to my script.
I need @minecraft/vanilla-data
Can u tell me how do u use vanilla-data module ?
I mean I need it towork
I mean where did u put it
Use commands. For install. The npm commands. Install.
Right click on your scripts folder, then open in terminal
Run npm i @minecraft/vanilla-data
import { MinecraftEntityTypes } from "@minecraft/vanilla-data";
Yeah i mean
U didn't put it in script's file ?
then import { MinecraftEntityTypes } from "./node_modules/@minecraft/vanilla-data/lib/index.js";
Did u use it directly from the game , i mean like server module ?
Does vscode then make code modifications? XD is that we don't know if those packages are natively inside Minecraft.
Wdym by code modifications?
It's not a question of intellisense, it's a question of compatibility. Better convert to js and put them where they need to go.
When in doubt, the most buxom.
The package that imports needs to exist internally. To avoid error.
Perfect.
?
:v we are the powerful of the server. XD
what about the manifest....... and I am getting [Scripting][error]-Plugin [§cPreview§r: §6Beta§r: Test Space BP - 1.0.0] - [main.js] ran with error: [ReferenceError: Module [node_modules/@minecraft/vanilla-data/lib/index.js] not found. Native module error or file not found.]
I lack power >:v
Let me explain u something
vanilla-data
You don’t have to add it to the manifest
Dosen't exist in the game
Do you know where I can find people for a small project that I have with a graphic designer?
also you need to download it in your scripts folder using NPM
U need to download it via npm
XD jaja
Hmmm
I ran that npm but it did not add any files to a folder that I can see
Did you run it in the scripts folder? It should create the usual NPM stuff including the node_modules
Put it in script file
Not sure it did it, it is talking about an audit
Then
import { MinecraftEntityTypes } from "./index.js"
hmm
I gtg :T
To calculate the amount inside the modules exported from index.
sorry?
We will never understand this guy : T
😭
Please ma'am
Just copy index.js from vanilla-data module
Put it in ur scripts file
The issue is, it’s not there when she runs npm install
What vanilla-data module.. where be this file on my computer
Then change the import to :
import { MinecraftEntityTypes} from "./index"
U see node_module
U see that path
Try running npm init then rerun the install
"mystructure:island"
put the full name with the id
its been a longgg time
I did that and had to press ctrl-C to get out, it was asking for ??
Thanks,m I am grabbing the enum code
that causing the error?
That will generate a package.json file for you which you can use to install packages
Or you can create the file yourself and just make the content this {}
Can I simulate breaking an object easily or will I have to play the sound and remove the object?
A block? You could use the fill command
Durability does not cause the destruction of the object.
That worked, now I have that folder...
Does importing the JS file work now?
No, cause it is TS and I am not set up for that.. can't find the extension I had to right-click convert.... and that command moved my main.js.. LOL
Wait wha-
hey
world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
const {block, player, itemStack} = ev
const tokens = {
"minecraft:nether_wart": 100,
"minecraft:nether_star": 200
}
const ores = ["minecraft:coal", "", ""]
const money = world.scoreboard.getObjective("Money")
if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){
if (itemStack?.typeId in tokens) {
const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand")
if (itemStack.amount === 1) hand.setItem()
else hand.amount--
player.addScore(player, tokens[itemStack.typeId])
}
}
})
Could someone help? itemStack is not defined why?
try use selectedSlot
found out why it was not defined but now am getting nothing at all even when am interacting with the block
player.getComponent("inventory").container.getItem(player.selectedSlot)
let me try that rn
still nothing at all
There is the index.js with scrunched code. I guess I can do a straight import of that file
Yeah!! That's how I do it
i did that
and it works
but this does not run
if (itemStack?.typeId in tokens) {
const hand = player.getComponent("inventory").container.getSlot(player.selectedSlot)
if (itemStack.amount === 1) hand.setItem()
else hand.amount--
player.addScore(player, tokens[itemStack.typeId])
}
{1,2,3,4} ?
Does this work?
if (itemStack?.typeId in tokens) {
const equippable = player.getComponent("equippable");
const hand = equippable.getEquipmentSlot("Mainhand")
if (itemStack.amount === 1) equippable.setEquipment("Mainhand")
else hand.amount--
money.addScore(player.scoreboardIdentity, tokens[itemStack.typeId])
};
what does this mean
itemStack?.typeId in tokens
It s synatx to see if that property exist in an object or not
when i hold the tokens in my hands i dont get no console warn
or nothing
Same as
tokens.hasOwnProperty(itemStack?.typeId)
Checks if it has a value in an object
Not the same
hey try this
Why not?
in - includes prototype properties
.
you are using faceLocation instead of the itemStack
I mean it's an object
if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){
console.warn("hello")
if (itemStack?.typeId in tokens) {
const equippable = player.getComponent("equippable");
const hand = equippable.getEquipmentSlot("Mainhand")
if (itemStack.amount === 1) equippable.setEquipment("Mainhand")
else hand.amount--
money.addScore(player.scoreboardIdentity, tokens[itemStack.typeId])
};
}
})
Nope
HasOwnProperty is used for something else
world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
// const {block, player, itemStack} = ev
const itemStack = ev.itemStack
const block = ev.block
const tokens = {
"minecraft:nether_wart": 100,
"minecraft:nether_star": 200
}
const ores = ["minecraft:coal", "", ""]
const money = world.scoreboard.getObjective("Money")
if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){
if (itemStack?.typeId in tokens) {
const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand")
if (itemStack.amount === 1) hand.setItem()
else hand.amount--
player.addScore(player, tokens[itemStack.typeId])
}
}
})
TBH I use that most of the time
Not good
still nothing..
No? Order doesn't matter in an object
What if that property was in constuctor prototype?
the file in imported to the main.js
U can't detect it
world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
// const {block, player, itemStack} = ev
const itemStack = player.getComponent("inventory").container.getItem(player.selectedSlot)
const block = ev.block
const tokens = {
"minecraft:nether_wart": 100,
"minecraft:nether_star": 200
}
const ores = ["minecraft:coal", "", ""]
const money = world.scoreboard.getObjective("Money")
if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){
if (itemStack?.typeId in tokens) {
const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand")
if (itemStack.amount === 1) hand.setItem()
else hand.amount--
player.addScore(player, tokens[itemStack.typeId])
}
}
})
dumbway
Don't think that would work
why
Why would I need to do that?
- wrong
hasOwnProperty
Only exists on Object class
how comes
Because half of script resources
Okay, I am in business... now to test...
Made with prototype
I don't think I've used anything from there LOL
Because maybe some of script api using prototypel inheritence
#debug-playground message
U can use
tokens[itemStack.typeId]
Instead of all that sh** 🤦🏻♂️
bro if i were you im just gonna console.warn all the variables
What s the problem?
yep i did, everything works but when i hold the acutally item the console log for that does not run at all
console.warn
yep did that
oh
all the code works outside of this
if (itemStack?.typeId in tokens) {
const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand")
if (itemStack.amount === 1) hand.setItem()
else hand.amount--
player.addScore(player, tokens[itemStack.typeId])
}
That doesn't work ?
guys how do i disable timeout
i found another way of doing it which works but now i would need to get the vaule of the tokens from the objects
world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
const {block, blockFace, faceLocation, itemStack, player} = ev
const tokens = {
"minecraft:nether_wart": 100,
"minecraft:nether_star": 200
}
const ores = ["minecraft:coal", "", ""]
const money = world.scoreboard.getObjective("Money")
if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){
console.warn("hello")
player.runCommand(`/clear @s ${tokens[0]}`)
money.addScore(player, tokens)
}
})
What s the problem !!!
i honestly dont know
kiro
how do i disable script itmeout
system.clearRun(iterval)
what
how do i get the 100 vaule from the object "minecraft:nether_wart"
U must put the interval in a variable
That s all ?
yeah
.. no idea that there are 1178 blocks
how do i disable watchdog
Go to Creator setting in settings
U will see the watchdog slider put it in max value
1.12.0-beta works?
ohh
Or see if there is a toggle to stop it
i cant change anything
it’s another module but you can disable it via system events https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_12_0_beta.SystemBeforeEvents.html#watchdogTerminate
Hmmm
Then check that
okay
this?
system.beforeEvents.watchdogTerminate.subscribe((ev) =>{
ev.cancel = true
})
Won't work on Realms. Mojang overrides that.
how to clear all effects without run command?
is this how i detect mending on gear
system.runInterval((e) =>{
for(const player of world.getAllPlayers()){
mending = new EnchantmentType()
const inventory = player.getComponent("inventory").container
const item = inventory.getItem()
const ench = item.getComponent("enchantable")
const men = ench.hasEnchantment({ type: new EnchantmentType("mending"), level: 1})
if(player.hasTag() !== "t1" && men){
player.runCommand(`/clear @s ${men}`)
}
}
})
hasTag() requires an arg.
Example:
const IF_TRUE = player.hasTag("money"); // Returns a Boolean
oh
How to get the "distance" between two vector3?
I told u use chebychev distance
hard to understand
am gussing its dx
some as the target selections in commands
what
/give @e[dx=1, x-2]
const player = world.getPlayers()[0];
const effects = player.getEffects();
effects.forEach(effect => {
const effectType = player.getEffect(effect);
player.removeEffect(effectType);
});
@remote oyster
function chebyshevDistance(vector1, vector2) {
let differenceX = Math.abs(vector1.x - vector2.x);
let differenceZ = Math.abs(vector1.z - vector2.z);
return Math.max(differenceX, differenceZ);
}
// Example usage
const vector1 = { x: 1, z: 2 };
const vector2 = { x: 4, z: 0 };
console.log(chebyshevDistance(vector1, vector2)); // Output: 3
const playerLocation = player.location;
const blockLocation = block.location;
const distance = Math.sqrt(
Math.pow(blockLocation.x - playerLocation.x, 2) +
Math.pow(blockLocation.y - playerLocation.y, 2) +
Math.pow(blockLocation.z - playerLocation.z, 2)
);
console.log(`Distance: ${distance}`);
Can you make a function
to calculate the distance betwern two vector3
You're blind.
Do you like mathematics?
...Make a function that receives 2 objects with 3 attributes each.
U need it
Then you do the calculation and a return with the formula, Pythagorean theorem.
I remembered that Mojang has a public library of mathematical utilities for working with vectors.
It is in npm attached to @minecraft
function distance(vector1, vector2) {
return Math.sqrt(
Math.pow(vector1.x - vector2.x, 2) +
Math.pow(vector1.y - vector2.y, 2) +
Math.pow(vector1.z - vector2.z, 2)
)
};
@remote oyster is this right?
I made a function using your method
No
He's horrible in the chat but yeah.
Y musn't be included
UHH
The return, place it.
If u want to calculate distance in 2D plane
vector3..…..
oh, oopsies thx
It is not native. I know, but it can still be used.
Ok i told u :T , what to do it s ur choice
I don't care about if it s native or not
{x, y, z}: Vector3
my function is for vec3
not vec2
U don't need to calculate the Y with them
what?????????
bro are you crazy
for example, if my code gets distance betwen x,z and x,z (from block to player)... And if i fly up from the block, it wont measure the distance....
x and z can get y?
Bruh
No
How is y not needed 😭
Distance is calculated in 3D plane
So let s say u have two block in the same x and z
But their Y is different
As example block above other block
You include the Y coordinate if you want to calculate the distance in 3D space, and you ignore the Y coordinate if you want to calculate the distance in 2D space. So depending on what your goals are will depend on which one you may desire.
Mi huevo. Jaja
But in that situation i don't think Y is useful
By the way, I'm a math student, I can help.
Good
I don't think he wants the extra dimension
So he will come back later
And tell us why my code isn't working
Because he calculating distance in 3d but he is assuming that the distance in 2D space
I returned. Make me a list of the boy's needs, be precise. I speak Spanish and I must translate, I want just one message.
The boy needed to measure the distance of two vectors, right? Now you need to measure the distance of two volumes?
Si vas a calcular la distancia entre dos ubicaciones, ¿usarás Y?
Yeah
That depends on their goal. If they only want the horizontal difference between two points then 2D space is fine, but if they are wanting true straight-line distance between two points, where height matters, such as teleportation, projectiles, or vertical movements, then 3D space is necessary.
A generalization of the Pythagorean theorem for Euclid spaces is used.
It is called space metric.
, but mostly no one uses the straight line , for the did
Only the horizontal one
That's false.
I said mostly
Mostly is still false. The majority here don't even know the difference let alone how to apply it correctly.
Correct
Ok let him uses the 3D space and i bet that he will return again , and tell us why my script isn't working
You just have to imagine the Pythagorean theorem and rotate the space. There are also ways to view it by iteration.
You can't say that because you don't even know what his actual intentions are. You are assuming and for that reason alone makes you arrogant lol. Let them specify in greater detail what they are trying to accomplish, then you can rationally determine which is more fitting.
Ok :-: my bad
Why does the boy want to measure the distance?
Tell him
X2
I think we should have told you that you can measure the intersection of two volumes and also that you can measure radial and vector sectors. XD
@prisma shard what are u trying to make ?
just the distance between a entity and the player
bruh you guys started a war lol
i just figured it out
so i dont need help now
calm down everyone
Math.hypot()
All could been avoided if people knew how to ask good questions
Yeah :T
Math.hypot(x1-x2, y1-y2, z1-z2)
(idk why you pinged me and deleted it)
When calculating the distance u need the horizontal distance
Or the straight line distance
I don't think anyone would use the straight line distance, because it can cause some weird calculations
And results
Like distance between
{ x : 0 , y : 0 , z : 0 }
And
{ X : 64 , y : 70 , z : 64 }
114.42027792310242
i know?
that what hypot dose
bruh
no you have to
I don't think you are fully understanding the difference between the two scenarios and how they can apply.
const player = world.getPlayers()[0];
const blockLocation = { x: 100, y: 64, z: 100 }; // Example block location
// Function to calculate 2D distance (ignoring the y coordinate)
function calculate2DDistance(point1, point2) {
return Math.sqrt(
Math.pow(point2.x - point1.x, 2) +
Math.pow(point2.z - point1.z, 2)
);
}
// Function to calculate 3D distance
function calculate3DDistance(point1, point2) {
return Math.sqrt(
Math.pow(point2.x - point1.x, 2) +
Math.pow(point2.y - point1.y, 2) +
Math.pow(point2.z - point1.z, 2)
);
}
// Get the player's location
const playerLocation = player.location;
// Calculate the 2D and 3D distances between the player and the block
const distance2D = calculate2DDistance(playerLocation, blockLocation);
const distance3D = calculate3DDistance(playerLocation, blockLocation);
// Define maximum allowed distances
const maxDistance2D = 10;
const maxDistance3D = 15;
// Check if the player is within the allowed 2D distance
if (distance2D <= maxDistance2D) {
console.log("Player is within the allowed 2D distance.");
} else {
console.log("Player is too far away in 2D space.");
}
// Check if the player is within the allowed 3D distance
if (distance3D <= maxDistance3D) {
console.log("Player is within the allowed 3D distance.");
} else {
console.log("Player is too far away in 3D space.");
}
The 2D calculation is useful for horizontal range checks, such as detecting if players are near each other for PVP or interaction purposes.
The 3D calculation is crucial for vertical interactions, such as checking if a player can interact with blocks or entities at different heights. Such as determining the effective range of vertical traps, elevators, or in scenarios where altitude affects gameplay mechanics.
With Y included
Without Y included
Y included can also count for horizontal direction because it's 3D space.
Yes but
It's application can vary depending on what it's needed for
Yes
But let s say : someone want s to calculate distance between him and his home
He will never use the 3D space
And most used is horizontal 2D space
Even in those situations
Or maybe i m wrong
After all it doesn't worth it
Try using 2D calculation when monitoring pvp battles and see how that works out.
As I said before, the application varies. Your example shows that 2D would be best preferred if height is not a concern in relation to whether the home is below ground or in the sky.
However, there are other scenarios where if you do not utilize 3D calculations, you will erroneously handle the environment.
Ok what about distance between two entities?
What we must use
In pvp battles, players jump and fly around. 2D would not be the choice of method when monitoring the traffic here, because height becomes crucial ensuring that vertical positioning is considered in range calculations.
is there a math function similar to math.clamp from molang? i want to make it so the summed value will be returned as 20 maximum
https://stackoverflow.com/questions/11409895/whats-the-most-elegant-way-to-cap-a-number-to-a-segment
or if you want mojang fancy way use minecraft/math https://jaylydev.github.io/scriptapi-docs/latest/functions/_minecraft_math.clampNumber.html
function clamp(value, min, max) {
return Math.max(Math.min(value, max), min);
}
// Usage
let value = 10;
let minVal = 5;
let maxVal = 15;
let clampedValue = clamp(value, minVal, maxVal);
console.log(clampedValue)
Yes
you are using 2d space
a = √b²+c²
What app are you using to make these diagrams. I must know.
powerpoint and paint lol
Haha, so simple. Very nice.
i use it for a lot tbh even some animations
what does clamp do?
what yall tryna do?
so clamping exists huh.... I normalized vector for applyImpulse() by using the distance. I thought about that solution for a whole day then clamping just shows up where I least needed it. dang
Make the value never pass maximum value and never be less than the minimum value
how do i make a variable in the constructor of a class work for all of its methods, like
class ClassExample {
constructor(entity) {
//the entity
}
method1() {
this.entity.kill()
}
}```
constructor(entity) {
this.entity = entity
}
do i still have to use this in the other methods?
Yes
I told u what this used for
yeah lmao i forget 😂
but for functions is it
this.myFunction = function() {
...
}```
In class ?
U need it inside it not outside it
how would that look like?
particularly where inside?
function() { this.idk }
There is object and class
Math.sqrt(x * x + y * y + z * z);
And
Math.hypot(x, y, z);
It's the same, right?
@distant tulip

slightly different handling of edge-cases
Doesn't really matter for minecraft use
whichever you prefer- I use hypot because it's easier to read
Truncation error?
yeh
alr
Computer inaccuracies
Happens a lot, nothing to really be worried about for regular use
prototype
I don't want to make prototype
idk
yeh you can assign arbitrary properties to the player after runtime.
Decimal ?
Elaborate
world.getPlayers().forEach(plr => plr.myprop = true)
I can't make it into the class itself?
myprop would be true for all players in that case
world.getPlayers()[0] and using forEach is the same?
huh?
You are defining the property here, you do not need to define it beforehand
what that [0] do then
Does it work tho ?
accesses first element of array
returns first player
as world.getPlayers() returns Player[]
oh oops
It does.
Nice
Note that the stored data is deleted when the world is reloaded/loaded
But it does carry between sessions- aka if a connected player has data saved that way, then logs out and back in, it will stay.
Thx u
If the host relogs, though, it will be lost, as the world is being restarted when that happens
Just assume they will be deleted upon logout and you'll be fine
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]
@valid ice it didn't work
whar
Wait a mib
A min
import { world, system, DisplaySlotId, EquipmentSlot } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe(e => {
if ( !e.initialSpawn ) e.player.colorsTags = {
black: { isAdded: player.getDynamicProperty("black") ?? false },
blue: { isAdded: player.getDynamicProperty("blue") ?? false },
cyan: { isAdded: player.getDynamicProperty("cyan") ?? false },
green: { isAdded: player.getDynamicProperty("green") ?? false },
orange: { isAdded: player.getDynamicProperty("orange") ?? false },
pink: { isAdded: player.getDynamicProperty("pink") ?? false },
purple: { isAdded: player.getDynamicProperty("purple") ?? false },
red: { isAdded: player.getDynamicProperty("red") ?? false },
white: { isAdded: player.getDynamicProperty("white") ?? false },
yellow: { isAdded: player.getDynamicProperty("yellow") ?? false }
}
})
system.runTimeout(()=> {
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
if (!player.colorsTags?.[getColorTag(player)]?.isAdded) {
let ColorTag = getColorTag(player);
teleportToTeam(player, ColorTag);
}
}
}); } , 20)
It tell me cannot access undefined of undefined

What ?
undefined of undefined lol
Yes
Will a mod using Minecraftserver 1.0.0 run smoothly on all versions?
Only on versions that support it- I think 1.19.60 and higher?
function getColorTag(player) {
for (const colorTag in player.colorsTags) {
if (player.hasTag(colorTag)) return colorTag;
}
}
tbh I do not see why you would need to temporarily store such a large amount of information
Wouldn't it be better to just stringify an array of objects or something to save in a dynamic property?
No
Instead of separate properties for every color
I tried it , isn't the best choice

Not really no
That's just a very... odd way of saving data..
if (e.initialSpawn)
Oh lmao
whats the best i can do to run a code whenever the world creates only
World initialize event?
Ok
So reload dont make it load again?
Only when the world is loaded up
mmm so if i relog to the same world it will load again
Yep
if thats the case i can just make it happen once with scoreboard
You can set a dynamic property on the world to prevent it tho
Or world time
if (world.getDynamicProperty('yes')) return;
ok
this test didnt worked me idk why
Ok it works but it has to have a little delay so it appears when the client completely logged in
@amber granite
import { world, system, DisplaySlotId, EquipmentSlot } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe(e => {
if (e.initialSpawn) e.player.colorsTags = ["black", "blue", "cyan", "green", "orange", "pink", "purple", "red", "white", "yellow"].reduce((o, k) => {
o[k] = {
get isAdded() {
return e.player.getDymamicProperty(k)
}
}
return o
}, {})
})
system.runTimeout(()=> {
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
if (!player.colorsTags?.[getColorTag(player)]?.isAdded) {
let ColorTag = getColorTag(player);
teleportToTeam(player, ColorTag);
}
}
}); } , 20)
Are y sure ?
Can someone lead me to a basic tutorial in using typescript instead for script api?
Ty
you can't bypass this right?
Does dynamic import works in the latest stable version of scripting api?
Nvm, searched a keyword, and found out a "Yes" in the latest 1.21.0+
no
case "setlore":
if (player.isOp()) {
let commandText = command.join(" ").trim();
let newLore = commandText.slice(8).trim().replace("\\n", "\n");
if (!newLore) {
player.sendMessage("§cLore text cannot be empty.");
break;
}
let inventory = player.getComponent("inventory").container;
let item = inventory.getItem(player.selectedSlotIndex);
if (item) {
item.setLore([newLore]);
inventory.setItem(player.selectedSlotIndex, item); player.sendMessage(`§gSet lore to ${newLore}`); } else {
player.sendMessage("§cYou need to hold an item to set it's lore.");
}
}
break;```
so I'd have to like
make it detect when you do \n
and make a new phyical line
.split('\n')
'this is a testing string!'.split(' ') -> ['this', 'is', 'a', 'testing', 'string!'] Example of splitting on spaces
so what I'm understanding here
Do note that there is a limit on lines as well- 20 max.
yes. maths
is that it's making it so you can have infinite lines, but each word must be <50 charaters each
Nice
20 lines, 50 chars per line
I've been asking for it to be extended since forever now...
1000 charaters isn't that bad
It's not, but color codes take up a decent chunk of mine
Even if it were increased to like, 50 lines 50 chars I'd be happy
I just want a lil more
just a pinch of extra lore
Is there a way for me to check what script event is causing a lot of lag?
Are you on pc?
Yes
Use the script profiler
Is that an app or something?
Or not...thanks slow internet
Okay thanks 👍
Is it possible to group custom components into one script file?
Say for example there is a block that does 3 things:
- it can be interacted with
- when placed, it does something every few ticks
- it does something when it is broken
Can you make a custom component where these 3 components are in the same script.
Or do you have to make a script for each component separately?
By script you mean one block or do you mean one fileM
one block, 3 custom components.
You should be able to
Did u try it?
Thanks.
I was not sure if one can.
Appreciate it.
how can I modify a projectile damage?
I want to make any projectile double its damage after a certain player action
is there a limit to structure blocks saves
with world editors no, but there is a limit for generating them
wym generating them
like you cant spawn an structure with a size of 1000 x 1000 xd
even if you use /structure load, will never load
and with world generation is worse, the limit is 48x48
How much is enough ram for a "waiting server". Just for people to join and "wait". I thought about 1gb but I think even the server won't handle. ||I am talking about BDS here||
Seems more for #off-topic
Hmm if you say so
anybody know why the item interaction is not working while riding the entity? it works when the player is not riding
import { world, system } from '@minecraft/server';
world.beforeEvents.playerInteractWithEntity.subscribe(
({ player, target, itemStack: item }) => {
let event = system.run(() => {
const isRiding =
player.getComponent('minecraft:riding')?.entityRidingOn.target;
if (isRiding) {
const cooldownComp = item?.getComponent('minecraft:cooldown');
if (item?.typeId === 'fs:melee_mm' && cooldownComp) {
const remainingTime = cooldownComp.getCooldownTicksRemaining(player);
if (remainingTime === 0) {
cooldownComp.startCooldown(player);
target.triggerEvent('fs:melee_ability');
console.error(
`${player.id} triggered the Melee Ability for ${target.typeId} Id: ${target.id}`
);
}
}
} else {
console.error('Player is not riding target');
system.clearRun(event);
}
});
}
);
Why did you just copy their message? @turbid oriole
Sssshhh
Dont shush me
Does any other event like player interact with block work?
i havent really tested that
I'm not going to help you if you don't tell me what you're trying to do.
i have the console errors there :/
it explains itself really
it's just an interaction event bud, nothing huge
@turbid orioleDude, don't be a dumbass please
If it's not important, what are you doing here? Be more specific with your interaction, don't be a terrible software designer.
Jaja 7w7 ups
Anyways, @solar dagger could you try my suggestion? playerIntearctwith block? I have a feeling it might be the riding entity interfering since you said the event works if you're not riding an entity. Maybe also just put console.warn or sendMessage in the first line before the system.run?
The Wei uses cooldownComp in the condition of an if, it is a component object.
When I did that by accident it failed me. It only works in case of undefined but I don't know how to declare true.
Yee I'll check it out later, a little busy rn with other stuff. I'll lyk if you'd like me to
An interactive action with an item while riding an entity. That's what I'm doing
cooldownComp !== undefined.
:v I haven't tried it completely but you're right.
When in doubt I retire to sleep.
yeah pro tip...don't help someone if you yourself don't know it either
It's rather annoying
XD I like to release my anger here.
Please dont
This is my final warning
Okay, I'm going to really help, what are considered entity interactions other than riding on them?
🫂
I have to go do something, I'll be back with the answer.
The rideable component has a rider_can_interact field that might be relevant here
Review your code, I recommend using an afterEvent to avoid using a system.run and avoid using this line which I consider unnecessary: const isRiding = e.player.getComponent("minecraft:riding").entityRidingOn.target;
What are you talking about?
:v Of something that is not for you.
I'm not looking forward to it, that's life daddy.
😭i was going to ask a question but i think i’ll pass after seeing that

