#Script API General
1 messages · Page 128 of 1
just use .setActionBar
or scoreboard
and .repeat('|',20) or something similar
hmmm
it's done using a mix of .setActionBar or scoreboard as minato said and some JSON UI to style it
anyway here's the docs so you don't get confused
if you really want to, this is not the place to ask
https://discord.com/channels/523663022053392405/1067870274894172260
one last can setActionBar display json ui?
no no
.setActionBar sets your action bar
JSON UI which is on the client can read the action bar style it
Is this possible while using json ui and scripting planning on making a jujutsu craft inspired add-on for bedrock
eh
i think it's possible
idk about the model in the middle
it's probably gonna be the biggest hurdle for you
Tbhs yeah that's a real problem I think
anyway use #1067869374410657962 bruh
Well it's relevant
4% of it
50%
legit it's entirely styling some text
justtttttt one last so basically when i trigger .setActionBar(custom1) it will display* the custom1 json ui i made? apologies if im asking it here im focusing on making the script work first eh
it's completely done by JSON UI
you can't even display hud elements using ScriptAPI to begin with
let alone the gradient
let alone the model
Fr?
let alone a custom font bruh

it's all JSON UI brolio
Idk I think i'll find a way
you just pass some data to it using text from ScriptAPI
it's possible, but JSON UI will do all the work basically
I see
uh
i don't think you understand
action bars aren't UIs
you don't show anything with the function call
you legit just pass something like gun#ammo or something like that idk
and JSON UI "reads" that info
and styles it
hmm i see
uhhh so is there a way to make the numbers show on top of the hotbar??
what?
i have a feeling what you're looking for is player.onScreenDisplay.setActionbar('an actionbar')
but i still don't understand, what do you mean by "the numbers"?
the scores?
the indexes?
what exactly
Okay, so basically I'm developing a code system for my addon,and im struggling to develop them with scripts since animation_controlls give me headache to deal with
each item changes a exact number until hit the exact number
And that's where this part of the script shines
bro
😭
i don't imagine myself making a code system with anything but script api
honestly it's crazy you got this kinda far
anyway so what exactly do you want from the codes?
like what should it do?
you can study the script i make and add your logic on it
a 4 digit code system is easy to make
Ok so basically..this. . . but i realized i need to use commands
Yeah it is
but what is the input for it?
i don't understand still
you want to display the code?
yeah!
ok so how did you store the code?
in binary?
in an array?
in a string?
nvm you store it in a bunch of scores..
well still
how do i display a variable on .setActionBar
y u p
i think storing the digit on the player via dynamic properties is better in that case
well,i already got the set up but the numbers don't show above the hotbar
first: i recommend you watch a javascript course, second use player.onScreenDisplay.setActionBar(variable) or however you want to format it
but it must be a string or like in the end have a way to be turned into a string
scores are not good bruh
a dp would be so much better
i won't even make you use bits or binary
it says this
let count = world.getDynamicProperty('am:mo')
the dynamic property can be undefined
also this is not good for multiplayer
use this:
let count = player.getDynamicProperty('am:mo') || 0;
mmm wym?
hmmm i have another dynamic property that sets it tho
that's not what i meant
what i meant is if it's the initial run and the section of the code that sets it didn't run yet, then it's gonna be unset
oh
I've noticed that summoning a mob then playing a animation at the same time it doesn't do the animation
But orrr not
it has a bit of desync
since the animation is played on the client side and not managed by the server
Hmmm
@marble spruce this is probably not the best version but i have tried to keep it as simple and performant as possible
try to learn from it
and test it out/play with it
const functions = {
'0340': 'omnip_decouple',
'4462': 'unlock_feedback',
'3411': 'unlock_upchuck',
'1219': 'failsafe_off',
'3821': 'failsafe_on',
'0023': 'unlock_iguana',
'9394': 'unlock_blob',
'7337': 'unlock_fungal',
'3267': 'unlock_eyeguy',
'1034': 'unlock_buzz',
'0400': 'destruct_timer',
'9036': 'unlock_master',
'7084': 'unlock_playlist_two',
'1460': 'unlock_idem',
'5531': 'unlock_spitter'
};
if (item.typeId === "ocp:set_sequence") {
const code = player.getDynamicProperty('code'); // use player.setDynamicProperty('code', '2730') for example
if (typeof code !== 'string' || code.length < 4) return; // u should send a message or something.
const fn = functions[code];
if (!fn) return; // also u should send a msg or idk
player.runCommand(`function ${fn}`);
player.onScreenDisplay.setActionBar(`§0<§aCode §a${code[0]}§0-§a${code[1]}§0-§a${code[2]}§0-§a${code[3]}§0>`);
}
yeah i noticed,i already fixed that
noice
Ok so,I already have the set sequence, what's missing is a number swap, like a locker,to change the numbers
i still don't know how to do that
i think that it'd be simpler by only doing
let code;
let out;
if (item.typeId === "ocp:set_sequence" &&
typeof (code = player.getDynamicProperty('code')) == "string" &&
code.length < 4
) {
switch (code) {
case '0340': out = 'omnip_decouple'; break;
case '4462': out = 'unlock_feedback'; break;
case '3411': out = 'unlock_upchuck'; break;
case '1219': out = 'failsafe_off'; break;
case '3821': out = 'failsafe_on'; break;
case '0023': out = 'unlock_iguana'; break;
case '9394': out = 'unlock_blob'; break;
case '7337': out = 'unlock_fungal'; break;
case '3267': out = 'unlock_eyeguy'; break;
case '1034': out = 'unlock_buzz'; break;
case '0400': out = 'destruct_timer'; break;
case '9036': out = 'unlock_master'; break;
case '7084': out = 'unlock_playlist_two'; break;
case '1460': out = 'unlock_idem'; break;
case '5531': out = 'unlock_spitter'; break;
default: return;
};
player.runCommand("function" + out);
const actionbar_text = '§0<'+code.split('').map(c => c+'§0').join("§a")+'§0>'
player.onScreenDisplay.setActionBar(`actionbar_text`);
}
Using a switch statement is slower than using an object
🧐 no way
yeah, it really is, how in hell is it even possible
in node its the opposite
it seems that quickjs doesnt know how to optimize it to a jump table
Yeah, quickjs doesn't have a JIT compiler. So a switch statement is the same as a bunch of if statements.
And Mojang chose to use quickjs!? 😭
QuickJS is lightweight and really easy to embed to any application
or maybe wasm, some wasm runtime would be good as well
i mean i still don't understand why "language" is a field that you can add in the manifest.json if javascript is the only language
V8 would be awesome and might happen in the future anyway, but its long far future i guess
bc they support only language now?
it make 100% sence
What's the new ui called? can anyone say?
what!?
i forgot it lwk
if javascript is the only option to pass into language in the manifest why expose/require it at all? just make it internal or some shit
its not required lol
but are there ideas for adding other languages?
default is JS if you don't specify
yea, no one said that there will never be more languages
if we move to V8, then its very likely we get WASM
it'd be damn easier if they simply used wasm from the beggining
real
still though, kinda weird to have it there if you don't plan on using it for so long (just saying 🤷♂️)
i mean if we got OreUI sonner than ScriptAPI then we would run on V8 already
who said that? Do you have some internal information on when the other language comes?
so this data driven ui would be some initial things for the OreUI stuff?
OreUI is the engine, DDUI is JSON files for screens layout
not what i'm saying at all... we've had only javascript ever since it released and it's been a thing in the manifest ever since
that's what i'm getting at
i mean its common thing to do in programming, no one whats to deal with refactoring or changing a lot of code, just make it ready for more options ahead of time lol
I hate to say it, but I don't think there's any chance we ever get another language than JavaScript. It's fast enough for almost every use case and any type of compiled language opens the door to all kinds of security nightmares.
yea but there is no argument to not having language option in manifest, and even so as its optional
thats what i am trying to say
Yo what can I do against players who grief my world with lumine proxy?
ask him nicely
I thought you could also do typescript? I mean.. I know they are both basically the same but there is at least that..
wdym? like a bunch of if statements?
yeah but typescript just compiles to javascript so either way it still goes back to one language
but yeah im not going to bother responding to this otherwise imma just get my head chewed off still talking about this
Yeah, I know.. I figured that was what you meant..
He uses alt accounts
The problem is he joins with op and does immediately /clear @a
anything that compiles down to js can be used
Thats the issue here the Client somehow allows the player to have op and the same dude who grieft Leon joined my multiplayer disabled world!
I told an admin on this server if he knew someone that work at Mojang, to do something about the website, but he didn't answer.
Could someone inform me what BlockBoundingBox is?
Bit confused by the wording on the top of this 😅
https://stirante.com/script/server/2.7.0-beta.1.26.10-preview.22/interfaces/BlockBoundingBox.html
Documentation for @minecraft/server
Its like a collision box.
Thats, quite it. Has a min/max.
Anyone know a script that open an more inventory?
whats a good method to privately connecting 2 vps's together? like they have a private connection where only they can communicate
no public ips should be able to access the bridge
Wireguard is probably your best bet
alright thank you
In which Minecraft version was scriptApi 2.0.0 got released?
1.21.90
Ok thanks
i made it
thanks for the support
this works pretty well actually
why is getEntitiesFromViewDirection returning undefined here
it return an array
hitEntity[]
iirc it is {entity, distance}[]
an array of hit entity?
so rayEntity[0].entity would work?
yes
is there any way to force-load chunks?
world.tickingAreaManager
is this a beta method?
yes
how come entity.isValid() isnt working for me
says isValid isnt a function in the console
like am I doing something wrong here
Should just be stand.isValid
Question if am checking if a player has a tag per entity hit then a check for a dynamic propriety per hit. which one is better?
it doesn't really matter, just do as you want
am asking for performance like which one is better for causing less lag
let me test..
hasTag is a little better
Can we detect critical hits?
#1455390633970630801 message - answered, albeit workaround.
no tags are laggier
how did u test it?
with actual players
saving the players pfid through tags
did ~500 ( maybe more ) and it was complete shit
such insane tps drop
but switched to dps and it fixed itself
show the code
it wasnt mine it was a friends
I don't believe u then, lol
Like, I literally measured their execution time yesterday. Although it probably depends on whether there's something in the DP or not, but I don't think an empty DP will be slower than a filled one
well im pretty sure its quite known that tags are complete shit performance
especially for storing data or having hundreds
all im saying is the more players that joined and the more tags it created made the server laggier and laggier
and when switched over to dynamic properties it was fine
like around 5000 dynamic properties without an issue for EACH player
I'm asking you about the results of your measurements, not that you "know"
and im telling you an actual experience with real players so 
tags should be stored as a Set...
they shouldn't perform worse if there are a lot of tags..
well.. u can test..
well on a bds, creating a tag for each new player seemed to significantly hinder tps but it was all resolved when having a dp for each player so
they may be faster in terms of getting and setting but besides that idk
I tested it, reading a tag is ~10% faster than reading DP, but writing a tag is 2 times slower than writing DP
reading and writing isnt the issue though so
get 500 players to join a bds and add their pfid as a tag and see if it has an effect on tps
I don't have 500 players, bro 😭
I just measured the time... that's all

Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Installation for @minecraft/server-ui
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
wouldnt gametest work?
or bedrock-protocol
too lazy for that
😎
is there any way to create an explosion without particle effects?
I need to use entities
and minecraft:explode component
entity.addTag("stunned");
The engine may need to do the following when you write a tag to a player, which could present itself to be extremely taxing when the player base grows:
-
Check the tag doesn’t already exist
-
Modify the entity’s tag container
-
Mark it for command/query systems
-
Potentially update selector caches
-
Potentially sync for clients
-
Flag it for saving
Tags are deeply integrated with commands and targeting under the hood and that would certainly explain why you noticed the difference in speed when writing a tag to a player.
That makes them powerful but also means more systems care when they change which can have a negative impact on performance.
entity.setDynamicProperty("stunned", true);
This typically:
-
Finds the property definition
-
Writes the value
-
Marks the DP storage dirty for save
Fewer external systems react instantly. So tags can be heavier to mutate. Especially if:
-
You write them often
-
Many entities are involved
-
The tag list is big
-
Selectors are frequently evaluated
Then the bookkeeping cost grows.
😱
I could be wrong since we can't truly see the source code to know, but let's be honest here, that's most likely what is happening under the hood when writing a tag lol.
well.. I just wanted to know what's faster, but thanks for this textwall
You are very welcome. Hope it was educational for you and anyone else that read it.
how do you add onto a players max health by a specific amount of hearts without health boost?
so say 11 hearts instead of the 12 that health boost 1 gives
U can't modify max health without entity.json or health_boost
really? I feel like that's such an important thing you should be able to do
its with things like this that I'm confused why mojang just doesn't let you do
I agree, but we can't do anything :/
is v26.0 of mc on windows still gdk ???
why are the gdk options for core-build-tasks removed?
there's only BedrockUWP PreviewUWP and Custom
No.
why do the changelogs not mention that
Mention what?
Why would they need to mention each update is GDK?
i asked if v26.0 is still GDK
you responding with no implied that this is no longer true, that they have reverted to some other type
Sorry, I misread it is all conbined with your other messages. The cofe build tasks never had an option for gdk as far as I know and people had to use custom.
ah ok thx
maybe i edited the gdk options in myself then in the old version i wouldnt remember lol
Is there a property like world.isPaused?
I want to test if the player has it on bc It does some issues with my code.
(world owner only)
Want to elaborate?
bc it set the tps to 0 and I have a performance mode when the tps is under certain number some modules get disabled
wouldn't that cause scripting to stop ticking as well?
It should but I've seen some people say system.runInteverval still executes if it's being pended.
None of my scripts work if the world is paused.
What?
if the world is paused
I doub't thats something that is exposed to us.
How do you expect the game to conitnue running when the whole purpose of a PAUSE mechanic is to pause the game.
I need to add a checker thanks guys
If you need a counter or timer use Date.now()
Hello, can anyone tell me the newest stable api version for @minecraft/server
how do i make it so the opponent doesnt take knockback when i cancel entityHurtEvent
cancel the hit
That's stable in the new update, right?
beta
Aw shucks
Thats a bug, next update its fixed
ah ok
import { system, world } from "@minecraft/server";
import { transferPlayer } from "@minecraft/server-admin";
const TARGET_IP = "1.1.1.1";
const TARGET_PORT = 19132;
system.runInterval(() => {
for (const player of world.getPlayers()) {
try {
transferPlayer(player, TARGET_IP, TARGET_PORT);
} catch (e) {
console.warn(`Failed to transfer ${player.name}: ${e}`);
}
}
}, 10);
anyone know why ts is broken
it expects 2 arguments not 3
its most likely transferPlayer(player, {ip: 123, port: 67})
ohhh
hostname port
Hang tight. I have your answer.
import { world } from "@minecraft/server";
import { transferPlayer } from "@minecraft/server-admin";
// Get first player from array for just an example
const player = world.getPlayers()[0];
// Expects two arguments
// 1. player object
// 2. TransferPlayerIpPortOptions or TransferPlayerNetherNetOptions
// Here we use TransferPlayerIpPortOptions
transferPlayer(player, {hostname: "example.smp.org", port: 13222});
Sorry for the delay. Dealing with a brain tumor so my memory is short and it took time to process my thoughts lol. Hopefully this helps bring clarity.
thanks but i have this
and it just crashes my game
No, your syntax is incorrect above.
Change this:
transferPlayer(player, TARGET_IP, TARGET_PORT);
To this:
transferPlayer(player, {hostname: TARGET_IP, port: TARGET_PORT});
Your IP might be wrong because you are targeting 1.1.1.1 which is a cloudflare DNS for filtering traffic.
I'm not familiar with using 1.1.1.1 with a designated port.
How tf would you decrease the durability of a tool when you mine something with it
get component -> update -> set back to slot.
Ok im lost on the update part
const durability = item.getComponent(mc.ItemComponentTypes.Durability);
if (durability == undefined) return
durability.damage++```
You can just do that 😭
if um setting alot of dynamic properties should i use
setDynamicProperties instead of several setDynamicProperty
I kinda made useState() in mc just like in react, except it's for dynamic properties
export function useState(player, prop, def) {
return [
player.getDynamicProperty(prop) ?? def,
val => player.setDynamicProperty(prop, val)
];
}
So to use it, must be like:
const [score,setScore] = useState(player, "scores", 0)
oh…
Alternatively, it can be like this
export function useState(prop, def) {
return [
(player) => player.getDynamicProperty(prop) ?? def,
(player, val) => player.setDynamicProperty(prop, val)
];
}
So we can use only one variable for each player
const [score,setScore] = useState("scores", 0)
setScore(player1, 20)
setScore(player2, 30)
How would you prevent a block from dropping anything when a player breaks it
BeforePlayerBreakBlock -> Cancel

One workaround, apply weakness 255, and use entityHitEntity.
u are 9 months late bro
Congratulations, you're already the 593rd person to leave the "100,000th message" 🎉

does using player.nameTag = asd for example work for changing players usernames?
and I'm talking like the visible display on top of their head
yes, that's also visible when doing /say
oh nice I was using scoreboards before then saw this in entity class
that will make things much easier
indeed
is there a way to change the players name for when they send messages in chat too
this .nameTag method worked for just display on top of your head but not when you send messages in chat normally
when PressurePlatePushBeforeEvent
Cool but not something i see many following
If you're using beta you can listen for BeforeChatSent, cancel that and resend message with changed nametag. Without beta not possible
yeah I know about that event but I was looking for some way to do it on stable bc beta api is a hassle
There is no stable method. Why is beta api a hassle?
Probably fear of breaking changes.
I no longer feel fear
Is it possible to prevent item entities from being stacked?
not a chance
Anyone getting TypeError: value is not iterable when looping over items from afterEvents.entityItemDrop?
for example:
world.afterEvents.entityItemDrop.subscribe(data => {
const { entity, items } = data;
...
for (const itemEntity of items) {
const itemComponent = itemEntity.getComponent('item');
if (!itemComponent) continue;
...
}
});```
It's an array not an object.
?
items.forEach
/**
* @beta
* Contains information related to an entity having dropped
* items.
*/
export class EntityItemDropAfterEvent {
private constructor();
/**
* @remarks
* The entity that has dropped the items.
*
*/
readonly entity: Entity;
/**
* @remarks
* The list of items the entity has dropped.
*
*/
readonly items: Entity[];
}```
the types say its a entity array?
Yes...you do a forEach on an array.
whats wrong with for...of
Why do you want to use for..of
thats what I always use? whats wrong with it
Ok. 👍 Good luck.
wait what? you didnt help at all?
why am I getting value is not iterable? here: for (const itemEntity of items) {
@wary edge
I did this:
world.afterEvents.entityItemDrop.subscribe(data => {
const { entity, items } = data;
...
console.warn(`items: ${typeof items} and ${JSON.stringify(items)}`);
for (const itemEntity of items) {
const itemComponent = itemEntity.getComponent('item');
if (!itemComponent) continue;
...
}
});```
and got this:
[TESTING] [2026-02-12 14:03:56:517 WARN] [Scripting] items: object and [{"typeId":"minecraft:item","id":"-837518622717"}]
[TESTING] [2026-02-12 14:03:56:518 ERROR] [Scripting] TypeError: value is not iterable at <anonymous> (index.js:1250990)```
Consider using forEach
Figured out the issue:
The items property on EntityItemDropAfterEvent is typed as Entity[] in the .d.ts, but at runtime Bedrock hands back a native C++ backed object that doesn't implement JavaScript's Symbol.iterator protocol.
However doing for (const itemEntity of Array.from(items)) { fixes it!
So minecraft has a issue here
I will report to navi
world.afterEvents.entityItemDrop.subscribe(data => {
const { entity, items } = data;
console.warn(`items: ${typeof items} and ${JSON.stringify(items)}`);
for (const itemEntity of items) {
const itemComponent = itemEntity.getComponent('item');
if (!itemComponent) continue;
}
});
No errors in [code](#1067535608660107284 message)
jeesh bru
navi made a oopsie
Do runCommand work? Is it safe? I use server 2.0.0 and for server ui 2.0.0
I run with these errors:
[Scripting][error]-TypeError: not a function at processBossDamage (custom/mage_damage_reduc.js:36)
at <anonymous> (custom/mage_damage_reduc.js:30)
[Scripting][error]-Error in entityHurt handler: TypeError: not a function
[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at <anonymous> (custom/snow_score_js.js:34)
[Scripting][error]-Plugin [first trial, mage finalization - 0.0.1] - [main.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined at <anonymous> (custom/snow_score_js.js:34)
]
Ima make a post for the scripts themselves
Is it still runCommand or is it runCommandAsync??
Is it possible to get the item's NBT using a script?
i think they deleted async
last time i used scripts it wasnt there
Yeah, my friend was hallucinating again
nbt isn't typically exposed to use at all let alone via the in game api so no 🙁
setLore support rawMessage but I cant get translate: to work, does anybody has any example?
whats your rawtext message look like?
item.setLore([{translate: `translation.item`}]);```
try ```
{rawtext:[{translate:translation.item}]}
still getting an error
what error?
That is ok
If it does not work probably RP related
Hello again, question, can i have an item event and block event in the same main.js?
If so where should i put the block event?
You can subscribe as much events you want
Do you know where should the new event go?
Please and thanks
its not, I copy pasted from lang and the console error says extected type: String | rawMessage[]
Scripting API Documentation -> use this as a reference and avoid using commands
With the snippet they give you above?
It has to be an array
[{rawtext:[{translate:`translation.item`}]}]
I know
not working
can you try by yourself?
I think its a bug
Im on my way
thank you
hmm
then I will take a look if I did something wrong
of course
well, thank you for confirm that is not a bug
idk where i can reliably report bugs but https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/entityitemdropafterevent?view=minecraft-bedrock-experimental does not include items in the equipment slots (armor and hotbar) whenever trigged by player death, only their inventory
How tf do I get the fox held item with scripts? Tried multiple things, I think I'm forgetting something, does someone know?
maybe getting "equippable" component, incase you haven't tried
with custom commands, using the customparamtype PlayerSelector, does it require the command sender to be operator?
I am just too lazy to keep updating all my manifests every time minecraft updates lol
We got a new manifest option a few months ago to always be the latest beta
I'm fuming, my minecraft updated and important scripts don't work no more
🤔
Can we get the target of an entity?
like which entity a mob is chasing?
Found a cool Library
Hell yeah
entity.target
did some testing, getComponents returned this
idk if I am forgetting something or we cant get foxes held items
I mean like fox.getComponent("equippable").setEquipment("Mainhand", new ItemStack("minecraft:diamond_sword"))
equippable is only available for players
Ohh
well, /replaceitem command is all we have
:/ but replaceitem doesnt get the equipment ?
well, u could use /testfor and hasitem entity selector
I guess only commands can
hmmmm, ill try that
Does Typescript automatically compiles on Minecraft script api
Or it needs some setup
Because I really need interfaces and rules to typing
You need to transpile it yourself.
I figured out I can use comments for typescript interfaces
too bad entityItemDrop doesnt have items from equippable
Soo my workaround was
Function in tick.json
Sets a tag containing what item does the fox have
And I do the rest with script
hi, quick question the wording for a onstep event for a block how would it be? i tried looking at the guide but they only have for before placing events
system.beforeEvents.startup.subscribe((initEvent) => {
initEvent.blockComponentRegistry.registerCustomComponent('magic:step_trap', {
// onStepOn triggers when an entity stands on the block
onStepOn: e => {
// Example: Turn the block into air
e.block.setPermutation(BlockPermutation.resolve(MinecraftBlockTypes.Air));
// Optional: Play a sound
e.dimension.playSound("dig.stone", e.block.location);
},
});
});```
i tried making this and it works, kinda, it tells me that 'Block.permutation' is not defined
i just want a custom block to turn into air when stepped on
i'd just do e.block.setType("air")
replacing e.block.setPermutation?
yes
it worked thanks, tho it still shows the message block.permutation is not defined even tho it works
system.beforeEvents.startup.subscribe((initEvent) => {
initEvent.blockComponentRegistry.registerCustomComponent('magic:step_trap', {
// onStepOn triggers when an entity stands on the block
onStepOff: e => {
// Example: Turn the block into air
e.block.setType("air")(BlockPermutation.resolve(e.block.setType("air")));
},
});
});```
i wonder if there is an easier way to define e.block.seType than using blockpermutation.resolve?
what the
forget it
turns out i didnt needed to use blockpermutation at all
e.setType("air") was enough
the tutorial i followed just was overcomplicating things
initEvent.blockComponentRegistry.registerCustomComponent('magic:step_trap', {
onStepOff: e => {
e.block.setType("air");
},
onStepOn: e => {
e.block.runCommand(`say hi`)
},
});
});```
little doubt, im trying to run both onStepOn/Off events, is this the correct form to link both events together? the console replies that 'onSteoOn' is not a function
Could it be possible to change getRotation into getViewDirection?
?
Like, could I turn the vector 2 of getRotation into the vector 3 getViewDirection
I dont think so
from getRotation alone nope
Why not just use getViewDirection?
It was essentially just a what of question as an analogy for what I actually need
I don't need either
But
Basically, I have location points (that I'm not fully calculating correctly) and since I have the pitch and heading/yaw between them I was wondering if I could using just the x/y rotation, find point B from point A using the offset and rotation
e.block.runCommand(`say hi`);```
if i want a block to run a command when stepped on this would be correct?
so... yeah...
should be
but afaik block itself doesnt have runCommand
oh...
use block.dimension.runCommand
oh it worked, thanks
yup
sorry for being annoying, but what do i do if the console is returning "Item custom component 'magic:cast' is not being used by an item, but the item in question has "magic:cast": {} in the components?
show code
Right away
const ItemUSeComponent = {
onUse(source) {
source.runCommand("say hi");
},
};
system.beforeEvents.startup.subscribe(({ itemComponentRegistry }) => {
itemComponentRegistry.registerCustomComponent("magic:cast", ItemUSeComponent);
});```
"format_version": "1.20.50",
"minecraft:item": {
"description": {
"identifier": "magic:test",
"menu_category": {
"category": "equipment"
}
},
"components": {
"minecraft:max_stack_size": 64,
"minecraft:icon": "test",
"magic:cast": {}
}
}
}```
wait what
tell me how to use it bro 😭💔
"beta" i think
{
"module_name": "@minecraft/server",
"version": "beta"
},
??
It is very much possible
You know the vector length and it rotation, you can easily get vercor3 normalized to 1
How would I go about doing so
Does it work like ^2.5.0 to update automatically
Or I'm dumb to say this
is there an easier way to test player related functions
because I cant be getting 20 people on my world to test an addon bro 💔
like is there a command to spawn a dummy or something
using SimulatedPlayer from server-gametest ig
or just use mobs
or modifying player.json so You can spawn it
so... any ideas?
Your format version needs to be 1.21.80 or higher.
hm, nope still having the same issue
try .60
nope
i mean nope since i just tried and still the same bug
1.21.60
is there a way to make a custom command enum that uses world.getAllPlayers()? it gives me an error when I make it with that
Do we can store cache via js, instead of using ingame features like dynamic props, tags, scoreboard
Map, Set, any js data types
Ahh alright, it's also temporary right
resets every /reload, yeah
something along the lines of you cant run it in restricted execution
oh this is param type?
so like this is how I use it for example?
also does it return an array of players if I do @a?
same with entities
okay this just doesnt work
it returns an object but I dont think its even a playe
player
like its not letting me use anything on it
.runCommand() .typeId .name all just dont work
it's same as getPlayers
so like Player[]
I figured out how it works with JSON.stringify()
it returns an array that has an object with id typeid or something
very weird to make it that though
const conversion = selectedP[0].id
console.warn(JSON.stringify(selectedP))
console.warn(conversion);
let selectedPlayer
for (const player of world.getAllPlayers()) {
if (player.id === conversion) {
selectedPlayer = player;
break;
}
}
id and typeId are like {id,typeId} kinda
it shows in JSON.stringify since it's ordinary property unlike getters/methods and such
spending so much time in freaking index.d.ts to find what im looking for because docs are useless
whatcha need?
It was just stuff on block permutations, lore, and whatnot
Docs are so bad that they don't give me anything
So I am resorting to looking at the index file
welp, can't blame them as i myself also dont document my stuff ;-;
having a handy object crawler can speed up the search in-game
hello guys
what would be the best way to "ban" players from a server
using script api
just kicking them when they join or is there something i could do with say server-admin to cancel their join or somethign
Wdym vector length
Probably magnitude
Try canceling their packets using @minecraft/server-net
can i get example
cant atm.
i hvent specifically focused on the wich packeta were sent during join
x = -sin(yaw) * cos(pitch)
y = -sin(pitch)
z = cos(yaw) * cos(pitch)
function rotationToDirection(rotation) {
const pitch = rotation.x * Math.PI / 180;
const yaw = rotation.y * Math.PI / 180;
const x = -Math.sin(yaw) * Math.cos(pitch);
const y = -Math.sin(pitch);
const z = Math.cos(yaw) * Math.cos(pitch);
return { x, y, z };
}
Thanks, this is sincerely appreciated
Would you mind explaining how it works, or sending resources on how it works
i have no idea how to explain it more than that, it is just converting spherical coords to cartesian coords
Perfectly fine with me
Doesn't make it any less useful either way
Thank you
this explain it more
https://mathinsight.org/spherical_coordinates
ρ is the distance (1 in our case)
θ is x angle, ϕ is the y
as long as you know those three you can get the coords in a 3d space
Illustration of spherical coordinates with interactive graphics.
isnt rotation body relative?
so is viewDirection?
you are getting a direction converted to a direction
nothing changed
I thought they wanted the world relative direction from the entity's head
you will need player head location in that case
but he asked for view direction
must have missed the "view direction" part then
is it possible to turn off sprinting?
ig this works
const {x:vX, z:vZ} = player?.getVelocity();
player?.applyImpulse({x:vX * -0.26, y:0, z:vZ * -0.26});```
isnt "isSprinting" writableß
my shift is broken
lol
?*
read-only typa thing
and this will only run when the player is sprinting,
indeed, that sucks :( it should be like crouching - writable
That will also work properly when they fall or get velocity from different actions?
idk about that "different actions", and falling seems to be just fine,
different actions like fishing hooks, entity knockbacks, pistons
look, im trying to make a stamina addon, and the only action that is messing me up is jumping, i just cant get it to work properly
Thats tricky. Have you tried adding effects when sprinting?
u know how the player exhaustion works, when u jump, that value will be increased, u just unable to do that using scripts
its either too tricky to deal with or just too buggy
yeah. with only pure addons, it will definetly be one of those things, if not both
effects, and velocity seem to be the only way
ill probably use that, and maybe just give the player blindness, that will prevent u from running or sprinting and feel too exhausted
i am using player.json in this addon, is there any possible way to detect when the entity jumps using the entity components?
No idea. Cant really tell you
is "minecraft:behavior.nearest_attackable_target" not enough for entity.target to work?
for me it returns undefined while the entity is chasing me
i don't think entity.target even work
afaik script api can't expose target of an entity
i already made my own jumping system
what i really need to do is making the player unable to sprint
search fromAngle in this channel i have provided a func for it
that's the version im using
Bruh why is getWeather use beta API but setWeather not
@mojang
it's minecraft, bro
what did u think?
Thats so dumb getWeather is more helpfull then setWeather
class Weather {
static #weatherMap = new WeakMap();
constructor(dimension) {
this.#dimension = dimension;
}
#dimension
/** @type {import('@minecraft/server').WeatherType} */
get id() { return world.getDynamicProperty('weather:' + this.dimension.id) || 'Clear'; }
/** @type {import('@minecraft/server').Dimension} */
get dimension() { return this.#dimension; }
isRaining() {
return ['Rain','Thunder'].includes(this.id);
}
/**
* @param {import('@minecraft/server').Dimension} dimension
* @returns {Weather}
*/
static get(dimension) {
return this.#weatherMap.get(dimension) || (this.#weatherMap.set(dimension, new Weather(dimension))).get(dimension);
}
}
world.afterEvents.weatherChange.subscribe(data => {
world.setDynamicProperty('weather:' + world.getDimension(data.dimension).id, data.newWeather);
});
U can use this
Thanks
I did something similar awhile back
guys so for context i wanna make an entity have 2 modes in the same boss phase, precision( normal ) mode and withering( buffed ) mode. so in precision it has 3 abilities, whch it can spam and it can gain "rot stacks" and continue till it has 15, once it has 15 rot stacks, it enters the state of withering mode where its given certain buffs for 30 seconds and the stacks revert to 0. im using the modes as seperate component groups, but i have no idea on how to make a system where it can do the stack thing and mode switching.
i jus need to make a script for the rot stack part
others are taken care of
pls ping me if anyone has a solution
well, it also depends on your code, but in general, u could use WeakMap and some world events to detect when the entity uses the abilities and with WeakMap store the amount of uses and do something when the amount is greater than 15
but I need to see ur code, If u want me to explain it in more detail
I mean the entity.json
why is this returning undefined? I have verified that world_wheel pos is the correct coordinate and there is a block less than 2 blocks below
entity.dimension.getBlockFromRay(world_wheel_pos, {x:0,y:-1,z:0}, {includeLiquidBlocks:false, includePassableBlocks:false, maxDistance:2});
maxDistance actually works really weird, try increasing the maxDistance and test for the actual distance manually
Is the block like, right below it?
Where is th pos? in the corner block? Center block?
I have some questions about using block from ray to get a block right below, but I digress.
I'm trying to get the distance to the surface, not the actual block
so I have to use a raycast for that
What, math.random() blah blah?
no, it's tied to an entity position
🍿 👀
even setting the max distance to 50 doesn't work
Hmmm
Can u show full code?
I'm trying to make this entity rotate to look like it's driving down for reference
const dimensions = [world.getDimension("overworld"), world.getDimension("nether"), world.getDimension("the_end")]
function getWheelOffset(entity, wheel_pos){
let forward = entity.getViewDirection();
let left = {x:-forward.z, y:forward.y, z:forward.x};
// js lack of operator overloading drives me insane
// forward*wheelpos.z + left*wheelpos.x + up*wheelpos.y + entity.location
let world_wheel_pos = {
x:left.x*wheel_pos.x + forward.x*wheel_pos.z + entity.location.x,
y:wheel_pos.y + entity.location.y,
z:left.z*wheel_pos.x + forward.z*wheel_pos.z + entity.location.z
};
//world.sendMessage(JSON.stringify(world_wheel_pos));
let hit = entity.dimension.getBlockFromRay(world_wheel_pos, {x:0,y:-1,z:0}, {includeLiquidBlocks:false, includePassableBlocks:false, maxDistance:2});
return wheel_pos.y - (hit ? hit.faceLocation.y : 4);
}
function run_hoglet_anims(){
dimensions.forEach((dim) => {
dim.getEntities({type:"bao_30k_bigchungus21220:hoglet"}).forEach((hoglet) => {
let offset_fl = getWheelOffset(hoglet, {x:9/16,y:8/16,z:13/16});
let offset_fr = getWheelOffset(hoglet, {x:-9/16,y:8/16,z:13/16});
let offset_bl = getWheelOffset(hoglet, {x:9/16,y:8/16,z:-13/16});
let offset_br = getWheelOffset(hoglet, {x:-9/16,y:8/16,z:-13/16});
let dx = offset_fl + offset_bl - offset_fr - offset_br;
let dz = offset_fl + offset_fr - offset_bl - offset_br;
world.sendMessage(dz.toString());
hoglet.playAnimation("animation.none", {stopExpression:`v.dx = ${dx*5}; v.dz = ${dz*5}; return true;`})
})
})
}
system.runInterval(run_hoglet_anims, 1)
I think theres some examples in #1072983602821861426 or #1046947779118895114
I recommend using DimensionTypes in case we ever getting custom dimensions... or mojang just can add another one
Idk 🤷♂️
only some trash
pretty sure that one doesn't stay tilted if you leave it to sit on a slope
oh
facelocation is relative to the block duh
weird
looks like the molang var is only being set the first time I play the anim
apparently you have to use the command
I seeeee. Willl send in a bit ( i jus woke up )
The trouble I've had is the transition being cached for the given controller it is defined with.
I suppose you could solve this with multiple controllers (like one defined as ""+Math.random()), but that's not a good idea. I bet making 20*N controllers every second would make the client cry after a while
May be better to synchronize this data with properties
yeah, I think I'll have to do that, it's really janky rn
is there even a shortcut to content logs?
like key to press to open the content log :\
ctrl + h
Line 90, Entity.hasTag is a function, comparing it with a string will always return false, u need to call the function and pass the string as an argument. For example:
if (entity.hasTag("stunned")) {
// some code
}
I'll check the rest a bit later
BTW, what app do u use to code? And are u coding on PC or on mobile?
it's in beta 🫠
So, next... line 29, movement component doesn't have setVelocity method and this try/catch is basically useless, it would be better to use it with dimension.spawnEntity, because it can cause some errors..
and line 22 also useless
line 40-42, instead of spawning particles 10 times, just increase the amount of particles in .json
same with 64-66
line 68, the attack isn't limited by radius
line 71, use entity.dimension instead of world.getDimension
and
for what you want u should do something like this:
const map = new WeakMap();
function triggerrandomability(entity) {
// other code...
const number = map.get(entity) || 0;
if (number < 15) map.set(entity, number+1);
else {
map.set(entity, 0);
// code...
}
}
does anyone know how i could add a way to activate this when a player right clicks
Does anybody know a good tutorial, where it is explained how to work with the classes, their properties and how those interact togehter?
I tried finding out myself, with the microsoft learn page and their references, but I cannot even get a consol.warn, after a player interacted with any block...
do u mean js classes themselves or the API classes?
the API classes
well, look, there is a documentation -> https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/minecraft-server?view=minecraft-bedrock-experimental
Basically, you can use anything from there, that is, import everything that is there. But in order for you to use a class, it must have static methods or a constructor, and not all have these. For example, ItemStack or EntityTypes can be used independently... But still, most of it is provided through the world and system objects, where you use their properties or methods to get objects of other classes, such as Entity, Player, Dimension, etc.
for example, sending player a message when it joins the world:
import { world } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe(data => {
if (data.initialSpawn) data.player.sendMessage('Welcome!');
});
I think I'm starting to understand
Here we import world, so we get its afterEvents property of type WorldAfterEvents, which has a playerSpawn property of type PlayerSpawnAfterEventSignal, which has a subscribe method that takes a function as an argument. This function will be called by Minecraft when a player spawns (joins or respawns), and pass data of type PlayerSpawnAfterEvent as an argument to this function, so we get a Player instance that just spawned and the initialSpawn property to find out whether it was a respawn or it just joined
It would be good if you also read about how classes work in JS
So if I wanted to get a message, when a player interactes with a block, I would start with this:
world.afterEvents.playerInteractWithBlock.subscribe(data => {
if ...
}
yep
but there is one point with playerInteractWithBlock, if interaction with this block does not give anything (for example, interacting with a stone), then afterEvents will not be called, but you can use beforeEvents for this
but if u are going to use beforeEvents or use V2 scripts u should know about the privileges system
behind the if statement:
(data.block)
Because the playerInteractWithBlock has this property?
Oh man, okay thank you. Very very much
?
well, yeah, PlayerInteractWithBlockAfterEvent has a block property, that gives u info about the block, the player interacting with
I just saw, that there is an example of this on the website about the privileges. Thank you, I will try to gether more knowledge, now that I know, where I need to head☺️
how would i escape early execution at the beginning of a script?
i've already read that, it doesn't help me in my current use case as i need to define global variables
show code
export var limitlessTechniqueHotbar = [
hotbarItem("jjk:ct_reversal_cast", "§l§pCursed Technique Reversal"),
undefined,
undefined,
hotbarItem("jjk:reversal_red_cast", "§l§cReversal Red§r"),
hotbarItem("jjk:hollow_purple_cast", "§u§k0§r §l§uHollow Purple §r§u§k0§r"),
hotbarItem("jjk:lapse_blue_cast", "§l§bLapse Blue§r"),
undefined,
undefined,
hotbarItem("jjk:infinity_cast", "§l§dInfinity§r"),
];
export function hotbarItem(identifier, name) {
const item = new ItemStack(identifier);
item.lockMode = "slot";
item.nameTag = "§r" + name;
return item;
}
export var limitlessTechniqueHotbar = [];
system.run(() => {
limitlessTechniqueHotbar.push(...[
hotbarItem("jjk:ct_reversal_cast", "§l§pCursed Technique Reversal"),
undefined,
undefined,
hotbarItem("jjk:reversal_red_cast", "§l§cReversal Red§r"),
hotbarItem("jjk:hollow_purple_cast", "§u§k0§r §l§uHollow Purple §r§u§k0§r"),
hotbarItem("jjk:lapse_blue_cast", "§l§bLapse Blue§r"),
undefined,
undefined,
hotbarItem("jjk:infinity_cast", "§l§dInfinity§r")
]);
});
export function hotbarItem(identifier, name) {
const item = new ItemStack(identifier);
item.lockMode = "slot";
item.nameTag = "§r" + name;
return item;
}
tysm
it works now
Dangggg. I usually code on bridge mod maker but also use vs code to fix/modify script related stuff when im running the world
Dangg
Basicallly a lot of stuff needs to be fixed
Which makes sense since am a beginner at tis😭😭
Thanks!
Pc ofc
I did try tht but decided to keep it as it is since i use those particles a lot for mobs/blocks of same biome
I got this code, but if I interact with the block, I get the message 5 times, instead of just one. What could I do to prevent that?
world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
if (data.block.typeId === "test:dirt2") {
data.cancel = true;
const Ort = data.block.location;
return world.sendMessage("Dirt 2 Interaction");
}
});
Is it possible to open chest UI on a player's screen?
Add check for data.isFirstEvent
Like
if (!data.isFirstEvent) return;
// other code
Thanks man, you are the best😁
Share the code and error
import { world, system, Player } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
world.beforeEvents.itemUse.subscribe((ev) => {
const { source, itemStack } = ev;
if (!(source instanceof Player)) return;
switch (itemStack.typeId) {
case "minecraft:nether_star": {
showForm(source);
break;
}
case "minecraft:stick": {
showDataForm(source);
break;
}
}
});
system.runInterval(() => {
for (const player of world.getPlayers()) {
player.onScreenDisplay.setActionBar(
Debug: ${player.name} is online!
);
}
});
function showForm(player) {
system.run(() => {
const menu = new ModalFormData()
.title("Test Form")
.header("This is a header")
.label("This is a label")
.textField("Input", "Type something here...");
menu.show(player).then((response) => {
if (response.canceled) return;
const inputText = response.formValues[0] ?? "No input";
world.setDynamicProperty("input", inputText);
player.sendMessage(`You entered: ${inputText}`);
});
});
}
function showDataForm(player) {
system.run(() => {
const data =
world.getDynamicProperty("input") ?? "No input yet!";
const dataMenu = new ActionFormData()
.title("Data Form")
.body(String(data))
.button("Exit");
dataMenu.show(player).then((res) => {
if (res.canceled) return;
if (res.selection === 0) {
player.sendMessage("Exit!");
}
});
});
}
header and label are included in formValues as null/no input
i'd recommend doing
response.formValues.filter((v) => v != null)
```and```js
const [text, index, num, bool, etc] = response.formValues.filter((v) => v != null)
Hey guys does server-admin work on realms? seems like the last update might have removed server-admin from realms.
sigh thanks
Documentation for @minecraft/server
Documentation for @minecraft/server
Does someone has a code that returns entities armor? If yes could you please share it?
only possible using a lot of runCommand and hasitem afaik
Im trying to make something where a players inventory gets cloned to a chest and when you change the chest inventory it syncs to the player (yes ik this has been done before), the issue is when I try to grab an item in the chest for some items it works just fine but some of them are locked in the slot, if I click it at all it just goes back to the slot and wont let me do anything with it, this is an issue Ive seen in some other addons, why is this happening? is there a fix?
This is my code so far (yes its horribly written dont judge 🙏)
let lastInventory = []
system.runInterval(() => {
let playerInvFormatted = []
const player = world.getPlayers()[0]
const dimension = player.dimension
const chestBlock = dimension.getBlock({x: -38, y: -60, z: -14})
const playerInv = player.getComponent("minecraft:inventory").container
const chestInv = chestBlock.getComponent("minecraft:inventory").container
for (let i = 0; i < playerInv.size; i++) {
const item = playerInv.getItem(i)
if (item && item.typeId) {
playerInvFormatted.push({
slot: i,
id: item.typeId,
quantity: item.amount
})
}
}
// console.warn(JSON.stringify(playerInvFormatted) !== JSON.stringify(lastInventory))
// console.warn(JSON.stringify(lastInventory))
// console.warn(JSON.stringify(playerInvFormatted))
if (JSON.stringify(playerInvFormatted) !== JSON.stringify(lastInventory)) {
for (let i = 0; i < playerInv.size; i++) {
const item = playerInv.getItem(i)
let itemSet
if (item) {
itemSet = item.clone()
}
if (i < 9) {
chestInv.setItem(i, itemSet)
} else if (i < 18) {
chestInv.setItem(i + 18, itemSet)
} else if (i < 27) {
chestInv.setItem(i, itemSet)
} else if (i < 36) {
chestInv.setItem(i - 18, itemSet)
} else {
chestInv.setItem(i, itemSet)
}
}
}
lastInventory = [...playerInvFormatted]
}, 50)
}```
okay thanks will try
what is the difference between using typescript and using javascript
Because TypeScript knows the expected types of variables, parameters, and return values, your editor can catch many mistakes while you’re writing the code, before you ever run it. For example, it can warn you if you pass a string where a number is expected, or if you try to access a property that doesn’t exist.
With plain JavaScript, many of these issues usually show up only when the program runs (unless you use additional tools like linters or heavy testing). TypeScript code is then compiled into normal JavaScript, which is what actually runs.
Typescript can help to speed up your ability to write more efficient code by avoiding common mistakes typically found in a JavaScript setting lacking additional tooling.
In short:
TypeScript is JavaScript with a type system. It helps your editor warn you about a lot of mistakes before you run the code, instead of discovering them later when something breaks.
Highly powerful tooling and definitely recommended
ohhh okay thanks for the answer i really appreciate it 💙🙏🏻🛐
Welcome
uhm also
about this
i'd recommend doing
response.formValues.filter((v) => v !== null)
```and```js
const [text, index, num, bool, etc] = response.formValues.filter((v) => v !== null)
.
i tried but its giving me undefined
function showForm(player) {
system.run(() => {
const menu = new ModalFormData()
.title("Test Form")
.header("This is a header")
.label("This is a label")
.textField("Input", "Type something here...")
.textField("Input2", "Type The number you like");
menu.show(player).then((response) => {
if (response.canceled) return;
const [input1, input2] = response.formValues.filter((v) => v !== null);
const inputText = input1;
const inputNum = input2;
world.setDynamicProperty("text", inputText);
world.setDynamicProperty("num", inputNum);
player.sendMessage(`You entered: ${inputText} + ${inputNum}`);
});
});
}
okay
world.afterEvents.itemUse.subscribe(ev => {
ev.itemStack.setLore(["Test 1", "Test 2", "Test 3"]);
});
Neither custom items nor vanilla items are applying setLore. Anyone know why? Saw another addon doing the same thing and it works fine (API 2.5.0).
😮💨
Bugrock...
setLore works, but u also need to set item back, like this:
world.afterEvents.itemUse.subscribe(ev => {
ev.itemStack.setLore(["Test 1", "Test 2", "Test 3"]);
ev.source.getComponent('equippable').setEquipment('Mainhand', ev.itemStack);
});
I already tried that too, it didn't work at all;-;
it works
show how u tried that
setItem, setEquipment, container, system...
.
literally like that
It wasn't even with vanilla items, I don't think it's the code, the error must be between the monitor and the chair.'-'

I typed it all wrong, it must be my launcher lol
i mean, that sound like you are calling yourself an error
I'll restart to see, but it must be something to do with the preview '-'
errorman
Bugrock
It's not my launcher, it's the game...
Mojang hates me...
does your script even run?
I've already tried debugging, console.log, and addEffect, and it works when I use the item, but setLore doesn't;-;
show codeee
I hate Mojang.
I had to uninstall the game and reinstall it for this to work, WHAT THE HELL.
Changing professions, add-on devs are no good, Mojang is ruining everything.
onPlayerInteract(event) {
let block = event.block // Block impacted by this event.
let p = event.player;
const currentThresh = block.permutation.getState("dsml:threshold") ?? 0;
const currentEvalMode = block.permutation.getState("dsml:evalMode") ?? "lt";
let form = new ModalFormData();
form.title("Threshold Comparator");
form.slider("Threshold", 0, 15, { defaultValue: currentThresh });
form.dropdown("Operator", operators, { defaultValueIndex: operators.indexOf(translateFrom[currentEvalMode]) });
form.submitButton("Configure");
form.show(p).then((data) => {
const thresh = data.formValues[0];
const op = data.formValues[1];
Debug.info(JSON.stringify(data));
block.setPermutation(block.permutation.withState("dsml:evalMode", translateTo[op]));
block.setPermutation(block.permutation.withState("dsml:threshold", thresh));
})
}
i have absolutely no clue why, but data is just undefined when i close the form
and i cannot figure it out
what does the Debug.info show?
undefined or something like {}?
because if it's the second option, then it's okay because I don't think ModalFormResponse or any FormResponse can be stringified normally
Stupid question:
Is "const itemComponentRegistry = data.itemComponentRegistry"
and "const { itemComponentRegistry } = data" the same?
well, yes
does HttpRequest.setTimeout even work?
this just doesnt work as expected
static retryRequest(req, timeoutSecond, maxRetryCount) {
req.setTimeout(timeoutSecond)
return new Promise((resolve, reject) => {
let retryCount = 0
const retry = async () => {
console.error(`Retrying request ${req.uri} ${retryCount}/${maxRetryCount}`)
try {
const response = await http.request(req)
console.error(`Request ${req.uri} succeeded after ${retryCount} retries`)
if (response.status == 200) {
resolve(response)
return;
}
if (retryCount < maxRetryCount) {
retryCount++
retry()
return;
}
resolve(response)
} catch (err) {
console.error(`Request ${req.uri} failed after ${retryCount} retries`)
if (retryCount < maxRetryCount) {
retryCount++
retry()
return;
}
reject(err)
}
}
retry()
})
}```
i have the timeout set to 1s and it just holds it until the server responds.
this is NOT the behavior i want, it should timeout as per the documentation.
/**
* @remarks
* Amount of time, in seconds, before the request times out and
* is abandoned.
*
* This property can be edited in early-execution mode.
*
*/
timeout: number;
NOTE: both setting req.timeout directly and calling req.setTimeout have the same behavior
how would i measure the players CPS with script api
and im not talking about like
using playerhitplayer
or entityhurt or whaterrver
i need the cps
at all times
i am using BDS btw
so i have all modules
Test in your world, tweak as needed. Not as effective without doing what you want to avoid unfortunately.
import { world, system, InputButton } from "@minecraft/server";
// A map of playerId → recent click timestamps
const clickTimes = new Map();
// Subscribe to *after input* events
world.afterEvents.playerButtonInput.subscribe((event) => {
const { player, button, newButtonState } = event;
// Only count jump presses
if (button === InputButton.jump && newButtonState === "pressed") {
const id = player.id;
if (!clickTimes.has(id)) {
clickTimes.set(id, []);
}
clickTimes.get(id).push(Date.now());
}
});
// Every tick - compute CPS
system.runInterval(() => {
const now = Date.now();
// Update each player’s CPS
for (const player of world.getPlayers()) {
const id = player.id;
const list = clickTimes.get(id) || [];
// Remove timestamps older than 1 second
while (list.length && now - list[0] > 1000) {
list.shift();
}
const cps = list.length;
player.onScreenDisplay.setActionBar(`CPS: ${cps}`);
// Save back the trimmed list
clickTimes.set(id, list);
}
}, 1);
You could definitely update that to cache world.getPlayers() and update that cache through the join and leave event to reduce unnecessary API calls. Would make it more efficient.
There's no InputButton.attack, only jump and sneak
.
Guys how do you locate structures with scripts?
Instead of checking chunk by chunk or something
Valid, I saw that when looking and still did it but in either case it can be replaced. It's not as effective without doing what they want to avoid.
world.afterEvents.itemCompleteUse.subscribe((ev) => {
const player = ev.source;
if (!ev.itemStack || ev.itemStack.typeId == "cosmos:health_fruit") {
player.addEffect("instant_health", 1, { amplifier: 2, showParticles: false });
ev.itemStack.getComponent("minecraft:cooldown").startCooldown(player);
}
});
why does it wait until the eating is done to apply the effect but it starts the cooldown on the start of the eating
minecraft itself starts cooldown when u start using item with cooldown component
any way around?
idk
whats the order of world.getAllPlayers based on? is it just random or does it put them in the array based on who joined first or like alphabetical order
just use getEquipment paired wirh getComponent
It's probably in the order players joined but if you're relying on the order definitely being the order that players joined you could create your own array and update it using player spawn/leave events
I would have to test this then ig
is there a way to rework this or like try to track when people use an armor trim on a chestplate because I really dont want to have to make like 20 different custom chestplates 😭
this is like the only documentation I found on armor trims so
Prolly distance to world origin , I think dimension get entities was that
i made it work, turns out the wiki is incomplete, apart of just put wiki:customcomponent, you have to put it inside a "minecraft:suctom_components: []"
"magic:cast"
],```
so you have something like this
this in the wiki is incomplete
having that solved...
"format_version": "1.21.60",
"minecraft:item": {
"description": {
"identifier": "magic:test",
"menu_category": {
"category": "equipment"
}
},
"components": {
"minecraft:custom_components": [
"magic:cast"
],
"minecraft:max_stack_size": 64,
"minecraft:icon": "test",
"minecraft:cooldown": {
"category": "magic:cooldown",
"duration": 1.0,
"type": "use"
}
}
}
}```
i managed to make the cooldown work but it doesn't have the sidebar animation of like when you use an ender pearl or spear
no, the wiki just uses the most modern format version
you're using an old (pre-1.21.90) format version which requires the minecraft:custom_components component
Doesn't work for mobs
Well it would have been good to know that beforehand
They should at least put that on the component page saying
"This is for post 1.21.90 version"
If you're following the wiki for blocks and items, you should be using the latest format version, it's at the top of almost every page
I do usually include when the last versioned change for a feature was though, I might add it as part of some item doc updates I'm working on
anyways changing subject, is there a component to make the cooldown bar animation to be displayed?
There was a fix mentioned recently in a 1.26.10 changelog that might be what you're talking about
https://feedback.minecraft.net/hc/en-us/articles/43005760577293-Minecraft-Beta-Preview-26-10-20#:~:text=Cooldowns on custom items now visualize correctly
oh
you might have to wait until it releases
i was gonna wait anyways
part of the mod is new animals and magic charged variations, so i need the new babies models for that
Does anyone know how to detect equipping armor without checking every tick?
not possible with scripts
you could limit your checks to only run after the inventory item change event or whatever it's called
wouldn't work for dispensing armour though
Ah ok, thanks!
inventoryChanged event
^ didnt see this
oop
it doesn't detect equipment changes
it doesnt however the armor will have to of been in the inventory for it to of been equipment UNLESS it was equipped via dispensers as mentioned by quazchick.
unless you mean it isnt triggered even when right clicking armor?
Yo, I am having this issue where I cannot make my chatSend.subscribe thing to work...
Can someone please help me?
Are you using beta APIs?
show us your manifest
{
"format_version": 2,
"metadata": {
"authors": [
"McCreatorHub"
]
},
"header": {
"name": "Planetoid scripts",
"description": ".",
"min_engine_version": [
1,
20,
60
],
"uuid": "b4b8d22d-e3d5-4cfd-a1c8-069a9dbb2189",
"version": [
1,
0,
0
]
},
"modules": [
{
"type": "data",
"uuid": "33ec695b-b828-48fa-b4b9-edc11813f271",
"version": [
1,
0,
0
]
},
{
"type": "script",
"language": "javascript",
"entry": "scripts/main.js",
"uuid": "bd4384de-fba4-4f60-9391-ebe0bdb84a09",
"version": [
1,
0,
0
]
}
],
"capabilities": [
"script_eval"
],
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "2.5.0"
},
{
"module_name": "@minecraft/server-ui",
"version": "2.5.0"
}
]
}
That's it
🙂↕️
@last latch @wary edge guys?
Ah, right, anyways change it from 2.5.0 to beta
How do I do that?
What are you using to make add-ons?
I have not used bridge so I have no idea.
Then open visual studio, open your manifest.json and change it from 2.5.0 to beta
Yeah.
Now open a post and post your code there.
Done
Is it possible to add a tooltip or hover text to a button in an ActionForm?
that would be #1067869374410657962
Hi everyone I'm looking for help with scripting my behavior and ressource's pack
is setArmorTrim supposed to be used with an ItemStack?
Could you be more specific?
Do you mean loot table items?
no just a normal itemstack
like on an itemUse afterEvent
u can't set armor trim with scripts, u can only do it with loot tables and then generate the loot table in scripts
what 😭
thats so lame
what I'm trying to make is a command that sets the armor youre holding to a specific armor trim
so youre telling me I have to make an entity with a loot table for each trim and use the loot table thing in the script then clear their chestplate and spawn the entity at their position then kill it? 💀
u don't need to make entity and kill it, u only need loot table
and then just generate it
through APIs
but yeah
u need a lot of loot tables
do I just need a loot table for one diamond chestplate then I use setArmorTrim based on what they have
bc I'm probably just gonna make diamond and netherite
yeah
does this work for custom armor too
should work
Hello, just wondering if
Anyone have entityDatabase class (using structures) or script i can use? 😅
you mean store entityDatabase by structure command?
Like similar to this https://discord.com/channels/523663022053392405/1252014916496527380 but for entities
Instead of item or data.
just make it yourself
@sudden nest
i might have one
lemme check
Ohhh, thank you in advance! 👀
i dont have one
I think, just set, delete, and get is enough
make one
Ah sadge😔 , thanks for trying though
unc
could someone check my dataModule out?
cuz im making this to share with my friends or any other people as if they needed
is there any way to force an entity to become aggressive towards a target?
all u can is use entity.json, scripts can't directly do it
Installation for @minecraft/server-admin
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
When i load a v26 world with minecraft/server api 2.4 sometimes sometimes it tells me that that version is unavailable
But just sometimes
it's very annoying help
Someone has the same issue?
I might have found a substitute solution for both of my problems where entity.getEquipment doesn't work, and entity.getViewDirection being bugged
I needed entity.getEquipment to get the item an entity is holding, modify its durability and return it, i can check if the mob doesn't have a certain dynamic property and run a series of commands to determine exactly which type and the durability of the item it is holding, for the durability i check if it's in the lower or upper half of the item durability range and keep halfing until i get the exact durability, and once i do, i can give the mob a dynamic property that will be in sync with the item's durability (when i want to damage the tool, i can just decrement the dynamic property, and re give the mob the same item with the new data value
I needed entity.getViewDirection, so get the block the mob is looking at, instead i can make the mob do a combination of BFS and flood fill to find the first match of the desired block that is within the mob line of sight and make the mob look at it
I havent an issue with getViewDirection being bugged.
Hey!!!
Do someone know how to have multiple .js files working?
Cuz I can only get my main.js file working
you have to import the other files to main.
And how do I do that?
using import
Do I get to import the hole script?
I am new to this, sorry, but how do I express that
like
import from './script.js'; ??
you can do that, or import specific things from the script if its exported
import './file.js'
thankssss
Is there any way to prevent players from moving items in their inventory without locking the items, like using a beforeEvents for the playerInventoryItemChange?
is it possible to import script files from other addons if i specify the right folder?
import { Lang } from '../../Other BP/scripts/main.js';
No
why
it is bugged for entities other than the player #1067535608660107284 message
all u can is to swam items back after they were swapped by player
I camt recreate.
the bug isn't specific to getViewDirection, it seems that entities just don't face the direction they are facing try /particle minecraft:basic_smoke_particle ^^^2 you will see that the mob is looking in a different direction from where the particle is spawning
Never had this issue.
#1067535608660107284 message
I remember having a bug where Entity.isValid() would show false even when it was right in front of me, and it was an app bug... it was a pirated version of mc tho, but I think you might have a bug in the app itself. Try doing this on a different device or reinstalling Minecraft, maybe
It seems all these are issues only you have had. I have never seen anyone else had this issue.
that is interesting, i have the game from the ms store tho?
It was just a guess that the problem might be with the app itself. As I said, try testing it on other devices
nope, also happening on mobile
/execute as @e[type=!player] at @s anchored eyes run particle minecraft:basic_smoke_particle ^^^2
Why is the game resting my settings every time?
the item.data selector does not accept ranges 😭
I don't know why i thought it does
/execute if entity @s[hasitem={item=golden_hoe, location=slot.weapon.mainhand, data= 0..16}]
i am not running 2032 commands to get the durability of a netherite tool
sooo do we still can't cancel the hit event between players?
bineary search
ah, less than and greater than also does't work
Documentation for @minecraft/server
Haven't used it so I can't vouch for its consistency.
How to make fishing system like fish it in builda??
ScriptAPI environment (QuickJS) is only locked to scripts/ folder for security reasons. You cannot import outside of your add-on, and that's why libraries are also soft-capped
made a scuffed system, not in a usable sense you do need to get the mining speed for every block and tool somehow
used block hit and a scuffed work around, swing event might have been better for this lol