#Script API General

1 messages · Page 128 of 1

cursive fog
#

im planning to add a custom ammo tally for the player

supple perch
distant tulip
#

or scoreboard

supple perch
cursive fog
#

basically the ammo tally on the side

cursive fog
supple perch
# cursive fog

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

distant tulip
cursive fog
supple perch
#

.setActionBar sets your action bar

#

JSON UI which is on the client can read the action bar style it

alpine ibex
#

Is this possible while using json ui and scripting planning on making a jujutsu craft inspired add-on for bedrock

supple perch
#

i think it's possible

#

idk about the model in the middle

#

it's probably gonna be the biggest hurdle for you

alpine ibex
#

Tbhs yeah that's a real problem I think

supple perch
#

anyway use #1067869374410657962 bruh

alpine ibex
#

Well it's relevant

supple perch
alpine ibex
supple perch
#

legit it's entirely styling some text

cursive fog
supple perch
supple perch
#

let alone the gradient

#

let alone the model

alpine ibex
#

Fr?

supple perch
#

let alone a custom font bruh

alpine ibex
supple perch
#

it's all JSON UI brolio

alpine ibex
#

Idk I think i'll find a way

supple perch
supple perch
supple perch
#

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

cursive fog
#

hmm i see

marble spruce
#

uhhh so is there a way to make the numbers show on top of the hotbar??

supple perch
#

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

marble spruce
# supple perch what?

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

marble spruce
marble spruce
#

Ah crap i realized this is script and not commands

#

Mb

marble spruce
#

😭

supple perch
#

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

marble spruce
marble spruce
supple perch
supple perch
#

you want to display the code?

marble spruce
#

yeah!

supple perch
#

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

marble spruce
#

oop aight

#

basically each item changes a certain digit

supple perch
#

ok

#

that's it?

cursive fog
#

how do i display a variable on .setActionBar

marble spruce
supple perch
marble spruce
#

well,i already got the set up but the numbers don't show above the hotbar

supple perch
#

but it must be a string or like in the end have a way to be turned into a string

supple perch
#

a dp would be so much better

#

i won't even make you use bits or binary

supple perch
#

show me the variable

cursive fog
supple perch
#

also this is not good for multiplayer

#

use this:

let count = player.getDynamicProperty('am:mo') || 0;
cursive fog
supple perch
#

if it's not set

#

etc.

cursive fog
supple perch
#

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

alpine ibex
#

I've noticed that summoning a mob then playing a animation at the same time it doesn't do the animation

#

But orrr not

supple perch
#

since the animation is played on the client side and not managed by the server

alpine ibex
#

Hmmm

