#Script API General

1 messages · Page 53 of 1

chilly fractal
#

And im just remaking it

#

If i face another error I'll make a posy

#

Post*

cerulean cliff
#

Am I just stupid or is there really no way to check for the difficulty in scripting?

wary edge
#

There's an enum but not used.

cerulean cliff
#

really?!

#

awwh that sucks

chilly fractal
#

I forgor to do a status update, so uh. await import(); works as per the script that has that

#

Like i need to get the relative path from the importer script's location to the imported script.

#

(Saying this incase you wanna use my importer class or make your own)

chilly fractal
sharp elbow
#

Bro went through an entire character arc over the course of twelve hours

remote oyster
#

A lore in the making

distant gulch
#

quick question mates

player.getAimAssist()
    .set(
        {
            presetId: ":default",
            distance: 10,
            targetMode: AimAssistTargetMode.Distance,
            viewAngle: { x: 0.25, y: 0.25 }
        }
    );

Is this how it works?

#

-# Is this everything i need to do?

#

W Admin is playing ZZZ

wary edge
wary edge
distant gulch
wintry bane
#

How do I convert queued_ticking into JS?

"minecraft:queued_ticking": {
  "looping": false,
  "range_interval": [30, 40],
  "on_tick": {
    "event": "remove_block",
    "target": "self"
  }
}
chilly fractal
wintry bane
#

thx

chilly fractal
#

You're welcome

wary edge
#

That way you can also use the tick component.

wintry bane
#

But doesn't that run every tick?

wary edge
wintry bane
#

So that's what it's used for..

#

Never could've guessed until I asked now, thanks

grave nebula
#

How do i set a block permutation using scripts?

#

im making a spawner for skyblock and when i stack them into a single block, it only drops one instead of how many ive put in

dim tusk
grave nebula
#

thx

fast lark
dim tusk
distant tulip
#

inventory.emptySlotsCount === 0

fast lark
dim tusk
dim tusk
#

hmm.

#

Okay lmfao

distant tulip
distant tulip
chilly fractal
#

Yeah just use minato's

dim tusk
chilly fractal
dim tusk
#

K

distant tulip
#

inventory.emptySlotsCount === inventory.size
mean you have 27 empty slot
inventory.emptySlotsCount !== inventory.size
mean you have less or more than that

dim tusk
#

Sorry, I'm kinda cold when responding

#

I'm manually putting params wait

distant tulip
#

it is alr

dim tusk
#
/**
 * This event fires for each BlockLocation destroyed by an explosion.
 * It is fired after the blocks have already been destroyed.
 *
 * @param {Object} event - The event object
 * @param {Block} event.block - The exploded block
 * @param {Dimension} event.dimension - The dimension of the explosion
 * @param {Entity | undefined} event.source - The entity that caused the explosion (if any)
 * @param {BlockPermutation} event.explodedBlockPermutation - The permutation of the exploded block
 */
world.afterEvents.blockExplode.subscribe(({ block, dimension, source, explodedBlockPermutation }) => {});```
#

Quick question, is this correct?

#

the @params
-# I rarely touch param comments lol

wicked girder
#

anyway to stop a player from swimming?

scarlet sable
#

where is the hunger system coded?

dim tusk
scarlet sable
#

oh

#

client sided I see

dim tusk
wicked girder
#

maybe is there a way to stop sprinting? I want to have it so the player is able to jump and move in water but not swim

distant tulip
#

if only isSwimming wasn't Readonly like isSneaking

dim tusk
#

using inputinfo and applyKnockback

#

tho inputinfo is still in beta

dim tusk
distant tulip
dim tusk
#

do some hacky ways to disable swimming

wicked girder
#

im just gonna have it constantly push them down if they are swimming

chilly fractal
#

Make them sneak

#

If they sneak

#

They can't sprint

#

And if they can't sprint

#

They can't swim

#

If they are swimming then make them sneak

#

.isSneaking = true

scarlet sable
dim tusk
sweet seal
#

t

#
    if (selectedIndex !== undefined) {
      const selectedItem = selectedIndex < 4 ? equippableComponent.getEquipment(armorSlots[selectedIndex]) : inventory.getItem(selectedIndex + 9);
      if (selectedItem) {
        const enchantableComponent = selectedItem.getComponent("minecraft:enchantable");
        const name = selectedItem.nameTag || selectedItem.typeId.replace("minecraft:", "").replace(/_/g, " ");
        const displayName = name.charAt(0).toUpperCase() + name.slice(1);

        if (enchantableComponent) {
          const enchantmentOptions = [
            { name: "Sharpness", type: "minecraft:sharpness" },
            { name: "Unbreaking", type: "minecraft:unbreaking" },
            { name: "Fire Aspect", type: "minecraft:fire_aspect" },
            { name: "Knockback", type: "minecraft:knockback" }
          ];

          const modalForm = new ModalFormData()
            .title("§l§dAdd Enchantment")
            .dropdown(`  \n§dSelect an enchantment to add:\n\n§dItem Selected: §5${displayName}\n`, enchantmentOptions.map(option => option.name))
            .toggle("§d§lConfirm Enchantment?", false);

          modalForm.show(player).then(modalResponse => {
            if (!modalResponse.canceled && modalResponse.formValues[1]) {
              const selectedEnchantment = enchantmentOptions[modalResponse.formValues[0]];

              const enchantment = { type: new EnchantmentType(selectedEnchantment.type), level: 1 };

              const enchComp = selectedItem.getComponent('enchantable');
              enchComp.addEnchantment(enchantment);

              player.sendMessage(`§d§lSuccess§5 >§r§d You added §l${selectedEnchantment.name}§r to §d${selectedItem.typeId}`);
            }
          });
        } else {
          player.sendMessage("§d§lError§r§d§l >§r§d This item is not enchantable.");
        }
      }
    }
  });
}

Why is it not adding the enchantment?

dim tusk
#

It's just name

#

like instead of minecraft:sharpness it's sharpnes

thorn flicker
#

and you need to set the item back into the slot to save changes to the itemstack.

thorn flicker
sweet seal
#
              try {
              player.getComponent('inventory').setItem(player.selectedSlotIndex, selectedItem);
              } catch (err) {
                world.sendMessage(`Error: ${err}`)
              }

why this not work?

thorn flicker
#

use the setEquipment method on the equippable component you have.

fast lark
#

someone know the name of the sound for an wrong command/answer like the boom

#

of the note block i think

#

player.playSound("note.bass")?

dim tusk
distant gulch
#

Guys, are theese the right npm modules?

chrome flint
distant gulch
remote oyster
distant gulch
remote oyster
distant gulch
#

Does the version contains stuff like chatSend?

rigid meadow
#

is it possible to use ts to read json file?

distant gulch
rigid meadow
#

i thought it was possible for the files only in the same folder of the scripts

distant gulch
sterile epoch
#

What's the method for making a sign honeycomb i forgot ir

pale terrace
#

is there an afterEvent that return when the player change its spawnpoint?

shut citrus
#

Why then you can get player system info?

dim tusk
#

other than that no

chilly fractal
#

You can cache their spawnpoint and check every now and then in an interval

chilly fractal
#

Yeah

#

It is that

chilly fractal
#

I think an import would also work for a normal json file

#

In any way you'd have to use either:

import data from './data.json';

console.warn(data.someProperty);

Or ```js
import * as data from './data.json';

