#Script API General

1 messages · Page 113 of 1

shy leaf
#

are you using manifest v3?

full idol
shy leaf
#

i see

unique apex
#

random question someone ping me if they know, but is there a place to check what is in which version of API dependencies?

or more specifically, does anyone know if simulated player is in the stable version of server-gametest? (0.1.0)

#

i went to the documentation on microsoft learn but its a bit outdated

shy leaf
#

also for the gametest part, no, theyre only in 1.0.0-beta still

unique apex
#

thanks guys! super helpful

somber cedar
distant gulch
#

Does /damage suicide command like when using the projectile method, does it also remove the stun delay

#

if using anything else besides projectiles

#

i tried it with an autoclicker for an item but it still had the stun

magic peak
#

hello everyone @magic peak here

dusky flicker
distant gulch
#

hello

#

i’m beginner in programming

#

python or javascript?

rare plume
distant gulch
#

thanks

dusky flicker
#

im really thinking on usint haxe to transpile to js instead of ts

#

it seems to be more interesting

magic peak
dusky flicker
#

quickjs is at least 20 times slower than bun and node for some tasks

meager pulsar
#

this is onlt showing (undefined) when i look at any entity, what am i doing wrong?

system.runInterval(()=>{
    world.getAllPlayers().forEach((player)=>{
        const lookAtEntity = player.getEntitiesFromViewDirection({maxDistance:100})[0]
        if(lookAtEntity){
            console.warn(lookAtEntity.id)
        }
    })
})```
drowsy scaffold
#

how do I get the item in a glow item frame? I would've assumed that they have an inventory component but they don't

#

nevermind, found it

drowsy scaffold
# wary edge You cant

for whatever reason Block.getItemStack returns the item inside the frame which is the exact opposite of what I would think that call would do but okay

drowsy scaffold
meager pulsar
prisma shard
drowsy scaffold
shy leaf
#

whats the required format version for item custom components in v2 scripting?

#

just need to note it somewhere

shy leaf
#

danke sean

wary edge
shy leaf
#

bet

prisma shard
#

Thoughts on this code?

rare plume
shy leaf
#

could make use of that

#

what is this for though

dusky flicker
rare kite
#

Does anyone know why you can’t run and execute command in scripts

#

It always throws and on the @ symbol

broken pawn
#

you use "runCommandAsync"?

#

it got removed by the way

rare kite
#

Yes

broken pawn
#

use "runCommand" instead

rare kite
#

Both still work either way it throws an error

#

The problem is something with the script not liking the exits command

prisma shard
prisma shard
rare plume
prisma shard
prisma shard
# shy leaf what is this for though

I don't know but thought could be useful, Such as doing clearRun stops interval but its harder, so this class what it does is helps to resume/pause a interval. Then when you need to abort the task, it does clearRun. I kinda wanted to make it Promise-like.
So yeah basically you can do:

const id = TaskScheduler.runInterval(() => {

})

id.stop() // this will stop the interval

id.start() // this will resume the interval again

So basically it makes managing tasks easier by allowing interval to stop or start which mojang doesnt allow this feature cuz clearRun just aborts the interval.

prisma shard
rare plume
#

i might honestly use this

prisma shard
rare plume
shy leaf
#

there can be some unexpected cases that isnt handled from scripting api

prisma shard
#

Such as?

#

It currently handles normal errors like if the task is already running, and if you try to run it again, it wil throw err

shy leaf
dusky flicker
#

and make onComplete generate other TaskScheduler in chain

#

even maybe make usage of promises to make it able to use await syntax

dusky flicker
#

@tranquil junco by the way, that idea of storing data in binary, im implementing it slowly

#

im making some tests yet

#

it seems to be working

#

i just must implement arrays

shy leaf
#

thats some peculiar looking ide

dusky flicker
#

its just 2 terminals

#

1 with helix, another one with, nothing

shy leaf
#

i see

dusky flicker
#

documentation may be incorrect

broken pawn
#

Ask a bit, if i increase the interval timer, does it reduce any lag?

import {EntityEquippableComponent,EquipmentSlot,system}from"@minecraft/server";
let S = system;

S.runInterval(()=>{for(let A of world.getPlayers()){try{
    let B=A.getComponent(EntityEquippableComponent.componentId);
    let C1=B.getEquipment(EquipmentSlot.Head);
    let C2=B.getEquipment(EquipmentSlot.Chest);
    let C3=B.getEquipment(EquipmentSlot.Legs);
    let C4=B.getEquipment(EquipmentSlot.Feet);
    if(C1.typeId.includes(":")&&C2.typeId.includes(":")&&C3.typeId.includes(":")&&C4.typeId.includes(":")){A.addEffect("resistance",300,{showParticles:false})};
}catch(e){}}},150);
cursive fog
#

Can you read player entity properties using scripts?

#

Im using getProperty but my script wont read it somehow

dusky flicker
#

put a tag on the player when it wears something

#

and put the effect with time infinite

broken pawn
cursive fog
#
import { world, system, Entity, ItemStack } from "@minecraft/server"

const TARGET_ITEM = "vdg:coltwalker"  // target item ID
const DAMAGE_PER_USE = 1    // durability consumed per use
let useitem

world.afterEvents.worldLoad.subscribe(() => {
  useitem = world.getDynamicProperty('vd:shooting')
})

world.afterEvents.itemUse.subscribe(ev => {
  const { source: player, itemStack } = ev
  if (!player || !itemStack) return
  if (itemStack.typeId !== TARGET_ITEM) return

  const dur = itemStack.getComponent("minecraft:durability")
  if (!dur) return
  if (useitem === false) return;
  if (dur.damage == 12) system.run(() => player.runCommand('function coltwalker/empty'))

  dur.damage += DAMAGE_PER_USE
  const container = player.getComponent("minecraft:inventory")?.container
  if (!container) return
  container.setItem(player.selectedSlotIndex, itemStack)
});


console.warn
dusky flicker
#

when it removes, you remove the tag as well as the effect

#

the tag is mainly to check if it's got the effect

cursive fog
#

Why wont my script return if my property is false?

broken pawn
#

using world.afterEvents.itemUse.subscribe??

cursive fog
#

Should i put my useitem part on the itemuse.subscribe?

#

Idk

broken pawn
#

well, idk tho

dusky flicker
celest fable
#

test

dusky flicker
#

but im testing it

#

it just doesnt have

#

i gotta update it

celest fable
dusky flicker
#

but im working with binary serialization

celest fable
#

i know that, but for what:v

dusky flicker
#

for storing binary instead of json yknow

celest fable
#

oowh, thats nice

dusky flicker
#

at least on that tiny example i was testing, the binary got at least 6 times smaller

#

but compacting 2bytes to 1 char it may get something around 11 chars

celest fable
#
async function forceOpen(player, form) {
  let res = await form.show(player)
  while (res.cancelationReason === "UserBusy") res = await form.show(player)
  return res
}

how do you think about this compact "forceOpen"?

dusky flicker
#

it's doing its job, so it's good

celest fable
#

lol literally the same respond from my friends

dusky flicker
#

arrays implemented 👍

fast pond
#

whats command for downloading all latest scritpapi packages and versions?

#

I remember there was some command here

distant tulip
fast pond
#

works the same

unique apex
#

man i cannot take a break from this, i leave the space for like 3 months and have to relearn half of it

we went from worldload to worldinitialize back to worldload 😭

i also cant get my block component registry to work anymore so ill have to look into that one

broken pawn
#

interesting

looks like it's the reason registryBlockComponent somehow didn't work as intented

wheat condor
#

what's the current beta api in 1.21.111?

thorn flicker
wheat condor
#

ty

ivory bough
#

What's the name of that method which sets a entity property on a specific client?

twilit tartan
#

How i can place a armor enchanted in a entity?

#

h

#

100000 messages Xd

sharp elbow
remote oyster
lone mango
#

How does one make a custom UI element show on the HUD? And how do you feed it values for things like meters and such.

#

The JSON UI tutorials don't really explain how to do that from the scripting API

spark kayak
#

I don't actively code bedrock addons like I used to
I had the idea of coding a spelling bee detecting keyboard inputs to play with my friends

#

is that even possible?

#

I don't think you can detect keystrokes like that

full idol
#

Bedrock Dedicated server keeps crashing with this when a mob gets punched. Sometimes when it restarts the issue is gone, but then eventually it comes back. No idea how or why, but could this be an addon thing?

distant tulip
twilit tartan
spark kayak
#

but yeah I guess I can build a website 😔

#

would've been fun to build a map and stuff

distant tulip
#

well... if you really want that you can build a website and link it to a map

magic peak
#

hello everyone

dusky flicker
#

hello

rare plume
magic peak
dawn zealot
#

just here to ruin everyones day, the D in down for dropdown doesnt work if uppercase, however textField does and textfield doesnt, thank me later:)

mystic harness
#

genuine question, is there a way that achievement is enabled with script api running?

wary edge
mystic harness
#

it still prompts me this as you said addons dont disable achievements anymore

mystic harness
#

got it thanks

fallow minnow
#

its just camel case

chrome gyro
#

How do you iterate an entity list in an order. I've tried using:

  entitys.forEach(entity => {
  for (let e = 0; e < 64; e++) {
   const entity = entitys[e]
   if ( entity == undefined ) { break };

but these both execute all the entities at the same time, or atleast too fast between each iteration for it to matter. I'm trying to kill an entity if it detects a duplicate entity, but keep running into entities killing eachother.

random flint
#

What do you mean by duplicate?

The same typeId? (zombie & zombie)
or the exact same entity you want to filter out?

#

You can use the Set() object to record unique elements

chrome gyro
#

I'm using a property to detect same type. But doesn't matter much to me. Ok I'll look into using Set() thank you!

lethal bramble
#

how would i modify the contents of an itemstack, for example a chest that the player is holding?

#

ive tried using ItemInventoryComponent, but it just returns undefined

#

this component is so stupid. LITERALLY EVERY ITEM DOES NOT HAVE IT. that includes:

  • chest
  • barrel
  • shulker box
  • bundle

WHY???

lethal bramble
#

it doesnt

#

i used the hascomponent thing and it said false

distant tulip
#

you are in beta?

lethal bramble
#

ye

lethal bramble
distant tulip
#

send code

lethal bramble
#
system.run(() => {
       const shulkerBox = new ItemStack("minecraft:bundle", 1);
       console.log(`bundle has component: ${shulkerBox.hasComponent("minecraft:inventory")}`);
       const container = shulkerBox.getComponent("minecraft:inventory").container;

       for (let i = itemsRequired; i > 64; i -= 64) {
                    container.addItem(new ItemStack("minecraft:redstone", 64));
       }
       if (itemsRequired % 64 > 0) container.addItem(new ItemStack("minecraft:redstone", itemsRequired % 64));

       shulkerBox.nameTag = signalStrength.toString();

       origin.sourceEntity.getComponent("minecraft:inventory").container.addItem(shulkerBox);

       return {
          status: CustomCommandStatus.Success,
          message: `Gave ${origin.sourceEntity.nameTag} shulker box`
       }
})```
distant tulip
#

