#Script API General
1 messages · Page 66 of 1
oh
then
you have to make a for loop
then do y++ on the player.location
until the block isSolid()
No.
getBlockFromRay() exists
system.runInterval(() => {
for (const player of world.getPlayers()) {
const { dimension } = player;
const { min, max } = dimension.heightRange;
const weather = dimension.getWeather();
if (location.y < min || location.y > max || weather === 'Clear') continue;
const blocks = dimension.getBlockFromRay(player.getHeadLocation(), { x: 0, y: 1, z: 0 }, {
maxDistance: max - location.y,
includeLiquidBlocks: true,
includePassableBlocks: false
});
if (!blocks) {
// ...
}
}
});```
@shy leaf
yeah uh im already using this #1318313719377428602 message
getting if the block above is air is not an issue
but the rain depends on biomes
ahh, then good luck.
I just got annoyed with the guy above lmfao, you're literally saying if in the rain bro just keep insisting getWeather() is the solution
sorry
Can I define a custom property inside a script instead of using entity's behavior json file and defining it there like below?
"client_sync": true,
"type": "bool",
"default": false
}```
No.
You can use custom entity for an accurate reading:
query.is_in_water_or_rain
Returns 1.0 if the entity is in water or rain, else it returns 0.0.
sadly it doesnt seem like an option since i need it for 'before the damage happens'
cant have a tick delay in the slightest
and no, i need to check it for victim, not the damaging entity
???
combat test
Im so confused what youre trying to do, stop the damage?
Then Do it before the check around the player attack range?
please no
Because im confused, your message implies it isnt in BE.
the
hold on let me check my messages
The
Based answer ngl.
Combat Test 4 has separated mechanics from the official one
I am aware.
My intent was to say it isnt in JE right now but it is in BE.
though the most problematic part is checking biomes to check if the biome can rain
like, im in savanna, why are you giving me dripstone cave
What are going to use the inRain detection for
for trident impaling
custom one?
no im recreating the entire combat
But...again...impaling already does extra damage to mobs touching water in Bedrock.
Im so confused.
the entire java combat actually
i did finish it a while ago but i forgot trident exists and
yeah
So you're importing Java's trident into Bedrock?
well not everything
im keeping the 'more damage against mobs in water or rain' cuz java trident sucks ASS
Are you planning to adjust its damage or keep it as default like vanilla?
wait uh did you mean impaling damage or
trident damage
Trident damages (Java & Bedrock)
- Melee damage: 9
- Ranged Damage: 8
- Impaling adds 2.5 damage to each level.
So, you're keeping it as vanilla?
system.sendScriptEvent() idk if its preview but its beta
ye
that like
Are u using damage sensor to cancel these damage?
no, i did this
I see, so it's the melee problem.
Why not switch the player attack back to 1 if they hold the trident?
what your goal, i don't see any point in triggering scriptevent from the script, you already is at the script side at that point
im using this
IPC?
why are you sending another script event?
I think you can directly plug the code for swing
system.afterEvents.scriptEventReceive.subscribe(({ sourceEntity: player, id }) => {
if (id != 'script:swing') return;
if (player instanceof Player) {
// ur code
}
})
world.afterEvents.playerJoin.subscribe(() => {
player.runCommandAsync(`scriptevent script:swing`)
})
@distant tulip
i'd have to do this
here, it only executes when the scriptevent command is ran
Why do you need to send scriptevent to trigger a code
Just trigger it directly
Across packs? Sure
But in a single addon, there is no point
how
world.afterEvents.playerJoin.subscribe(() => {
//put the code that you want to trigger here directly
})
using funcs?
i have to use scriptevent
;-;
Ok
so how
its right?
How to fix this?
[Scripting][error]-[Watchdog] Unhandled critical exception of type 'Hang' in behavior pack 'PACK'```
This did not work:
```system.events.beforeWatchdogTerminate.subscribe(eventData => eventData.cancel = true);```
events?!!??
there's afterEvents or beforeEvents
Don't know. I got it from a past post. I'll try the other ones. Thanks.
👀
did u use ai
Not in this case.
you should see the docs
yup
it's just slowing down
and pretty useless additional logic
That's not valid btw, where'd you define player?
then just world.getAllPlayers().forEach(() => {})
import { world } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe(({ initialSpawn, player }) => {
if (!initialSpawn) return
player.runCommandAsync("scriptevent script:swing")
});
tf?
bro tryna be intelligent but failed.
thx
There is a native method
system.sendScriptEvent() ??
is it preview
idk
or beta
evemts 🤣 🫵
One question, why scriptevent?
IPC from player.json
@ minato
not in stable Minecraft yet
I am only familiar with typing after and clicking intellisense after
it got better
mine always auto correct "beforeEvents" to "before events"
It's annoying...
Huh
?
Wrong channel
-# somehow
I am on PC
but on phone I have turned off auto correct
it's really annoying sometimes
system.afterEvents.scriptEventReceive.subscribe(({ sourceEntity: player, id }) => {
if (id != 'script:swing') return;
// my code
})```
cant i do this? (from here: https://discord.com/channels/523663022053392405/1323024128877527211)
will it not work without running the scriptevent on playerSpawn
it executes a scriptevent command as a player if he has just joined the world/server (Realms too)
Its so funny
The API is so inconsistent, I can do the most invasive thing, spawn a structure from the world data...
but I can't get the beforeEvent for a player hurting an entity.
you can do some work-around this
but yeah, pretty inconsistent
just laugh.
tbh most of things are possible using some work-arounds
I only need slash commands and player's XUID and address
I know, that I can use a mod-loader like Endstone or just my own proxy, which also have more advantages, but I would like to do implement all of it directly in my add-on
]```
Oof, I am not in @minecraft/server 2.0.0-beta. What is the equivalent of this in 1.17.0?
can you send full code?
Why?
import { checkEntities } from "./entityChecker.js";
system.beforeEvents.watchdogTerminate.subscribe((event) => {
event.cancel = true;
console.warn(
`[Watchdog] Canceled critical exception of type '${event.terminateReason}`
);
});
system.runInterval(() => {
checkEntities();
});
Code
It works in 1.18.0-beta but not in 1.17.0.
Because its beta
Beta features are not accessible on stable, because its beta
So there is no way to terminate it in an earlier version?
Is beta...
You are in the latest stable version
Well, I know. Thanks I guess.
I seee. Thanks, ima just spam chance in scripts with every hit they do :L
Does anyone know if using setDynamicProperty() on an item automatically replaces the itemStack with one that includes the dynamic property or do I have to replace it manually
You need to set it back.
damn racist alright thanks
sorry i meant the unction is racist bc i wishd it already did that to me;
Have you tried setting it via container slot class? https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.ContainerSlot.html#setdynamicproperty
I think they mean outside in the rain so if there in a house your funtion would still be true
would that work?
without having to replace item?
because im using an item with use modifiers and I don't want the event itemstopuse to run when i set the dynamic property
lmao
with scripts can i get if an armor has a trim on it?
damn
how to get all death conditions?
damageSource.damagingEntity;
I am trying to get all death conditions
which event are you using to handle entity's death?
entitydie
pretty weird
wait, the player has died due to a creeper explosion or the creeper just blew up?
try using entityRemove event
it might be a bit more complicated to handle death, but will work all the way
IF creeper blow up, creeper is gone.
it's not gone it returns in creative inventory
Creeper just wants a hug
Hi
is it possible to give a monster spawner with a mob inside
can someone get me an invinsible armor stand json ive tried but always failed my other project i had to turn off collision but wont work here as i need ppl to see the name of the armor stand
animations 🤷
and btw, not possible to grab the chest's name right?
how does animations prevent ppl destroying my armor stand
damage sensor
custom_hit_test
I tried that with my other so ima need more then that
You’re looking for a display name entity?
i want it so my armor stands cant be broken as there what displays the city owner
Damage sensor component can cancel all damage
i tried that in my last project and it didnt work
even with all of this {
"minecraft:entity": {
"description": {
"identifier": "minecraft:armor_stand",
"is_spawnable": false,
"is_summonable": true,
"is_experimental": false
},
"components": {
"minecraft:type_family": {
"family": [
"armor_stand",
"inanimate",
"mob"
]
},
"minecraft:collision_box": {
"width": 0.0,
"height": 0.0
},
"minecraft:health": {
"min": 600,
"value": 999,
"max": 999
},
"minecraft:knockback_resistance": {
"value": 1.0
},
"minecraft:nameable": {},
"minecraft:persistent": {},
"minecraft:physics": {},
"minecraft:pushable": {
"is_pushable": false,
"is_pushable_by_piston": true
},
"minecraft:conditional_bandwidth_optimization": {},
"minecraft:damage_sensor": {
"triggers": [
{
"cause": "all",
"deals_damage": false
}
]
}
},
"events": {}
}
}``` there was still a small are that if hit you could kill the armorstand
on this project that is less effective as i need collision box
Even if you do hit the hitbox of the entity you should not be able to kill it; the damage sensor makes sure of that
Consider opening a post in #1067869022273667152
is my syntax off i just tested with 2 2 hit box (dont do this if you want the armor stand next to water lol) it still breaks after a few hits
Amor stands may be special.
Custom entity would be ideal
update your format version
cough #1067869022273667152
@valid ice if i did a custum entitity to resemble an armor stand and replaced armor stands with it how would i do that i know 0 about entities and entities chat is dead
🗿 You didn't even post a question.
Open a post and I can help out there
does anyone know how you can get a block to output a redstone signal?
and detect inputs?
Output cant
Input getRedstonePowerLevel or something
Output cant
Input getRedstonePowerLevel or something
duplicated message lol
No not directly but you can load that armour through a structure file
Is it possible to improve this script to have less lag?
import { world, system } from "@minecraft/server"
system.runInterval(() => {
world.getDimension("overworld").runCommand("gamerule commandblocksenabled true")
world.getDimension("overworld").runCommand("gamemode a @a[m=!survival]")
}, 0)```
you can use native methods for those
world.gameRules.commandBlocksEnabled=false; and gamemode change event for the other one
Can you edit this script to your liking? I don't really know anything about scripts, and this was done by a friend who's usually very busy.

