#Script API General

1 messages · Page 32 of 1

idle dagger
#

How to search entities instead of players? Like that?

const target = [...world.getEntites()].find(e => e.hasTag(`stand`))
random flint
#

dimension.getEntities

dim tusk
warm mason
random flint
#
world.getEntities = function (option=null) {
    return [
        ...world.getDimension("overworld").getEntities(option),
        ...world.getDimension("nether").getEntities(option),
        ...world.getDimension("the_end").getEntities(option)
    ]
}
warm mason
#

What do these dots mean?

random flint
#

if u didnt use the dot it'll become a nested array (array in array)

dim tusk
warm mason
#
[...[1,2,3], ...[4,5,6]] = [1,2,3,4,5,6]
``` ?
random flint
#

yes

distant gulch
#

does it uses the symbol.iterableIterator?

#

ohh thats okay

random flint
#

Deleted cus I'm not sure either :P

distant gulch
#

hmm dw

random flint
distant gulch
idle dagger
#

How to make mobs to not attack players without changing difficulty?

random flint
idle dagger
random flint
#

google search

#

any github repository or smt

idle dagger
crude flame
#

how do i spawn a mob, which is a baby?

#

or like spawn mobs with components

thorn flicker
#

to find that, look in their files.

crude flame
#

is it like possible to "clone" a mob, with all their components

thorn flicker
#

for sheep, there's an event called spawn_baby

crude flame
thorn flicker
#

there's no official method to clone mobs yet

crude flame
#

and to "copy" components to another mob?

thorn flicker
#

no

crude flame
#

ok

crude flame
#

i want to make a wand that turns every mob in a range into a baby, but the problem is, that the mobs have different baby events. Is there a solution to this

grim raft
#

yo

#

wanna know how to make code colored when I send it in discord

distant tulip
distant tulip
dull shell
#

whats the best way to start to learn this

#

microsoft docs?

drifting ravenBOT
#
Learn JavaScript

As the Script API is a framework built on JavaScript code, having an understanding of JavaScript is key.

If you are being shown this, then you most likely are a beginner with JS and could use a little guidance.

Videos on Learning JavaScript
Javascript in 1 hour
Javascript Classes in 1 hour

Web Guide:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

Reference Sites:
https://www.w3schools.com/jsref/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://javascript.info

wary edge
dull shell
#

Thank you!

thorn spindle
#

Hey anyone know how I can save the player inv even when player disconnect?
const inventory = player.getComponent('minecraft:inventory').container;
With this method once the player disconnects the variable gets erased

idle dagger
# thorn spindle Hey anyone know how I can save the player inv even when player disconnect? const...
let cache = {}

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
            let items = []
            for (let i = 0; i < 36; i++) {
                const item = player.getComponent("inventory").container.getItem(i)
                if (item) { items.push(item) }
            }
            for (const equipment of ["Offhand", "Head", "Chest", "Legs", "Feet"]) {
                const item = player.getComponent("equippable").getEquipment(equipment)
                if (item) { items.push(item) }
            }
            cache[player.name] = items
           if (!item) return cache[player.name] === undefined;
        }
});

world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
    if (!initialSpawn) return;
    for (const item of cache[name]) {
            dimension.spawnItem(item, location)
        }
});
idle dagger
thorn spindle
#

But the problem is the saving in the world

craggy stratus
#

world.sendMessage(`§4${attacker.nameTag , "killed The Ender Dragon"}`);
whats the proper formatting for a sendMessage command like this?

thorn spindle
#

Alright sure, thanks!

slow walrus
#

itemstacks aren't entirely serializable so you'll lose nbt data if you do it this way

#

you could copy all the items to a storage entity and then save it in a structure though

distant gulch
#

🧐

distant gulch
slow walrus
#

wdym?

distant gulch
#

What data in an Itemstack cannot be serialized

slow walrus
#

a lot of it

#

technically none of the itemstack can be serialized in place

#

you gotta first get the typeid, enchants, lore, nametag etc

#

and then serialize those

#

and then make a new itemstack and set those

remote oyster
#

Rough draft @thorn spindle

import { world } from '@minecraft/server';

world.beforeEvents.playerLeave.subscribe((event) => {
    const player = event.player;

    let inventoryData = {};
    const inventoryContainer = player.getComponent('inventory').container;
    const inventorySize = inventoryContainer.size;

    for (let index = 0; index < inventorySize; index++) {
        const item = inventoryContainer.getItem(index);
        if (!item) continue;

        let itemData = {
            typeId: item.typeId,
            count: item.amount,
            lore: [],
            enchantments: []
        };

        // Get item lore (if any)
        const lore = item.getLore();
        if (lore.length > 0) {
            itemData.lore = lore;
        }

        // Get enchantments (if any)
        const enchantmentsComponent = item.getComponent('enchantments');
        if (enchantmentsComponent) {
            const enchantments = enchantmentsComponent.getEnchantments();
            if (enchantments.length > 0) {
                itemData.enchantments = enchantments.map((enchantment) => ({
                    id: enchantment.type.id,
                    level: enchantment.level
                }));
            }
        }

        // Get custom name tag (if any)
        const nameTag = item.nameTag;
        if (nameTag) {
            itemData.customName = nameTag;
        }

        // Store the item data in the inventoryData object
        inventoryData[`item_${index}`] = itemData;
    }

    // Serialize and save the inventory data
    let serializedInventory = JSON.stringify(inventoryData);
    world.setDynamicProperty(`savedInventory_${player.id}`, serializedInventory);

    console.log(`Saved inventory data for ${player.name} (ID: ${player.id}) to the world.`);
});
glacial widget
#

Does anyone know how to set armor from a chest into your equipment slot(armor slot)

distant gulch
quick shoal
#

Who can help me fix this error

#

I so confuse of this

distant tulip
warm mason
#

debugger is wrong

quick shoal
#

Oh

#

God I trapped by it for a long time

buoyant canopy
#

FINALLY!

past blaze
buoyant canopy
#

we no longer need laggy 3D nested loops to search for blocks

sage portal
#

is there a stable way to remove tags from a player that is disconnecting from the world?

winter plaza
#

How do I execute a command when I break a stone block?

warm mason
winter plaza
#

Thanks

#

api 1.13.0

warm mason
#

hmmm...

#

Not sure if it will work there

winter plaza
#

ok

scarlet lynx
#

How do I store player data as world? So I can edit/retrive it offline?

#

In dynamic propertys opfc

#

ofc*

granite badger
fading sand
#

How do i run an command when an player named "ID" joins the server?
Also how do i check if an player kicks an other player?

valid ice
#

player spawn event for the first one

#

Second one- player leave, although you can’t find if they were kicked or just left on their own

fading sand
valid ice
#

There sure ain't

terse pulsar
#

Why the tag don't assing?

#
export function showForm(player) {
  let filiationForm = new MessageFormData();
  filiationForm.title("§l§0Choose Your Filiation");
  filiationForm.body("Wich side you gonna get in? there are two options, the marine(honor) and   the pirate(bounty), you can change it");
  filiationForm.button1("§l§9Marine");
  filiationForm.button2("§l§cPirate");

  filiationForm.show(player).then(r => {
    if (r.canceled) {
      system.runTimeout((() => showForm(player)), 10)
    } else {
      world.sendMessage("Welcome to §lBlock Fruits server§r, you selected " + (["§l§9Marine", "§l§cPirate"][r.selection]));
      if (r.selection === 0) {
        world.getEntity(playerId).addTag("marine")
      } else {
        world.getEntity(playerId).addTag("pirate")
      }
    }
  })
}

world.afterEvents.playerSpawn.subscribe(eventData => {
  if (eventData.initialSpawn) showForm(eventData.player)
})
#

The error:

#
[Scripting][error]-Unhandled promise rejection: InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: string

valid ice
#

What is playerId

#

And you can just do player.addTag(), you don't have to do world.getEntity()

valid ice
#

No worries

winter plaza
# warm mason ```js let commandList = ["say test", "say test2"] world.beforeEvents.playerBre...
world.beforeEvents.playerBreakBlock.subscribe(data => {
  let player = data.player;
  let block = data.block;
  if (block.typeId == "minecraft:oak_log" && isHoldingAxe(player, "minecraft:axe")) {
    breakTree(block);
    player.runCommand("say 1");
  }
  if (block.typeId == "oak_log" && isHoldingAxe(player, "minecraft:axe")) {
    breakTree(block);
    player.runCommand("say 2");
  }
  if (block.typeId == "minecraft:oak_log" && isHoldingAxe(player, "axe")) {
    breakTree(block);
    player.runCommand("say 3");
  }
  if (block.typeId == "oak_log" && isHoldingAxe(player, "axe")) {
    breakTree(block);
    player.runCommand("say 4");
  }
  if (block.typeId == "minecraft:oak_log" && test(player, "Mainhand", "netherite_axe")) {
    breakTree(block);
    player.runCommand("say 5");
  }
  if (block.typeId == "oak_log" && test(player, "Mainhand", "minecraft:netherite_axe")) {
    breakTree(block);
    player.runCommand("say 6");
  }
  if (block.typeId == "oak_log" && test(player, "Mainhand", "minecraft:netherite_axe")) {
    breakTree(block);
    player.runCommand("say 7");
  }
  if (block.typeId == "minecraft:oak_log" && test(player, "Mainhand", "netherite_axe")) {
    breakTree(block);
    player.runCommand("say 8");
  }
});