sound like a bug

#

the component is for bundle like items

dusky flicker
dusky flicker
#

if you store the entities in the set

final ocean
#

I am creating a prison map should I use chest ui or actionformdata

meager cargo
#

Is there a way to cancel event on interaction with dispenser block, but then opening ActionForm and set up some commands on the buttons?

I made script for canceling events with beforeEvents.playerInteractWithBlock ev.cancel = true;
But then I can't open ActionForm. I figured it out that I can open form by using script events, but now I'm struggling with seting up working commands on the buttons in this form...

meager cargo
#

I made workaround - I canceled event on dispenser but added interact with button on it. So it solved my issue. I'm sorry I deleted wrong code

restive light
wary edge
#

Both.

restive light
sly valve
#

Mostly OOP and sometimee Functional

dawn zealot
dusky flicker
# restive light

i use classes because thats the only way to make objects have methods, but im really interested in using f# to compile down to js

#

but i really hate the fact of not having a bunch of functional features

#

im used to rust, and in general thing.method() is just a sintax sugar to TypeOfThing::method(&thing)

#

so im used to think of things like this

restive light
restive light
twilit tartan
#

anyone can help me with my question plsbao_foxxo_smile Sisi #1423380725373341856

sly valve
restive light
#

I typically use OOP for database related stuff and functional for everything else

sly valve
#

I use it for everything nearly

#

I love a good structure

#

And yeah I also use Functional for little scripts, like my Tag game, or a simple Rank system

restive light
#

I tried to use oop but a lot of my code would just be a collection of function

sly valve
restive light
#

and how much are you uses instances

sly valve
#

Services or helpers are static

#

And I use instances for like Enemies or Towers in a tower defense

#

Hoe much in total idk

fair fern
dusky flicker
#

i mean, a bunch of things that follow the same pattern

#

not a single one

#

but in general a simple struct and it's functions should be enough

final urchin
#

the getEntitiesFromRay api is cooked 💔

#

So I am the codev of a hitbox/collision box pack and suddenly this update certain entities just dont get picked up by the ray system

#

like items, arrows, tridents, potions, xp orbs, and more.

#

standard mobs are detected just fine though :/

gaunt salmonBOT
jolly citrus
#

erm

#
npm i @minecraft/[email protected]
npm error code ERESOLVE
npm error ERESOLVE unable to resolve dependency tree
npm error
npm error While resolving: [email protected]
npm error Found: @minecraft/[email protected]
npm error node_modules/@minecraft/server
npm error   @minecraft/server@"^2.3.0-beta.1.21.111-stable" from the root project
npm error
npm error Could not resolve dependency:
npm error peer @minecraft/server@"^2.0.0" from @minecraft/[email protected]
npm error node_modules/@minecraft/server-ui
npm error   @minecraft/server-ui@"2.1.0-beta.1.21.111-stable" from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
deep quiver
jolly citrus
#

but why is this even an issue

#

i did but like

deep quiver
#

They messed up the dependencies somehow

prisma shard
#

world.afterEvents.worldLoad.subscribe(() =>{})
Using this event,
Now how do I make a function like waitForWorldLoad(), so whatever code after this function, will wrap inside the event

subtle cove
weary umbra
nova flame
#

is it possible to make it so regular players with member permissions not be able to use target selectors like /w @a[tag=hasTagThisOne]

#

or just make them not be able to use /w

#

and stuff like that

round bone
cursive fog
#
import { world, system, Entity, ItemStack } from "@minecraft/server"

const TARGET_ITEM = "vdg:coltwalker"  // target item ID
const DAMAGE_PER_USE = 1    // durability consumed per use