console.log(data.someProperty);

chilly fractal
#

All should work

#

So just use what is easier for you

dim tusk
#

That's a lot of OOOR

#

Are you a seal? 🦭

chilly fractal
#

Nope

#

I do deals

#

With the await import()

granite badger
#

you can't read json files in scripts folder, use a bundler instead

chilly fractal
chilly fractal
unique acorn
#

is there any way to get what trim an itemStack has?

#

sucks.

scarlet sable
#

since we're getting a game pause next update will that also mean we'll get more control over the in game time?

boreal siren
#

Guys, how can I implement a system for naming an entity with the ability to have a new line?

fallow rivet
#

Does the "itemstack" of an item contain dynamic properties?

warm mason
warm mason
warm mason
fallow rivet
#

That's not what I'm wondering

#

For example, if an item has dynamic data, will the dynamic data be deleted if I clone this item with a script?

subtle cove
#

well dynamic property is exclusive to one pack only from when it's been saved
it uses the manifest uuid saved in db file in the world

fallow rivet
subtle cove
#

idk, havent tried it

warm mason
subtle cove
#

it looks like this

rigid meadow
#

using like webpack?

chilly fractal
#

Yeah even make your own simple bundler

#

All you have to do is resolve dependencies

#

Aka remove any import calls and just put everything it import's into the same file

hushed ravine
#

Can I stop fishing rod damage if I grab a player with it?

chilly fractal
#

Not now at least

#

You can use damage sensors tho

hushed ravine
chilly fractal
#

And use some property + damage sensor + event + scripting api

#

The first 3 are related to the player entity

#

Meaning youll need to edit the player.json

#

Which will make your addon inportable with other addons that might use it

chilly fractal
nocturne berry
#

How do you detect the healing potion?

           system.run(() => {
               block.dimension.spawnEntity("eidolon:healing_potion", { x, y, z });
           block.setPermutation(block.permutation.withState('eidolon:brazier', 9));
          });
           }
fallow rivet
#

Is it possible to test if a player has opened an entity?

#

For example, a player opens a chest in Minecraft

round bone
#

both have their listener variants in before (read-only) and after (regular) events

#

for chests, there is a sample

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

world.beforeEvents.playerInteractWithBlock.subscribe((eventData) => {
    const { player, block } = eventData;

    if (block.typeId === "minecraft:chest") {
        // code for player that is interacting with a chest
        return;
    };
});
fallow rivet
round bone
#

some NPC interaction or what do you mean?

fallow rivet
#

Ui Open and close

round bone
#

you can't really detect if player has close some inventory atm

fallow rivet
#

This is sad

bold lily
#

how i can create a block instance?

wary edge
uncut fjord
#

is there a way to add an argument to a custom component for a block?

alpine ibex
#

Anybody online lol

uncut fjord
alpine ibex
#

Are there anyway to add interaction to mobs?

#
      "minecraft:interact": {
        "interactions": {
          "on_interact": {
            "target": "self",
            "filters": {
              "test": "has_tag",
              "operator": "=",
              "value": "slayer"
            },
            "event": "bossfight"
          }
        }
      },
#

This doesn't work

wary edge
alpine ibex
wary edge
dim tusk
#

Yey, I'm the 100k message

granite badger
dim tusk
#

the example for awaitTicks() it's awaitTick() without s

granite badger
#

That’s fixed

dim tusk
#

I guess yes? imma just check some of my screenshots if any

dim tusk
#

the example used emoteId instead of personaPieceId

granite badger
#

filed a bug on that

tidal wasp
#

Can you set multiple different states with one setPermutation

charred gorge
#

Yes

warm mason
chrome flint
#

how do i spawn a structure again?

chrome flint
#

oh its under the world, i thought it was from dimension

#

thanks

acoustic basin
#

hey guys! so i'm using Poggy's template for double plant, and for some reason, just modified, registration of custom component, beforeOnPlayerPlace doesnt trigger, only onPlayerDestroy works, any clues y?