supple perch
#

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>`);
    }
marble spruce
marble spruce
#

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

dusky flicker
# supple perch ```js const functions = { '0340': 'omnip_decouple', '4462': 'unlock_feedback...

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`);
}
fiery solar
dusky flicker
#

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

dusky flicker
#

the switch is faster

fiery solar
cyan basin
#

And Mojang chose to use quickjs!? 😭

honest spear
honest spear
#

don't say so

#

lol

dusky flicker
#

or maybe wasm, some wasm runtime would be good as well

cyan basin
#

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

honest spear
#

V8 would be awesome and might happen in the future anyway, but its long far future i guess

honest spear
#

it make 100% sence

finite ice
#

What's the new ui called? can anyone say?

cyan basin
#

what!?

finite ice
#

i forgot it lwk

dusky flicker
#

ddui

#

data driven ui if im not mistaken

cyan basin
#

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

dusky flicker
honest spear
#

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

dusky flicker
#

it'd be damn easier if they simply used wasm from the beggining

honest spear
#

real

cyan basin
#

still though, kinda weird to have it there if you don't plan on using it for so long (just saying 🤷‍♂️)

honest spear
#

i mean if we got OreUI sonner than ScriptAPI then we would run on V8 already

honest spear
dusky flicker
honest spear
cyan basin
#

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

honest spear
# cyan basin 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

fiery solar
#

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.

honest spear
#

thats what i am trying to say

whole pulsar
#

Yo what can I do against players who grief my world with lumine proxy?

honest spear
#

not much

#

just report him i guess?

distant tulip
#

ask him nicely

devout sandal
devout sandal
cyan basin
#

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

devout sandal
whole pulsar
whole pulsar
honest spear
#

how does he joins with OP?

#

How is that possible?

dusky flicker
weary umbra
#

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.

lyric kestrel
#

Could someone inform me what BlockBoundingBox is?

wary edge
#

Thats, quite it. Has a min/max.

lyric kestrel
#

Oh. Interesting

#

Thank you

blissful hazel
#

Anyone know a script that open an more inventory?

fallow minnow
#

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

fiery solar
fallow minnow
weary umbra
#

In which Minecraft version was scriptApi 2.0.0 got released?

weary umbra
#

Ok thanks

marble spruce
zinc breach
zinc breach
distant tulip
#

hitEntity[]
iirc it is {entity, distance}[]

zinc breach
#

so rayEntity[0].entity would work?

distant tulip
#

yes

lucid dust
#

is there any way to force-load chunks?

past blaze
lucid dust
past blaze
#

Yeah

#

I think?

distant tulip
#

yes

zinc breach
#

how come entity.isValid() isnt working for me

#

says isValid isnt a function in the console

#

like am I doing something wrong here

wary edge
zinc breach
#

thanks

glacial widget
#

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?

warm mason
glacial widget
warm mason
wary edge
#

Can we detect critical hits?

#

#1455390633970630801 message - answered, albeit workaround.

fallow minnow
warm mason
fallow minnow
#

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

warm mason
fallow minnow
#

it wasnt mine it was a friends

warm mason
#

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

fallow minnow
#

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

warm mason
fallow minnow
#

and im telling you an actual experience with real players so shrug

warm mason
#

tags should be stored as a Set...

#

they shouldn't perform worse if there are a lot of tags..

#

well.. u can test..

fallow minnow
#

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 shrug they may be faster in terms of getting and setting but besides that idk

warm mason
#

I tested it, reading a tag is ~10% faster than reading DP, but writing a tag is 2 times slower than writing DP

fallow minnow
#

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

warm mason
#

I just measured the time... that's all

fallow minnow
gaunt salmonBOT
last latch
#

or bedrock-protocol

warm mason
last latch
#

😎

lucid dust
#

is there any way to create an explosion without particle effects?

warm mason
#

and minecraft:explode component

remote oyster
# warm mason I tested it, reading a tag is ~10% faster than reading DP, but writing a tag is ...
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:

  1. Check the tag doesn’t already exist

  2. Modify the entity’s tag container

  3. Mark it for command/query systems

  4. Potentially update selector caches

  5. Potentially sync for clients

  6. 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:

  1. Finds the property definition

  2. Writes the value

  3. Marks the DP storage dirty for save

Fewer external systems react instantly. So tags can be heavier to mutate. Especially if:

  1. You write them often

  2. Many entities are involved

  3. The tag list is big

  4. Selectors are frequently evaluated

Then the bookkeeping cost grows.

remote oyster
# warm mason 😱

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.

warm mason
remote oyster
#

You are very welcome. Hope it was educational for you and anyone else that read it.

zinc breach
#

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

warm mason
zinc breach
#

its with things like this that I'm confused why mojang just doesn't let you do

warm mason
jolly citrus
#

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

wary edge
jolly citrus
#

why do the changelogs not mention that

wary edge
#

Why would they need to mention each update is GDK?

jolly citrus
#

you responding with no implied that this is no longer true, that they have reverted to some other type

wary edge
#

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.

jolly citrus
#

ah ok thx

#

maybe i edited the gdk options in myself then in the old version i wouldnt remember lol

weary umbra
#

Is there a property like world.isPaused?

wary edge
#

What are you trying to do?

weary umbra
#

I want to test if the player has it on bc It does some issues with my code.

#

(world owner only)

weary umbra
#

bc it set the tps to 0 and I have a performance mode when the tps is under certain number some modules get disabled

fallow carbon
#

wouldn't that cause scripting to stop ticking as well?

weary umbra
#

doesnt seems to do that

#

idk

wary edge
#

None of my scripts work if the world is paused.

weary umbra
#

yeah thats the issue

#

I want to return that

wary edge
#

What?

weary umbra
#

if the world is paused

fallow carbon
#

I doub't thats something that is exposed to us.

wary edge
#

How do you expect the game to conitnue running when the whole purpose of a PAUSE mechanic is to pause the game.

weary umbra
#

I need to add a checker thanks guys

wary edge
#

If you need a counter or timer use Date.now()

inner tinsel
#

Hello, can anyone tell me the newest stable api version for @minecraft/server

woven loom
nova flame
distant tulip
#

cancel the hit

sage portal
#

That's stable in the new update, right?

distant tulip
#

beta

sage portal
#

Aw shucks

weary umbra
nova flame
nova flame
#
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

fallow minnow
#

its most likely transferPlayer(player, {ip: 123, port: 67})

nova flame
nova flame
#

@fallow minnow

#

it just crashes my game now

remote oyster
nova flame
#

okey dokey**

remote oyster
# nova flame ```js import { system, world } from "@minecraft/server"; import { transferPlayer...
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.

nova flame
#

and it just crashes my game

remote oyster
nova flame
#

i fixed that

#

as GO7HN

#

told me

remote oyster
#

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.

tidal wasp
#

How tf would you decrease the durability of a tool when you mine something with it

wary edge
tidal wasp
#

Ok im lost on the update part

winged drift
deep arrow
#

if um setting alot of dynamic properties should i use
setDynamicProperties instead of several setDynamicProperty

stray spoke
#

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)
granite badger
#

oh…

stray spoke
#

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)
tidal wasp
#