world.afterEvents.itemUse.subscribe(ev => {
  const { source: player, itemStack } = ev
  if (!player || !itemStack) return
  if (itemStack.typeId !== TARGET_ITEM) return

  let useitem = world.getProperty('vd:shooting') == false

  const dur = itemStack.getComponent("minecraft:durability")
  if (!dur) return
  if (useitem) return
  if (dur.damage == 12) system.run(() => player.runCommand('function coltwalker/empty'))

  dur.damage += DAMAGE_PER_USE
  const container = player.getComponent("minecraft:inventory")?.container
  if (!container) return
  container.setItem(player.selectedSlotIndex, itemStack)
});

console.warn
#

Uhh why?

#

Help😭

distant tulip
#
  let useitem = world.getProperty('vd:shooting') == false

this is not a thing, please don't use ai if you don't know what are you doing

snow knoll
#

It even looks over complicated

#

What are you actually attempting to do?
I'm sure that a simpler solution can be made to help you if you ask

nova flame
cursive fog
cursive fog
#

After 6th use of the item it triggers a replace item function

prisma shard
#

In which script documentation did you even saw

round bone
prisma shard
#

Fr?

wheat condor
#

variable == variable returns true/false

prisma shard
#

but Only for entities

wheat condor
#

let variable = variable1 == variable2
// variable = true/false

cursive fog
prisma shard
#

U used world.getProperty

#

Not entity

cursive fog
#

It says not documented or smth

#

Idk

snow knoll
# cursive fog

A property can only be retrieved from an entity with a property defined in their entity file
Was it defined?

prisma shard
#

Well for getting the property you need to define it in Entiy json

prisma shard
wheat condor
#

Tuff

snow knoll
cursive fog
snow knoll
prisma shard
#

Guh

snow knoll
#

Essentially the game knows it exists

wheat condor
cursive fog
#

Oh

snow knoll
cursive fog
#

Hmmm

#

So should i seperate the get property part on a diffrent worldload thingy or keep it there

wheat condor
#

you need an event or some function to get the entity first

wheat condor
#

no

#

you have to get the entity somewhere

prisma shard
#

"properties":{"mba:light":{"type": "int","range":[0, 15],"default":0}}

#

Here

#

Like this u define property inside entity json

wheat condor
#

for example

const entities = dimension.getEntities()
const entity = entities[0]
cursive fog
prisma shard
#