world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('v360:double_plant', {
        beforeOnPlayerPlace({block, permutationToPlace, cancel}) {
            const above = block.above()
            if (!above.isAir) {
                cancel === true
                return
            }
            above.setPermutation(permutationToPlace.withState('v360:double_plant', 'upper_bit'))
        },
        onPlayerDestroy({ block, destroyedBlockPermutation }) {
            const below = block.below()
            if (below.typeId === destroyedBlockPermutation.type.id)
                below.setType('minecraft:air')
        }
    })
})```
dim tusk
#

that's why poggy didn't destruct it because the cancellation won't work.

acoustic basin
#

aaaaaa

dim tusk
#

also that's not how you set a value. It's always =

acoustic basin
#

i didnt know it wouldn't work y destructing

dim tusk
#

=== is comparing

acoustic basin
#

so i should make index file and everything exactly like in the template?

dim tusk
acoustic basin
dim tusk
#

I mean, can't you just copy the component ID on every block?

acoustic basin
#

like, 1 single custom component for all blocks that have custom components?

wary edge
#

Destructuring bad.

acoustic basin
#

i ahvent thought of that

dim tusk
#

tho it depends if you want those blocks to have a plant thingy

acoustic basin
#

and if being honest, idk what destructuring means in scripting

wary edge
#

Custom compoments are supposed to be reused by multiple items/blocks.

acoustic basin
#

i have 1 custom component, v360:double_plant for all of my double plants

dim tusk
acoustic basin
#

i did everything according to the template, but beforeOnPlayerPlace still doesnt work, only onPlayerDestroy works

#

i cant understand what am i doing wrong

wary edge
acoustic basin
#

yes, it is registered

#

since onPlayerDestroy works

wary edge
acoustic basin
#

just copy-pasted template code

wary edge
#

No idea. Open a post then with your updated code. Are you using an item proxy?

acoustic basin
#

and the upper bit is not getting placed, and the event is not getting canceled when there's a block above the plant

dim tusk
#

try doing console.error()

acoustic basin
#

oh

#

right

#

its probably broken with item

#

i have an item block placer...

#

nice mojang

wary edge
dim tusk
acoustic basin
#

okey... itemUseOn...

#

thank u anyway guys

prisma shard
#

hi everyone

woven loom
#

hi

wheat helm
#
system.runInterval(() => {
  world.getDimension("overworld").getEntities({
    location: {
      x: 508, y: 75, z: 15
    },
    volume: {
      x: 0, y: 0, z: 0
    }
  }).forEach(e => {
    e.runCommandAsync("say in block")
  })
})```

How do I change this to only get entities who are standing exactly inside of the block location, and not entities who are only touching the blocks.