How would you prevent a block from dropping anything when a player breaks it

wary edge
tidal wasp
#

Scripting rn

#

And uh

#

Ternary operator is pretty based

alpine ibex
#

9999999 ahhh

#

Les go I'm the one who added the count to 100k+

woven loom
marble sigil
honest spear
warm mason
alpine ibex
zinc breach
#

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

subtle cove
#

yes, that's also visible when doing /say

zinc breach
#

that will make things much easier

honest spear
#

indeed

zinc breach
#

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

jolly citrus
#

when PressurePlatePushBeforeEvent

deep arrow
winged drift
zinc breach
cinder shadow
remote oyster
cinder shadow
#

I no longer feel fear

wicked girder
#

Is it possible to prevent item entities from being stacked?

mystic vector
#

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;

    ...
  }
});```
mystic vector
wary edge
#

items.forEach

mystic vector
# wary edge 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?

wary edge
#

Yes...you do a forEach on an array.

mystic vector
wary edge
#

Why do you want to use for..of

mystic vector
wary edge
#

Ok. 👍 Good luck.

mystic vector
#

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)```

wary edge
#

Consider using forEach

mystic vector
# wary edge 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

granite badger
#
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;
  }
});
gaunt salmonBOT
mystic vector
#

navi made a oopsie

warped kelp
#

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??

fallow rivet
#

Is it possible to get the item's NBT using a script?

last latch
#

last time i used scripts it wasnt there

warped kelp
#

Yeah, my friend was hallucinating again

fallow carbon
pale terrace
#

setLore support rawMessage but I cant get translate: to work, does anybody has any example?

fallow carbon
#

whats your rawtext message look like?

pale terrace
fallow carbon
#