{
"filters": {
"test": "light_level",
"value": 0
},
"add": {
"component_groups": ["light_level:0"]
}
U can then change the property using event trigger

#

Okay nice

snow knoll
#

But, everyone, the most important thing is probably that he doesn't even need the entity property

He isn't interacting with anything outside of scripts, so he could just use a dynamic property instead of editing the player file and wasting one of only 32 properties

cursive fog
#

Been thinking of that for a while but yeah
Besides that the vd:shooting property is alr reused twice

prisma shard
#

So then because your setting property on player,
U should get player:

const player = world.getPlayers()[0].getProperty("b")
distant tulip
safe stream
#

Why do we not get the Player object in params

cursive fog
prisma shard
open urchin
#

Player represents an entity

prisma shard
cursive fog
#

Wait guys
does getDynamicProperty work on world?

prisma shard
#

Yes

wheat condor
distant tulip
cursive fog
#

Alr ill try that

safe stream
#

i see thanks guys

snow knoll
prisma shard
#

Oh if u mean world.getProperty is not a thing, Oh yes yeah

distant tulip
#

yes

safe stream
#

the day we get dynamic properties on blocks

#

im so tired of setting world dynamic properties with xyz as an alternative

prisma shard
#

lol for real

cursive fog
safe stream
#

whereas dynamic properties can be defined via script directly without touching json files

cursive fog
#

Hmmm

prisma shard
distant tulip
cursive fog
cursive fog
#

Alr my bad for bothering yall guys😭
Just one last which one works better?

safe stream
#

its a cached variable tho

#

not reliable

prisma shard
#

Yeah

snow knoll
safe stream
#

usually dynamic properties are used for long term data storing

#

or at least multi session

prisma shard
#

Yea

snow knoll
#

Or just an alternative to using properties cause many dont like to tamper with the player.json

safe stream
#

what

prisma shard
#

Guys, One question,
I've rarely seen people using the .unsubscribe in events. What use case it could be used for?

safe stream
#

i actually dont know what is that for (or at least its practical purpose)

prisma shard
#

Yep me too

safe stream
#

same as world shutdown

distant tulip
# cursive fog Alr my bad for bothering yall guys😭 Just one last which one works better?

they are different thing
getProperty
accessing static properties provided from the entity file itself in the entity definition in its behavior pack
getDynamicProperty
accessing script defined properties stored in the entity, world, or item, those properties are unique and linked to each add-on uuid and can't be accessed by other add-ons
so it depend on your use case

prisma shard
# round bone Stops listening to an event.

Oh, But I've seen using unsubsribe after a subscribe, But it does run everytime.

const callback = world.afterEvents.projectileHitEntity.subscribe((arg) => {
                const { source, projectile } = arg;
                const hitInfo = arg.getEntityHit();
                if (hitInfo?.entity && source instanceof Player && projectile === entity) {
                    const shooter = source;
                    const target = hitInfo.entity;
                    const projectileType = projectile.typeId;
                world.afterEvents.projectileHitEntity.unsubscribe(callback);
                }
            });

Such as I have this code, this does run everytime player hits a entity, and the projectilesHitEntity event does run, but it's unsubscribing in this code..?

round bone
#

Yep, it just stops listening to this event. I do not recommend relaying on dynamic event listeners, unless you know how to deal with them.

distant tulip
#

there is not a lot of good use cases really

safe stream
#

does it just kill that firing?

distant tulip
distant tulip
round bone
#

I think discord.js uses unsubscribe for once listeners.

distant tulip
#

worldLoad

#

i don't think it actually matter

round bone
distant tulip
#

yeah

round bone
#

I used unsubscribe in @minecraft/server only once in my entire life, but it actually can lead to optimization at few percents, so I still like it.

distant tulip
#

i mean yeah, but there is probably no performance impact if the event stop in the game code itself.

#

i mean for worldLoad

safe stream
#

getAttachedBlocks() does not return the block that was pushed?

round bone
distant tulip
#

yeah when you have subscribe in a loop or a scope that execute more than once, unsubscribe is very necessary

round bone
#

Yup.

cursive fog
#

Im gonna loose my sanity

#

How do you make a script single use only

#

Like

#

When i use item

#

It triggers only once

#

Then after i use the item again it triggers once too

sly valve
thorn flicker
thorn flicker
cursive fog
#

Got any idea

#

I am loosing my sanity man💔

thorn flicker
#

almost like I said that

cursive fog
#

So...

#

Scripts always run non stop?

thorn flicker
#

I think you are misunderstanding something, can you share the code that you are working with

cursive fog
#

Alr w8

#
import { world, system, Entity, ItemStack } from "@minecraft/server"

const TARGET_ITEM = "vdg:coltwalker"  // target item ID
const DAMAGE_PER_USE = 1    // durability consumed per use



world.afterEvents.itemUse.subscribe(ev => {
  const { source: player, itemStack } = ev
  if (!player || !itemStack) return
  if (itemStack.typeId !== TARGET_ITEM) return

  let useitem = world.getDynamicProperty('vd:shooting') == false

  const dur = itemStack.getComponent("minecraft:durability")
  if (!dur) return
  if (useitem) return
  if (dur.damage == 12) system.run(() => player.runCommand('function coltwalker/empty'))

  dur.damage += DAMAGE_PER_USE
  const container = player.getComponent("minecraft:inventory")?.container
  if (!container) return
  container.setItem(player.selectedSlotIndex, itemStack)
});

console.warn
thorn flicker
#

its because of system.run

cursive fog
#

@thorn flicker i just need it to run once

cursive fog
thorn flicker
#

yes.

cursive fog
#

Basically it deals damage to durability of an item

#

The run command is for replace item

thorn flicker
#

im using your code and it seems to work.

#

it doesnt trigger more than once

cursive fog
#

@thorn flicker yo sorry for ping
I removed the system part but uhh it started screaming at me

cursive fog
thorn flicker
#

yeah because you didnt remove the arrow function.

#

and nvm about the system.run thing I was wrong.

cursive fog
thorn flicker
#

yeah you dont need to ping me, im right here with you lol

floral timber
thorn flicker
#

let useitem = world.getDynamicProperty('vd:shooting') == false

cursive fog
#

Ohhh

thorn flicker
#

dude

#

this is why i cant help people in the morning

#

i keep messing up

cursive fog
floral timber
#

sorry wrong reply

cursive fog
thorn flicker
#

np

#

it triggers once for me though

floral timber
cursive fog
#

Im using AC and property to make sure it returns but doesnt seem to work

thorn flicker
#

what does the function do?

cursive fog
#

But the durability only deals 1 damage when i kept using the script

cursive fog
sly valve
#

Its not accurate to use it

thorn flicker
#

yeah

floral timber
#

and decrease durability on stopUse?

sly valve
#

Or directly on StartUse

thorn flicker
#

oh is this a chargeable item?

cursive fog
cursive fog
thorn flicker
#

either it is or not lol

sly valve
#

Isnt there a component to make it chargeable?

thorn flicker
#

shooter component

cursive fog
#

My bad @distant tulip 😭😭 i kept going around the entity property part

cursive fog
thorn flicker
#

why would it trigger multiple times then

floral timber
#

there's eat or edible component ig? use modifier things..

thorn flicker
#

oh, you are using the food component?

sly valve
floral timber
#

sure, sounds good

thorn flicker
#

in that case I can see how its being used multiple times

cursive fog
cursive fog
floral timber
#

it should work

#

or change ticks according to what fits

floral timber
#

NOO!

thorn flicker
#

or just do this



if (player.start === undefined) {
player.start = true
// damage stuff...

system.runTimeout(() => { player.start = undefined }, 20)
}
#

just by creating a temporary property on the player

sly valve
#

Or use a Map/Set

#

But idk if theres a big difference

floral timber
#

anybody's ready to spoon feed?

#

Minato?

thorn flicker
#

I am spoon feeding

#

kinda

cursive fog
#

Naww😭

sly valve
#

I would help but I cant code on phone

sly valve
cursive fog
floral timber
cursive fog
#

Coding on phone is hell

floral timber
thorn flicker
#

this is why I would wait until I could get a computer if I were in your shoes

sly valve
cursive fog
#

@floral timber where can i find the itemStartUse on the documentations?

sly valve
#

On the official docs, or any else

floral timber
sly valve
cursive fog
sly valve
#

I remember when I was new to JS and had lots of issues with brackets
(I made my command handler with 30 statements and no if else)

sly valve
summer path
#

hey does anyone wanna help me out

sly valve
#

Btw what the °=° is LinearSpine

thorn flicker
sly valve
summer path
#

like player1 has died

sly valve
#

And theres an event if a entity dies

thorn flicker
#

and use EntityDie

sly valve
#

Just filter either if its typeId, instance (or my thr filter object) if its an player

summer path
#

no i want it to show entities to

sly valve
#

Only Players

thorn flicker
#
world.afterEvents.entityDie.subscribe(data => {

}, {entityTypes: 'minecraft:player'})
sly valve
#

If you want to also Trigger if a entities dies, remove the filter

summer path
sly valve
#

Okay then it may be a little more work

summer path
#

i dont have anyone to test with thats why

thorn flicker
#

its just getting the entity that killed them...

sly valve
#

You need definitions of death messages with placeholders like

{
  "entityAttack": "%player% got killer by %attacker%"
}
#

A parser to insert the names

summer path
#
import { world } from "@minecraft/server";

world.afterEvents.entityDie.subscribe(event => {
  const victim = event.deadEntity;
  const attacker = event.damageSource?.damagingEntity;
  
    world.sendMessage(`§c${victimName} §7was killed by §a${attackerName}`);
  });
#

would this work

sly valve
#

And a manager/handler to show the correct message

#

It would, but only for entity attacks

#

If you also want like falldamage, fire damage or explosion, you need a lottle bit more

sly valve
#

If you only want to make it being used on entity attacks, yeah

summer path
#

i want to know if it lodas correctly too but idk how to do that

#

i do /reload all and reload but it does nothing

cursive fog
#

Yup this should work

sly valve
summer path
#
{
  "format_version": 2,
  "header": {
    "name": "Test",
    "description": "Test",
    "uuid": "20c744da-6f9f-8f0d-f212-a96ed88a5eb8",
    "version": [
      1,
      0,
      0
    ],
    "min_engine_version": [
      1,
      17,
      0
    ]
  },
  "modules": [
    {
      "type": "data",
      "uuid": "cb6f1da2-40be-9411-bd3c-08c1395ba634",
      "version": [
        1,
        0,
        0
      ]
    }
  ]
}
sly valve
#

Also check for the log, maybe errors appear

summer path
#

thats my manifest

sly valve
#

our manifest is wrong

summer path
#

:c

#

same issue as last time

sly valve
#

@thorn flicker Can you help him? Kinda hard on phone

summer path
#

i just cant do this properly

#

🙏

sly valve
summer path
#

I hope

#

What's wrong with it tho?

sly valve
#

Void took too long, here

summer path
#

Already used that

sly valve
summer path
#

Oh how do i add that

#

the metadata thingy?

sly valve
#

No

#

Wait

summer path
#

I'm like really sorry for being dumb as fuck

sly valve
#
{
    "format_version": 2,
    "header": {
        "name": "Bedrock Add-ons",
        "description": "Script API Template",
        "uuid": "<UUID>",
        "version": "1.0.0",
        "min_engine_version": [1, 21, 90]
    },
    "modules": [
        {
            "uuid": "<UUID>",
            "version": "1.0.0",
            "type": "script",
            "language": "javascript",
            // Your entry file; where Minecraft will read your code from.
            "entry": "scripts/main.js",
        }
    ],
    // Uncomment to use eval() and Function() inside your code (unrecommended), remove if not neccessary
    // "capabilities": ["script_eval"],
    "dependencies": [
        {
            // Enables the use of @minecraft/server module, with a version of 2.0.0 (the latest stable version available).
            "module_name": "@minecraft/server",
            "version": "2.0.0"
        }
    ]
}
#

Use this

thorn flicker
#

my bad

sly valve
#

No worries

#

Make sure your main/core file is named main.js

thorn flicker
#

latest stable is 2.1.0

sly valve
#

And remove the capability

#

script_eval

sly valve
#

For anything else please ask Void, I gotta go

summer path
#

Cya

cursive fog
summer path
#
{
  "format_version": 2,
  "header": {
    "name": "Bedrock Add-ons",
    "description": "Script API Template",
    "uuid": "20c744da-6f9f-8f0d-f212-a96ed88a5eb8",
    "version": [1, 0, 0],
    "min_engine_version": [1, 21, 90]
  },
  "modules": [
    {
      "uuid": "cb6f1da2-40be-9411-bd3c-08c1395ba634",
      "version": [1, 0, 0],
      "type": "script",
      "language": "javascript",
      "entry": "scripts/main.js"
    }
  ],
  "dependencies": [
    {
      "module_name": "@minecraft/server",
      "version": "2.1.0"
    }
  ]
}

this?

thorn flicker
summer path
#

dyk how i can see if it loaded?

#

i got no 1 to test w/ rn

thorn flicker
#

you'll have to wait until you can test because im busy, it seems good though.

sly valve
#

-# you need to re-add the addon, because we changed the UUID of it

summer path
#

i didn't

#

same uui

#

should i change it

sly valve
#

But we added things to it

#

So re-add it

summer path
#

is it needed

#

ok

sly valve
#

So it will work properly

#

Gtg now

thorn flicker
#

not sure if version is required

summer path
#

idm

sly valve
#

Never share your UUID, those are used to estimate your location

summer path
#

oh

sly valve
#

Xd just joking

summer path
#

💀

thorn flicker
summer path
#

but like idc

thorn flicker
#

that doesnt make sense

#

lmfao

summer path
#

its not like that they gonna swat me

#
import { world } from "@minecraft/server";


world.sendMessage('hi')
world.afterEvents.entityDie.subscribe(event => {
  const victim = event.deadEntity;
  const attacker = event.damageSource?.damagingEntity;
  
    world.sendMessage(`§c${victimName} §7was killed by §a${attackerName}`);
  });
sly valve
summer path
#

how do i make the hi happen when i join

#

or something

#

so i know it loaded

thorn flicker
sly valve
#

playerJoin or playerSpawn

sly valve
thorn flicker
#

wdym the earth is flat

#

100%

summer path
#

after events or

sly valve
#

Finally someone who is awake too

thorn flicker
sly valve
thorn flicker
#

world.afterEvents.playerSpawn

#

there's a property to check if the player has spawned by joining

sly valve
#

initialSpawn ig

thorn flicker
summer path
#
import { world } from "@minecraft/server";


world.afterEvents.playerSpawn.subscribe(event => {
  world.sendMessage('test')
})
world.afterEvents.entityDie.subscribe(event => {
  const victim = event.deadEntity;
  const attacker = event.damageSource?.damagingEntity;
  
    world.sendMessage(`§c${victimName} §7was killed by §a${attackerName}`);
  });
sly valve
#

Yes

thorn flicker
#

check for the initialspawn property

sly valve
#

That will now tell the whole world "test"

summer path
#

can this just be because i'm on linux

thorn flicker
#
if (event.initialSpawn) { world.sendMessage('test') }
sly valve
#

If someone differently joins, youll see it

summer path
#

and i cant get anyone to

#

let me check if it shjows on lan

sly valve
#

You could make it delayed

thorn flicker
sly valve
#

Load FASTER

#

But we are pros ✓
It will work, no need to test it

summer path
#

is there a chat event to test it?

thorn flicker
#

you have to find a way to check if the player is loaded in or not

#

or delay the message

sly valve
summer path
#

i DONT know js

sly valve
#

Learn it

thorn flicker
#

you should learn js then, kinda useful

#

ngl

sly valve
sly valve
summer path
sly valve
#

Hmmm

#

Depends

summer path
#

10 i g

thorn flicker
#

heres the thing everyone has different loading times.

summer path
#

is this ticks

sly valve
#

So...

#

Lets make it more advanced

#

After the join wait untill the player pressed any button

#

And then send the message

summer path
#

tbh i think this is all because the addon isnt loaded or some silly thing

thorn flicker
#

eh

#

there has to be a better way.

sly valve
thorn flicker
#

yes...

#

ive used an addon recently that has done this

sly valve
#

iie void-san... iie

summer path
#

let me copy some old code

sly valve
#

CTRL C and V my beloved

#

But gtg frl now

#

Cya

summer path
#
  const { message, sender } = ev;
  const [cmd, ...args] = message.split(' ');

  if (sender.hasTag('muted')) {
    ev.cancel = true;
    return sender.sendMessage('§cYou are muted and cannot chat!');
  }

  if (cmd.startsWith('!')) {
    ev.cancel = true;
    
    const findPlayer = name => world.getAllPlayers().find(p => p.name.toLowerCase() === name?.toLowerCase());
    
    if (!sender.hasTag('admin')) return sender.sendMessage('§cError: You don\'t have permission!');

    const target = args[0] ? findPlayer(args[0]) : sender;
    if (!target && args[0]) return sender.sendMessage('§cPlayer not found!');
    
    const reason = args.slice(1).join(' ') || 'No reason specified';
    
    switch (cmd) {
      case '!warn':
        target.sendMessage(`§cYou've been warned. Reason: ${reason}`);
        break;
      case '!mute':
        target.addTag('muted');
        target.sendMessage(`§cYou've been muted. Reason: ${reason}`);
        break;
      case '!unmute':
        target.removeTag('muted');
        target.sendMessage('§aYou\'ve been unmuted.');
        break;
    }
  }
});```
#

found ts

#

Ok it's 100% nto loaded

#

onthing works

summer path
#

@thorn flicker YAY

floral timber
# cursive fog Yup this should *work*

dont cry now, here.

import { world, system } from "@minecraft/server"

const TARGET_ITEM = "vdg:coltwalker"  // target item ID
const DAMAGE_PER_USE = 1    // durability consumed per use
const TIME_DELAY = 1

const store = new Map()

world.afterEvents.itemStartUse.subscribe(ev => {
    const { source: player, itemStack } = ev
    if (itemStack.typeId !== TARGET_ITEM) return
    if (store.get(player.id)) return

    const id = system.runInterval(() => {
        player.runCommand('function coltwalker/empty')
    }, TIME_DELAY * 20)
    store.set(player.id, id)
});

world.afterEvents.itemStopUse.subscribe(({ source: player, itemStack: item }) => {
    const id = store.get(player.id)
    if (!id) return
    const dur = item.getComponent("minecraft:durability")
    dur.damage += DAMAGE_PER_USE
    player.getComponent("minecraft:inventory").container.setItem(player.selectedSlotIndex, item)
    system.clearRun(id)
    store.delete(player.id)
})

thorn flicker
#

🥣

cursive fog
#

I cant get used to this💔

floral timber
cursive fog
#

But alr ill take it❤️

thorn flicker
#

lol

summer path
#

@thorn flicker Is there an autocomplete

thorn flicker
#

you can install npms to get autocompletions

summer path
#

Yes

#

world.beforeEvents.chatSend.subscribe(ev => {
  const { message, sender } = ev;

  if (message === '!spawn') {
    ev.cancel = true;

    sender.runCommandAsync('tp @s 0 100 0');
    sender.sendMessage('§aTeleported to spawn.');
  }
});
#

help someone fr

floral timber
#

dont use AI if you dont know what you are doing

summer path
#

OK

#

thats true but idk docxs

thorn flicker
#

-# dont use ai period

summer path
#

i dont know how to get autocomplete

#

idk what im doign

floral timber
#

for starters, change runCommandAsync to runCommand

#

it got depreciated a long while ago

summer path
#

ok did that

#

the event still doesnt cancel tho

deep quiver
summer path
#

ok

#

ohi dont even have node

#

Ok i got it

#

but how do i actually get chat messages

floral timber
#

it should work, are you using beta module?

summer path
#
{
  "format_version": 2,
  "header": {
    "name": "Bedrock Add-ons",
    "description": "Script API Template",
    "uuid": "6c2285a9-e037-476d-935e-59bfa8f264df",
    "version": [1, 0, 0],
    "min_engine_version": [1, 21, 90]
  },
  "modules": [
    {
      "uuid": "ddee3837-c6f7-4fb7-98be-0895b1dadb05",
      "version": [1, 0, 0],
      "type": "script",
      "language": "javascript",
      "entry": "scripts/main.js"
    }
  ],
  "dependencies": [
    {
      "module_name": "@minecraft/server",
      "version": "2.1.0"
    }
  ]
}
#

thats my json

floral timber
#

chat event's only in beta

summer path
#

how do i get beta then?

floral timber
#

fr?

thorn flicker
floral timber
wheat condor
#

2.3.0*

thorn flicker
#

oops

summer path
#
  "dependencies": [
    {
      "module_name": "@minecraft/server",
      "version": "2.3.0-beta"
    }
  ]
}
#
import { world } from "@minecraft/server";

world.beforeEvents.chatSend.subscribe(ev => {
  const { message, sender } = ev;

  if (message === '!spawn') {
    ev.cancel = true;

    sender.runCommand('tp @s 0 100 0');
    sender.sendMessage('§aTeleported to spawn.');
  }
});
#

[Scripting][verbose]-Plugin [Bedrock Add-ons] - promoted [@minecraft/server] from [2.1.0] to [2.2.0] requested by [Bedrock Add-ons - 1.0.0].

[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined    at <anonymous> (main.js:3)


[Scripting][error]-Plugin [Bedrock Add-ons - 1.0.0] - [main.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined    at <anonymous> (main.js:3)
]

dawn zealot
#
system.run(() => {
    beforeEvents.asyncPlayerJoin.subscribe(async (data) => {
        console.warn("test", data.persistentId)
        const name = data.name
        const pfid = data.persistentId; // This is the PlayFab ID
        const map = JSON.parse(world.getDynamicProperty('pending_pfids') ?? '{}');
        map[name] = pfid;
        world.setDynamicProperty('pending_pfids', JSON.stringify(map));

        return Promise.resolve();
    });
})
```Anyone know why this isnt working? it wont even log the data.persistentId, however its working in other packs im lost rn
thorn flicker
#