(Currently when placing a block at the defined location, and you stand on top of it/next to it it will detect it as if you're standing inside of it)
#

In addition, I also want it to work with a wider volume (e.g. volume.x = 10) which means using maxDistance instead of volume will not work

shut citrus
#

Can I do it with scripting now?

gaunt salmonBOT
chilly fractal
#

Yo

chilly fractal
#

No one?

#

Really?

#

It's just concept

#

Not even code

thorn flicker
#

be patient

untold magnet
#

mhm, is it possible to make the fishing time faster using scripts && vanilla fishing rods ?

untold magnet
#

f

#

anyways

untold magnet
chilly fractal
#

But

#

I haven't really slept the last 2 days

#

Kinda

thorn flicker
#

why

chilly fractal
#

I am operating from yesterday's sleep

chilly fractal
#

And i have a deadline

chilly fractal
deep arrow
chilly fractal
#

How am i based

deep arrow
#

¯_(ツ)_/¯

chilly fractal
#

Okay then

#

Have a great day

thorn flicker
#

people say based to anything

deep arrow
#

Indeed

#

Mainly to relatable things

#

Anyways im bored so im joining this convo

chilly fractal
#

Cool

deep arrow
#

Whats going on yall

chilly fractal
#

Does anyone wanna help?

#

With concept

deep arrow
wary edge
#

Please don't go fishing for help.

#

Seriously.

chilly fractal
#

Nah dude

#

Just

#

Someone is bored

wary edge
#

It really isn't our responsibility that you have a deadline.

deep arrow
#

Yo sup smokey

chilly fractal
#

But nathan is bored and wants to join this convo so i decided why not

#

Anyway, i kinda wanna send data across addons but securely

deep arrow
#

I believe his point is your just fishing from the channel specifically not me

deep arrow
chilly fractal
#

Nahnah it isnt

#

I got good encryption

#

It isn't cryptographic

#

But its pretty good

#

You have to decrypt with an encrypted api key

#

My problem is

#

The api key is sent with the command in the /scriptevent command

#

Which means even if you didn't decrypt

#

Any other addon can just reconstruct the command and call the api of the main addon

#

And get the response

deep arrow
#

Look into http encryption and you can use the same public and private key systems

chilly fractal
#

Kk thanks

#

I really appreciate it

valid ice
#

I would suggest server admin secrets, but that doesn’t seem to work well here

deep arrow
#

Never looked into them

chilly fractal
#

Thanks also!

deep arrow
chilly fractal
valid ice
deep arrow
# chilly fractal No one...

Realistically theirs no reason to encrypt things like that, because the normal player cant access script events let alone read them or modify addons within a world

#

Complex ipc doesnt need such encryption atm tell it become more radicalized

#

And becomes more common

deep arrow
#

Is that like why you'd use that

valid ice
#

Never heard of it

deep arrow
#

I've heard of it but it doesnt seem possible

valid ice
#

It’s mainly for if you have other people editing your addons and don’t want your sensitive information available to them

deep arrow
#

Since nothing related to them should be sent to clients

valid ice
#

Like, your login information for a voting site, say, so you can tally votes. You have your password & email as secrets, so then the other coders can just call the secrets vote_email or something without ever seeing the real email address

deep arrow
#

Ahh i should incorporate that to my firebase api later then

#

Is the actual data just stored in a json somewhere in the server files?

valid ice
#

Note that it’s only available on BDS, because you need to define the variables in a separate file (which is only available on BDS)

deep arrow
#

I wonder if it reads irt

valid ice
#

What’s irt

deep arrow
#

In Real Time

#

My bad

valid ice
#

You can’t set any data to the secrets, if that’s what you’re looking for

#

Just read

deep arrow
#

I was more thinking of external programs modifying the file

valid ice
#

Hmm, that may be possible, given that it’s just a file

#

Never tested it, so

#

Hell, I’ve never used the secrets regardless, so

deep arrow
#

I might test it later and see if it modifies in real time

deep arrow
valid ice
#

By chance, does your firebase do cross-server communication (e.g. a ban database that can be accessed across multiple servers)?

deep arrow
#

Mine?

valid ice
#

The API thing you mentioned

deep arrow
#

Oh yeh

#

It does

valid ice
#

I’m just looking for something that communicates cross server for global network management

deep arrow
#

It doesnt cache anything so everything is read irt, which kinda slows it down

#

But im planning on a v2 that has a ttl system

valid ice
#

Neato

deep arrow
#

The api is very minimal tho just set and get lol

deep arrow
valid ice
#

Sure!

deep arrow
#

I also plan on minifying v2 into 1 file

valid ice
#

I’ll take a look later, thanks 🙏

daring prawn
#

hello, how can I store integer value in block

daring prawn
# deep arrow Wym

i have energy pipe that store energy and i want to store how much power it contains

deep arrow
# valid ice I’ll take a look later, thanks 🙏

Also idk if its worth it but it might be faster, if you run all the servers on local network, you can host your own database such as mysql, and have a nodejs webserver act as a communicator taking http requests from the addons and interacting with the databse

#

It would most likely be faster than firebase since its ran locally

valid ice
#

Yeah, I'm hosting through a third party service, so

#

Would love to self host but I don't have the resources to do so

untold magnet
#

it is possible to detect when the player shoots an arrow using a bow right?

untold magnet
untold magnet
thorn flicker
#

it will.

untold magnet
#

alright ty

thorn flicker
untold magnet
#

ya i see

chilly fractal
#

I see

#

The 26th time probably we reached 100k messages

#

This is funny lol

warm drum
#

cant script access lootable?

wary edge
warm drum
#

they should support it

deep arrow
#

screw it, im bored imma make reverse geyser, add java to bedrock

dim tusk
#

-# I'm clueless asf

slow walrus
deep arrow
twilit tartan
#
import { world, system } from '@minecraft/server';

const TELEPORT_DISTANCE = 5; 
const TELEPORT_OFFSET = 1.2;

system.runInterval(() => {
    const players = world.getPlayers();
    players.forEach(player => {
        const entities = player.dimension.getEntities();

        entities.forEach(entity => {
            if (entity.typeId === 'minecraft:sheep') {
                const distance = Math.sqrt(
                    Math.pow(player.location.x - entity.location.x, 2) +
                    Math.pow(player.location.y - entity.location.y, 2) +
                    Math.pow(player.location.z - entity.location.z, 2)
                );

                // Si la oveja está cerca del jugador
                if (distance <= TELEPORT_DISTANCE) {
                    const viewDirection = player.getViewDirection();
                    
                    const newPosition = {
                        x: player.location.x + viewDirection.x * TELEPORT_OFFSET,
                        y: player.location.y + 0.8,
                        z: player.location.z + viewDirection.z * TELEPORT_OFFSET
                    };

                    entity.teleport(newPosition);

                    player.runCommandAsync(`tp @e[type=minecraft:sheep] ${player.location.x} ${player.location.y + 0.8} ${player.location.z} facing ${player.name}`);
                }
            }
        });
    });
});```
#

I need the sheep to always see the player, but this command doesn't work. Does anyone know how to do this?

fervent topaz
#

do u know how to give them propertys

knotty plaza
#

Entity properties have to be predefined first on their json files

#

That means you would have to edit player.json

covert goblet
#

folks, is it best to use playerPlaceBlock or itemUse when tracking the blocks a player places?? they both work i was jsut wondering on peoples preferences??

knotty plaza
#

itemUse can fire even if the block was not successfully placed

covert goblet
#

it certainlky does seem more concise, plus the PlaceBlock does expose the block item

trail marten
#

is there a way to get player's locale (language)?

#

and maybe possibly get a translated string based on the key in the lang locale file

trail marten
#

AH

#

okay thanks

thorn flicker
#

not everything supports it though

#

like item lore

trail marten
#

im trying to apply it on server body forms

#

from

- get.HouseKey
- get.ActionHouse

to

- Get a house key
- Get a house.
#

hmmmm...

thorn flicker
#

it supports rawMessage

trail marten
#

yes

trail marten
#

you know what imma make my own language system (not based on player's current selected locale)

scarlet sable
#

my storage keeps running out while live editing addons

#

where does all of this data come from?

#

and how do I free it back

wary edge
scarlet sable
#

nvm

#

45 gb lmao

scarlet sable
noble bolt
#

turn off content log file

#

u probably dont need it

scarlet sable
#

how do I link a variable in teh behavior pack with an element in the resource pack?

chilly fractal
#

(You are gonna need to edit the player.json file tho)

scarlet sable
#

ahhh I see

chilly fractal
#

But here is how to link it:
player.setProperty('namespace:dangImLinked', true);

#

Also

#

Tip

#

It will not work on simulated players

empty light
#

is there a way to modify blocks before they load in the game....

chilly fractal
#

Uh no

empty light
#

ass

chilly fractal
#

Probably not

empty light
#

i have this idea in my head

#

and i want it

#

but i have to modify every block in the world

chilly fractal
#

Elaborate

#

You actually might be able to do it but

empty light
#

well basically, the thought is to have all blocks in the world be barries, and they turn back to their normal form once the player interacts with them

chilly fractal
#

Uh

#

Yeah thats kinda

#

Not very performant

empty light
#

so every single damn block would need its id stored

#

YEAHHH I FIGURED

chilly fractal
#

You can pre do this

empty light
#

any ideas?

chilly fractal
#

Yeah

#

Here let me make a code

empty light
#

!!!

chilly fractal
#

Snippet

empty light
#

what a kind young man

#

😭

#

i really just need a toggleable way to make blocks invisible

scarlet sable
#

btw was there an update to the manifest file?

#

I'm having a hard time getting my pack detected

chilly fractal
scarlet sable
empty light
#

im so lost on how to do this i thought this would be way easier just not performant

chilly fractal
chilly fractal
empty light
chilly fractal
#

Here

#

It isn't complete and won't save stuff like inventory, you have to make a serializer and deserializer for those. And also i dont actually set the block back when you interact with it because thats also complicated, and also this doesn't really manage ticking areas or does it go far. It just loops in the 50 by 50 range around all players and does it's thing. Implement that logic and you should be good to go.

deep arrow
#

Whats going on yall

scarlet sable
#

idk what's the problem with mine

chilly fractal
chilly fractal
oblique birch
#

my recipies keep overlapping when I scroll in the crafting table; anyone know a fix for this?

oblique birch
deep arrow
scarlet sable
tender ocean
#

i have your same issue, ever found a fix?

scarlet sable
#

nvm

#

what is @minecraft/server-ui btw?

#

never seen it before

valid ice
#

Allows for intractable, customizable forms created by the user

chilly fractal
scarlet sable
#

is it a new thing?

valid ice
#

Been around since 1.19.50 or so

deep arrow
somber cedar
#

@granite badger why are there blank squares in your docs

unique dragon
#

publicity

#

xd

scarlet sable
somber cedar
#

now it disappears

granite badger
#

I accidently pushed empty div elements from prototype code

deep arrow
#

Lol

chilly fractal
deep arrow
chilly fractal
#

I wonder what you'll achieve in the end

#

I wanna try it out lol

deep arrow
#

Im developing it as a plugin on SerenityJS

#

So far i got cross chat working and im working on chunkloading rn

scarlet sable
#

isSprinting is true or false right?

chilly fractal
#

Well best of luck to you!

chilly fractal
scarlet sable
scarlet sable
#

it's very clear

scarlet sable
#
function thirst(){
  if(system.currentTick %20 === 0){
  const playerCount = world.getAllPlayers();
  playerCount.forEach(player => {
     const state = player.isSprinting;
     if(state === true){
      world.sendMessage("player is sprinting");
     }
     world.sendMessage("player is not sprinting");
  }
)
system.run(thirst)
  }
system.run(thirst);
} 

#

mb

scarlet sable
dim tusk
#

tho why bother making a delay if there's a built-in delay in runtInterval?

scarlet sable
scarlet sable
dim tusk
#
system.runInterval(() => {
   for (const player of world.getPlayers()) {
      if (player.isSprinting) {
         // ...
      }
   }
});```
#

as simple as this

neat hound
#

try to space that out a few ticks... like 5

scarlet sable
#

But I want each player to have a set of variables later

scarlet sable
#

Basically this is the start of thirst system

distant tulip
dim tusk
#

use dynamic property or an object variable

#

each player has thirst data saved?

#
const thirst = {};
thirst[player.id] { duration: 10 };

const thirst = JSON.parse(player.getDynamicProperty('thirst') || '{}');
thirst.duration = 10;
player.setDynamicProperty('thirst', JSON.stringify(thirst));```
scarlet sable
dim tusk
scarlet sable
#

Oh nice

dim tusk
#

tho you can't access if the player isn't in the world obviously

scarlet sable
#

i thought I had to make like a system that creates a var for each player

dim tusk
#

so yeah, not a good idea

scarlet sable
#

Yep now that I think about it

#

It was a dead end

dim tusk
#
const thirst = JSON.parse(player.getDynamicProperty('thirst') || '{}');
thirst.duration = 10;
player.setDynamicProperty('thirst', JSON.stringify(thirst));```
sharp elbow
#

It is a native function in JavaScript that takes a string and parses it as JSON. The resulting value is an object you can manipulate

dim tusk
# scarlet sable Whats Json.parse tho?

JSON. parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string.

scarlet sable
#

Ahhh

#

That's so cool

sharp elbow
#
const InJSON = '{"key":"value"}';
const Obj = JSON.parse(InJSON);
console.warn(Obj.key);  // "value"
scarlet sable
#

So obj became an object with the InJson's elements inside?

sharp elbow
#

Yea, you could think of it that way

scarlet sable
#

Mhm that's useful

#

Ty guys

olive rapids
#

Can someone help me create a script that makes a sound sound when I touch a block?

#

please

olive rapids
#

sound and add score

scarlet sable
olive rapids
scarlet sable
deep arrow
distant tulip
deep arrow
#

Cactus doesnt do anything when u interact with it?

olive rapids
deep arrow
scarlet sable
olive rapids
#

commands slow

olive rapids
deep arrow
#

Oh you coukd just detect if the block at the player's location is that block

distant tulip
#

lol

#

give me sec, i will make something

dim tusk
olive rapids
#

😦

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

const checkInterval = 10; //run every 10 ticks
const r = 0.4; //radius to check for blocks, adjust it until it make sense
const targetBlock = "minecraft:gold_block"; //block to detect
const soundEffect = "random.orb"; //sound to play

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const { x, y, z } = player.location;
        
        //scan a small area around the player
        for (let dx = -r; dx <= r; dx++) {
            for (let dy = -r; dy <= r; dy++) {
                for (let dz = -r; dz <= r; dz++) {
                    const block = player.dimension.getBlock({ x: x + dx, y: y + dy, z: z + dz });

                    if (block && block.typeId === targetBlock) {
                        player.playSound(soundEffect);
                        return;
                    }
                }
            }
        }
    }
}, checkInterval);

