#Script API General
1 messages · Page 3 of 1
jayly has send a link, its a good docs thingy
Let object=
{ PI : 3.14 , PI2 : 6.28 }
Let str = JSON.strigify(v)
And when u parse it u will get the values that was in the object with their types saved
Okay but what when i didnt saved an object
world.setDynamicProperty(`${databaseId}:${key}`, STRINGIFIED_VALUE);
like when i saved a value
in dynamicProperties
And then my database gets the value to add it to the cache
it would work to parse the value
Okay
Listen to me
1 - first , work on object and put the values on it
2 - strigify that object and
3 - declare new variable as examples : myData
4 - add the strigified object to him
so every value i save needs to be an object
okay..
not true
My lang is sh** , i mean it mainly used for objects
If u wnat to stringfy something use toString is better
How do you clear a slot? Would it be like typescript ...setItem(i, null)?
null or undefined
the docs suggest undefined
Alr I'll use undefined then
did you update your manifest server ui version?
it's on 1.3.0-beta right?
yeah
should work then
hm
any error?
not a function
yes
UIManager.closeAllForms(player)
should work
this is a wired syntax
they should just make it a player function
How do you check if a variable is a Vector3 or not?
checking if it doesnt return xyz, i think?
i dont think theres a dedicated way for this
Variable instanceof Vector3
@near siren
o
Tried that, but it just says this. And when I try importing Vector3 it says it's not an import
Oh from minecraft math?
Yeah
U can also u
External module
Use external module
To not change the manifest
What are you trying to do?
Yesh i think import it from Minecraft math
It s better to be compatible with ur code
You dont really need the vector class if you dont use math operations
I'm trying to see if a variable is a vector3 or a number so I can add them accordingly
U can use a function
And see if this variable has x and y and z propreties
If not it will return false
So that method does in fact work. Side note, dont think I've ever used minecraft/math before and I'm unsure as to how to make it work with bridge
v.x && v.y && v.z?
Thats what I ended up doing
Ok import it ur js file
import { Vector3 } from 'minec..math idk"
Then use instance of
How do I increase the block state by 1 point with script?
When the tick component, which is added in the block behavior, fires off.
Is there a way to get block update event?
not afaik
why do the onPlace keep getting called with the playerinteract?
initEvent.blockTypeRegistry.registerCustomComponent('wiki:something', {
onPlayerInteract: (e) => {
console.warn('Block interact')
},
onPlace: (e) => {
console.warn('Block place')
}
});
Just check the block being interacted ain't ur custom block.
how do i make a code to repeat for specified ticks
runInterval?
.runInterval(func, 10 <- ticks)
o
The very block being interacted with is the custom block?
Then, the placeOn event is called too
I kinda guess what happening, the onPlayerInteract setPermutation, then it triggers the onPlace
Then cancel ur placement? Interaction takes priority over placing. Or do you want to do the opposite?
How can I do that?
i figured it out
btw
is there a way to change a specific state without changing other block state?
permutation.withState() (return BlockPermutation)
it doesn't actually change the block, so you gotta use
block.setPermutation()too
That doesnt help much
nvm
how do i make spawnEntity to not trigger if the entity already exists?
tried filtering out by using tags or dynamic properties but it either doesnt work or the first entity wont spawn
so i have a dummy entity that spawns and teleports to mobs in range when an event triggers
the dummy entities teleports via runInterval (and clearRun when the entity dies or disappears)
but i cant get the dummy entity to "not spawn when theres already an existing dummy entity on the mobs in range"
ill get you a vid
yep
getEntities({maxDistance : 40, type : "dummy"})
Then the length proprety
getEntities..length === 1 ?
And so on
And then check the length proprety
Because getEntities
Give u an array
Of those entities
ill get you a video hold on
you can see that the health bar doesnt update but overlaps instead
the health bar disappears when the mob dies
I don't get it
when the event fires, the dummy entity spawns and teleports to affected mobs, updating the mob's health using nametag
but as you can see, the dummy entity spawns even if there's already an entity
thats korean
U mean Chinese
🗿 thats korean and im korean
const healthbar = system.runInterval(() => {
// spawnEntity(id).teleport(vector3) goes here...
if (entityded...) {
healthbar.remove()
system.clearRun(healthbar)
}```
writing code in discord is painful
so yeah thats how the spawnEntity code runs rn
Agree
Hmmm
Am little busy
Right now
take your time
alright
If u are not need it rn
yes its not really urgent, take your time
Yes
ive thought of a workaround:
instead of making entities to summon upon hit by player, make all the entities in range to have a dummy entity without nametag, and then make a new entityHurt event that sets the nametag as health bar
it can be performace heavy because it spawns entities to all the mobs in range
but i can filter that out with health component
just cache the entity nameTag
if (!entity.nameEntity)
entity.nameEntity = dimension.spawnEntity() //No duplicate
you have to look at the entities to make the nametag appear
which is something i cant do anything with
thats why im using a dummy entity with custom nameable component for this
couldve been more simple if you could make an entity to ride without rideable component
but we cant have nice things 
I would suggest still limiting it to a few entities per player.
for performance?
And visibility.
true
Hey what's the difference between running a command with async and without?
Async return Promise and have a limit per tick
is script BP manifest necessary to make custom components or can you do it without
ok so this turned out to be horribly inconveient
Promise?
How do i check if an entity is invincible and canot take damage from projectiles?
not sure if you can check it
if the entity is made invincible via entity json, you can check for the property, i think?
I mean i need to check for it in script
Yes it returns:
Promise 🤞🏻
Promises Something after you request it.
Nah promises
Are just a cllabacks
Something like them to handle errors too
Like try and catch with asynchronous
I meant in a literal sense
Dawg, english/literal sense. I wasn't commenting on a technological standpoint
Oh
Yeah
Because that it called promise
Because it s like a contract between u and the language, to get something whatever it takes of time
But u will take it finally
Wo , u xab playAnimaton ?
will the player.runCommand check if the player is OP or run pretty much every commands?
It won't check
Use isOp()
That's still sortof broken
for real 💀💀
people who born there has 100% of bad luck 💀
hey sinevector! Can you make more tutorials for script api in your channel? you just stopeed at part 2 of script api, about creating forms
hello!
How can I open a inventory ui from script?
Any way to detect left click? without animations controllers
Help
?
Left click ?
Invincible = has damage sensor/creative mode
Oh
Yeah
U can use testfor command
And turn it into a function
And use it to know whether that entity is creative or not
Wasnt there class too? Also i neef tp check for General invincibility
let container = player.getComponent("minecraft:inventory");
let item = container.getItem(player.selectedSlot);
const lore = new ModalFormData()
.title('§a• §fLore §a•')
.textField('lore', 'Lore (Use (line) to break the line)');
lore.show(player).then(res => {
if (res.canceled) {
return;
}
let loreText = res.formValues[0];
if (!loreText) {
player.sendMessage(`§a•≫ §4Please enter the lore content`);
} else {
let loreArray = loreText.split("(line)").map(line => line.trim());
item.setLore(loreArray);
}
});
}```
What wrong with it?
What is it doing (or not doing)?
Yep
Like punching with an item inhand
Using getBlockFromViewDirection can you also detect air blocks?
No
why would you detect that? it makes no sense
I can't find a good Open Source repository to gain experience. Does anyone have anything I can work on? Github.
See methods under Entities and explore those that seem to move it
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_11_0.Entity.html
It depends on how you want to move it. Rotation would turn in place, playAnimation seems like it would if defined for it, and teleport would move location.
its not working on the player, it says applyImpulse cannot be applied to the player
Anyone got an idea how to check if an entity can take damage from an certain projectile? (Needs to be a way i can check instantly)
try applyKnockback
i wanna move the entity, not knock back it, I'll use it only if it works like the applyImpulse
impulse is the same thing as knockback
can always TP them up that many blocks... same effect, no?
doesn't knockback push vertically
i think you can set that
yeah
Yes, I see it can... https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_11_0.Entity.html#applyKnockback
I'll try it
i found a little problem, its not working on item entity, applyImpulse can move items & entitys, but not players
wait i got an idea
i better make that move entities & items using applyImpulse, and make another one but for the player
I've been mainly focusing on software development which takes a long, long time. Plus those tutorials are outdated so I'm redoing them again.
i mean using both of them,
applyImpulse for items & entities
applyKnockback for the player
hmmm, i actually should make it not moving the player, so it will not be annoying
Help
entityHurt?
I need to check if it can take damage in projectile hit event
That doesn't seem possible as we don't have access to damage sensors
And theres no other way arround? Like somehow make it take damage or define something that will become undefined when the entity cant take damage
anyone have an updated manifest I can use
Wdym updated?
Can you load a structure from the top down with scripts?
yeah structure manager
Right, that's what I'm using, and I'm using the StructureAnimationMode to do layer by layer. But it always loads the structure from the bottom to the top. Is there a way to reverse this? There's no options to do so in the StructureManager.
#1207733595746340876 message
hmm i actually dont know cuz i dont use structure manager as much
@wary edge
How do I detect players in a radius of 10 blocks and add a tag to them?
I just need to know how do I detect the player
player.dimension.getEntities({maxDistance: 10, type: "player"})
player.dimension.getPlayers({ location: player.location, maxDistance: 10, excludeNames: [player.name]})
any idea?
You can't do it by the "intended say".
Either:
A) Use JSON UI to display the inventory if certain elements appear on the client's screen.
B) Try recreate the inventory via ServerForms
You can't force UI to pop on the player's client.
This includes containers, furnaces, and crafting.
Except ServerForms. With its mechanic and appearance.
Well its a unfortunate truth that I'll have to accept. Thanks!
how to fix this ^
as you can see that on right click with axe on plank it spawns stick but it does not load in inventory unless i do right click on stick
anyone have setLore addon?
a query, how do I give myself a book with an enchantment with js?
see doc
did you put the stick code inside the axe use code
Is there an add-on for Smash Bros type attacks?
Maybe on mcpedl
Invalid Argument Error: Unexepted typed passed to function argument [0]. Expected type: number how to fix this error
@hazy nebula What function? In what context? You need to describe much more for us to be able to answer that. The problem is what it says: You failed to pass a number—but we cannot know why
Say I wanted to run a test on a mob, like this https://learn.microsoft.com/en-us/minecraft/creator/reference/content/entityreference/examples/filters/surface_mob?view=minecraft-bedrock-experimental. Would I have to modify the mob's json file or is there a way to run the test from the scriptapi without modifying the mob?
The simpler filters may have a scripting equivalent (e.g. has_tag, in_overworld, is_sneaking), but for those that do not I'm afraid you would need to modify the entity's definition.
yeah I don't think surface_mob has a script equivalent
Although I am curious about what the game calls a "surface mob." If only the description was not so nebulous
i would like to use this on literally every mob lol it would bloat so much
i'm assuming a surface mob is a mob that spawns as a part of the surface cap instead of the cave cap
true for surface cap, false for cave cap
If it is something like "test if the mob exists on the surface of the dimension," a la "around the sea level", that could be emulated by testing for a variety of things like sky exposure, height, biome, and so on
that's another reason i think its a test for whether the mob is part of the surface or cave cap-- because other things it could be can be done other ways
whether it's a part of the surface or cave cap is essentially a property it has-- it doesnt change caps after spawning no matter where it goes
Perhaps that is something you could assign upon the entity's spawning, to be looked up on at any time thereafter
I looked into it
there are so many edge cases it would be very hard to maintain
it looks like either way of going about this would cause a host of issues when the game updates
Has anyone made it yet?
so people dont need to reinvent the wheel
The third way ?
...
(edited)
-# (edited)
ur -# looks like "-#" for me
add space after it
hmm wait, update your discord first
wait wat
how
editing three times? hmm
(edited)
(edited)
(edited)
-# (edited)
lmaooo 🤣
editing five times
There is more but please move to #off-topic or #bot-usage
How do I make a custom cave vines with script?
####### (edited)
Math
@hazy nebula no crossposting
this cross posting rule is kinda bad
sending "can some one help me here Link"
shouldn't count as cross posting. the only think shouldn't be allowed is posting the same question in different channels
Thats literally what they did
But also phising for help is hella annoying and shows youre impatient
lol
nvm then
If youre truly irritated by such rules we have #1051300915161858120 for a reason
i can see how that will be annoying
you guys are active here more than me
so it is up to you
I know, but a post that gets little attention usually won't have any responses and will just get lost.
mb
how can we detect player break block then its position?
the position of the broken block?
import { system, world } from "@minecraft/server";
world.beforeEvents.playerBreakBlock.subscribe((event) => {
const {block,player} = event;
const location = block.location
if (block.typeId == "minecraft:diamond_block") {
system.run(() => {
player.runCommandAsync(`say ${location.x} ${location.y} ${location.z}`);
});
}
});```
I would not recommend using the beforeevent
player break block before event doesnt have block properties?
im kinda sick with the microsoft doc
sometimes it said a feature is stable, but its not
now this....
What feature?
nvm
it does say extend to block
are there any alternatives other than runInterval
why so
isnt it minecraft use tick as the fundemental time scale?
system.runInterval(() => {
// this will run each 1.5 tick
}, 1.5)```
}, <tick>)
put the tick at the last line there
it will run each specefied ticks
is this what you wanted?
hate to break this but they don't support float as a param, they'll just round the number up
How can I add functions in hud elements ??
alr
i was on mobile, so i am having a heart attack editing the code
I just copy pasted that from a file
i'd use afterEvents if i was on pc
whatever lol i just talk too much
If the item in entity state, they can group together, how can I remove just one item?
does anyone know why just recently ive been receiving delay opening mc settings or editing a world/realm?
guys, applyKnockback doesn't really work like applyImpulse
also i think the teleport thing will make the screen cannot be moved and kinda glitched
so is there anything i can use to move the player?
you have to use applyKnockback
applyImpulse can't be used on player
^
ik
I don't think float ticks are supported
.
hi everyone,
i have a question, Is it possible that the result of a TextField of a menu can be written to another file to keep the data ?
no
use dynamic property
dose this not work anymore?
https://wiki.bedrock.dev/blocks/precise-interaction.html
what is the goal of Dynamic Property ?
store numbers text boolean across reloads
and vectors3
this didn't work for me
so i made it the hard way 💀
It looks very interesting thing
@distant tulip
Try to simulate a block like a vault with it
kinda the same
Works ?
working on a building thing
Only?
yeah the buttons work
I thought u said building blocks
yep
i don't mind sharing the code if you want
that block control some stuff
ok for example if i want to keep that js const name = r.formValues[0] const data = (r.formValues[0] + block.location.x + block.location.y + block.location.z) how can i do ?
That will be nice of you
player.setDynamicProperty("name", name)
like that ? js if(r.formValues[0]) player.setDynamicProperty(name, name && block.location.x && block.location.y && block.location.z)
name is a const item
make sure the block collision is 1 px wide or you need to change the values
and pass the event to the function
no
not directly but you can
so how ?
Oh nice
player.setDynamicProperty(key, value)
key need to be a string
and the value one of the ones i said above
using
name && block.location.x && block.location.y && block.location.z
will just store a boolean and i don't think that what you want
convert the corrds to a string
just nice? lol
need more info?
i shared the idea here
https://discord.com/channels/523663022053392405/1180134429734228060
i think that can work js const name = r.formValues[0] const location = `${block.location.x} ${block.location.y} ${block.location.z}` if(r.formValues[0]) player.setDynamicProperty(name, location)
you can store block.location directly
oh yes i'm stupid x)
const name = r.formValues[0]
if(r.formValues[0]) player.setDynamicProperty(name, block.location)```
so that can work ?
yeah
ok ty
but don't use name as key
use something that you know
so you can get the dp later
player.getDynamicProperty(key)
You can also do setDynamicProperty(key, JSON.stringify({name: r.formValues[0], location: block.location})) and then JSON.parse(getDynamicProperty(key)) if you want to store an object of values.
ok ty
I would standardize the key across all players, though- no reason to have it different if you're storing standard data.
am confused am i being a dumbie or smth?
ps: nvm i fixed the problem lol
ok but now i want to list every Dynamic Property of the player into the form UI but that don't work, can you help me ?
Anyone tried Acode with typings ?
no sorry but do you know how help me (message above)
sure send code using https://codeshare.io , i avoid files
have you the access with my link ?
Hey, is client side camera a thing?
@woven loom
the code is wrong, to get the keys you use
let ids = player.getDynamicPropertyIds()
ids.forEach( id => {
form.button( id )
} )
ok but i want only the Dynamic Property with on their name the name of the player
how do you change the entity facing?
So run a filter beforehand
how ?
.filter
then that ?js let ids = player.getDynamicPropertyIds()
https://stirante.com/script/server/1.14.0-beta.1.21.20-preview.22/classes/Dimension.html#spawnEntity
Documentation for @minecraft/server
why stirante?
Theyre the same?
How would you spawn an item with nbt data? (like control pickblock with just scripts)
I saw that its possible with mob spawners but idk if it works for stuff like chests or barrels.
You cant
is teleporting the entity the only way to change where it's facing?
Download the pack and read its code then?
so it converts it to strings?
Gotcha
yes
let value = 54;
console.log('This is multiplication: ' + 54 * 2);
console.log("This is multiplication: " + 54 * 2);
console.log(`This is multiplication: ${54 * 2}`);
All three produce the same results
The third is just easier to read, for most folks
i have a question, is it possible to get the name of buttons of a form UI ?
Not unless you define them beforehand
how can i define their name ?
const array = ['name 1', 'name 2', 'whatever'];
array.forEach(name => form.buttom(name))
for instance
yes but i talk about the result for identified their name
then you index the array using the selection value to get back the name
with r.selection, we get a number 0 until the end of the button
so no it's not their name
You do array[r.selection]
is it will give me their name and not a number ?
yes
ok ty
are you here ?
No
nice x)
Tried. Its obfuscated. -_-
i want to test every dynamic property until find one with the same name of my buttons form UI
but that don't work
how can i do ?
If anyone wants to help me, I would like some help trying to figure out how to spawn an item entity or give a player an item with additional data inside. (a (+DATA) item.)
https://discord.com/channels/523663022053392405/1263319963608023070
Any help is appreciated.
autocomplete?
block.getItemStack(1, true)
The true copies the data of the block
pls
Idk what you’re asking for
jsut one thing before i explain
the array for button give me number but i want the name of the buttons
let names = [r.selection]```
that give me numbers and not names
You need the array name in front of the brackets
i don't understand
Please, learn JavaScript syntax before doing scripts- it makes things easier on yourself and people trying to help
sorry, i will soon
i did it
see js let names = [r.selection]
That is literally the same thing you pasted 20 minutes ago
yes but idk what he wants
Then why did you say you did it
can you tell me what he wants
He wants you to watch a video on JS syntax
i talk about this
i think i did what he said
ik
Then why did you ask what he wants
because his sentence is not correct
see js let names = [r.selection]
what's the difference ?
between is reponse and my code
If you just have a variable in brackets, like you do (With no reference to an array), then it can do a few things.
- If the variable is an array, it will return the first element in the array.
- If the variable is not an array, it will return the value in an array
i know that but you told me to do that before
how can i resolve the problem ?
Note the differences
I would highly recommend stop working on ScriptAPI and learn the basics of JS first. Please. It's frustrating not only for you but others as well
Also note that array indexing is basic javascript/
oh ik that
well... use it then
yes but that no what i want
my english is bad so i understand
I would like the r.selection not to be a number but the original name given to the button
how do you have the output in vsc?
I always test the values in minecraft XD
Thanks! I'll see what I can do.
Isnt that...just JS?
Not trying to ask too much from you since I'm really bad at scripting, but could I get an example of how to use this?
jk
Nevermind, I think I got something working... I think
Hey. Need some help actually
how can i make player falling faster?
Hello! Was the Vector class removed? I'm trying to import it but it doesn't exist?
It was moved to the math module
You can either bundle & import the math module or make your own vector class
minecraft/math
Ohh I see
s' like the vanilla data module but for math funcs
I'm gonna try and create it because why not ¯_(ツ)_/¯
Oh wait, since its from Minecraft, do I also need to add a minecraft/math dependency? Or is it just like those type modules you need to install and import?
install & import- it's not included in the base game like server, server-ui, server-gametest and the rest are
yes it is supported.
Awesome! Thank you so much 
yea
how can i pass information from scripts to json ui
text bindings
THE FLOAT IS MEANT TO BE A NUMBER
i meant it as number
floats are numbers
Floats are numbers.
Integers are numbers.
You can wear horse armor and get its armor protection value lol
That works?!!
I did it! Sorta.
It weirdly only works with certain blocks
anyone know how to make player falling faster?
entity.applyKnockback
Send them down
Apparently, Bedrock's horse armor doesn't have armor toughness like Java has.
Source: Trust me bro
Wanna help me polish an addon?
(this one)
what is toughness? can i add toughness to custom armor?
okay surprisingly Acode editor supports typings, atleast locally 🙂
tutorial please
will do in #1067535712372654091
i can't wait for it bro
text is enough or video is needed ?
nah its simple setup
alr
How to make a piece of code like this: 1 test to see if there is tnt in the player's inventory and amount 2 in the player's hand, does the player hold any amount of tnt?
wait wat
NO WAY
npm typing in mobile??
That sounds like a super win for mobile coders
\o/
ye
I NEED IT
we all need it
uh
can anyone record a video for me?
of a script
like, i want to make a showcase of my script
but i can't record on my pc
can you please? its urrgent
thank you bro\
Where is the Block.redstonePulse(power: Number)
at home
||that a lie we don't even have the "home" version||
lol
q.is_baby?1.4:1 what : mean? what operator is it?
I'm working on a parity addon for dispensers dispensing armor stands. I'm doing it by subscribing to the entitySpawn afterEvent and checking to see if the entity was an armorstand item and if so, check to see if there's a dispenser around it facing the logically correct version to have dispensed it. If this checks out, then I kill the armor stand item and spawn an armor stand. This is for the most part working fine, , except I'm hitting a few edge cases. When I have a dispenser facing down and the resulting armor stand is broken in such a way that the "loot" armorstand item is spawned in the space below the dispenser, then it automatically changes back to the Armorstand entity.
anyone have any thoughts on if there's a better way of doing this or handling this issue?
I haven't been able to find a way to detect what spawned the entity that's triggered the event.
I'm doing this will all stable api's, I don't want to mess with trying to get experimental stuff to work.
can u send short video
anyone know where to find res stuff
what?
Were talking to me regarding the short video?
yep
Maybe match the triggered_bit to 1 as well?
Bah, it doesn't work if the Redstone pulse is too short
I cant get the onTick to run
world.beforeEvents.worldInitialize.subscribe(initEvent => {
initEvent.blockTypeRegistry.registerCustomComponent('wiki:example', {
onTick: (e) => {
console.warn('TICK!');
}
});
});
"minecraft:tick":{
"interval_range": [1, 1],
"looping": true
}
What did I do wrong?
can you do location.dimension.getEntities()?
can you get the dimension from a location?
I see
is the one on the bottom inside a json?
yeah, in the block
you did not register the custom component
already
you also need to add "minecraft:custom_components"
that's what you put in the wiki:example
I compared mine and yours there seems to be no problem
it works now
what.....
💀
it probably was not working cause it's very fast?
i think it has to do with the block is placed before the change is made?
i assume when add the minecraft:tick component, it applies too
Script API is typing
is math bad for minecraft?
What
division and multiplication and stuff
Why would math be bad for the game
Math operations are the last thing that would ever slow down the game
Any modern code engine can handle metric tons of math operations with blistering speed
Unless you are making high-iteration code (in the tens of thousands) or using numerical methods to calculate stuff, you do not ever need to worry about it
import { system, world } from '@minecraft/server';
world.beforeEvents.playerInteractWithBlock.subscribe((ui) =>{
const {player: source, itemStack, block} = ui
if(block.typeId == "minecraft:diamond_block"){
console.warn("works")
}
})
does anyone know why this does not work?
is there error on the logs?
also is the player supposed to have colon? or comma?
{player, source, itemStack, block}
letme check taht
taht*
that*
bru
const source = ui.player
const { player: source } = ui
you need sleep
oh alr
const {player: source, itemStack} = ui
const block = ui.block
the colon is just to rename the variable
im confused on the format
alr thank you
just practice w/o the {} for now
i did wwithout the {} and still does not work
i updated my npms so it cant be that
wrong property key then
playerInteractWithBlock does not work anymore or smth?
w8 it's right properties there
yeah, so am confused
is it probably the block?
put the warn just above the if condition
alr
just spam em console.warns lol
so file isnt active, BP inst working...
stable or beta api
using beta api
Wait for calculus 😛
playerInteractWithBlock should work with beta api
am not getting any errors at all
.
can someone help me with math later
i cant post code rn but ill be here in 10 mins
?
Try doing it with your empty hand and interact the block
Use a brush to interact with the block
thats what i been doing but still nothing
is the file even working?
Logic error perhaps? Or your file isn't imported?
i tried ItemUse and works fine
RAHHHH I LOVE MATH
import { system, world } from '@minecraft/server';
world.beforeEvents.playerInteractWithBlock.subscribe((ui) =>{
const {player: source, itemStack} = ui
const block = ui.block
console.warn("works")
if(block.typeId == "minecraft:diamond_block"){
world.sendMessage("hey")
}
})
I see the mistakes now
I don't even know what the mistake is lol
the const's were wrong i think
i used ItemStopUse to detect weather the player stopped using the item before it completely finishes but for some reason it doesn't run, it's kinda like this
world.afterEvents.itemStopUse.subscribe((data) => {
const useDuration = data.useDuration;
if (useDuration > 0) {
...
}
})```
Does it trigger if you have something outside of the useDuration part?
I would like the r.selection not to be a number but the original name given to the button
Does the item have the chargeable component on it?
so reference from the original array, like I showed you in the screenshot
the item uses use_modifiers
do you understand why?
alright
That's weird, because my item triggers the event
whats ur minecraft version?
/reload ?
last time i checked the function has no errors aswell
1.21.2
did that with no errors
i mean, i did try it in separate worlds multiple times, does reload make a difference? (mb mb, wrong reply)
yes ik but the r.selection get the name of the dynamic property but me i want just the name of the button
Try to rejoin the world then
So index from the array you are displaying in the buttons, or transform the gotten dynamic property name after you get it to make it look like the button name.
const buttonNames = [];
buttonNames.forEach((name)=>{
serverForm.button(name);
})
serverForm.show(player)
.then((response)=>{
console.warn("Name: "+buttonNames[response.selection])
})
ok so i have a code that tracks the change in health via white bar
damaging works fine but i cant figure out how to do healing part
i fixed it
What was the stupid bug was?
So pretty!
use healthChange event
i mean yeah im using that
i should be more specific
oh damn wait i think i figured it out
oldValue newValue difference
Is there a good way to prevent tnt from dropping items
turns out i just forgot to use typeId in the funciton 
explosion after events -> get impacted blocks -> kill entities at block location for each
Oh thanks, thats so much better than what i tried to do
Do I want to know what you tried?
No math? 
explosion before events -> cancel -> get impacted blocks -> set blocks into air
better than killing the entity tbh, it could risk killing some innocent bystander
whar
there is a 0.1% chance of killing an innocent bystander
what happened if the block broken is a container like chest? (filled)
It would be janky to search the correct one
they said they want it to not drop anything
Then get all entities at block location and filter ones if the item component type ID matches the broken block! 
(This is a joke btw)
i was going to filter items by the typeid by getting the blocks broken
which wouldve worked but it wouldve been kinda slow
Also don’t forget to filter out air blocks from getImpactedBlocks()
it can pickup air?
ok got it thanks
My code for before explosion was not the fastest thing ever- still isn’t- but removing all air from impacted blocks make a significant difference
Won't this not work for some blocks?
Stone turns into cobblestone, And some ore becomes the raw materials.
yeah but i can work around that with a few arrays
it would jsut be slow
but i think i can fix it
I wish getItemStack() had a parameter for silk touch or something
tbh, this approach sounds more clean
that don't work
the console log me : Name: undefinied
Cus the buttonNames Array is empty lol, fill it with string lol
Does anyone has JS challenge quest?
Quest:
Subjugate 5 bugs in your code, I shall give you 5 Copper Points.
Well thats not related to JS
i mean direct JS challange
For example this
world.events.playerJoin += function Ya(event){
//code
}
in entity.applyDamage, the option "cause" when I set to "projectile" doesnt work, the log say that projectile doesnt exist, anyone can help me?
entity.applyDamage(damageMob, { cause: `projectile`, damagingEntity: caster }```
Make a parrot dance
what a dastardly thing to do
I am but a little bit devious
Make a Bot that tries to beat the game.
Well, i mean something to related to vanilla JS, not apis or somekind of game
but nvm
can we use script to spawn item?
i have a custom block "wiki:test_block" and i want to spawn the block as item
Make a 3D render
not related to vanilla JS
I mean functions/class/variables/prototype this kind of stuff
i have like 32 block that follow the same format except for the id
You can call getItemStack from permutation so you can use that
and i dont want to make 32 lootable file for each of them
Dimension.spawnItem(item: ItemStack, location: Vector3)
i have only the string?
then get permutation for that string
BlockPermutation.resolve("myblock:yes");
Is it possible to detect entity right click atm with stable api?
or is it not
oh ok x)
ty
but when i want to compare the name of the button and the dynamic property for the result, that don't work and idk why
if(block.typeId === "minecraft:sand") {
const tpmenu = new ActionFormData()
tpmenu.title('Menu de téléportation')
let privatetp = player.getDynamicPropertyIds().filter((name) => name.startsWith(`@${player.name}`))
let publictp = player.getDynamicPropertyIds().filter((name) => !name.startsWith('@'))
privatetp.forEach(tp => {
tpmenu.button(tp.replace(`@${player.name}`, "§l§5>§r§b") + ' §l§5<§r\n§aCliquez pour vous téléporter')
})
publictp.forEach(tp => {
tpmenu.button(`§l§5>§r§e ` + tp + ` §l§5<§r\n§aCliquez pour vous téléporter`)
})
const buttonNames = [privatetp + `,` + publictp];
tpmenu.button('Supprimer un point de téléportation')
tpmenu.show(player).then((r) => {
if(r.canceled) return;
const selection = [r.selection]
let privatetpname = buttonNames.filter((name) => name.startsWith(`@${player.name}`))
privatetpname.forEach(name => { name.replace(`@${player.name}`, "")})
selection.forEach(search => {
if(buttonNames === privatetpname) {
player.sendMessage('test')
}
})
})
}```
💀 I'm not patient enough to teach, gtg sleep (time zone)
Agree
Please open a post
anyone?
player.teleport(-109.64 92.00 -199.43)
how do i use the tp notation
player.teleport({x: -109.64, y: 92.00, z: -199.43})
ty
Has to be passed in as a vector 3- x, y, and z components
oh how comes?
Just what the function needs
can't teleport somewhere if you don't know the y coordinate
oh yh true
Using the Vector3 interface across the codebase is convenient. Positions are already stored as Vec3s—that function signature could easily be teleport(x, y, z), but then any call to it would need to "deconstruct" a vector, rather than just passing it directly
Back in my day we had Location & BlockLocation API classes
Teleporting a player to themselves could be written as the following, but thankfully it is not.
player.teleport(player.location.x, player.location.y, player.location.z)
does anyone have a database for saving items
import { world, system, Player} from '@minecraft/server';
import { ActionFormData, MessageFormData, ModalFormData, ModalFormResponse } from "@minecraft/server-ui";
const rule = new ActionFormData()
.title("Rules")
.body("Test")
world.beforeEvents.playerInteractWithBlock.subscribe((ui) =>{
const player = ui.player
const block = ui.block
console.warn("works")
if(block.typeId == "minecraft:lectern"){
player.sendMessage("the rules")
rule.show(player)
}
})
i dont understand the error for the actionform not opening, could someone help?
import { world, system, Player} from '@minecraft/server';
import { ActionFormData, MessageFormData, ModalFormData, ModalFormResponse } from "@minecraft/server-ui";
const rule = new ActionFormData()
.title("Rules")
.body("Test")
.button(`test button`,"textures/ui/arrow_left")
world.beforeEvents.playerInteractWithBlock.subscribe(async (ui) =>{
const player = ui.player
const block = ui.block
console.warn("works")
await null
if(block.typeId == "minecraft:lectern"){
player.sendMessage("the rules")
rule.show(player)
}
})
Thanks
isnt there also ntityApplyDamageByProjectile?
or is it smth different?
I enjoy that as my code gets more complex, I eventually have no idea what I'm doing and I start making miscellaneous variables and doing 100 different things until something works 😔
at least it works
?
Refactor time!
no that's what I've already done several times
it took me an entire year to finally work on this junk again
I'll throw it to chatGPT and see if it says anything reasonable
“Yeah naw bro just restart”
- chat GPT
this is what i do everytime lol, its the result of working on something for a long time and forgetting about things and being lazy to review it all
but at least it works tho
how does EntityApplyDamageByProjectile work?
Zoomer
damagingProjectile, but my entitiy isnt a projectile
Sure it not makes projectile damage? Or did you already try it? Because the name says apply damage by projectile, so basicaly apply projectile damage
it throws a log error saying projectile doesnt exist
nvm I will use entityAttack
Hey anyone here knows translation keys rules ?
I thought its smth different than ApplyDamage..
Like entity.applyDamageByProjectile
Wdym?
does anyone know what this means?
[Scripting] ReferenceError: Native function [HttpClient::get] does not have required privileges. at <anonymous> (cmd.js:21)```
Use system.run(()=> {})
ohh
thanks
Uw
Use it on things
That need to be written in worlds
Like spawnEntity etc...
beforeEvents are just for reading
And cancelling the events
?
kinda not true
there is some things you can do like setting dynamic property
That does not exist sean
U know what translation keys means?
Fuck you mean?
Old: item.sirlich:hoe.name=Hoe
New: item.sirlich:hoe=Hoe
Essentially you just need to remove the .name
id aint a property on item
they want to get the item display name with scripts
it isn't always in that format
there's no way currently
They !
They just asked for the translation key pattern
oh I see
Who is they ?
YOU
they is neutral
like you
Right....vanilla items still use the old format...why they have two different formats is peak Mojang moment
sorry 😔
Finally
ok nvm i still have issues 
so the health bar is built like this
the length of health bar depends on effectiveMax (or set value), and outside the health bar code, it gets damage done via getting oldvalue + currentvalue(not newvalue) and stores into entity's dp, named 'health diff'
the red part is current value of hp, and the gray part is calculated by removing the amount of hp and 'health diff' dp on health bar length
inside runinterval, theres a code that reduces 'health diff' dp that it creates white part in health bar dynamically
but since only the empty part is calculated, it cant set the red part
which makes the white part to show on gray part (you can notice it if you look closely in the vid)
I cannot see that
Are white & grey separate things? What do each do?
gray is 'empty part of hp bar' and white shows damage done
ill record a vid
iron golem's hp is way too large so its a bit unnoticable
If I understand this right:
- Dark red is missing HP from max
- Light red is current HP
- White is damage done
- Dark red replaces white slowly
edited understanding there
i can post the code if you want, i just have to strip the unrelated code
the hp bar wasnt supposed to disappear but since the white part exceeds the hp bar length it just breaks
Can't you just delay it?
I think i made the best function to retrieve Name based on ID
the hp part?
Is it supposed to disappear when the HP deduction animation is done playing?
What does keeping the HP bar do when the entity representing it already died?
If it length issue, there's Math.min() and Math.max()
^
wait what does it do
Math.min(0, 6) returns 0 as its lower
Chose between numbers which one is smaller or larger
Math.max(0, 6) returns 6 because it’s higher
holy
Using both, you can “clamp” a number between a min & a max- in your case, between zero and the max HP of the entity
i never knew those existed omg


(dont question it please)
well you see
I mean, it's possible recreating it using if else lol
But like, min & max are… pretty basic…
in my defense i probably missed those in JS tutorials
I am scared for what other built in functions you may be missing
I’m sure