what the hell

dawn zealot
#

?

floral timber
#

where is beforeEvents defined?

dawn zealot
thorn flicker
#

ohhh

summer path
#

guys help me

dawn zealot
summer path
#

how do i

#

when was it added

dawn zealot
#

awhile ago

#
import { system, CommandPermissionLevel } from "@minecraft/server";

system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
    // Register the custom command
    customCommandRegistry.registerCommand(
        {
            name: "lab:home",
            description: "Create a home.",
            permissionLevel: CommandPermissionLevel.Any,
            mandatoryParameters: [
            ],
        },
        (origin) => {
            system.runTimeout(() => {
                create_waypoint(origin.sourceEntity)
            })
        });
});
summer path
#

bru..

thorn flicker
#

its in stable too

#

unlike chatsend

dawn zealot
#

😭

#

chatSend is too far gone atp

summer path
#

yoo

#

ok

#

worked

dawn zealot
# summer path

yk instead of sending us the error you could read it and fix it 😭

summer path
#

true

#

i had to reload all

#

i'm just a noob fr

dawn zealot
#

yeah

#

reload all for taht stuff

#

anything for custom components

thorn flicker
#

just the registration stuff.

summer path
#

now i have to figure out how to give someone a random kit when they die..

#

w/ random enchants

#