try ```
{rawtext:[{translate:translation.item}]}

pale terrace
fallow carbon
#

what error?

pale terrace
#

expected type: String | RawMessage

#

I will make a post about it

native osprey
#

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?

cold grove
native osprey
#

Do you know where should the new event go?

cold grove
#

After line 14

#

I will send you some articles that might help you

native osprey
#

Please and thanks

pale terrace
cold grove
cold grove
#

It has to be an array

[{rawtext:[{translate:`translation.item`}]}]
pale terrace
#

not working

#

can you try by yourself?

#

I think its a bug

cold grove
pale terrace
#

thank you

cold grove
#

@pale terrace works for me

#

You're setting back the item into the slot?

pale terrace
#

then I will take a look if I did something wrong

pale terrace
#

well, thank you for confirm that is not a bug

turbid delta
fair quarry
#

How tf do I get the fox held item with scripts? Tried multiple things, I think I'm forgetting something, does someone know?

stray spoke
#

maybe getting "equippable" component, incase you haven't tried

summer cloud
#

with custom commands, using the customparamtype PlayerSelector, does it require the command sender to be operator?

zinc breach
cinder shadow
warped kelp
#

I'm fuming, my minecraft updated and important scripts don't work no more

warm mason
buoyant canopy
#

Can we get the target of an entity?
like which entity a mob is chasing?

stray spoke
#

Found a cool Library

fair quarry
#

Hell yeah

fair quarry
#

idk if I am forgetting something or we cant get foxes held items

stray spoke
#

I mean like fox.getComponent("equippable").setEquipment("Mainhand", new ItemStack("minecraft:diamond_sword"))

warm mason
stray spoke
#

Ohh

fair quarry
#

isnt there a workaround?

warm mason
fair quarry
#

:/ but replaceitem doesnt get the equipment ?

warm mason
stray spoke
#

I guess only commands can

fair quarry
stray spoke
#

Does Typescript automatically compiles on Minecraft script api

#

Or it needs some setup

#

Because I really need interfaces and rules to typing

wary edge
stray spoke
#

Ohh

#

So it only supports js?

stray spoke
#

I figured out I can use comments for typescript interfaces

subtle cove
#

too bad entityItemDrop doesnt have items from equippable

fair quarry
native osprey
#

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

open urchin
#

i'd just do e.block.setType("air")

native osprey
#

replacing e.block.setPermutation?

fair quarry
native osprey
#

it worked thanks, tho it still shows the message block.permutation is not defined even tho it works

native osprey
#
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?
slow walrus
#

what the

native osprey
#

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
snow knoll
#

Could it be possible to change getRotation into getViewDirection?

woven loom
#

?

snow knoll
#

Like, could I turn the vector 2 of getRotation into the vector 3 getViewDirection

last latch
#

from getRotation alone nope

ripe dune
#

Why not just use getViewDirection?

snow knoll
#

It was essentially just a what of question as an analogy for what I actually need

#

I don't need either

#

But

ripe dune
#

lol

#

ig its totally possible

#

how? idk

snow knoll
#

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

native osprey
#
        e.block.runCommand(`say hi`);```

if i want a block to run a command when stepped on this would be correct?
native osprey
#

so... yeah...

ripe dune
#

but afaik block itself doesnt have runCommand

native osprey
ripe dune
#

use block.dimension.runCommand

native osprey
#

oh it worked, thanks

ripe dune
#

yup

native osprey
#

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?