export function isHoldingAxe(entity,tag){
    const inventory = entity.getComponent("minecraft:equippable");
    if(inventory.getEquipment("Mainhand") != null){
        const mainhandItemTag = inventory.getEquipment("Mainhand").hasTag(tag);
        return mainhandItemTag;
    }
}

export function test(player,equipmentSlot,itemName){
    const equippableComponent = player.getComponent("minecraft:equippable");
    if(equippableComponent.getEquipment(equipmentSlot)!=undefined){
        return equippableComponent.getEquipment(equipmentSlot).typeId == itemName;
    }else{
        return false;
    }
}
#

I tested it like this and it wasn't any

#

:/

terse pulsar
# valid ice No worries

Same error

[Scripting][error]-Unhandled promise rejection: InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: string

valid ice
#

Would recommend adding a .catch(error => console.warn(error, error.stack)) at the end of your form .show() so you can get the line the error is on

#

like: form.show(…).catch(…

winged gull
#

it is not completely random, it is only pseudo-random.

#

if you want proper color space conversion, I recommend https://www.npmjs.com/package/color-core

glacial widget
#

why does this not work?

world.afterEvents.entitySpawn.subscribe((e) => {
  console.log(`Entity spawned: ${e.entity.typeId}, NameTag: ${e.entity.nameTag}`);
  if (e.entity.typeId !== "minecraft:item") return;
  if (e.entity.nameTag === "§d§lStarter") e.entity.kill();
});
winged gull
#

if you don't want to use a js bundler like ESBuild then here is an already bundled one from one of my add-ons:

glacial widget
#

meant to kill entitys with "§d§lStarter" name

winged gull
glacial widget
winged gull
#

is it giving you any errors

glacial widget
#

none

winged gull
#

are you getting the console log

glacial widget
winged gull
#

and do you have your content log level set to "info" in settings

glacial widget
#

no errors at all

winged gull
#

so it did log it in the console?

glacial widget
#

still nothing

shy leaf
#

check if the entitySpawn event is firing at the first place

winged gull
#

oh wait

#

is it supposed to kill ITEMS with the name

winged gull
#

or

#

other entities

glacial widget
winged gull
#

oh then are you sure the formatting codes are in the EXACT same order on both

winged gull
#

wait so is the

console.log(`Entity spawned: ${e.entity.typeId}, NameTag: ${e.entity.nameTag}`);

function working at least

glacial widget
#
world.afterEvents.entitySpawn.subscribe((ev) =>{
  console.log(`Entity spawned ${ev.entity.typeId}, NameTag: ${ev.entity.nameTag}`);
})
#

this doesn't work like how

#

wait its warn lol

#

now i get a warning but i dont get the "NameTag"

distant gulch
#

Your asking for a double undefined

ev.nameTag```
glacial widget
#

oh

#

this works but doesnt kill the entity

world.afterEvents.entitySpawn.subscribe((ev) =>{

  const entity = ev.entity
  console.warn(`Entity spawned ${ev.entity.typeId}, NameTag: ${ev.entity.nameTag}`);
  if (entity.typeId != "minecraft:item") return;
  if (entity.nameTag === "§d§lStarter") e.entity.kill();
})
distant gulch
#

e is not defined

glacial widget
distant gulch
#

I already told you why your code does not work

dull jungle
#

Quick question, how am I getting large watchdog spikes? All I have in my scripts is a system interval that says test.

#

It happens whenever I join the game.

distant gulch
#

gametest moment

dull jungle
#

...

distant gulch
#

Gametest(Js engine) is dependent on your system if its on a local world. Your computer is probably allocating more resources in loading the world then actually running gametest, leading to a watchdog notification

dull jungle
#

Ah okay, thanks.

shy leaf
dim tusk
#

Guys, is there a way to place a block from an item with it's DATA? We know you could turn blocks in the world into item stack...

dim tusk
random flint
#

Depend on what block

#

shulkerbox? yes

#

Alternatively, simulated players

dim tusk
random flint
dim tusk
random flint
#

I cant find it

#

It's deeply buried

dim tusk
#

Lol

neon thunder
#

I have this code: ```javascript:

let dynamicUI = new ActionFormData()
.title("Select Destination");

        for (let i = 0; i < anarray.length; i++) {
            dynamicUI.button(anarray[i].name);
        }``` but it doesn't work.  How do I do this, dynamically add buttons to a server-ui ActionFormData form?
#

Grr. Why won't it syntax highlight?

#

Ahh opps. my bad 🙂

dim tusk
#

And what's inside of anarray

neon thunder
#

interesting things

#

I have it working now, I wasn't checking something

slow walrus
#

you can do that

neon thunder
#

How many buttons before it bombs out?

#

does it do pages, the ui?

dim tusk
neon thunder
#

ahh you can scroll. awesome

dim tusk
neon thunder
#

Hmm. I;ve decided I don't want to customise the ui json files because it is a potential source of incompatibility with other addons

dim tusk
neon thunder
#

Are the dynamic properties on world loaded when beforeinitialise event is called?

#

Okay, seems not to me

#

oh wait.. doh

remote oyster
dim tusk
#

Guys is the equippable component works on entities now?

remote oyster
dim tusk
dim tusk
#

How do I set item on the main hand if the entity not player... Shii I sound rookie here.

#

Need to get back on js now

hybrid island
#

how do i detect if a arrow hit a mob..

world.afterEvents.entityHitEntity.subscribe((data) => {
    let he = data.hitEntity
    let de = data.damagingEntity
    let det = de.typeId
    let dp = data.damageSource?.damagingProjectile;
    //let owner = dp.getComponent("minecraft:projectile")?.owner;
    if (!de) {
        world.sendMessage(`working`)
    }
})
dim tusk
fading sand
granite badger
#

Why do you wanna see who kicked someone? I thought only the host can do that

dim tusk
granite badger
#

Whoops

dim tusk
#

Anyways, I wanna share something

#

If you know a solution just tell me, so the entityHitBlock function returns the block and source who broke it. When you're in creative it still triggers it but when you want to put the block in a structure the structure is empty because you broke the block so fast it didn't have time to load lmao.,

grim raft
#
function health(Player) {
    const health = new ActionFormData();
    health.body({ "rawtext": [{ "text": "§l\n§r" }, { "text": "§lLevel:§r" }, { "score": { "name": "@s", "objective": "Speed" } }, { "text": "§l\n\n\n\n\n\n\n\n\n\n\n§r" }] })```
Scoreboard not appearing in menu
warm mason
grim raft
#

when opening the menu I want the score speed to show next to level:

warm mason
#

Make sure the name is correct and try * instead of @s

grim raft
#

ok

warm mason
#

if it is called speed, then the menu also needs speed, not Speed

grim raft
#
{ "rawtext": [{ "text": "§l\n§r" }, { "text": "§lLevel:§r" }, { "score": { "name": "*", "objective": "Speed" } }, { "text": "§l\n\n\n\n\n\n\n\n\n\n\n§r" }] }```
#

like this?

warm mason
#

yes

grim raft
#

ok gonna try it

grim raft
warm mason
# grim raft

I suggest then not to bother with rawtext and just write js "Level: " + (world.scoreboard.getObjective("Speed")?.getScore(player) || 0)

grim raft
#

didnt think of that

#

it works now

#

but how do I add space?

#

is it the same as in rawtext?

warm mason
#

\n

grim raft
#

ok

#

I want it after the scoreboard

warm mason
#
"Level: " + (world.scoreboard.getObjective("Speed")?.getScore(player) || 0) + "\n\nText"```
warm mason
#

hmm

grim raft
#

this is why I wanted to use rawtext lol

warm mason
#

It works for me

#

Ahh

#

You put the wrong signs. You need \ and you put /

#

@grim raft

grim raft
#

oh

#

OH

#

MB

round bone
round bone
#

didn't read

quick shoal
grim raft
#

and thats a very good info

quick shoal
#

Okey

grave thistle
#

I'm trying to rename a spawned item with myItemStack.nameTag = { translate: "translation.key" }. However, the item is just called object. Is it not possible to rename items using translation keys?

#

same when typing it as rawText

warm mason
grave thistle
#

ah, what a shame. I'm making more bucketable mobs and have it so the mobs name is retained. I was hoping to have the words "Bucket of" be a translation key followed by the mobs name

somber echo
warm mason
#

There are a lot of bugs with ghosts in Minecraft

#

Sometimes my entities stop being valid for no reason...

distant tulip
cold grove
#

Hey

#

Items (entity) velocity are bugged or something?

#

Like, an known issue?

distant gulch
#

Did PeterGriffin_num1fan just got banned?

dim tusk
#

I called the mods

distant gulch
#

Due his latest messages?

dim tusk
distant gulch
dim tusk
distant gulch
#

you mean oojimayuuki01 ?

dim tusk
distant gulch
#

Someone he mentioned before

dim tusk
#

Anyways let's change the topic admins will delete this

distant gulch
#

Sure my bad

#

How's yall day today

dim tusk
#

Now my ankles are twisted like crazy

distant gulch
#

hah, tell

#

that's shit

#

my day was pretty okay

#

Anyways - if anyone needs help with scripts im open (for less than 5kb)

dim tusk
dim tusk
distant gulch
#

For gods sake

#

idk what to say now

fading sand
neon thunder
#

Heyas.. I'm looking at Container.addItem... What does it return exactly? Does it return the untransferred item or something else?

neon thunder
#

That doesn't tell me what the return values mean. I'm assuming undefined when the item was transferred just like transferItem

subtle cove
#

It returns the untransferred/excess/remains, otherwise undefined/none

neon thunder
#

yep

#

How can I destroy items having only the itemstack?

#

In the PlayerInteractWithEntity afterevent, I'm trying to manipulate the beforeItemStack and itemStack members of the event. It tells me that itemStack is read only. How can I trick it into transferring the items and reducing the counts etc?

neon thunder
#

Dang even in survival mode, its duplicating the items

neon thunder
#

Oh man, even trying to get the equipment slot doesn't give me what I need to do a transferitem

distant gulch
neon thunder
distant gulch
#

?

#
 private constructor();
    /**
     * @remarks
     * The ItemStack before the interaction succeeded, or undefined
     * if hand is empty.
     *
     */
    readonly beforeItemStack?: ItemStack;
    /**
     * @remarks
     * The ItemStack after the interaction succeeded, or undefined
     * if hand is empty.
     *
     */
    readonly itemStack?: ItemStack;
    /**
     * @remarks
     * Source Player for this event.
     *
     */
    readonly player: Player;
    /**
     * @remarks
     * The entity that will be interacted with.
     *
     */
    readonly target: Entity;```
#

The event returns readonly

neon thunder
#

And?

distant gulch
#

If you want to modify it you have to elevate its permissions

neon thunder
#

I need to delete the itemstack entirely

distant gulch
#

You can set it as a empty item stack by setting the amount to 0

neon thunder
#

Doesn't seem to work

#

And the documentation says it must be greater than 0

distant gulch
#
setItem(slot, null)```
#
    /**
     * @remarks
     * Sets an item stack within a particular slot.
     *
     * This function can't be called in read-only mode.
     *
     * @param slot
     * Zero-based index of the slot to set an item at.
     * @param itemStack
     * Stack of items to place within the specified slot. Setting
     * `itemStack` to undefined will clear the slot.
     * @throws
     * Throws if the container is invalid or if the `slot` index is
     * out of bounds.
     */```

``` * `itemStack` to undefined will clear the slot.```
neon thunder
#

yeah but I couldn't find the slot. I eventually got it from the equippable component's getEquipmentSlot("Mainhand")

dim tusk
neon thunder
#

no you wouldn't need system.run I don't think to get the equipment slot for the item and change that

#

The only reason I'm using system.run myself in this event handler is because I'm presenting forms

dim tusk
#

That's all... Nothing else

neon thunder
#

ugh it has nothing to do with anything I'm actually trying to achieve

#
const destcontainer = djinn[formData.selection].getComponent("inventory")?.container;
const remainder = destcontainer.addItem(itemStack);

const equip = player.getComponent("equippable");
const equipslot = equip.getEquipmentSlot("Mainhand");

equipslot.setItem(remainder);``` would be able to be done without system.run I highly suspect
#

why doesn't it syntax highlight??

distant gulch
#

lol what

dim tusk
neon thunder
#

setItem

dim tusk
#

Didn't notice the last one

distant gulch
#

const remainder = destcontainer.addItem(itemStack);
what is up with this?

#
addItem``` does not return anything
neon thunder
#

I have been trying various transfer methods and that's some remanent code

neon thunder
#

No! addItem does return an ItemStack

distant gulch
neon thunder
#

No, less any items that were transferred

distant gulch
#

What?

neon thunder
#

yeah, if they can't be added, they are returned

dim tusk
#

Bro why you always sound angry 😆

distant gulch
neon thunder
#

huh? Sure it does

distant gulch
#
const destcontainer = djinn[formData.selection].getComponent("inventory")?.container;
const remainder = destcontainer.addItem(itemStack);

const equip = player.getComponent("equippable");
const equipslot = equip.getEquipmentSlot("Mainhand");

equipslot.setItem(remainder);```
#

This?

neon thunder
#

yeah?

distant gulch
#

use camel casing, its very hard to read

#
const destContainer = djinn[formData.selection].getComponent("inventory")?.container;
const remainder = destContainer.addItem(itemStack);

const equip = player.getComponent("equippable");
const equipSlot = equip.getEquipmentSlot("Mainhand");

equipSlot.setItem(remainder);```
#

Who is player defined as?

#

Who is equip defined as?

neon thunder
#

From the event

distant gulch
#

What event?

neon thunder
#

PlayerInteractWithEntity before

distant gulch
#

Show me how your setting that up

dim tusk
#
const inventory = player.getComponent('inventory').container;
inventory.addItem(new ItemStack('minecraft:stick', 1));

const equip = player.getComponent('equippable');
equip.setEquipment('Mainhand', new ItemStack('minecraft:stick', 1));```
distant gulch
neon thunder
distant gulch
#

event.cancel = true;

#

Why are we canceling it?

neon thunder
#

so I can present forms instead of showing the entity inventory

dim tusk
distant gulch
#

dont know why anyone would use addItem when you can just scan the inventory for a empty slot and then use setSlot

neon thunder
#

No, it finds one and returns the remainder if it can't find a slot

#

Because I'm "giving" an item to an entity who is then transferring it to another entity

distant gulch
#

What?

#

thats not what your code does

neon thunder
#

Sorry if I sound less than cordial, I'm very busy trying to write code and just prefer getting to the point

#

Sure it is

#

It does what I want now

distant gulch
#

I dont even think you understand this... You should be using js player.getComponent('minecraft:inventory').container See if they have a open slot, and if not just cancel anything more from happening

neon thunder
#

I'm not giving the item to the player - its going to an entity

#

the items is coming from the player via the interact entity to yet a third party

distant gulch
#

"items is coming from the player"

#

Item or items?

neon thunder
#

stack

#

I was trying singular items instead of whole stacks but got over it as it wasn't working

distant gulch
#

if the entity has something in their mainhand, then you want the item to be given back?

dim tusk
#

This part confuses me a lot.

const equip = player.getComponent("equippable");
const equipslot = equip.getEquipmentSlot("Mainhand");
equipslot.setItem(remainder);```
neon thunder
#

No, I want it to go to a third party

neon thunder
#

Niether of yourself nor the person you're talking to

distant gulch
#

😭

neon thunder
#

But an entity you select

#

Its a mailer system... sigh

distant gulch
#

Try drawing out what your trying to do, I dont understand what your saying

dim tusk
#

I'm gonna rethink my life choices first

#

Then read your script

neon thunder
#

Each player gets a djinn assigned to them and then you can post items to other players via them

distant gulch
# neon thunder But an entity you select

                        let djinn = player.dimension.getEntities({ type: "mewp:maildjinn" });

                        for (let i = 0; i < djinn.length; i++) {
                            const ownerId = djinn[i].getDynamicProperty("mewp:ownerId");

                            if (ownerId == player.id) {
                                djinn.splice(i, 1);
                                break;
                            }
                        }

                        for (let i = 0; i < djinn.length; i++) {
                            let ownerName = djinn[i].getDynamicProperty("mewp:ownerName");

                            if (ownerName == undefined) {
                                ownerName = "<error>";
                            }

                            playersUI.button(ownerName);
                        }``` so from here?
#

Ok, so they click on a other player?

#

And then they get this menu

#

and in this menu they click on a animal to send somthing to?

neon thunder
#

They interact with their djinn and can send the item they are holding to another player's djinn

#

Or, interact with no item and see the items you've been sent

distant gulch
neon thunder
#

It is working now....

distant gulch
#

ok

neon thunder
#

I'm quite happy... Hopefully I can also make memo items

distant gulch
#

Let’s hope

neon thunder
#

I think its quite clever.. I see it all the time, people wanting a mail system in their worlds... Now I have one

#

Although, you can't send items inter-dimensionally since it can't find the destination djinn if they aren't in the same dimension as you

#

I could maybe fix it...

sage portal
#

Is there an actual approach to detecting what a player changes their mainhand item to, or do we just have to use system.intervals for that?

sage portal
#

What a shame 😔

distant gulch
#

can i find entity using location?

neon thunder
#

depends how you want to find it - Dimension.getEntitiesAtBlockLocation?

#

Umm.. With System.runInterval, is there an issue passing data to the callback? How do I tell it about things? I can just take data from consts declared outside the call???

#

do the jobs persist between server restarts?

neon thunder
#

Is there semaphores or blocking in javascript?

#

Do I need to use them?

#

It feels really strange running this job without them

slow walrus
#

huh?

#

js is single threaded if I'm understanding your question correctly

#

so no semaphores

#

really have no idea wtf those even are so I hope wikipedia's definition is right

slow walrus
slow walrus
slow walrus
neon thunder
#

got it

neon thunder
#

How can I replace a block with nothing? I am trying Block.setType("minecraft:air") but this doesn't seem to be working? It might be another issue though...

dim tusk
#

idk whats your problem

distant tulip
#

send your code or any error you are facing

dim tusk
#
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const block = player.getBlockFromViewDirection({maxDistance: 6})?.block
    block.setType('minecraft:air')
  }
});```
#

yeah i just use this to test if it worked lmfao

neon thunder
#

oh dear

neon thunder
dim tusk
neon thunder
#

Oh, I've moved on from that simple test.. But I'll show you the code now just 'cause you asked... ```js
function tickerTick() {
for (let i = 0; i < mewp_tickerdata.length; i++) {
const dimension = world.getDimension(mewp_tickerdata[i].dimension);
const block = dimension.getBlock(mewp_tickerdata[i].location);

    world.sendMessage(`Testing ticker ${i}`);
    if (block != undefined) {
        const power = block.getRedstonePower();

        if (power != undefined && power > 0) {
            for (let j = 0; j < 5; j++) {
                const y = mewp_tickerdata[i].location.y + (5 - j);

                for (let k = 0; k < 11; k++) {
                    const loc = { x: mewp_tickerdata[i].location.x + k, y: y, z: mewp_tickerdata[i].location.z };
                    const plot = dimension.getBlock(loc);

                    if ((k + mewp_tickerpos) >= 20 || mewp_tickerstrs[j].charAt(k + mewp_tickerpos) == ' ') {
                        plot.setType("minecraft:black_concrete");
                    }
                    else {
                        plot.setType("minecraft:sea_lantern");
                    }
                }
            }

            mewp_tickerpos += 1;

            if (mewp_tickerpos >= 20) {
                mewp_tickerpos = 0;
            }
        }
    }
}

}```

#

The next steps are to try to implement a directional input control and then.. then... snake challenge duo!

dim tusk
neon thunder
#

I stopped doing it. I was using redstone lanterns and redstone blocks to make the glowing "pixels" but there was lag in them turning on and off which caused display glitches I couldnt' live with so I changed it to sea lanterns and black concrete

#

I was only doing it the way I did initially because that's how I was having to do it with pistons and command blocks but now I have script.. wee hee

#

I have a small (1.6MB) video showing the result if anyone wants to see and I'm allowed to post it

subtle cove
#

Kindly create a ppst for it for further discussion

neon thunder
#

Oh whoops. I thought I had done, sorry

subtle cove
neon thunder
#

Guys, I am trying to lock a player in place while reading the input via getVelocity... In order to do that, I'm teleporting them in place all the time (runInterval) because using the inputPermissions prevents any reading of the user input. However, I need to provide the TeleportOptions because I want the view to be freely movable and I cannot calculate a facingLocation. How do I calculate something that teleport will be happy with to keep them in place and looking at relatively what they were. Here is the code I have now: ```js
const viewdir = mewp_inputplayer.getViewDirection();
const headloc = mewp_inputplayer.getHeadLocation();
const facedir = { x: headloc.x + viewdir.x, y: headloc.y + viewdir.y, z: headloc.z + viewdir.z }

        mewp_inputplayer.teleport(mewp_inputlocation, { facingLocation: facedir, rotation: mewp_inputplayer.getRotation() });