i'm SO cooked

#

idek how to get death

thorn flicker
#

not if you learn javascript and then the api

summer path
#

is there some simple kit system i can copy from

thorn flicker
#

whats the point being here if you dont want to learn

dawn zealot
thorn flicker
summer path
#

like too lazy

#

maybe /replace item but how would i enchant it

thorn flicker
#

too lazy

#

whats the point getting into this then

summer path
#

idk

floral timber
sly valve
thorn flicker
#

he knows now

sly valve
sly valve
midnight ridge
#

is there a way to feed animals without interacting with them just by using script api?

thorn flicker
#

you can get the tameable component on entities

midnight ridge
thorn flicker
#

you cant get the breedable component though

midnight ridge
thorn flicker
midnight ridge
midnight ridge
thorn flicker
midnight ridge
midnight ridge
tidal wasp
#

how would i take 1 item from the player's mainhand and replace it with another item?

restive light
# restive light
poll_question_text

What type of programming do you use for scripting?

victor_answer_votes

7

total_votes

13

victor_answer_id

2

victor_answer_text

OOP

sharp elbow
#

It is good to know and be able to apply both patterns.

untold magnet
#

detecting the potion type is still beta right?

sharp elbow
#
interface MyObject {
  a: number;
  b: number;
}

const myObjectProto = {
  sum(this: MyObject) {
    return this.a + this.b;
  }
}
const myObject: MyObject & typeof myObjectProto = Object.create(myObjectProto, {
  a: 1,
  b: 2
});

myObject.sum() // returns 3
dusky flicker
#

hadnt see it yet

dusky flicker
#

by the way @slow walrus what chars exactly the id of a scriptevent doesnt handle?

#

im testing with some arbitrary numbers and it's working

#

seems to be sending and receiving the bytes correctly

#

on the id

#
import { system, System, world } from "@minecraft/server";



world.afterEvents.playerButtonInput.subscribe(ev => {


    const buffer = new ArrayBuffer(128);
    const view = new DataView(buffer);
    for (let i = 0; i < 64; i++) view.setUint16(i * 2, Math.random() * 0xffff, true);
    for (let i = 0; i < 128; i++) if (view.getUint8(i) == 0) view.setUint8(i, 1);
    const arr = new Uint16Array(buffer);
    const id = String.fromCharCode(...arr);
    console.warn("Sending this shit\n", arr);
    system.sendScriptEvent("test:" + id, '');
})```
the sender one

```ts
import {system} from "@minecraft/server";