i think it is better to hard code the places to check (8 dir around the player feet, 8 around the head, up and below), but i don't have time to make that

olive rapids
#

thank u so muchhh

#

:DDDDDDDDDDDDDDDDDDDDDDD

distant tulip
#

ur wlc

#

it is passed midnight, time to get some sleep

#

good night guys 👋

scarlet sable
#

Isn't block.typeId enough?

thorn flicker
#

blockVolume is out of beta.

distant tulip
#

it is beta

thorn flicker
#

its not

distant tulip
#

it is

thorn flicker
wary edge
distant tulip
#

my npm is outdated 😅🤦‍♂️

distant tulip
thorn flicker
oblique heath
#

Is getBlocks out of beta yet?

olive rapids
#

.-.

thorn flicker
oblique heath
distant tulip
#

read?

thorn flicker
#

if you are not trolling...

#

read

#

scroll up

#

to be fair I said blockVolume was out of beta, not getBlocks

oblique heath
#

sorry I saw block volume and thought about getBlocks

thorn flicker
#

it is

oblique heath
#

I haven't touched scripting api in a few months

thorn flicker
#

out of beta

#

both are

oblique heath
#

nice

thorn flicker
#

blockVolume came out of beta before getBlocks

oblique heath
#

when did it come out of beta?

distant tulip
thorn flicker
#

doesnt make sense

distant tulip
#

yep

thorn flicker
wary edge
#

Well...i think some events were marked stable but the listeners were marked beta.

thorn flicker
#

ive seen people talk about that

#

didn't it confuse people on documentation

olive rapids
#

One question, what do you think of those people who steal maps from other creators and nodify them?

olive rapids
fallen hearth
#

how do i get the namespace of the item that is in my hand?

dim tusk
fallen hearth
#

undefined

dim tusk
#

where are you using it?

fallen hearth
sterile epoch
#

how do i remove the "you have been kicked" like on the hive when someone gets banned

fallen hearth
#

@dim tusk I'm managing to return the entity ID, but I want to remove "minecraft:cow" and leave just cow

#

How can I do this?