native osprey
#

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": {}

        }
    }
}```
zinc breach
#

tell me how to use it bro 😭💔

last latch
cinder shadow
distant tulip
stray spoke
#

Or I'm dumb to say this

zinc breach
#

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

ripe dune
#

using SimulatedPlayer from server-gametest ig

#

or just use mobs

#

or modifying player.json so You can spawn it

wary edge
native osprey
subtle cove
#

try .60

native osprey
#

nope

subtle cove
#

i use .60 on block cus other version bugs

#

i havent tested for item tho

native osprey
subtle cove
#

1.21.60

zinc breach
#

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

subtle cove
#

playerselector

#

wdym error

stray spoke
#

Do we can store cache via js, instead of using ingame features like dynamic props, tags, scoreboard

subtle cove
#

Map, Set, any js data types

stray spoke
#

Ahh alright, it's also temporary right

subtle cove
#

resets every /reload, yeah

stray spoke
#

But it's enough

#

Yes thankyou

zinc breach
#

wdym

zinc breach
subtle cove
zinc breach
#

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

zinc breach
#

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

subtle cove
#

so like Player[]

zinc breach
#

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;
            }
        }
subtle cove
#

id and typeId are like {id,typeId} kinda

#

it shows in JSON.stringify since it's ordinary property unlike getters/methods and such

dense coral
#

spending so much time in freaking index.d.ts to find what im looking for because docs are useless

dense coral
#

Docs are so bad that they don't give me anything

#

So I am resorting to looking at the index file

subtle cove
#

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

nova flame
#

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

snow knoll
#

Probably magnitude

subtle cove
nova flame
subtle cove
#

cant atm.
i hvent specifically focused on the wich packeta were sent during join

distant tulip
#
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 };
}
snow knoll
#

Thanks, this is sincerely appreciated
Would you mind explaining how it works, or sending resources on how it works

distant tulip
#

i have no idea how to explain it more than that, it is just converting spherical coords to cartesian coords

snow knoll
distant tulip
last latch
distant tulip
#

so is viewDirection?

#

you are getting a direction converted to a direction
nothing changed

last latch
#

I thought they wanted the world relative direction from the entity's head

distant tulip
#

you will need player head location in that case
but he asked for view direction

last latch
#

must have missed the "view direction" part then

untold magnet
#

is it possible to turn off sprinting?

untold magnet
last latch
#

my shift is broken

#

lol

last latch
untold magnet
untold magnet
last latch
last latch
untold magnet
last latch
untold magnet
last latch
#

Thats tricky. Have you tried adding effects when sprinting?

untold magnet
#

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

last latch
#

effects, and velocity seem to be the only way

untold magnet
untold magnet
steep hamlet
#

is "minecraft:behavior.nearest_attackable_target" not enough for entity.target to work?

#

for me it returns undefined while the entity is chasing me

distant tulip
#

i don't think entity.target even work

ripe dune
#

afaik script api can't expose target of an entity

untold magnet
untold magnet
woven loom
native osprey
weary umbra
#

Bruh why is getWeather use beta API but setWeather not

warm mason
#

what did u think?

weary umbra
#

Thats so dumb getWeather is more helpfull then setWeather

warm mason
# weary umbra 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

weary umbra
#

Thanks

thorn flicker
floral copper
#

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

warm mason
#

but I need to see ur code, If u want me to explain it in more detail

warm mason
floral vessel
#

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});

warm mason
wary edge
#

Where is th pos? in the corner block? Center block?

floral vessel
#

yes

#

the pos is just some arbitrary point

wary edge
#

I have some questions about using block from ray to get a block right below, but I digress.

floral vessel
#

so I have to use a raycast for that

wary edge
floral vessel
#

no, it's tied to an entity position

warm mason
#

🍿 👀

floral vessel
#

even setting the max distance to 50 doesn't work

floral vessel
#

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)

wary edge
#

I think theres some examples in #1072983602821861426 or #1046947779118895114

warm mason
floral vessel
#

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

floral vessel
#

apparently you have to use the command

floral copper
sharp elbow
#

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

floral vessel
#

yeah, I think I'll have to do that, it's really janky rn

warm jungle
#

is there even a shortcut to content logs?

#

like key to press to open the content log :\

floral vessel
warm mason
# floral copper

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?

buoyant canopy
warm mason
# floral copper

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

warm mason
#

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...
    }
}
summer path
slender aurora
#

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...

warm mason
slender aurora
#

the API classes

warm mason
# slender aurora 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.

Contents of the @minecraft/server module

warm mason
slender aurora
#

I think I'm starting to understand

warm mason
# warm mason for example, sending player a message when it joins the world: ```js import { wo...

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

slender aurora
#

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 ...
}

warm mason
# warm mason 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

warm mason
slender aurora
#

behind the if statement:
(data.block)

Because the playerInteractWithBlock has this property?