system.afterEvents.scriptEventReceive.subscribe(e => {
  const splitted = e.id.split(':')[1];
  const arr = new Uint16Array(splitted.length);
  for(let i = 0, j = splitted.length; i < j; i++) {
    arr[i] = splitted.charCodeAt(i);
  }
  console.warn('Received\n', arr);  
  
});```
#

the receiver one

#

just made to console the id instead

#

it seems that as long as the chars are not control ones, its safe

#

well, actually only bytes 10 and 13 are causing troubles

#

only, 0, 10 and 13

#

i aint got idea of why the fuck 10 and 13 cannot be sent on the ID

#

anyways, anything that isnt these 3 work. Using something like base32767 would be enough probably

#

10 is line feed and 13 is cariage return

#

i thing that might be the problem

#

yeah, \n and \r are the only problems

slow walrus
#

what the helly

dusky flicker
#

i tested with base32768, no problems at all to send bytes

slow walrus
#

bruh

#

ig navi changed that as well without telling me

dusky flicker
#

just by avoiding 0xA and 0xD and obviously 0x0 can be enough

sly valve
#

Is it good?

sharp elbow
#

It's all right. I have yet to build anything big using that pattern, mostly because TypeScript is really pissy about typings and prototype chains.

#

TS would much rather you use classes.

dusky flicker
#

im almost switching to f# due to the lunatic type system ts has

#

and because f# is purely functional and transpiles to js

#

so it would be pretty fun to learn more abort really FP languages

stray marsh
#

Dang 99999 msgs

simple zodiac
viral wigeon
#

hey i left scripting api for a while

#

does someone know if typescript is supported natively now?

#

or still have to compile

vast grove
#

Still have to compile

#

Getting MC to natively support TS won't happen.

#

Since TS is it's own thing...

viral wigeon
#

?

#

ts is literally just a superset of javascript

#

ts is javascript but with better typings

#

it shouldn't be that hard to implement

#

idk why they haven't done it yet

dusky flicker
#

its hard as fuck

#

and that isnt Mojang job to create a language for us

#

anyways, one of the reasons why its hard is because js works focusing on the duck typing and being fully dynamic

#

if making it run ts natively, it woukd have to be another runtime than js

#

actually ts hasn't a real runtime anywhere you find

#

node, bun and deno internally build the ts code to js and then run it

#

ts is just a language that transpiles, it doesn't have its own runtime

dusky flicker
#

i think the harder would be to implement new optimizations and male the runtime

gaunt salmonBOT
floral timber
remote oyster
# viral wigeon idk why they haven't done it yet

Because TypeScript isn’t something you run directly, it’s a language that gets transpiled (converted) to JavaScript before execution. The Minecraft Bedrock engine only runs JavaScript at runtime, so there’s no real benefit in adding native TypeScript support. Running TypeScript directly would require embedding a compiler or interpreter in the engine, which would be less efficient and add unnecessary complexity. That’s why it’s not implemented, and likely never will be.

honest spear
#

Such a good time reading it

#

Also i want to say the TS is not just superset as it contains things like Enums that are not JS feature at all so it requires transformation steps and thats already part of the compiler, its not just that you can drop types bao_ext_toldyouso

round bone
fickle dagger
#

is it possible to change the filepath of a particle texture using js?

prisma shard
fickle dagger
#

aw damn, guess that leaves me with the other method of using offset on texture uv

#

atleast that's possible, right?

prisma shard
#

huh

#

idk

fickle dagger
#

gotta find out myself

#

or maybe docs has anything about it

#

actually yeah it's possible

prisma shard
#

that could be texture editor

#

and just moving the uv possible

fickle dagger
# prisma shard how

using variables on the particles, even if we can't set the offset directly, it should be possible to offset by multiplying the values of it
example :

x = 16
y = 16 * v.uvOffset```
prisma shard
#

interesting

#

men I know nothing about Particles

#

someone teach me

fickle dagger
#

it's like an entity that's also not an entity

#

and it can store variables inside

distant tulip
fickle dagger
prisma shard
#

What would be a good offset value for setting camera to third person over shoulder of player?

#

Like a bit up and right over shoulder

round bone
prisma shard
#

oh yes

#

external js script

elder spindle
#

Do I have to pre-register a dynamic property or can I just set a value to one and it will automatically register?

prisma shard
#

How do i get variable list for vanilla particles?

#
world.getDimension("overworld").spawnParticle("minecraft:note_particle", loc, new MolangVariableMap().setColorRGB("variable.note_color", { red: Math.random(), green: Math.random(), blue: Math.random() }));```
#

For example this code, How does one get that "variable.note_color" exists?

open urchin
prisma shard
#

Thank you

prisma shard
#

Why does the particle look black when I set RGB values?

#
system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        world.getDimension("overworld")
            .spawnParticle(
                "minecraft:note_particle",
                { x: player.location.x, y: player.location.y + 2, z: player.location.z },
                new MolangVariableMap().
                    setColorRGB("variable.note_color",
                        {
                            red: 1,
                            green: 0,
                            blue: 0
                        }));
    }
})```
#

my code

#

The particles look black instead of red :/

jolly citrus
#

does bds script api have the ability to intercept entity name tag related packets yet

#

last time i checked was like a year ago and based on what packet events it could listen to back then there wasn’t an ability to do so

open urchin
# prisma shard ```js system.runInterval(() => { for (const player of world.getAllPlayers())...

you're setting the third argument of spawnParticle to the result of setColorRGB which is undefined
you should be setting it to the MolangVariableMap

const variables = new MolangVariableMap();
variables.setColorRGB("variable.note_color", {
    red: 1,
    green: 0,
    blue: 0
});


spawnParticle(
    "minecraft:note_particle",
    { x: player.location.x, y: player.location.y + 2, z: player.location.z },
    variables
);

btw getting all players and the overworld dimension every time the interval runs is unnecessary and could cause lag

jolly citrus
#

i’d hope the list’s been updated since

drifting ravenBOT
#
What format version should I use?

"format_version" tells the Minecraft API which version of the add-on system to use for a specific file. It's sadly not as simple as matching the game version however, since some systems are not updated very frequently. You may have to use an old format version with them!

You can read more about format versions here: https://wiki.bedrock.dev/guide/format-version.html

elder spindle
#

I have a custom command, however its showing two versions of the same command. Is there anyway to hide the one with a prefix?

import { world, system, CommandPermissionLevel, CustomCommandStatus} from "@minecraft/server";

system.beforeEvents.startup.subscribe(init => {
    const rankUpCommand = {
        name: "up:rankup",
        description: "Rank Up",
        permissionLevel: CommandPermissionLevel.Any
    };
    init.customCommandRegistry.registerCommand(rankUpCommand, rankUp);
});

function rankUp(origin, entities) {
    world.sendMessage("Rank Up!");
    return {
        status: CustomCommandStatus.Success
    };
}
prisma shard
#
system.runInterval(() => {
    for (const player of world.getAllPlayers()) {

        const dim = player.dimension;

        const variables = new MolangVariableMap();
        variables.setColorRGB("variable.note_color", {
            red: Math.random(),
            green: Math.random(),
            blue: Math.random()
        });

        dim.spawnParticle(
            "minecraft:note_particle",
            { x: player.location.x, y: player.location.y + 2, z: player.location.z },
            variables
        );
    }
})

And yeah i knew about calling the overworld dimension everytime

#

What does setVector3 do? does that set the particle's location? but don't we determine particle's location already when we spawn it?

sharp elbow
#

Read the comment provided to it. It says it stores the components of the vector to a struct of the given name

#

Something like this IIRC:

variables.setVector3("variable.foo", {x:1, y: 2, z: 3});
// variable.foo.x = 1
// variable.foo.y = 2
// variable.foo.z = 3
kind zenith
#

it is possible to get light level by entity with api?

prisma shard
drowsy scaffold
#

how do I make new potions

#

with newest API version

prisma shard
#

Also uh can anyone send me a full Form template? I have never touched UI stuff, So i want to do tinkering with it.

prisma shard
elder spindle
#

Eeek, okay. I guess I just gotta hope and prey that they allow us to do it in the future

round bone
round bone
drowsy scaffold
#
Potions.resolve(new PotionEffectType(`instant_healing`), new PotionDeliveryType())

How do use this to make potions? can I even get documentation for these?

drowsy scaffold
#

they changed the signature for making potions and it's weird because you would think both of those would be enums but they're classes

honest spear
#

Try looking for something like EffectTypes.get()

#

or something like that

shut citrus
#

minecraft bedrock as usual

lethal bramble
#

is there a way to synchronously run jobs? for example

system.runJob(job1)
system.runJob(job2)

I want to run job2 after job1 has finished. is there a way to achieve this?