dim tusk
fallen hearth
#

?

dim tusk
fallen hearth
#

nice!

#

thankys friendy

celest abyss
#

How can I detect when an entity is in the same position as the player?

#
system.runInterval(() => {
  let players = world.getAllPlayers()
  for (let player of players) {
    if (player.dimension.getEntities({ x: player.location.x, y: player.location.y, z: player.location.z }).typeId == 'entity:entity') {
//code
#

This doesn't work

valid ice
#

getEntities returns an array, not a single entity

wary edge
valid ice
#

^

wary edge
celest abyss
#

Oh

#

So what should I use?

#
getEntitiesAtBlockLocation

This?

wary edge
dim tusk
#

like how you do the getAllPlayers()

sterile epoch
#

is an average tps of 19.84 good?

#

I was calculating my tps and it kept bouncing between 19.70-20.20 I'm not sure if this is a good sign or not? should my tps be consistently above 20 or is fluctuations below 20 okay?

fallen hearth
#

What is getLore() for?

dim tusk
fallen hearth
dim tusk
fallen hearth
dim tusk
dim tusk
fallen hearth
#

okay

#

thankys

celest abyss
#

can you modify a players speed with script without using the speed effect?

charred gorge
edgy elm
#

can u write a code in game with modalFormData textfield?

charred gorge
#

What?

edgy elm
# charred gorge What?

is it possible to run a code ingame with modalFormData? for example if u want to execute sending message or more complicated code like opening a form?

trail marten
#

idont know whats wrong with my script but everytime that i call getDynamicProperty() on a Player class, the game crashes

#

whats the actual proper way to handle it anyway

charred gorge
edgy elm
#

@charred gorge If u have, maybe u could drop it here and mention me. This would be a great help for me. Cause I've been planning to update my addons into importing the codes in game. Its like if I want to add new button. Ill just inport the code in game.

charred gorge
#

No I don’t have the function that you are looking for, I was just showing you how to execute a function/property using text you’re going to need to code it yourself. I was referring to my own code which I can show you parts if you want; however it probably won’t be a ton of help though, my code in parts does what you are doing but has a pile of other aspects.

misty pivot
#

how do i use the variables from molangVariableMap in my particle's json?

#

i used v.example_name.speed but nothing really happened

dim tusk
misty pivot
#

hold up a sec

#
const dash = new MolangVariableMap();
player.dimension.spawnParticle("dby:dash_manual", {x: player.location.x, y: player.location.y + 1.2, z: player.location.z}, dash.setSpeedAndDirection("particle", 0.1, player.getViewDirection()))```
#

in game it would fly off very fast and face a random direction

dim tusk
misty pivot
#

how so?

dim tusk
misty pivot
#

alright lemme try

#

it did send me these errors

#

[Molang][error]-particles/dash_manual.particle.json | v.particle.speed | Error: unable to find member variable .speed

[Molang][error]-particles/dash_manual.particle.json | v.particle.speed | Error: unhandled request for unknown variable '.speed'

[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_x | Error: accessing a variable that doesn't currently exist in this entity: variable.particle

[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_x | Error: unable to find member variable .direction_x

[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_x | Error: unhandled request for unknown variable '.direction_x'

[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_y | Error: accessing a variable that doesn't currently exist in this entity: variable.particle

[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_y | Error: unable to find member variable .direction_y

[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_y | Error: unhandled request for unknown variable '.direction_y'```
dim tusk
#

It might be sensitive that's why

misty pivot
#

it didn't work, i changed the particle to dash

dim tusk
#

Did you use snowstorm?

misty pivot
#

yep

chilly fractal
#

Yo hol up

#

I haven't messed with velocity in scripting api for a whilr

#

While*

#

Would a good'ol player.getVelocity() work?

#

Perfect answer:
I'll test

scarlet sable
dim tusk
#
const velocity = player.getVelocity();

Math.sqrt(velocity.x ** 2 + velocity.y ** 2 + velocity.z ** 2);```
#

-# not sure if this is the right math lmfao... That's why I failed math

distant tulip
scarlet sable
#

I like the syntax of ofEach lol

#

also how could for be better?

distant tulip
#

@celest abyss btw
{ x: player.location.x, y: player.location.y, z: player.location.z }
player.location is already a vector3
so just use it directly

scarlet sable
distant tulip
scarlet sable
#

it's better even for arrays?

#

interesting

distant tulip
#

yeah

scarlet sable
distant tulip
#

yeah

distant tulip
#

but why not just store the number directly

dim tusk
scarlet sable
scarlet sable
#

btw are custom effects possible?

dim tusk
scarlet sable
#

that sucks

scarlet sable
#
system.runInterval(() => {
  for(const player of world.getAllPlayers()){
const thirst = JSON.parse(player.getDynamicProperty('thirst') || {})
thirst.hydration = 100;
if (player.isSprinting === true){
  thirst.hydration -= 1;
}

player.setDynamicProperty('thirst', JSON.stringify(thirst));

}
world.sendMessage(thirst.hydration)
}, 40)
#

is this syntax correct?

#

nvm I forgot the ' at '{}'

scarlet sable
#

how do I detect when a player eats a certain type of food?

charred gorge
#

I think that one of the events detects that itemCompleteUse maybe and then you just check what item was used in the interaction.

wary edge
scarlet sable
#

I tried this

#

but it causes multiple detections

#

and I doubt it would work with a filter

#

and even if I don't finish the interaction it counts as a complete one

scarlet sable
#

update: it's all working now

cinder shadow
#

I noticed this when I was working with potions

#

same thing happens with food

deep arrow
#

I wonder if anyone had made a physics engine with script api

woven loom
#

what you mean by that ?

#

why would anyone make a physics engine that works at the rate of 20 times / s
🤔

scarlet sable
#

so it would subscribe multiple time's in the same interaction

distant gulch
#

How do I get an entities inventory because people say to use getComponent('minecraft: inventory').container but it doesn't pop up on the bridge auto completions

dim tusk
distant gulch
# scarlet sable can you send your script?

It's literally nothing besides a custom component with me getting the source entity then adding get component with the inventory but their is no auto completion for container or inventory

dim tusk
#

that's how you get it...

distant gulch
scarlet sable
dim tusk
#

Don't ALWAYS trust bridge

dim tusk
distant gulch
dim tusk
#

you can just make the item usable or eatable and use startUse and stopUse

distant gulch
#

I'm not just gonna do what I do with Roblox scripts and blind eye my code

dim tusk
scarlet sable
#

I used the completeUse

distant gulch
dim tusk
#

that's how you get the inventory

distant gulch
#

Bro

#

WHY DOESN'T IT SHOW ON THE AUTO COMPLETIONS

dim tusk
#

It maybe not updated

distant gulch
# dim tusk don't sweat it too much

How when I'm literally trying to make something that's important in my mods function but I can't because I can't find the auto completions which makes it way harder for me because I have to keep going back and forth looking at different things

#

And plus I'M CODING ON XBOX WHICH MAKES IT EVEN HARDER

dim tusk
dim tusk
distant gulch
#

No I use the website duh

dim tusk
#

Ohh sorry if I ask since there's an app version of it 🤷

distant gulch
#

Ik

#

Used to use VSCode but my laptop broke so I can't anymore

#

That's why I think VSCode is way better than bridge in every way

#

I had 6 years of experience on VSCode and now I can't use it anymore

distant gulch
# dim tusk It maybe not updated

And it obviously has been updated they update the auto completions almost every time Minecraft updates, it USED to have the auto completions for it working but NOW it doesn't for SOME reason and why TH does the changelogs say "changed from string to T" WTH IS T

scarlet sable
#

@distant gulch you're making a custom container?

distant gulch
#

Custom Block Component

distant tulip
#

coding on Xbox???

distant gulch
distant tulip
#

is that a thing

distant gulch
#

If you wanna pay 3$ then yes

distant tulip
#

isn't it better to use your phone

distant gulch
#

No

#

Xbox has better performance

#

In my case

distant tulip
#

alr

distant gulch
#

It was on sale for like 0.79$ before

#

But I bought it when it was 3$

distant tulip
#

free apps don't stick for long

distant gulch
#

There's a free trial for it

#

For 24 hours

#

I used to keep creating Microsoft accounts to use it before I actually bought it

scarlet sable
distant gulch
#

It's for my keycard reader but I made a separate script from the actual key card reader script so it wouldn't take up more

#

Needs to soley only detect when you're holding NOTHING

#

Because other items/blocks already activate the "Keycard Level num+ required" and the empty mainhand doesn't because it detects when an item is being used on it

sweet seal
#
world.beforeEvents.playerLeave.subscribe(ev => {
    const player = ev.player;
    let combatEndTime = player.getDynamicProperty("combatTime");

    if (combatEndTime && Date.now() < combatEndTime && player.hasTag("pvp")) {
        system.run(() => {
        world.sendMessage(`${player.name} combat logged`);
        player.addTag("combat_logged");
        playerLeaveInCombat(player);
        })
    }
});

failed to get property 'nane' at anonymous

valid ice
#

Player becomes invalid once they leave- and a system run delaying the code by a tick makes it run after the player has left.

sweet seal
#

how can I fix

valid ice
#

Define the player name before using it (outside the system run)z

#

And you cannot add a tag or run that function

sweet seal
#

anti combat log systm

untold magnet
#

hmm, is it possible to make my entity look at the player using scripts?
like getting the player from view distance, and somehow applying rotation to the entity to make it look directly at the player,

scarlet sable
#

With just command blocks

#

Probably possible

untold magnet
dim tusk
#

get the direction vector of entity location and the target locations

#

I mean subtract them

#
function faceTarget(e, t) {
    const dx = t.x - e x, dy = t.y - e.y, dz = t.z - e z;
    const yaw = Math.atan2(-dx, dz) * 180 / Math.PI;
    const pitch = Math.atan2(dy, Math.sqrt(dx * dx + dz * dz)) * 180 / Math.PI;
    e.applyRotation({ x: yaw, y: pitch });
}```
fast lark
#

Hi yall

#

I dont remember how can i take a item in a placed shulker box(slot 2)

let 2 = ???

dim tusk
fast lark
dim tusk
fast lark
#

Can i ask something else?

dim tusk
dim tusk
dim tusk
fast lark
# dim tusk ye?

Is it possible to give a person a shulker box pre loaded without structure block?

fast lark
#

Sad

dim tusk
#

best way is to place a shulker box then put items and so Block.getItemStack()

#

you can get the items Inside

fast lark
#

Too much work

dim tusk
#

I mean if you don't want structure yes

#

either way it's your choice

fast lark
#

Thx

scarlet sable
#

how do I randomize an action?

#

like instead of a monotone -1 operation from a var it could do -1 or -2

scarlet sable
#

again it was done with Math.random

untold magnet
#

hm, is it possible to detect catching a fish or anything from the sea using a fishing rod?

woven loom
#

test

deep yew
#

but is a fish caught by a fishing rod considered an entity, or is fishing just an event that gives you a loot table?

valid ice
#

entity remove cuz the bobber

deep yew
#

but then you get the bobber

valid ice
#

maybe item use, then

deep yew
#

the item given is a physical item that gets pulled to you though....

#

that's probably how

valid ice
#

before item use-> scan & save inventory
after item use -> compare against before event's inventory to see changes (what was caught)

deep yew
#

was going to say that

#

but it has issues because of a player fishing, then picking up another item, then catching or not catching a fish and then it's a false positive

valid ice
deep yew
#

yeah idk

valid ice
#

The events would both run when they reel in

deep yew
#

ah true

valid ice
#

So you'd be comparing the inventories within a tick of each other or so

deep yew
#

so it's a split second

#

but that tick is possibly enough for the item to not reach the player

valid ice
#

That's for testing to figure out

deep yew
#

yep

#

and fish farms using hoppers or whatever could mess with it

#

so many factors

valid ice
#

The best course of action is to remake the fishing system from scratch ech

deep yew
#

world.afterEvents.playerCatchFish

chrome flint
#

does anyone have a db manager?

fallow minnow
#

a

knotty plaza
#

I would just listen for the fishing hook being removed and then the item being spawned in a certain range from that position

#

I remember doing a system for that but I don't remember in what part of my computer it is now

chrome flint
#

does block.above() returns air or undefined?

untold magnet
dim tusk
distant tulip
dim tusk
distant tulip
#

huh

dim tusk
distant tulip
chrome flint
#

oh okay, that's why lol

#

i gotta use .isAir() to detect air

distant tulip
#

uh... i just said no

distant tulip
#

@untold magnet

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

world.beforeEvents.entityRemove.subscribe((event) => {
  const hook = event.removedEntity;
    if (hook.typeId === "minecraft:fishing_hook") {
        const loc = hook.location;
        const date = Date.now()
        const dimension = hook.dimension
        const id = system.runInterval(() => {
          const id2 = system.runTimeout(()=>system.clearRun(id),20)

          const items = dimension.getEntities({type:"minecraft:item", location: loc, maxDistance: 1})
          for(const item of items){
            if(date - (itemSpawnDate.get(item)??0) < 100){
              console.warn(`Caught item: ${item.getComponent("item").itemStack.typeId}`);
              system.clearRun(id)
              system.clearRun(id2)
              return
            }
          }
        });
    }
})

const itemSpawnDate = new WeakMap() 

world.afterEvents.entitySpawn.subscribe((event)=>{
  if(event.entity.typeId !== "minecraft:item") return;
  itemSpawnDate.set(event.entity, Date.now());
  system.runTimeout(()=>{
    itemSpawnDate.delete(event.entity)
  },20)
})
fast lark
sage sparrow
#

hi there, how can I find structures saved with structureManager? I mean, is it available in any folder that I can download? cannot find it

granite badger
#

It's saved in db folder like all structures

noble bolt
#

Hi

sage sparrow
granite badger
untold magnet
distant tulip
#

it didn't work for you?

#

brb

untold magnet
untold magnet
distant tulip
untold magnet
distant tulip
#

3 is a bit too much

fallow rivet
distant tulip
#

read the messages for context?

untold magnet
#

anyways,

#

bao_comm_ty for helping

#

hmm

untold magnet
#

lemme send u the updated one.

#
world.beforeEvents.entityRemove.subscribe((event) => {
  const hook = event.removedEntity;
    if (hook.typeId === "minecraft:fishing_hook") {
        const loc = hook.location;
        const date = Date.now()
        const dimension = hook.dimension
        const { x, y, z } = hook.location
        const id = system.runInterval(() => {
          const id2 = system.runTimeout(()=>system.clearRun(id),20)

          const items = dimension.getEntities({type:"minecraft:item", location: loc, maxDistance: 2})
          for(const item of items){
            if(date - (itemSpawnDate.get(item)??0) < 100){
              if (fisherman_hat === true) if (Math.random() <= 0.1) dimension.runCommandAsync(`loot spawn ${x} ${y} ${z} loot "gameplay/fishing"`)
              system.clearRun(id)
              system.clearRun(id2)
              return
            }
          }
        });
    }
})```just help me make it work only at the player who is fishing and equipping the hat.
slow walrus
#

why don't you just subscribe to the spawnEvent inside the hook event?

#

it's a beforeevent, so the event listener should fire in the same tick

#

then it's easier to test items since you don't have to do that date map thing

distant tulip
distant tulip
untold magnet
fast lark
#

yo @dim tusk how can i return the id of the item with the shulker box thing

#

bc it dosent work

valid ice
woven loom
granite badger
#

i have to manually update the docs for v2.0.0-beta

woven loom
#

wonder what builder class is

scarlet lynx
woven loom
#

it is

#

from basic hello world to anything complex

valid ice
#

Knowing how script API 2 interacts with the world is pretty important

granite badger
#

check the minecraft/server docs and look what i wrote

warm drum
#

guys, with the v2.0.0-beta

unique acorn
warm drum
#

what do u think the upcoming features will be

deep arrow
distant gulch
#

Same message with index.js ending

woven loom
#

plugins/index.js

#

you using dev packs?

distant gulch
covert goblet
#

Your import Exec is looking for a file called plugins.js in the core directory

distant gulch
#

I changed

#

It itself replaces aliases with this path

#

there is no extension at the end, it should look for index.js itself

distant gulch
covert goblet
#

So are you saying there is a plugins.js file in the plugins directory??

distant gulch
#

The import doesn't say anything about the extension, it know that the index.js file should be inside this folder. But even after manually adding the index.js to path it doesn't change anything, it still doesn't want to use this file.

#

Everything starts working only after renaming all the index.js files in the project is for something else

#

like main.js

covert goblet
#

What does your manifest look like??

distant gulch
#

nvm fixed

covert goblet
#

Excellent news, what was it??

distant gulch
#

idk

#

I renamed all the index.js files to others and everything works

#

for some reason, after running the build task with tsc-alias, the code does not find files with the name index.js

covert goblet
#

Aaahhh......ZediaphConfused

#

Well glad you got it sorted!!!

chrome flint
#

how to make blocks items to be unstackable

scarlet sable
chrome flint
wary edge
fast lark
#

Idk if it’s possible

edgy elm
#

Hello here, i just want to ask if I have 2 custom ui installed in my world. can i run the ui one at a time? 2 addons for different ui?

woven loom
#

custom json ui?

edgy elm
woven loom
#

you can make ur ui's conditional based on title

chilly fractal
#

Yo

#

I am trying to make a foolproof way of detecting when someone lands

#

I kinda got the velocity of someone jumping.. aka (y = 0.42...)

#

player.getVelocity().y >= 0.42

#

But that still would flag for someone launched

#

Oh yeah right i can just increase the number and do some more operations

#

player.getVelocity().y < 0.43
For anyone wanting to detect when someone landed completely foolproof

#

I think at least

#

Kinda have been testing too much

#

I'm sure jumping and that jump swim in water are much less then 0.43

#

Jump is 0.42

#

And that "jump swim" is 0.34 i think

prisma shard
#

thats it

#

guys actually im doing scripting after a lot of month

#

can any one tell me what has changed within these months

sterile epoch
hybrid island
#

how to set item durability? cuz

thorn flicker
hybrid island
#

cuz it says its read only

thorn flicker
#

no it doesnt.

#

it says it cant be edited in read only mode

hybrid island
#

ya

thorn flicker
#

wdym "yeah"

hybrid island
#

i wanna change the durabilityy of a item

thorn flicker
#

you are misunderstanding what it says.

hybrid island
#

so what does it mean?