junior hill
#

does anyone know how to list the specfic scoreboard of the player in MessageFormData buttons?

knotty plaza
#

Never tried that so idk if it would work

little orchid
wheat condor
#
values() {
        if (!this.#validNamespace) return this.#MESSAGE.ERROR_INVALID_NAME(this.#settings.namespace);
        const allIds = world.getDynamicPropertyIds()
        const values = []
        const get = (key) => this.get(key)
        const filtered = allIds.filter(id => id.startsWith(this.#settings.namespace + ":"))
        system.runJob((function* ids() {
            for (let i = 0; i < filtered.length; i++) {
                values.push(get(filtered[i]));
                yield
            }
        })())
        return values;
    }

does runjob work without async (ignore the other code)

#

if its into a function in a class

junior hill
#
const topEntityLocation = {
            x: block.location.x + 0.5,
            y: block.location.y + 1,
            z: block.location.z + 0.5
        };
        const rotation1 = { x: 45, y: 0 };
        const topEntity = world.getDimension("overworld").spawnEntity("swmc:door_entity", topEntityLocation);
        topEntity.setRotation(rotation1);

why does setRotation wont work with alr inputed rotations?

#

it works with cardinal_directions of blocks

#

but not with const

junior hill
#

it tilts the head

cold grove
#

Yeah

junior hill
#

is there another way?

#

or just setRotation

cold grove
#

Y

junior hill
#

y doesnt work for me

#

y just rotates its around, i need a sideways

dim tusk
junior hill
junior hill
dim tusk
crude bridge
#

Is it possible to create a new command? Like /(command)

junior hill
#

Anyway to fix?

#

Or to do ?

dense sun
#

hey, how can i set armor durability ?

const equipInv = hitEntity.getComponent("equippable").getEquipment("Chest").damage
            console.error("test :", `${equipInv}`)
dim tusk
#

Check it using this

dim tusk
#
const equipInv = hitEntity.getComponent('equippable').getEquipment('Chest');
const durab = equipvInv.getComponent('durability').damage;```
steep hamlet
#

how do i check if an entity is alive?

#

neither isValid() or entity !== undefined worked for me :/

distant gulch
#

How do i get players around a particular entity?

thorn flicker
thorn flicker
thorn flicker
#

np

strong oar
#

Is it possible to make a script to change the models and texture of the leaves before entering the Minecraft world?

#

Like making a bushy leaves

misty pivot
#

how would i set a light block with the light level of 2? preferably using setBlockType?

thorn flicker
misty pivot
#

ah i see, thanks

dim tusk
#

guys is it possible to set the bouhding box of the structure block you placed??

dense sun
winter plaza
#
export function summonPower(player, powerId, eventId, name, offset, test) {
  const location = offsetPower2(player.location, player.getRotation().y, offset);
  common(location);
  function common(location) {
    const rotation = setRotation({x: 0, y: player.getRotation().y});
    const power = player.dimension.spawnEntity(powerId,(location, rotation));
    if (power && name != null) {
      power.nameTag = `${name}`;
    } else power.nameTag = `entidade`;
    if (power && eventId != null) {
      power.triggerEvent(eventId);
    }
  }
}

export function offsetPower2(location, rotation, offset) {
    function round100000(number) {
        return Math.round(100000 * number) / 100000;
    }
    const yaw = (rotation + 90) * (Math.PI / 180);
    const offsetX = round100000(Math.cos(yaw)) * offset[2];
    const offsetZ = round100000(Math.sin(yaw)) * offset[2];
    return {
        x: location.x + offsetX,
        y: location.y,
        z: location.z + offsetZ
    };
}
#

help

shy leaf
#

help with what

winter plaza
#

setRotation is giving an error

#

Inf:summon a mob with location selected, and with player's setRotation Y

thorn spindle
#

Anyone knows how to get ingame time

#

Tried this but doesn't work: const time = world.getDimension('overworld').runCommand('time query daytime').data;

woven loom
#

how's going everyone

distant tulip
unique acorn
woven loom
#

what ppl creating now

distant gulch
#

Any ideas what I could try to code for #1067535712372654091

distant tulip
dim tusk
distant tulip
dim tusk
distant gulch
#

undefined*

distant gulch
glacial widget
#

Would this cause lag?

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

const targetCoords = { x: 27.53, y: 90.00, z: 27.51 };
const radius = 5;


function calculateDistance(pos1, pos2) {
    return Math.sqrt(
        Math.pow(pos1.x - pos2.x, 2) +
        Math.pow(pos1.y - pos2.y, 2) +
        Math.pow(pos1.z - pos2.z, 2)
    );
}

function checkPlayersInRange() {
    for (const player of world.getPlayers()) {
        const playerPos = player.location;
        const distance = calculateDistance(playerPos, targetCoords);

        if (distance <= radius) {
            if (player.hasTag("pvp")) player.removeTag("pvp");
            if (player.hasTag("bs")) player.removeTag("bs");
            if (player.hasTag("cpvp")) player.removeTag("cpvp");
        }
    }
}

system.runInterval(() => {
    checkPlayersInRange();
}, 20);
#

i dont think for because of the amount of checks that is happening on the player, however ik this runs for every player on the world.

gaunt salmonBOT
glacial widget
# shy leaf probably not

I was asking for ik there is a easy way to do this with commands but i wanna move away from them lol

shy leaf
#

oh yeah definitely not with commands

winter plaza
#
export function summonPower(player, powerId, eventId, name, offset, test) {
  const location = offsetPower2(player.location, player.getRotation().y, offset);
  common(location);
  function common(location) {
    const power = player.dimension.spawnEntity(powerId, location).setRotation({x: 0, y: player.getRotation().y});
    if (power && name != null) {
      power.nameTag = `${name}`;
    } else power.nameTag = `entidade`;
    if (power && eventId != null) {
      power.triggerEvent(eventId);
    }
  }
}
#

const power is as if it didn't exist

knotty plaza
winter plaza
#

I did this, but it summons and has a 1 second delay to set the rotation, I want the rotation to be activated as soon as it is summoned

warm mason
winter plaza
#

no

#

beta no!!

warm mason
#

?

#

hmmm

#

Well then you can spawn the entity with the command

#

There are no other options

winter plaza
#

as?

warm mason
#

I don’t remember exactly how this is spelled in the command, but it seems something like this.

dimension.runCommandAsync("summon pig [loc: x] [loc: y] [loc: z] [rot: x] [rot: y]")
winter plaza
#

the question is that I want to make a mob be summoned in front of the player but the rotation doesn't matter, another thing is that it has to be only in the y rotation, since if I look up, will not spawn above, only in front

#

I don't think it's possible with a command

warm mason
thorn flicker
#

but ignore vertical

winter plaza
#

summon an entity in front of me, regardless of the x rotation, but ignoring the y coordinate

#
dimension.runCommandAsync("summon pig [loc: x] 0 [loc: z] [rot: x] [rot: y]")
warm mason
winter plaza
#

but like this, it wouldn't spawn in front of me, if I put 4 in z

winter plaza
#

at my height, not at the height of my vision

warm mason
#

Now I understand.

thorn flicker
#

so you need to get the player's view direction and do some math.

#

also dont use commands, use the native method

#

dimension.spawnEntity('minecraft:pig', vector3)

winter plaza
#

ok

warm mason
#
let view = player.getViewDirection()
let entity = player.dimension.spawnEntity("pig", {
  x: player.location.x + view.x*5, // 5 - distance
  y: player.location.y,
  z: player.location.z + view.z*5
})
warm mason
winter plaza
warm mason
#

So that's what you need, no? Where should it appear?

winter plaza
#
dimension.runCommandAsync(`summon pig ${player.location.x + view.x*5} 0 ${player.location.z + view.z*5} [rot: x] [rot: y]`);
warm mason
#

...

thorn flicker
#

..

#

why are you using the command still

warm mason
thorn flicker
#

also you are not inserting the values in the strings

winter plaza
warm mason
#

Why do you set the height to 0?

thorn flicker
#

to use template literals correctly you need to use backticks to form your string, not double quotes or single quotes

thorn flicker
winter plaza
#

:/

warm mason
#

rotation of the entity or where will it appear?

#

Once again, describe in detail and in simple text what you need.

winter plaza
#

When it is spawned, it has to be facing the same direction as the player who summoned it is facing.

#
let view = player.getViewDirection()
let entity = player.dimension.spawnEntity("pig", {
  x: player.location.x + view.x*5, // 5 - distance
  y: player.location.y,
  z: player.location.z + view.z*5
});
entity.setRotation({x: 0, y: player.getRotation().y});
#

If I do it like this, it has a 1 second delay to be rotated

#

I don't want delay

warm mason
#
dimension.runCommandAsync(`summon armor_stand ${player.location.x + view.x*5} ${player.location.y} ${player.location.z + view.z*5} ${player.getRotation().x} ${player.getRotation().y}`);
winter plaza
#

VoidVcell said not to use command lol

warm mason
#

Because we didn't understand you

winter plaza
#

Ah ok

#

So I use the command anyway?

thorn flicker
#

in preview

#

there's a way to set the initial rotation when spawning a mob with the native method

warm mason
thorn flicker
#

didnt see that

#

lol

winter plaza
#

lol

warm mason
#

Lots of "lol"

winter plaza
#

You English speakers are funny

thorn flicker
warm mason
winter plaza
#

thank you guys

#

no

#

I'm Brazilian, and I know a little English.

thorn flicker
warm mason
winter plaza
#

I know little, sometimes I use a translator

#

There are words I don't know

#

and sentences that I don't know how to put together

thorn flicker
warm mason
winter plaza
neat hazel
#

How do I detect fatal damage to my entity?
I want to execute a command if my entity receives fatal damage

warm mason
clear pendant
#

did microsoft say something about custom keybinds?

#

or if there will even be the ability to add them?

thorn flicker
clear pendant
#

oh, f

distant tulip
thorn flicker
#

because this is all we have rn

distant tulip
clear pendant
#

how do you use oreUI?

thorn flicker
thorn flicker
clear pendant
#

i see some ppl using it tho

thorn flicker
#

ask them then

clear pendant
thorn flicker
clear pendant
#

yeah, that's what i tought

distant tulip
clear pendant
#

keybinds?

thorn flicker
#

im assuming he means like, press K and it does something

clear pendant
#

and buttons for mobile

#

yep

thorn flicker
distant tulip
#

only WASD jump and sneak

thorn flicker
#

thats cool

clear pendant
#

i wanted to use custom inputs to control my plane lol

#

i'll need to be creative then

#

can you prevent the player from leaving the seat when he presses shift?

distant tulip
#

yeah

clear pendant
#

how?

thorn flicker
distant tulip
#

give me a sec

#

player.inputPermissions.setPermissionCategory(8,false)
@clear pendant

clear pendant
#

thx

dim tusk
#

I want to do cctv camera for so long that you can control now you can do it... Is sick asf

#

I know it's preview but bruh

distant tulip
#

yeah
lets hope it get released soon

dull shell
#

how would I go about having my block run a function when interacted? unless you still can via json?

rapid sail
#

a script to get matching blocks in a certain area?

dull shell
#

I just want a command to run when I interact with my block

#

but the on_interact doesnt work anymore

rapid sail
#

are you using CC?

#

custom compoments?

thorn flicker
dull shell
#

thank you

rapid sail
#

did i set this up void?

thorn flicker
#

what is area_0?

#

and the 3 if statements above, you could simplify that.

rapid sail
#

those are for different outcomes

#

area 1 is simplified as i used to do if (block.dimension.getBlock({ x: 0, y: -60, z: 0 }).typeId === "glowstone" && block.dimension.getBlock({ x: 0, y: -60, z: 0 }).typeId === "glowstone"

#

thats just an example

#

the true is there because i thought it wouldnt cause it to run even thought the blocks arent there

simple arch
#

will anybody help me with this issue with my code. please I can't find the solution to it.

dim tusk
# distant tulip

Dude can you give the scripts you used? I wanna try in mine...

distant tulip
woven loom
#

What is MV Vec

scarlet hemlock
#

Guys, is there a way to change a written book title?

dim tusk
distant tulip
distant tulip
scarlet hemlock
woven loom
distant tulip
# woven loom yes

normalized xy vector for the player input for example
forward: {x:1,y:0}
backward {x:-1,y:0}
right {x:0,y:1}
left {x:0,y:-1}
and so on
it is in preview

distant tulip
shy leaf
#

found a uuidv4 generator for javascript in internet after finding out uuidgenerator.net is horribly slow skull_issue_c

scarlet hemlock
#

I have a book inside a saved structure. Do you know where can I find those files?

woven loom
distant tulip
distant tulip
shy leaf
scarlet hemlock
#

don't worry

shy leaf
#

yeah but

#

i just went out for existing one cuz im lazy

dim tusk
dim tusk
shy leaf
#

im lazy thats all

granite badger
distant tulip
distant tulip
dim tusk
granite badger
#

mind if i add this info to docs

woven loom
# shy leaf im lazy thats all
let fu = () => '00000000-0000-0000-0000-000000000000'.replaceAll( '0', v => Math.floor(Math.random()*16).toString(16) );
distant tulip
shy leaf
#

that

#

is that uuidv4?

woven loom
#

nah pseudo

dim tusk
shy leaf
#

o

distant tulip
shy leaf
woven loom
#

game doesnt check that so its fine

distant tulip
#

yeah

shy leaf
#

it doesnt?

woven loom
#

nah

shy leaf
dim tusk
#

Lemme check my scripts files if I have my old uuid generator

distant tulip
#

that for the best tbh
i used to use the same uuid and change it just a bit

dim tusk
#

Found it.

function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        const r = (Math.random() * 16) | 0;
        const v = c === 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
}
woven loom
#

Logically it doesn't make any sense to validate if the pack uses the actual uuid4 or not, from the game's pov

dim tusk
#

I have done it since 1.20

woven loom
#

All they need is an id system

shy leaf
#

we are using the same one

distant tulip
dim tusk
#

It's old soo idk

woven loom
#

bruh quickedit has crypto

#

just use that

shy leaf
#

uh

#

its quickedit

#

wait

#

it does?

woven loom
#

ye

shy leaf
#

it never said abt it anywehre in the app wtf

woven loom
#

They use ext lib for js runtime, and if you see their doc, it has ut

dim tusk
#

For God sake guys, I don't do commissions.. my DMS are full of that

#

Ohh my god

#

Guys how do I disable my DMS or some shii

woven loom
#

lucky you

dim tusk
distant tulip
#

mine is full for help questions or free work lol

shy leaf
distant tulip
dim tusk
#

Learn to do it 😄

woven loom
shy leaf
#

oh that one

#

ty

woven loom
#

@shy leaf

shy leaf
#

ooohhhhhh

#

stupid me i was trying to run it on editor side

distant tulip
woven loom
#

i have 50.26

dim tusk
#

If im correct lmao

woven loom
#

Thanks

distant tulip
#

ur wlc

woven loom
#

That behaviour is intended? where it works even in the disabled state

distant tulip
chilly fractal
#

Yo is there a way to get item rarity in scripts?

#

Like an ender dragon egg would be epic rarity as you can see it having the colorcode "§d", and something that's common would be of no rarity so white, yellow for uncommon, and blue for rare, and magenta for epic. You can see this in-game by grabbing a trident from the creative menu it's rare, then you add a Enchantment to it, it becomes epic.

#

I don't think there is anyway, so basically I'll have to map everything. But I just wanna know if there is a component or something

chilly fractal
#

Good to know.

#

Sad but it's at least good to make you focus on what you are doing.

dim tusk
#

Guys how do I get the center of two points?

warm mason
dim tusk
warm mason
#

So you messed something up somewhere

dim tusk
#

The armor stand should be in the middle but nah

warm mason
warm mason
#

And here you don’t even need the center function.

dim tusk
#

first time it didn't work cause usually it does idk why

distant tulip
#

why not use get entity options?

dim tusk
distant tulip
#

dose the entity get teleported?

warm mason
#

You chose the wrong points

dim tusk
dim tusk
warm mason
#

Well, according to the code everything is correct

distant tulip
#

can you log the tow pos and the tp location?

dim tusk
#

thn what? why the hell you said you chose the wrong points?

warm mason
#

Because you chose points 1 and 2 as the same, or changed them somewhere

#

If you stood exactly in the middle of two blocks, then everything would be correct

dim tusk
#

bruh i ai'nt getting what you are saying no matter what how many times you change the loc of those two points it should properly say the center of it

warm mason
#

Well, you chose the points wrong. That's it. When you clicked on "set pos" you selected them so that the center is not in the center of the blocks, but in the center of 1 of the blocks

distant tulip
dim tusk
warm mason
#

I tried to tell you this 3 times

dim tusk
dim tusk
distant tulip
#

hmm
get the armor stand position and check if it is the same

dim tusk
#

as what serty said, it's getting the center of 1 block only

distant tulip
#

it should be right

dim tusk
#

my smoll brain

distant tulip
#

lol

dim tusk
distant tulip
#

i have no idea what are you talking about lol

dim tusk
#
const xCenter = (pos1[player.id].x + pos2[player.id].x) / 2 + 0.5;
const yCenter = (pos1[player.id].y + pos2[player.id].y) / 2 + 0.5;
const zCenter = (pos1[player.id].z + pos2[player.id].z) / 2 + 0.5;```
#

here. it gets the center of the two location

distant tulip
#

yeah

dim tusk
#

mb, i am shit in explaining things, that's why my english is my lowest grade lmao

dim tusk
distant tulip
#

get the tow blocks center first then get the center
just add 0.5 to both before the / 2

dim tusk
#

same in doing execute as @p at @s align xyz run tp @s ~0.5 ~0.5 ~0.5

remote oyster
# shy leaf found a uuidv4 generator for javascript in internet after finding out uuidgenera...

Here you go.

function generateRandomUUID(): string {
    const lut: string[] = [];
    for (let i = 0; i < 256; i++) {
        lut[i] = (i < 16 ? "0" : "") + i.toString(16);
    }

    const d0 = (Math.random() * 0x100000000) >>> 0;
    const d1 = (Math.random() * 0x100000000) >>> 0;
    const d2 = (Math.random() * 0x100000000) >>> 0;
    const d3 = (Math.random() * 0x100000000) >>> 0;

    return (
        lut[d0 & 0xff] +
        lut[(d0 >> 8) & 0xff] +
        lut[(d0 >> 16) & 0xff] +
        lut[(d0 >> 24) & 0xff] +
        "-" +
        lut[d1 & 0xff] +
        lut[(d1 >> 8) & 0xff] +
        "-" +
        lut[((d1 >> 16) & 0x0f) | 0x40] +
        lut[(d1 >> 24) & 0xff] +
        "-" +
        lut[(d2 & 0x3f) | 0x80] +
        lut[(d2 >> 8) & 0xff] +
        "-" +
        lut[(d2 >> 16) & 0xff] +
        lut[(d2 >> 24) & 0xff] +
        lut[d3 & 0xff] +
        lut[(d3 >> 8) & 0xff] +
        lut[(d3 >> 16) & 0xff] +
        lut[(d3 >> 24) & 0xff]
    );
}

function isValidUUID(uuid: string): boolean {
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    return uuidRegex.test(uuid);
}
shy leaf
#

that also works

#

ty

remote oyster
#

It's v4.

remote oyster
#

Have at it.

neat hound
#

Is there a way for a system.runInterval (() =>{})to reference it's own job ref (in order to cancel/stop itself?)

subtle cove
#

without

const runId = system.runInterval(()=>{})
```?
warm mason
#

Well, you can make your own runInterval

neat hound
#

I will be starting a job for each player upon spawn, but don't want to make a job keeper... I need it to stop running when the player leaves.

#

if player is not valid, cancel

warm mason
# warm mason Well, you can make your own runInterval

For example this:

runInterval(func, delay) {
  let interval = new class {
    constructor() {
      this.loop = 0
    }
    stop() {
      system.clearRun(this.id)
    }
  }
  interval.id = system.runInterval(() => {
    func(interval)
    interval.loop++
  }, delay)
}
neat hound
#

I feel like I stepped into advanced JS.. I am not sure how to turn ```JS
/**
*

  • @param {Player} player
    */
    export function playerCounterJob (player) {
    system.runInterval(() => {
    //add stopping mechanism here
    DynamicPropertyLib.add(player, dynamicVars.aliveTicks, TicksPerSecond);
    }, TicksPerSecond);
    }``` into that. What am I passing to runInterval?
warm mason
neat hound
#

I do not know how to use these parts..

wary edge
subtle cove
#

uhh, shouldn't that be

DynamicPropertyLib.add(
  player,
  dynamicVars.aliveTicks,
  TicksPerSecond,
  system.runInterval(()=>{
    player.isValid()
  })
)
warm mason
wary edge
#

I personally would store the jobID in a dynamic property and before player leave grab the property and stop the job.

neat hound
warm mason
neat hound
#

If a player Alt-F4 quits.. job never cancels

misty pivot
#

which is better to store a temporary data in a player? player.test = true or dynamicProperties?

subtle cove
misty pivot
#

what? 😭

subtle cove
#

that also works

#

search for cacheing methods

neat hound
misty pivot
#

i see, alrighty

neat hound
#

Imma see if this works....JS export function playerCounterJob (player) { const thisJob = system.runInterval(() => { if (player.isValid()) DynamicPropertyLib.add(player, dynamicVars.aliveTicks, TicksPerSecond); else { //cancel this job system.clearRun(thisJob); } }, TicksPerSecond); }

warm mason
#

How to understand this?

remote oyster
# neat hound Imma see if this works....```JS export function playerCounterJob (player) { ...

Just pinging you with a made up logic to demonstrate runInterval() assignments. In case it helps.

import { world, system } from '@minecraft/server';

let playerIntervals = {};

// Function to create and assign an interval to a player
function createIntervalForPlayer(playerId) {
    // Only create a new interval if it doesn't already exist for this player
    if (playerIntervals[playerId]) return;

    let runId = system.runInterval(() => {
        let player = world.getEntity(playerId);
        if (player) {
            // Perform player-specific actions, e.g., logging every second
            console.log(`Interval running for player with ID: ${playerId}`);
        } else {
            // If the player is no longer in the world, clear the interval
            system.clearRun(runId);
            delete playerIntervals[playerId];
        }
    }, 20); // 20 ticks = 1 second

    // Store the player's interval run ID
    playerIntervals[playerId] = runId;
    console.log(`Interval assigned to player ${playerId}`);
}

// Player join event handling
world.afterEvents.playerJoin.subscribe((eventData) => {
    let playerId = eventData.playerId;  // Retrieve player ID from the event data
    
    // Assign an interval to the player only if it's not already assigned
    createIntervalForPlayer(playerId);
});

// Player leave event handling (before the player leaves)
world.afterEvents.playerLeave.subscribe((eventData) => {
    let playerId = eventData.playerId;  // Retrieve player ID from the event data

    // If the player has an interval running, we stop it and remove it from the list
    if (playerIntervals[playerId]) {
        system.clearRun(playerIntervals[playerId]);
        delete playerIntervals[playerId];
        console.log(`Interval stopped for player ${playerId}`);
    }
});
neat hound
#

LOL, gonna be a bitch to test... single player on PC....

remote oyster
#

Haha

neat hound
#

Maybe the console log can still show

remote oyster
#

You could create a simulated player.

sharp elbow
#

If a hard exit occurs, you probably won't need to care about it since the game's state may not have saved

neat hound
#

that is when on single player, but this will be for a realm.... and if a player hard exits, game is still running until last player leaves

sharp elbow
#

True. Might get finicky if the player fails to send a Disconnect packet then

neat hound
#

is the player sending the packet, or is the world handling it?

remote oyster
#

I'm pretty confident when a player leaves the event is triggered. At least, I see the results on BDS when looking at the console lol.

#

Hard exit that is.

sharp elbow
#

Technically the client does. When the user disconnects from a server normally the client is supposed to tell the server its intentions. If the game crashes and that packet isn't sent, then the only way the server knows if the client is gone is by waiting for its requests to time out

remote oyster
#

Whether data is saved, corrupted, or lost is another topic 🧐

sharp elbow
#

That's my assumption anyway. Bedrock could be operating on a different communication model though

neat hound
#

Seems like the player leave after event, is just playerId and name also... I am thinking this is on world level, and not player

#

where as before event is player object

remote oyster
#

Correct, because they still exist.

neat hound
#

like with join

subtle cove
#

hence entity.isValid() eh...

neat hound
#

yes, but that is on the player object... but if the leave after event, does not have the object ( because player is gone-gone), then maybe it is the world object handling that event

sharp elbow
#

I see all events as being handled by the "world," or the scripting engine. It then polls whatever data is relevant to act upon in that event

warm mason
sharp elbow
#

I figured one could directly use the handler in the clearRun method, yeah. Might behave weirdly if the interval is 0, but I assume the engine would at least finish the assignment before executing the next loop

warm mason
neat hound
#

and id

warm mason
#

And long

remote oyster
gentle mist
#

Hii can someone help me? Want create a duel system 😭

neat hound
#

All I see is he used the player object in the before join... so changed to eventData.playerId.. gonna test it out as is with that one change.

remote oyster
warm mason
#

world.beforeEvents.playerJoin does not exist

warm mason
distant tulip
remote oyster
#

Ah crap lol, my bad. I mixed myself up with the other event.

distant tulip
#

so? what is the problem

gentle mist
#

Nothing huh

#

I just asked

distant tulip
#

bruh

neat hound
#

I will alter accordingly to test

subtle cove
warm mason
subtle cove
#

some kind of player initializer, dunno can't remember

remote oyster
subtle cove
#

was tryna make a custom getPlayers

warm mason
subtle cove
#

all objects are linked

#

well most of em

warm mason
#

the playerJoin event fires

before the player spawns.

So getEntity(playerId) will return undefined and the interval will end immediately

remote oyster
warm mason
#

Use playerSpawn

unique acorn
#

since block.setDynamicProperty isnt a thing, anyone know another way?

remote oyster
#

Making it bold doesn't explain it. If the event returns the object then the object is retrievable, so how would world.getEntity() return undefined?
@serty.name

warm mason
subtle cove
remote oyster
warm mason
#

Because playerJoin and playerSpawn are different things. playerJoin - the player is connected to the server playerSpawn - the player has spawned. Until the player spawns, he is not on the list, so you are trying to get the player, too early

sharp elbow
remote oyster
#

If the player hasn't spawned then explain the object?

unique acorn
remote oyster
#

Spawn or not, the object is there.

wary edge
sharp elbow
#

I know.

remote oyster
#

.... Entity would be the object. The event returns the object.

#

Am I on repeat?

warm mason
#

Do you see what I highlighted? You understand how documentation works. it returns entity or undefined

subtle cove
#

meanwhile me abt to test

warm mason
#

undefined it returns when the entity is in the world.

wary edge
#

What is the argument right now?

remote oyster
#

If the object didn't exist, as you claim, then how would the object be retrievable in the playerJoin event "because they haven't spawned yet"?

warm mason
#

Let me explain in detail

wary edge
#

As far as I know, playerJoin retrieves the player object.

remote oyster
#

Exactly

warm mason
subtle cove
#

it does retrieve the player in playerJoin

warm mason
#

There is not

subtle cove
#

using the id

warm mason
#

because that's what playerSpawn is for

subtle cove
#

maybe mojang made changes on it

#

it wasnt possible to get the player in that event before

wary edge
#

All I know is that if you do world.getPlayers in playerJoin, the player that joined will be included.

warm mason
#

No. As I said, playerJoin and playerSpawn are different events. join - the player has joined the SERVER. spawn - the player has appeared in the world. There is a difference. So you can't immediately get the player object in playerJoin because it doesn't exist yet.

remote oyster
#

I'm gonna write code to test and verify.

wary edge
subtle cove
#

alr did ;-;

warm mason
#

No

remote oyster
turbid gulch
#

how to detect if player interacted with block on specific coordinates?

subtle cove
#

i used world.getEntity(playerId) and its possible

warm mason
#

I say it again. join - before the player appeared in the world. that is, the player is not yet on the list of players. it's not valid

remote oyster
#

Case closed.

#

Moving on.

wary edge
#

This was a code I used for a project

world.afterEvents.playerJoin.subscribe((eventData) => {
    const player: Player = world.getEntity(eventData.playerId) as Player;
    player.setDynamicProperty('namespace:property', false);
    console.log('player initialized');
});

And it works.

warm mason
#

are you testing it in a single world?

wary edge
neat hound
#

okay.. so what is available in the event for player join is only strings whereas the world.getEntity has access to all players, even pre-spawn... is that what we are saying?

warm mason
#

I used this on a server. When you enter the world yourself, playerSpawn and playerJoin are triggered immediately. Because you are the host and you don't need to connect to the server

warm mason
warm mason
subtle cove
warm mason
remote oyster
#

The player exists when they join. I suppose the logical way to view it as one instance the object is valid and the other instance the object is not valid, but the object still exists either way.

subtle cove
remote oyster
#

And it seems it's valid either way based on that image lol

neat hound
#

I think Serty is saying this his experience of this on a server (not realm) is different.

warm mason
#

I remember that it doesn't work like that on servers

subtle cove
#

same, but it was long ago

remote oyster
#

The functionality may vary between local, realm, and server. I honestly could believe that behavior to be factual. Would not surprise me at all honestly lol.

neat hound
#

is there anything special you have to do to run scripts on a server.. I have one I can test with, just not tried any scripting add-ons

subtle cove
warm mason
#

i would use playerSpawn because there is no need to get the player via getEntity and based on my experience it is better

subtle cove
#

that i agree

wary edge
#

Unfortunately, you would need to track an additional data because if a player dies? Unless I misread the use case.

subtle cove
#

hence entity.isValid() ;-;

warm mason
#

as long as the player is valid then the interval is there

remote oyster
distant tulip
#

player is still valid tho

wary edge
# warm mason Why?

My interpretation is that they want to do an action if a player joins a world. Wouldn't playerSpawn trigger this event numerous times?

warm mason
#

data.initialSpawn exists

distant tulip
#

dose that leave any use case for player join?

#

i guess it dose trigger before that, so idk

wary edge
warm mason
#

I don't think that 1 line will interfere much. Moreover, it is completely understandable

distant tulip
#

the player don't exist yet when that trigger from what i remember

warm mason
#

In short... use whatever you want. I'm leaving

distant tulip
#

lol

neat hound
#

guess I need to player to exist as I am altering his dynamic vars

steady canopy
#

yo what happened to WorldBeforeEvents.playerPlaceBlock??

#

why it now only has an after version

#

in the last beta

#

1.16.0-beta

steady canopy
#

I was literally using this event in 1.14.0-beta

wary edge
steady canopy