sudden verge
lethal bramble
sudden verge
#

i think theres a way to see if a job is still running or not

#

i dont entirely remember tho

lethal bramble
#

it only returns a number for clearing the job

sudden verge
#

but if you can do that, then in job2 check if the job1 has finished or not each tick then only really start once it has

prisma shard
#

Use my code
Using this class, you can manage runJobs easily

prisma shard
lethal bramble
#

because this seems useful

shut citrus
#

What different between runjob, async/await and promise?

lethal bramble
# shut citrus What different between runjob, async/await and promise?

system.runJob is specific to the Minecraft Scripting API, and queues a generator to be run whenever free time is available each tick.

However, a Promise is a ECMAScript feature that returns a value, but not always instantly. it is basically what an asynchronous function returns.

lethal bramble
#

thats not ai

prisma shard
distant tulip
#

uh, that's not how that work

hybrid bobcat
#

Is it normal that when using spawnEntity the entity despawns instantly when I move away only 16 blocks?

hybrid bobcat
hybrid bobcat
shy leaf
#

nope, sorry

hybrid bobcat
#

alr ty

distant tulip
#

how do one use setCameraWithEase if it doesn't have rotation and location properties?

distant tulip
#

nvm

edgy elm
#

does anyone knows how to fix this error? I am using the QIDB https://discord.com/channels/523663022053392405/1252014916496527380 but this gives me error

[Scripting][inform]-§aQIDB > Set key PlayerShop:Plund_mgeyo28y succesfully. 2ms §r10/06/2025, 10:01:23.556 AM

[Scripting][inform]-§eQIDB > Saving, Dont close the world.
§r[Stats]-§eRemaining: 1 keys | speed: NaN keys/s §r10/06/2025, 10:01:23.726 AM

[Scripting][inform]-1

[Scripting][error]-Unhandled promise rejection: InvalidArgumentError: Invalid value passed to argument [0]. 'qidb:storage' is not a valid entity type. at #load (db/QIDB.js:167)
at #romSave (db/QIDB.js:204)
at <anonymous> (db/QIDB.js:110)

[Scripting][inform]-§aQIDB >Saved, You can now close the world safely. §r10/06/2025, 10:01:23.745 AM

prisma shard
#

current commpilers use AI to compile js to ts

distant tulip
#

that's not compiling

prisma shard
#

converting?

distant tulip
#

yes

deep quiver
#

Transpiling

slow walrus
tidal wasp
#

Does anyone know how to use custom parameters in custom components

thorn flicker
#
system.beforeEvents.startup.subscribe(({ itemComponentRegistry: icr }) => {
    icr.registerCustomComponent('custom:component', {

        onUse(data, { params }) {
           world.sendMessage(`${params.test}`)
        }

    })
})
{
    "format_version": "1.21.100",
    "minecraft:item": {
        "description": {
            "identifier": "minecraft:item"
        },
        "components": {
            "custom:component": {
                "test": 0
            }
        }
    }
}
tidal wasp
thorn flicker
#

yeah

rapid sail
#

so how does getRedstonePower work?

#

wait nvm...

elder spindle
#

Can forms show after the result of a command?

dusky flicker
#

i've already built compilers and transpilers, they dont and wont use ai

midnight ridge
#

In @minecraft/server API 2.2.3-beta, worldLoad doesn’t give access to blockComponentRegistry. What event should I use to register custom block components?

true isle
#

Yeah its set to increase speed even if the speed isnt qhats defined lol youll havw to have something to trigfer the speed decreing

lethal bramble
magic peak
#

hello @magic peak here

#

sorry i haven’t been active recently i’ve been moderating my own discord server

#

but it was nuked by some bad people

verbal aurora
#

Why is installing npm package so bitchy now?

wary edge
#

Always had been.

verbal aurora
#

It lets me install server but then bitches at me with errors for server ui

#

Only time I've ever not had this issue is with using bun

#

Had to use --force to get around it

round bone
magic peak
#

npm audit

#

npm force

dusky flicker
#

or something like it

#

i use bun so in generap i dont see these problems

gusty bramble
#

Can someone please help me make a simple script that detects if a Minecart “dies” and if so say a message in chat. For the life of me I can’t get it to work….

#

I’ve tried almost everything I can think of including just detecting when the item spawns… but no matter what I can’t make it work

gusty bramble
#
import { world, system } from "@minecraft/server";

const triggeredItems = new Set();

world.afterEvents.entitySpawn.subscribe(ev => {
  const entity = ev.entity;
  if (!entity) return;

  if (entity.typeId !== "minecraft:item") return;

  const itemComp = entity.getComponent("minecraft:item");
  if (!itemComp || !itemComp.itemStack) return;

  if (itemComp.itemStack.typeId !== "minecraft:minecart") return;

  if (triggeredItems.has(entity.id)) return;
  triggeredItems.add(entity.id);

  const loc = entity.location ?? { x: 0, y: 0, z: 0 };
  const dim = entity.dimension;
  if (!dim) return;

  dim.runCommandAsync(`say Minecart item spawned at ${loc.x.toFixed(1)} ${loc.y.toFixed(1)} ${loc.z.toFixed(1)}`);

  system.runTimeout(() => triggeredItems.delete(entity.id), 20 * 10);
});```

That’s the item based one..
prisma shard
#

use entityDie event?

prisma shard
#

use runCommand

gaunt salmonBOT
prisma shard
#

Lol i didnt have typings installed for UI module and i was like why isnt typings showing

gusty bramble
# prisma shard use entityDie event?

I tried that and nothing happened. My only guess would be Minecarts don’t really “die”? Idk I also considered just tracking if the UUID exists and when it doesn’t it died but that seemed cringe

prisma shard
#

Hm makes sense why would minecart die

#

why dont you check if it is alive/valid

#

and when it is not valid anymore, You can detect that it was removed

#

entity.isValid

verbal aurora
#

Sorry not at pc rn so couldn’t send anything

distant tulip
#

What was the error

shut citrus
prisma shard
prisma shard
final ocean
#

How to create a backpack (no ui and use dynamic property), if you mine a block it will automatically put items in the backpack.

warped kelp
#

Good evening, I'm using a command to detect entities several blocks higher than the player/entity but it seems to be a bit inefficient. Is there anyway I could use scripts to make it easier?

Command in quesiton:
/execute if entity @e[type=!player] at @e[type=!player,dy=3] run tp @s ~~3~

It's very simple using dy to detect a different entity's Y level to run a command/function

dusky flicker
# prisma shard a

probably uses "ai" for propaganda, or this one really does use ai because doesn't know how to write a transpiler

#

but the normal process is to write all the frontend by hand

#

frontend i mean text relates stuff, the syntax and grammar

granite badger
#

A GitHub copilot in disguise

slim forum
#
const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
#

I couldn't stand my ADHD confusing me with Math.max and Math.min anymore, so I created this globally

#

(There is no Math.clamp in javascript for some reason)

shy leaf
#
function clampNumber(val, min, max) {
  return Math.min(Math.max(val, min), max);
}
#

tho its basically the same as what youre using

distant tulip
#

lol, i allways keep doing Math.clamp, Math.round

shy leaf
#

oh

#

not that math module...

slim forum
#

I don't think it exists, it doesn't even appear in autocomplete

shy leaf
#

i meant minecraft math module

slim forum
#

Yes, I use it in json

slim forum
#

But in JavaScript apparently there is no such thing

shy leaf
#

its only available in npm