I am not going to rewrite the code for you lol
😭
why are you mentioning smokeystack
Bro just copy what he wrote
^
so...
It seems I forgot how to cancel block interaction with playerInteractWithBlock beforeEvent xD
You forgot how or forgot you can?
forgot how xD
I keep getting a read-only error or it doesn't work
I realised I can't put it in system.run, but still doesn't fix the not working part
Oh wait, I have it outside of system.run but still getting read-only error
tf
world.beforeEvents.playerInteractWithBlock.subscribe((ev, { block, player } = ev) => {
if (block.typeId === 'minecraft:chest') {
ev.cancel = true;
system.run(() => {
// ...
});
}
});```
OHHHH
I had this
world.beforeEvents.playerInteractWithBlock.subscribe(e => {
const { block, player, itemStack, isFirstEvent, cancel } = e;
const blockType = itemStack?.typeId;
cancel = true
//....
})
I didn't realise I couldn't do that
You can destructure cancel
ye, I just did xD
that's why I did this
(ev, { block, player } = ev)
although, I'm a bit confused why structuring doesn't work for cancel
because it's not a property of the playerinteractwithBlock itself but only beforeEvents
ah
for simple, don't destruct when you cancel
Can you force close chat window from a chat event
no
how do I make this apply when the player has a tag?
well changing it would require component groups linked to events
its not in here but I was trying to make it so if I have a tag I can't hurt any non-player entity, and if I have a different tag I can't hurt any player.
but im thinking it would be tedius to do.
Do dynamic properties follow the same integer limit of 2.147b
I am trying to use player TP and ticking areas, while also teleporting the player 10k blocks away and saving a structure then deleting those blocks and then TP back. This causes issues and varies in severity depending on network speeds, causing loss or deleted structures. What would be the fastest way to load chunks that aren't in render/simulation distance?
tickingarea or a ticking entity are the only ways
and they both take a few ticks to actually load the chunks
an entity that has the tick world component
I tried making one and failed, so maybe not that
I know it can't all be done instant or fast, but I also need to save and unload those blocks using structures for when that player leaves
because it's a plots system that loads and unloads but is far away from spawn
Do ticking areas cause chunk loading or do they just keep the last player-loaded chunks intact?
that sounds like it counters itself
It sounds like I'd want to make a tickingarea for each player that isn't currently at their plot, but there must be 1 tickingarea for spawn and 1 for each player
why would you need tickingareas for players who aren't at their plot?
If they leave or unload the plot, the ticking area will have the chunks loaded and unload the island and remove the blocks from the world. I am thinking I can just add a ticking area when they leave and not try to worry about it being super fast like 5 ticks or less and more like 5 seconds or less, but I was just trying to find fast efficiency
is there any way to get the current render distance of a player?
Use the ticking components in a dummy entity, it is way better
Way better, how?
Not limited in term of count, and you have much control over it sense it is an entity
But this shows the maximum render distance possible on that device. Not the player's render distance
I immediately agreed when you said it because of the count of the entities not being as restricted, but I wonder about the loading and persistence of the entity when it's far away
or it just keeps itself loaded because it's ticking?
You have control over that too
Over what, the persistence and stuff?
Yeah
Simply, all I need is a way to keep some, preferably all, islands loaded basically at all times so everything that needs to tick does tick and when a player unloads the plot, it doesn't lose data or chunks
and I need it to work when the player's device is slow
as I know from the alt account on the laptop next to me, it can cause some good issues
how do I check if entity is tamed before death
get tameable componentjs const tameable = Entity.getComponent('tameable'); tameable.isTamed
Works like a charm, you're amazing
I want to store that, it is tamed before death
dynamic property
how
Entity.setDynamicProperty('<name>', <value | Boolean | string | Vector3 | number>); Entity.getDynamicProperty('<name>');
use dataDrivenEntityTrigger to detect the tabe
ok
Or use playerinteractwithblock and get the tameable items
I am using command
aw hel naw
for what?
check
If died entity is tamed and revive it tamed
it wasn't checking if died entityis tamed but revied entity was always tamed and it's chosing the last killed entity and saves it's data for revival
leading to making the killed wild pets revive being tamed
got it working now it store data only for tamed entity
I don't know how it will affect multi-player though
How to spawn fake lightning?
maybe more of a #1067869022273667152 question?
you'd have to make a entity someting same as the lightning but not damage the player. i think is this what you meant by a fake lightning?
Light block
How do i set player.netTag on my own? or i can just set other's nameTag
or do i change player.json to make players nametag editable
Player.nameTag = 'Test' is already enough
tho in chat's it doesn't change.
can't i see my own name tag
Wdym const see my own name tag? You can't in the first place tho.
i am simulating a player in the game right
- go third person
- look at my own player
- can i see my name tag?
thats what i mean
Is there any way to cancel vanilla commands? Like for instance, "kill @a" any way to cancel this?
if you're not using BDS, then this solution is not for you
you can detect CommandRequest packet and cancel it, there's no really solution to detect certain commands via Script API
hey does bds support download links? If so, if I call that where will it download the file?
Oh k
is there a way to detect the color of water in a couldron?
Yes.
You can also set the colour.
To a custom item?
Wdym?
Like leather armor
Just use the dyeable component?
Oh that's a thing...okay forget what I asked them
Does anyone know to use scripts to display particles that only the targeted player can see?
player.spawnParticle("particle name", location)
This will make it only show for the player, and it is in beta
Oh neat! Thanks!
Health display
Display player's health below player's name tag using scripts.
Does anybody have any tips with folder/structure layout for scripting? I'm pretty decent with coding, but because I'm self taught I don't have a good way of knowing when to separate things into different files (I usually end up with most things running on main.js with a few folders for my own math related classes like vector maths or trig)
((Sorry if this is a bad place to ask))
Always go for readibility and modularity
I personally dont like to put things on the main script file
I separate events in different files, same with server forms
Oh yeah, I've been doing that more recently too but it's kind of a struggle working solo and trying to figure out what would be readable for others ^^" the modularity thing is something I've been looking to get around to as I've been thinking of setting up my own libraries beyond my maths ones
Thanks ^^
i dont remember how can i block the movements of a player
inputpermission.
little example?
const input = player.inputPermissions
input.setPermissionCategory(2, false)
Documentation for @minecraft/server
thx
2 is movement
and thx
check out the link to see what number is what
alr did
also would be nice if there was a input permission for sprint
hopefully in the future
in how many years?
Either import InputpermissionCategory for easy choice for Camera, Movement etc. or just number.
5202
lol
kind weird it's numbers though, why not a string
The cat destroyed all the string
Im surprised at how msny structures a script can make before it has idmssues
how much
I made 20k before a watchdog error
Whats the game rule to turn off the recipe unlocking
/gamerule recipesUnlock false
If im making a rts game about attacking and conquering players ciries should input the cities underground making you need to mine in order to find other cities
I had ai generate random names for my cities i liked it up until 1 of the cities name was volsungstead
very European name
Hmm if its a realistic name even if foreign ill keep it i thought it was over the top
I was this many years old when i learned BigInt was a thing
Considering i got it to acuratly display the result of 123456789 × 123456789 which is way past integer limit that is cool
I want to set up a command script to see list of tamed pets by owner can anyone help
New habbit to get into add n to every number for dynamics and integar limit becomes a non issue lol
any way to show entities that are only visible for 1 player?
I don't know any way at the moment
I dont think so but if im wrong do let me know
client side rendering (preview)
Who plans to watch minecraft live saturday
meeeeeeeeeeeee
thirst bar update?
What time is it on exactly
11 pm
Its game deletion update
if u wanna talk about it more lets go to #off-topic !
how
@distant tulip how to use that?
player.setPropertyOverrideForEntity
How do I fix this?
[Scripting][error]-Plugin [The Black Silence Trial 1.2 - 0.0.1] - [main.js] ran with error: [ReferenceError: 'world' is not defined at <anonymous> (custom/on_hit_gebura_2.js:12)
]
Import world
can anyone help provide snippet
im trying to list player tamed entities
by making list command but pet is not getting listed 😕
You are using tameable component?
yes
It doesn't work for vanilla entities or any entity that remove the component ehen tamed
than what I supposed to use¿
it revives tamed pets untamed ,and retames i did it through entity die and entity spawn
the list is available after at least all pets are killed once
any other way?
can the same be done using type_family
@distant tulip
wdym
using type_family to get tamed
How...
That doesn't make much sense
Ok i could thing of a way, what if we used the data driven event and prevented the removal of the tameble component for a second untill we stored the player id somewhere @chilly moth
There is a thing in that event called commponentGroupToRemove
does bedrock support delay
In what way
tags?
Health display
Display player's health below player's name tag using scripts.
not sure where to post this or ask about it but does anyone know how i can fix this
have the better on bedrock, a magic way relics and rings true weapons and java combat addons on
worked fine for 40 in game days
then randomly the world froze but i didn't
and this popped up
tried removing and readding the packs
still doesn't do anything i unless i remove all the packs
then the world works
1.21.51
so their isn't any method to store pet dynamically?
how can i make a timer of a hour and when it finish someting happens
Do you have your content log enabled? Is it saying what is causing the exception?
Method 1: declare a variable and assign the value 3600 to it, then use a runInterval to decrement 1 number every second then check if the number is equal to 0.
Method 2: make a variable with the value Date.now() then every once in a bit keep checking if the current date is bigger than that variable + 3600000.
Method 3: same as method 2 but instead use system.currentTick and check if the current tick is bigger than that variable + 72000
Method 2 is your most time-accurate choice. There is no guarantee that the server's tick rate per second will be consistent enough for an hour.
no lemme turn it on and see
How exactly could I use this? Will I make a property for my desired entity and then set its value and then make the geo file's query in molang in RP the property?
Correct!
couldn't get a screenshot cause the whole pc froze but it sayed Novelty api hangtime 132482ms then said shutting down server
Hm. You're sure having any one of those packs applied caused the exception?
not sure cause it was perfectly fine
till i download an older version of the relics addon
cause it had a feature that wasn't in the newer on
one
and when i removed the new version and added the old one
it worked fine for a few hours
then randomly the world just froze
but i was still able to move
like lag in a multiplayer world
then it won't let me play the world
unless i remove all the addons
made a new world same exact addons
works perfectly
Does it seem to occur when you perform any particular action?
can't even get in the world
no but i just removed the novelty api from active behaviour packs and got the same message
Ah, it's also in A Magic Way
what could be the cause
also why does it persist despite not being enabled
novelty api isn't active but i still get that message
I suspect that A Magic Way has merged the contents of the Novelty API into its pack, so they are basically carbon copies
is there a way i clone the world without the magic addons then delete everything and download them from the web so they start working again
they have a common lib java script
Whatever either copy of these APIs are doing is causing Minecraft to think too hard
ah huh
this novelty manager is in both
could that be the problem?
I wouldn't think so, as Minecraft should be keeping these modules separate. It should be redundancy at worst
ok then
was it me removing the behavoiur pack
cause it said it might cause problems
Not sure. It is not easy to ascertain the cause without a stack trace, which Minecraft has so conveniently left out for us
There's a lead, at least, but the API is deeper than I first thought
any temp solution i can try
to just atleast get the world back
like can i somehow clone the world istelf without the addons
You could make a copy of the world, then remove the add-ons from the copy, I suppose
then re add them?
Re-adding them may very well re-introduce the issue
Actually, had a thought. Could you send me the world? I can try debugging it
haha, sure
or is there somethign you trust more
No worries with Mediafire
seem to work "fine"
are all the mods on?
cause i'm supposed to have a katana in the first slot
and a dane axe in the last slot
and in your screenshot they're not there
yeah
I'm so confused
actually, no
you removed the one causing the hang
oh yeah
should i send that one?
this?
nope, that addon is causing it
hhmm
so just removing it will fix everything?
but it's not even active and i still get that message
i didn't get it in the world you sent, only when i added it
let me look into it code
this is the worse addon i ever seen in term of performance
lmao
it is a older version cause the newer version straight up didn't work at all for me
DEAR GOD THE TPS, THE FRAME LOSS
Any way to make my entity break blocks like the player but not instantly? I know its not possible with entity.json
does anyone know how to actually spawn / create a simulated player from the gametest module
import { world, system } from "@minecraft/server";
import * as GameTest from "@minecraft/server-gametest";
GameTest.register("AI", "attack", (test) => {
const player = test.spawnSimulatedPlayer({
x: 1,
y: 2,
z: 1
}, `Player-Name`, "survival").maxTicks(100).structureName("structure").tag(GameTest.Tags.suiteDefault);
});
you do need a structure in your BP
replace structureName with that
ok
Grok is amazing @inland merlin
I fed it my entire codebase bit by bit, and had it refactor everything, it found stuff that was being called 600 times per second and dropped it to 20 per second. Like it found stuff that I had no idea was causing performance issues.
I also fed it my CPUPROFILE capture, so it had more context of what might be causing performance issues
it actually improved the sound system script too, like audio for waves plays the way I originally wanted it to, but I never noticed!
Its pretty insane, it would have been HOURS of debugging and comparing profiler data, but it was done in 10 minutes.
Thank you so much for letting me know about it, normally I dont touch elons stuff but grok really is just good at what it does objectively.
Glad it's helped you! It's saved me hours of work as well!
Its been like integral to my development workflow 😭
Grok 3?
Yeah.
hi guys i have this code
import { world, EquipmentSlot } from "@minecraft/server";
const NightStoneOnUse = {
onUse({ source }) {
const item = source.getComponent("minecraft:equippable").getEquipment(EquipmentSlot.Mainhand)
source.runCommand("time set night")
}
};
world.beforeEvents.worldInitialize.subscribe(({ itemComponentRegistry }) => {
itemComponentRegistry.registerCustomComponent("SurEx:NightStoneActivate", NightStoneOnUse);
});
i am trying to get the name of the item to reuse the code and just get item name and apply the necessary time change.
my question is where can i see more about the "getEquipment" and what data can i get out of it.
item.name doesnt give anything, item.typeId, nothing. and thats only from checking discord history but could f ind nothing in the wiki
minecraft tameable component gets removed on tame so check
has component is_tamed
@distant tulip
it worked for me
that doesn't work for getting the owner
I haven't tested multiplayer so I don't know about that
thank you
about itemStack.amount, my item is set to max Stack 1 but when i want to remove it using ".amount" it says that my item needs to be greater than 0
are there other ways to remove it other than the amount property?
source.getComponent("minecraft:equippable").setEquipment(EquipmentSlot.Mainhand, null)
set the slot to null, that's a way to remove an item
thank you
Is it possible to place a sign with writing inside?
yes you can use the sign component
const block = world.getDimension("overworld").getBlock(location);
const signComponent = block.getComponent("sign");
signComponent?.setText("Hello, world!");
Thanks
uh, which component can detect the player movement? besides that input key component thing
none.
ah,
You'll use velocity
Player.getVelocity()
i see,
but, that will be affected if the player is moving but by another thing like riding a mob or on the minecart, right?
yes.
Everything as long as he's moving the getVelocity() it will return values.
to make sure that not happened, i should detect it only when the player is not riding another mob
Either use beta or wait for it to be stable next version
ah, its not even stable
well, my addon isn't for marketplace anyway so i can use it
This bot was created by SmokeyStack for the purpose of making a FAQ bot for the Bedrock Add-Ons Discord Server.
To manage entries, please make a pull request on GitHub.
input key is not stable too right?
like i can use it to detect the player movement ( north south east west )
i dont have to detect up/down,
getMovementVector is beta in .60
well, detecting the player movement is beta anyway right?
that's literally method to detect movements
I mean WASD movement detection
i mean is there anything stable i can use to detect if the player is moving or not?
stable - getVelocity()
beta - getMovementVector()
i see,
What I mean by stable is a stable version of the script.
1.17.0 or 1.18.0-beta
system.runInterval(() => {
for (const player of world.getPlayers()) {
const { inputInfo } = player;
const movement = inputInfo.getMovementVector();
const normalizedX = Math.abs(movement.x) > 0.2 ? Math.sign(movement.y) : 0;
const normalizedY = Math.abs(movement.y) > 0.2 ? Math.sign(movement.y) : 0;
if (normalizedY > 0) console.error('forward');
else if (normalizedY < 0) console.error('backward');
if (normalizedX > 0) console.error('left');
else if (normalizedX < 0) console.error('right');
}
});```
1.17.0
This one is for 1.18.0-beta
i know, but im not using beta,
what's the run command to go to that develoment pack
Huh?
%LocalAppData%\Packages\Microsoft.MinecraftUWP_8wekyb3d8bbwe\LocalState\games\com.mojang??
uh, is it possible to detect if the player is riding a mob?
const ridingComponent = player.getComponent("riding");
const entityThatThePlayerIsRidingOnTopOf = ridingComponent?.entityRidingOn;
if (entityThatThePlayerIsRidingOnTopOf.typeId == "minecraft:horse") {
//run code
}
i dont have to detect the mob, just checking if the player is riding something or not.
so i just have to get the riding component,
dude json ui broke my scripts skills
you can check if the entityRidingOn exists
if (entityThatThePlayerIsRidingOnTopOf) {
//run code...
}
What script can I use to limit a specific mob to only allow 1 to exist at a single time?
use entitySpawn or runtInterval to detect if the ID spawned is already in the world, if yes remove the spawned entity.
to check entities in the world just do entity.dimension.getEntities({ type: '<id>' })
Umm, I'm everywhere. Wdym?
I see, thanks
why you're so surprised as if you don't see me everyday.
Is this right?
function canSpawnEntity(og:roland_tier1) {
const entities = world.getDimension("overworld").getEntities({ type: og:roland_tier1 });
if (entities.length > 0) {
return false;
}
return true;
}
world.afterEvents.entityCreate.subscribe((event) => {
const entity = event.entity;
if (entity.typeId === "og:roland_tier1") {
if (!canSpawnEntity("og:roland_tier1")) {
entity.remove();
console.warn("Only one tier_1 can exist at a time!");
}
}
});
entityCreate where'd you get that?
A hallucination from deepseek 🔮
world.afterEvents.entitySpawn.subscribe(({ entity }) => {
if (entity.typeId === 'minecraft:armor_stand') {
const armorStands = entity.dimension.getEntities({ type: 'minecraft:armor_stand' });
if (armorStands.length > 1) {
entity.remove();
}
}
});```
BRUHHHHH.
Lmao. It sounded smart, too. Create entity? Waw
What if I'm not using armor stands? Like, what do I place in the const armorStands =
Change the variable name.
it can be anything you want.
Ah, right. I'll place the entity's name
world.afterEvents.entitySpawn.subscribe(({ entity }) => {
if (entity.typeId === 'minecraft:creeper') {
const entities = entity.dimension.getEntities({ type: entity.typeId });
if (entities.length > 1) entity.remove();
}
});```
{
world.afterEvents.entitySpawn.subscribe(({ entity }) => {
if (entity.typeId === 'og:roland_tier1) {
const BlackSilencephaseI = entity.dimension.getEntities({ type: 'og:roland_tier1' });
if (BlackSilencephaseI.length > 1) {
entity.remove();
}
}
});```
Ima remove the numbers on the name
Why make the variable names complicated?
Ikr? Idk, makes it feel complete
Simple as this is already straightforward
Alright boss, thank you boss 💯
Is there a way to know what pixel in a block the player is looking at?
Or smtg close to that
Not what block
faceLocation.
Angle of head? What?
Add hitBlock.location to faceLication
Ok
world.beforeEvents.playerInteractWithBlock.subscribe(({ block, faceLocation }) => {
console.error(JSON.stringify(faceLocation));
console.error(JSON.stringify(block.location));
});```
Ty
Guys, I faced a very difficult task, I need a database with a small and non-critical number of minuses. I thought to use a dynamic property of the world, but faced a problem in the form of speed and volume of data, as well as an optimization problem. Then I thought to use NBT, but I realized that it also has problems, in the form of inconvenience in management, complexity of control and use in the future. Before that I thought to use ScoreBoarb, but immediately refused this torment, almost the same problem as a dynamic property, but it also supports only the method (key, value in a digital type) and in addition it loads the world very much, as well as tags.
Do you have any ideas on how to create a database?
what do you need the database to do?
dynamic properties are generally the best in-game database option
if you're having issues with performance, then you probably just need to optimise how you actually store stuff
um, why do people use scoreboards to make a entity kill counter?
woulldn't this be easier?
let counter = 0;
world.afterEvents.entityDie.subscribe(({ damageSource.damagingEntity: player, deadEntity}) => {
if (player instanceof Player) {
counter++
}
player.onScreenDisplay.setActionBar(`Kill Counter: ${counter}`)
})
that would not be good for multiplayer support.
also the variable's value wont save when you leave the world or reload the script
I want to create a base for developing different mini-games (that is, a basis or foundation for further development), such as SkyWars, BedWars, ... and the basis for this is a database in which information is stored (arena locations, statistics, settings), a system (or, more simply, a core or template with which it will work).
and that's why the option with the dynamic property is not suitable for me, its functionality, as it seemed to me, is not suitable
No Multiplayer support, since you did increase the variable itself, means everyone was affected, you need to use object first then every player.id add a number, second it won't save every time they quit or the world is close.
const kills = {};
kills[player.id] = (kills[player.id] || 0) + 1;```
I think you should already know why they use the scoreboard.
anyone know how to fix this or if this is an issue
is there something wrong with the code
that's main.js. The error is in Amputate.js
there is no Amputate js
not in the Novalty API script folder atleast
there has to be an Amputate.js somewhere, since it's being used, and it never said it's inside the Novalty API
but it said slowdown from novelty api
oh yeah i found it
was in a seperate pack
but they both happened simoultanuesly when i did one specific actions
i got grok to explain it makes sense
and fix works
Have anyone here made a stonecutter recipe before?
Any way to make the host of a world unable to use commands even if cheats are enabled?
Ooh! What was the issue?
well 2 addons where conflicting so i fixed that first cause the amputate constantly checked for a change to the player
and placing or removing a ring from the accesory menue
would trigger it
then to reduce the slow down thing
it basically just reduced runtimes and shi ion really know
but like making it run every 5 ticks instead of every tick
and some other stuff
i just told it to optimise the code
and copy pasted
That does seem like some neat software
don't get a slowdown at all anymore and works fine
yeah low-key unfair
i wonder if i could literally get it to code an addon for me without doing anything myself
besides resources and textures which even that it might be able to do haven't tried
uh, how am I going to detect the itemStack data? ( like detecting the water bottle, its id is just potion thing,
potion component
getComponent thing?
well, i think im good with make players sick with all kinds of potions
Any way to make the host of a world unable to use commands even if cheats are enabled?
in a BDS you can with the @minecraft/server-net module
but this mod is not for bds any other alternative way?
no
How to spawn named entity with spawnEntity?
const spawnedEntity = dimension.spawnEntity("name", location);
spawnedEntity.nameTag = "Bob"
uuh, is it possible to detect when the dynamic property number has been changed?
check the value
a system.runInterval will be enought
but how exactly
detecting if the value have been changed and run something for once

the first value of the dynamic property is it fix?
or it is variable
the value will be updated every like a minute or via other things like interacting or walking, so i have to detect if the value have been changed or not.
the value i am talking about is from 0 to 20
lets say the value is 0 and it has been updated to 5 or 6, the script will detect that update and run something for once.
const value = world.getDynamicProperty("value")
if(value === 5){
//do somthing
} ```
do something for once and no more,
- its inside of an interval
yup,
instead of using tags, how about turning on/off another dynamic property?
set another dynamic
and controle it value
let previousValue = world.getDynamicProperty("name");
system.runInterval(() => {
if (world.getDynamicProperty("name") !== previousValue) {
//run code...
}
previousValue = world.getDynamicProperty("name");
}, 2);
this could work
i thought about it too but he said he want to turn it on and off
or idk
uh,
what does that mean
my whole entire issue is with titles, i don't want to spam the titles and for some reason its kinda bugged for some reason
like when i change the value and send the title with the new dynamic property value, it will show the previous one instead of the new one
it only runs once btw
i tried having it inside of a runTimeout and it has the same exact issue
do have an existing code?
if (hyd === 0) {player?.setDynamicProperty('hyd', 5); player?.onScreenDisplay.setTitle(xHydTB:${hyd})};
it should update the dynamic property value and apply it into the title, which did update the value but didn't apply it to the title
what did you assign to the variabe "hyd", and are you saying that it should show the new value in the title?
let hyd = player?.getDynamicProperty('hyd');
world.setDynamicProperty('hyd', 'value');
let hyd = world.getDynamicProperty('hyd'); // hyd will have the value 'value' assigned to it.
world.setDynamicProperty('hyd', 'newerValue')
console.log(hyd) // should return 'value' and not 'newerValue'
Here is an example, so in your code it should show xHydTB:0 to the player
does that make sense
I tried explaining it
if that is even the issue you're having
well I'll try to fix it somehow
well i think i know how to fix it, instead of using a good method that is causing this issue, I'll use my bad method to make it worke 100% better than ever
so let's just remake somethings...
fixed,
i literally used if else and it fixed everything, literally everything
how can i store a string in a dynamic property
store a string in dynamic property? Or make the values stored by dynamic property into a string?
first one
if its possible
<player|item|world|entity>.setDynamicProperty("key", "string")
blocks when 🥺
Never
Np
what is a generator function and how do I use it in the context of filling large areas
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/system?view=minecraft-bedrock-experimental#runjob>
also has an example of filling a large area 👍
what didn't work ?
case '!unfreeze':
if(!eventData.sender.hasTag("host")) return;
var arg = msg.message.slice(11).toLowerCase();
if (arg.startsWith("@")) {
arg = arg.slice(1);
}
for (let i = 0; i < players.length; i++) {
const player = players[i];
eventData.sender.runCommandAsync(`inputpermission set ${arg} movement enabled`);
}
break;```
I would like that when the command executes the command according to conditions but it tells me that the "case" does not work and that the error is this famous "case"
Can you send the error you’re getting
you're missing the closing } of the for loop. also, please fix your formatting
i don't have error but my player name dont working
the msg isnt not definited
I got no clue bro
okk
We have so many database solutions now, I believe we should make a list and add it to the wiki, so help people find them easily.
or teach people aproches to not rely on these hacky solutions
Why?
probably redundant cus dnyamic properties are already good
Hmm true IG as I have not seen anyone use more than 32kib in one go yet.
i did, but i felt like that was not efficient so i changed my method
i believe Jayly did too, although i am not sure if that was for testing or what
waiting for someone to make a SQL database
a wiki section that guides people how to use external databases would be great
is there a way to attatch a particle to an entity in script?
try slot 0
Health display
Display player's health below player's name tag using scripts.
Description
Replaces chat emoji when a player types name of emojis in chat.
Credits
These scripts were written by GlitchyTurtle32
@distant tulip you can save player id with dynamic property
I tried it,
it saves my gamertag name
your method is not multiplayer friendly
hm I guess so
does anyone knows why sidebar gives number to every line?
How to detect if a block was broken in a specific structure?
not possible
What about using the getting block permutation through structure class and see if the block exists or not according to the structure's origin
that could work, but only with custom structures
Yeah I am using my own custom structure. Also does the structure manager return structure through the getStructure or whatever it was only if it is placed somewhere in the world or if its in the game files?
game files or saved using structure block or command or script api
How to make it run only if it is placed on the world? Doesn't matter if it was loaded with structure manager or features. I will make it generate through whatever works
make a custom ticking block that run some code that let you know it is loaded
How?
custom components
Yeah but how to know if it's loaded what are things in scripting api that could help me make this?
Related to what I wanna make
on tick trigger automatically
Ok maybe I am dumb but how to make it detect when structure loads?
Ok maybe I am just not understanding
Oh wait I think I should make a dummy block in my structures and then use it's position to get the blocks in structure
uh, how am i going to detect when the player is left the world and give him a dynamic property?
playerLeave have only the playerId and playerName, i cannot give the player the dynamic property in that way..
Can you use the PlayerLeave BeforeEvent?
I believe setting dynamic properties is supported within a read-only context. Correct me if I am wrong.
it wont work, I tried it before
[2025-03-23 18:36:09:456 ERROR] [Scripting] Unhandled promise rejection: ReferenceError: Native property setter [ItemStack::nameTag] does not have required privileges.
this has to be one of the stupidest things ever ngl
I remember Coddy said that it wont be an issue anymore in before events in 2.0.0
Maybe run a function outside of the playerLeave like make a function outside of it and then call it? Idk if it works
meh, i was trying to find a way to fix my titles issue without spamming the titles.
Uhh no? Using before events and setting dynamic property works
wait what
Yeah, dynamic property doesn't modify the world it's just scripts so the script doesn't throw the required privilege
always has been, since dynamic property was out it always worked like that.
that doesn't apply to all functions that dose not modify the world
but I'm only talking about dynamic property 🤷...
you linked it behavior to it not modifying the world... 🤷♂️
yeah, the before events and dynamic property works fine with me.
I didn't try it in .70 yet.
that is how dynamic property work from the start, .70 shouldn't be any different
I know...
That's why I said this too 😂
didn't read that tbh
Is there any way to remove the item's durability when I use it, through CustomComponent?
Do you know what is wrong with it? There is no error message about it, but the commands are not executed as they should be.
I don't know why, but every now and then when I use the item, it doesn't remove the durability, but executes the command.
how to make subtitle visible without doing command for title?
/title @s subtitle
function giveItem(player, itemId, name) {
let newItem = new ItemStack(itemId, 1);
newItem.nameTag = `§r` + name;
newItem.lockMode = "inventory";
const playerContainer = player.getComponent('inventory')?.container;
if (!playerContainer) return;
playerContainer.addItem(newItem);
}
it won’t work with just title command?
you need json ui for that
const durability = item.getComponent("durability");
durability.damage = 0;
the higher the damage the lower the durability
@p cannot be used there
since there is no one running the command except for the dimension
which means there is no @p
yw
hello i want to make a hostile entity attack a player that the player receives in the entity and can't go down until something specific happens example a ghost hits the player and the player cannot be heard go down until the ghost dies or reaches a certain height, I wanted to know if someone can help me
uh, how am i going to detect the world difficulty?
nvm its beta..
i downloaded a train addon that use scripts for rotating the wagons inmediately, when you spawn them, so i found this script, how can i make a script with that function?
can ayone send sleep or wait function like sleep(ticks)
Just use the built in system.waitTicks?
commands.forEach(command => {
world.getDimension(`overworld`).runCommand(`execute as ${sender.name} at ${sender.name} run ${command}`);
});
```anyone know why this shit just not working
idk maybe provide more of the code
make sure your min_engine_version is 1.20 or higher
are you using system.run?
no
oh yeah i gforgot that existed
detecting chatmessages is beta right?
yes.
damn, but whatever
its just spawning and removing the cave spider right? but meh i don't really think its worth it,
i mean making u not losing thirst with the peaceful difficulty is not that necessary tbh
yeah, you could make your own entity
but that is the only way in stable currently
well, maybe for something else but for the thirst addon, meh its not worth it
is it possible to check if player has operator permission wo using tags
player.isOp()
beta api
Help
with what
I cant send the code
I hate that
I have some issues that i got on #debug-playground
I dont know how to solve
Here is the file
Anyone know why glass is considered a "passable block" in raycasts?
I do wonder if it considers it as non solid being passable.
Then they should introduce a third filter for solid/non-solid and separate the two
What is solid?
Because by "passable" I assume "walkable by player" (vines, ladders, flowers, glow lichen, etc)
Vsauce, Smokey here.
However, it also includes leaves, scaffolding, slabs, cauldrons(!!), campfires, grindstones, lecterns, end portal frames, glass panes & glass in that category
I wanna check the Java code again because i think my adk script lib references passable.
iirc someone made a post in #1067535382285135923 saying includePassableBlocks doesn't work as intended.
welp
await system.waitTicks(ticks)```
i need help regarding setting preserved title text on all players. these values exist, its just only 1 title shows. i tried to use waitTicks but still showing the last setTitle but i want to show them all
system.runInterval(() => {
function setTitle(title) {
return world.getDimension("overworld").runCommand(`title @a title ${title}`)
}
const active = db.getByIndex("quests", 0);
setTitle(`qt:${active.name}`)
setTitle(`qd:${active.type}`)
setTitle(`qp:${active.progress}`)
})
what is the db class u used there db.getByIndex()
one sec
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const active = db.getByIndex("quests", 0);
setTitle(player, active.name)
setTitle(player, active.type)
setTitle(player, active.progress)
}
})
function setTitle(player, title) {
return player.dimension.runCommandAsync(`title @a title ${title}`)
}```
@leaden elbow
let me try one sec
@leaden elbow
- so, first thing firrst, the function usage is like
setTitle(player, title)but you used like "setTitle(qt:${active.name})" when you already used ${} in the function. - why put function inside runInterval()
- consider using
player.dimensioninstead ofworld.getDimension()
nvm
either way that's unnecessary
Why put in dimension if you still use title @a
Or use the player's dimensions itself
await system.waitTicks(ticks)```
oops
i just woke up so im blind lol
thx
worked thanks
Same it is 4 in the morning
yw
how to save 1 block using structure manager?
why would you
one last thing, can i only run it once instead of using interval? tried playerJoin but it doesnt show titles cus its still loading
Check if the player is moviny
There's no better way to check if the player is actually loaded, like see the blocks etc
okok ill try this one instead thanks
also are javascript Set() supported in script api?
yes. new Set, Map, WeakMap
Ah I just realised I could use Set in a better system for my blocks if I ever want to improve it that horrendously more
coddy can you tell me what is the difference between using a Array and a Set
the first difference is that the array supports duplicate elements while the set doesn't. Second, set is faster than the array.
thanks!
i benchmark it before and doing Set.has() is faster than Array.includes() not noticeable in small cases but yeah
oh yeah another one is there's no indexing in set
like you do the [0] if you get what I meant.
you need to put it in array.
ah
const set = new Set([10, 20, 30]);
const array = [...set];
console.log(array[0]);```
ohh shiit
Array.includes iterates over each element until it finds the correct one.
Set is internally a Map where the key and value are the same, so has just tries to find the value associated with a key in a hashmap, which is much faster
pretty cool
yeah cool
You can also dojs const set = new Set([10, 20, 30]); const [first] = set; console.log(first);
yeah, that's why I mostly use set rn instead of array objects
system.runInterval(() => {
world.getAllPlayers().forEach((player) => {
const chakra = player.getDynamicProperty('chakra')
const chakraLimit = player.getDynamicProperty('chakraLimit')
const dojutsuMode = player.getDynamicProperty('dojutsuMode')
const cost = player.getDynamicProperty('cost')
player.onScreenDisplay.setActionBar(`§e ${chakra}`)
if (dojutsuMode !== 'none') {
player.setDynamicProperty('chakra', chakra - cost)
} else {
if (chakra <= chakraLimit) {
player.setDynamicProperty('chakra', chakra + 1)
}
}
})
},20)
Why doesnt work?
Debug result for [code](#1067535608660107284 message)
Compiler found 3 errors:
[36m<REPL0>.js[0m:[33m9[0m:[33m49[0m - [31merror[0m[30m TS2362: [0mThe left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
[7m9[0m player.setDynamicProperty('chakra', chakra - cost)
[7m [0m [31m ~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m9[0m:[33m58[0m - [31merror[0m[30m TS2363: [0mThe right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
[7m9[0m player.setDynamicProperty('chakra', chakra - cost)
[7m [0m [31m ~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m12[0m:[33m53[0m - [31merror[0m[30m TS2365: [0mOperator '+' cannot be applied to types 'string | number | boolean | Vector3' and 'number'.
[7m12[0m player.setDynamicProperty('chakra', chakra + 1)
[7m [0m [31m ~~~~~~~~~~[0m
There are no errors from ESLint.
Here the error that i got with full code
[36mmain_6.js[0m:[33m100[0m:[33m41[0m - [31merror[0m[30m TS2365: [0mOperator '>=' cannot be applied to types 'string | number | boolean | Vector3' and 'number'.
[7m100[0m if (player.getDynamicProperty('chakra') >= mode.cost) {
[7m [0m [31m ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~[0m
``````ansi
[36mmain_6.js[0m:[33m123[0m:[33m49[0m - [31merror[0m[30m TS2362: [0mThe left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
[7m123[0m player.setDynamicProperty('chakra', chakra - cost)
[7m [0m [31m ~~~~~~[0m
``````ansi
[36mmain_6.js[0m:[33m123[0m:[33m58[0m - [31merror[0m[30m TS2363: [0mThe right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
[7m123[0m player.setDynamicProperty('chakra', chakra - cost)
[7m [0m [31m ~~~~[0m
``````ansi
[36mmain_6.js[0m:[33m126[0m:[33m53[0m - [31merror[0m[30m TS2365: [0mOperator '+' cannot be applied to types 'string | number | boolean | Vector3' and 'number'.
[7m126[0m player.setDynamicProperty('chakra', chakra + 1)
[7m [0m [31m ~~~~~~~~~~[0m
```
you just repeated what i did... would be great to get the error from content log
Ok
Dynamic properties are good, but I wish they had functions similar to Map's. You kind of need to make a wrapper to make them actually usable (Especially if you value performance).
Also not sure how I feel about string chunking. I feel like you're doing something wrong if you're storing that much data.
Something to also consider is that the dynamic property API can change in the future. Having a wrapper is good so you only need to update your code in one place instead of a million different places.
And a set can only hold 1 character per iteration
like Set("a", "b", "c"), etc
What is there to change though? I feel like it's at it's peak
There's just little things that are annoying. Like deleting a property shouldn't require setting it to undefined.
Checking if a property exists isn't straightforward too. Especially if the value can be falsy.
get !== undefined is hard?
I never said it was hard. It just doesn't look good when you're reading the code. An explicitly named function that returns a boolean is better.
hmm, well that's what a wrapper is good for
That's exactly my point. 😅
otherwise if you're checking if a value exists, then grabbing it, you're wasting an extra native call instead of just checking if the fetched value is undefined
How to make my entity have a chance to replace the block beneath it with another block when its walking?
I said it tho.
how to detect a block can store like chest, shulker box?
getComponent()
what component?
Inventory component
const inventory = Block.getComponent('inventory')?container;
if (inventory) {
// ...
}```
?.
I'm lazy to fix. 😝
😅
ok
what about sign?
sign.
sign block
How to make my entity have a chance to replace the block beneath it with another block when its walking?
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.BlockSignComponent-1.html
const block = Dimension.getBlock(Entity.location);
block.below().setType()```
Oh, my bad 😅
No detection of movement. That's the one I mainly neef
need
getVelocity()?
This is for entities not players right? If yes then that's the only thing you could do.
Guys, is it possible to use scripts to make an item fly in the air and be impossible to pick up?
Entity.applyImpulse({ x: 0, y: 100, z: 0 })