slender aurora
warm mason
#

well, yeah, PlayerInteractWithBlockAfterEvent has a block property, that gives u info about the block, the player interacting with

slender aurora
# warm mason ?

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☺️

lucid dust
#

how would i escape early execution at the beginning of a script?

warm mason
lucid dust
lucid dust
# warm mason 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;
}

warm mason
# lucid dust export var limitlessTechniqueHotbar = [ hotbarItem("jjk:ct_reversal_cast", "...
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;
}
floral copper
floral copper
#

Basicallly a lot of stuff needs to be fixed

#

Which makes sense since am a beginner at tis😭😭

warm jungle
floral copper
slender aurora
#

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");
  }
});
fallow rivet
#

Is it possible to open chest UI on a player's screen?

warm mason
#

Like

if (!data.isFirstEvent) return;
// other code
slender aurora
hidden perch
#

could anyone help?

#

idk what i did wrong but

#

the output gives undefined

remote oyster
hidden perch
# remote oyster 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!");
        }
    });
});

}

hidden perch
#

cuz

subtle cove
#

i'd recommend doing

response.formValues.filter((v) => v != null)
```and```js
const [text, index, num, bool, etc] = response.formValues.filter((v) => v != null)
haughty gust
#

Hey guys does server-admin work on realms? seems like the last update might have removed server-admin from realms.

haughty gust
#

sigh thanks

zinc breach
#

why cant I use .lookAt() or .setRotation for players

#

is there another way to do it

weary umbra
#

Does someone has a code that returns entities armor? If yes could you please share it?

ripe dune
tardy bane
#

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)
}```
hidden perch
#

what is the difference between using typescript and using javascript

remote oyster
# hidden perch 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

hidden perch
#

ohhh okay thanks for the answer i really appreciate it 💙🙏🏻🛐

remote oyster
#

Welcome

hidden perch
#

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)
hidden perch
#

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}`);
        });
    });
}
subtle cove
#

hmmm

#

make it !=

hidden perch
#

okay

haughty kernel
#
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...

warm mason
haughty kernel
distant tulip
#

it works

warm mason
haughty kernel
#

setItem, setEquipment, container, system...

warm mason
warm mason
#

ok, I will test it

#

maybe ev.itemStack is a getter...

distant tulip
haughty kernel
# distant tulip

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.'-'

distant tulip
#

what?

#

ah

#

lol

haughty kernel
distant tulip
#

i mean, that sound like you are calling yourself an error

haughty kernel
#

I'll restart to see, but it must be something to do with the preview '-'

haughty kernel
#

It's not my launcher, it's the game...

#

Mojang hates me...

warm mason
haughty kernel
haughty kernel
#

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.

night acorn
#
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

warm mason
#

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

slender aurora
#

Stupid question:
Is "const itemComponentRegistry = data.itemComponentRegistry"
and "const { itemComponentRegistry } = data" the same?

naive agate
#

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

nova flame
#

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

remote oyster
# nova flame how would i measure the players CPS with script api

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.

runic maple
runic maple
#

Guys how do you locate structures with scripts?

#

Instead of checking chunk by chunk or something

remote oyster
nova flame
#
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

warm mason
warm mason
zinc breach
#

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

marble sigil
open urchin
zinc breach
#

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

runic maple
native osprey
#
                "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
open urchin
weary umbra
native osprey
#

They should at least put that on the component page saying

"This is for post 1.21.90 version"

open urchin
#

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

native osprey
#

anyways changing subject, is there a component to make the cooldown bar animation to be displayed?

open urchin
native osprey
#

oh

open urchin
#

you might have to wait until it releases

native osprey
#

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

spice finch
#

Does anyone know how to detect equipping armor without checking every tick?

warm mason
open urchin
#

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

spice finch
#

Ah ok, thanks!

warm mason
naive agate
#

unless you mean it isnt triggered even when right clicking armor?

woeful vine
#

Yo, I am having this issue where I cannot make my chatSend.subscribe thing to work...

#

Can someone please help me?

woeful vine
#

I am pretty new to codeing

last latch
woeful vine
#

{
"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?

wary edge
#

Ah, right, anyways change it from 2.5.0 to beta

woeful vine
#

How do I do that?

wary edge
#

Open editor -> backspace 5 characters -> type beta

woeful vine
#

Editor?

#

What editor?

wary edge
#

What are you using to make add-ons?

woeful vine
#

bridge

#

but

#

Nono

#

I am just scripting with visual

#

like, old fashion scripting

wary edge
#

I have not used bridge so I have no idea.

woeful vine
#

No no

#

I am not using brdige

#

I am just using visual studio

wary edge
#

Then open visual studio, open your manifest.json and change it from 2.5.0 to beta

woeful vine
#

This???

wary edge
#

Yeah.

woeful vine
#

Aight

#

Done

#

Let me try

#

That's the error now

#

@wary edge

wary edge
#

Now open a post and post your code there.

woeful vine
jolly junco
#

Is it possible to add a tooltip or hover text to a button in an ActionForm?

fallow minnow
open blade
#

Hi everyone I'm looking for help with scripting my behavior and ressource's pack

zinc breach
#

is setArmorTrim supposed to be used with an ItemStack?

cold grove
#

Do you mean loot table items?

zinc breach
#

like on an itemUse afterEvent

warm mason
zinc breach
#

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? 💀

warm mason
#

and then just generate it

#

through APIs

#

but yeah

#

u need a lot of loot tables

zinc breach
#

bc I'm probably just gonna make diamond and netherite

zinc breach
#

does this work for custom armor too

warm mason
sudden nest
#

Hello, just wondering if

Anyone have entityDatabase class (using structures) or script i can use? 😅

hidden perch
sudden nest
#

Instead of item or data.

harsh robin
#

i might have one

#

lemme check

sudden nest
harsh robin
#

i dont have one

sudden nest
#

I think, just set, delete, and get is enough

harsh robin
#

make one

sudden nest
#

Ah sadge😔 , thanks for trying though

sudden nest
#

Need to relax my back (oldzie @ 23y)

harsh robin
#

unc

hidden perch
#

could someone check my dataModule out?

#

cuz im making this to share with my friends or any other people as if they needed

lucid dust
#

is there any way to force an entity to become aggressive towards a target?

warm mason
gaunt salmonBOT
cold grove
#

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

sly currentBOT
#
tadasecake

it's very annoying help

cold grove
#

Someone has the same issue?

buoyant canopy
#

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

wary edge
#

I havent an issue with getViewDirection being bugged.

woeful vine
#

Hey!!!

#

Do someone know how to have multiple .js files working?

#

Cuz I can only get my main.js file working

thorn flicker
woeful vine
thorn flicker
#

using import

woeful vine
#

Do I get to import the hole script?

woeful vine
#

like

#

import from './script.js'; ??

thorn flicker
woeful vine
#

I want the hole script to work

#

I just import from './script.js'; and that's it?

thorn flicker
woeful vine
#

thankssss

haughty kernel
#

Is there any way to prevent players from moving items in their inventory without locking the items, like using a beforeEvents for the playerInventoryItemChange?

onyx locust
#

is it possible to import script files from other addons if i specify the right folder?

import { Lang } from '../../Other BP/scripts/main.js';
onyx locust
buoyant canopy
warm mason
buoyant canopy
#

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

wary edge
#

Never had this issue.

buoyant canopy
#

#1067535608660107284 message

warm mason
wary edge
buoyant canopy
#

that is interesting, i have the game from the ms store tho?

warm mason
buoyant canopy
#

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?

buoyant canopy
#

i am not running 2032 commands to get the durability of a netherite tool

midnight ridge
#

sooo do we still can't cancel the hit event between players?

distant tulip
#

ah, less than and greater than also does't work

final ocean
#

How to make fishing system like fish it in builda??

round bone
distant tulip
#

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