#Script API General

1 messages · Page 74 of 1

fathom hemlock
#

that list

#

with the tems

#

*items

leaden elbow
#

wdym how to use

fathom hemlock
#

yes how do I add custom items

#

for chestui

cyan basin
#

you just adjust the number in the main file

#

if you're using the latest version i think he made it weird and called it keys or some shit

leaden elbow
#

up, imma do smth

cyan basin
leaden elbow
#

so player.name returns default name, while player.nameTag returns name tag

cyan basin
#

yeah

leaden elbow
#

ok thanks

ivory bough
#

Nah

      entity.nameTag = "aaaaaaa"
     });

You cannot directly change it since its not a method and instead a property. You need to use the above

leaden elbow
#

so how do i change the name of specific player? like for example

#

i will use playerSpawnAfter event

#

that returns player right

cyan basin
#

yeah

leaden elbow
#

so i can directly do it?

cyan basin
#

you'd just get the player then change it to whatever

ivory bough
cyan basin
#
world.afterEvents.playerSpawn.subscribe((data) => {
    const { initialSpawn, player } = data;

    if (initialSpawn) {
        return player.nameTag = `[Noob] ${player.name}`;
    }
});```Something like this
leaden elbow
#

ok thanks

cyan basin
#

You might have to give them a few seconds to actually spawn in though

#

just decided to test it to make sure, left one is name and right one is nametag so yeah lol

ivory bough
cyan basin
#

Yeah, I just mentioned about giving them time since a few things I've wanted to do with the player when connecting doesn't run as the player hasn't technically loaded in yet

#

If it's not needed then fair enough

ivory bough
cyan basin
#

i don't get all the ins and outs of the script api yet lol.. i just know enough to get me through it 🤣

#

i'm actually stuck where i am with knowledge rn and it's a pain because i can't improve 😭

uncut sail
#

How to fix

    let item = wand.getComponent("minecraft:enchantable").getEnchantment({id: "unbreaking"}).level
  console.log(item)
distant tulip
#

getEnchantment(enchantmentType: string | EnchantmentType)
not an obj

uncut sail
uncut sail
cyan basin
#

well as minato mentioned.. it's not an object like you've written it to be.. it only accepts a string

cyan basin
#

I'm not fixing it for you lol

uncut sail
cyan basin
#

yeah

uncut sail
#

Not fix

cyan basin
#

is it enchanted?

#

your item?

uncut sail
#

No

cyan basin
#

welp, there's your issue then -_-

shy leaf
#

the content logs says enchantable component doesnt exist

cyan basin
#

it only gets enchants applied to the item

uncut sail
shy leaf
#

since it doesnt exist, .getEnchantment() doesnt exist too

#

hence the error

cyan basin
#

💀 lol

shy leaf
#

just... put a ? on component

#
wand.getComponent("minecraft:enchantable")?.getEnchantment("unbreaking")?.level
uncut sail
shy leaf
#

dear god

#

i cant see anything

cyan basin
#

can't read that for shit lmao

uncut sail
#

Bro any app for code in mobile?

shy leaf
#

quickedit

drifting ravenBOT
#
Please, no screenshots or photos!

Screenshots are hard to read, and photos even more so. This is especially true if you are using bridge or another tree editor, as this format obscures the JSON format.

We can help you best if you copy and paste your code here, or send it directly as a file.

nova flame
#

how do i give someone a mending book?

#

with scripts

#

ofc

#
const item = new ItemStack ("minecraft:enchanted_book")
                    item.nameTag = "Mending Book"
                    inventory.addItem(item)```
cyan basin
#

i don't think you can.. it's just an enchanted book but i don't think we can get the exact data for the books

uncut sail
shy leaf
#

zarchiver

uncut sail
#

Anyone from india

warped blaze
wise raft
#

Why do I get this error?

[Scripting][error]-Error: Failed to set property 'test:upper_block_bit' on block 'minecraft:air'    at onPlace (blocks.js:144)```
```js
        onPlace(event) {
            const above = event.block.above()
            const permutation = above.permutation
            if (!permutation.getState("test:upper_block_bit")) {
                above.setType("test:door")
                above.setPermutation(permutation.withState("test:upper_block_bit", true))
            }
        }```
gilded shadow
midnight ridge
wise raft
uncut sail
#

This is best i think

ivory bough
uncut sail
ivory bough
uncut sail
ivory bough
uncut sail
ivory bough
remote oyster
warped blaze
ivory bough
warped blaze
ivory bough
warped blaze
ivory bough
warped blaze
ivory bough
ivory bough
uncut sail
warped blaze
#

maybe he understand that way

uncut sail
#

I send link parasnal you ok

warped blaze
ivory bough
#

the translation may be janky

woven loom
#

nice

uncut sail
#

Bro i undarstand english Okkkk

ivory bough
uncut sail
woven loom
#

use can use acode or helix on ter,ux

ivory bough
woven loom
#

ye

ivory bough
#

No joke

uncut sail
ivory bough
woven loom
#

btw this, what u think

function getDirectionalGridXZ (r, x, z, X, Z) {
    let [ax, bx] = (Z + X > 0) ? [r, -r] : [-r, r];
    let [az, bz] = (Z - X > 0) ? [r, -r] : [-r, r];
    
    let result = [];
    let lerp = (a, b, t) => a + (b - a) * t;
    
    const dx = bx - ax
    const dz = bz - az
    const iLen = Math.abs(dx); // Steps for x-axis
    const jLen = Math.abs(dz); // Steps for z-axis 
    const xSign = Math.sign(dx)
    const zSign = Math.sign(dz)
    
    for (let i = 0; i <= iLen; i++) {
        result[i] = [];
        for (let j = 0; j <= jLen; j++) {
            const xVal = ax + x + xSign * i;
            const zVal = az + z + zSign * j;
            result[i].push([xVal, zVal]); 
        }
    }
    
    return result//.map(row => row.join('\t')).join('\n');
}```
#

As shown in this

uncut sail
woven loom
#

What?

ivory bough
warped blaze
uncut sail
woven loom
ivory bough
uncut sail
woven loom
#

This is achieved through a process known as varlet integration.

#

It is very simple, you can learn it on YouTube.

uncut sail
ivory bough
#

The guy above me is 100% a troll or someone's alt

warped blaze
ivory bough
woven loom
warped blaze
ivory bough
ivory bough
uncut sail
gilded shadow
warped blaze
warped blaze
#

he fooled us

ivory bough
ivory bough
uncut sail
woven loom
gilded shadow
#

there are other aspects in which score is better

woven loom
#

He used VI in that

uncut sail
#

Bro why say this

ivory bough
#

I thought I was talking in a dm

uncut sail
prisma shard
distant tulip
#

That not nice

wanton ocean
#

Are you able to detect how much damage an item should do??
for example if i enchant a sword with sharpness it does 8 damage
so i want its right click move to also do 8 damage. Just wondering.

distant tulip
#

not possible

prisma shard
#

Possible

#

Need some math from wiki for sharpness. And do applyDamage()

distant tulip
#

How are you going to get the item damage

#

Keep mind custom items

#

Welp, i guess it depends on his use case

prisma shard
#

Idk but i saw someone doing it

wanton ocean
lyric kestrel
#

YESSSSSSSSSSSSSSSSSSSSSSSSSSS

#

I've fixed the last thing I need for my wedge blocks to make them properly good now

#

I now just need to make some recipes, make the code a bit cleaner, and make a new file for those that want to add their own block textures!

#

That last one will be a later-on feature hopefully 🤞

nova flame
#
// List items and prices
const itemsPrizes = new Map([
    ["minecraft:dirt", 1],
    ["minecraft:oak_log", 2],
    ["minecraft:cobblestone", 3],
    ["minecraft:coal", 4],
    ["minecraft:coal_block", 40],
    ["minecraft:iron_ingot", 8],
    ["minecraft:iron_block", 80],```
#

why is oak log not working?

#

ive tried naming it just minecraft:log aswell

restive nexus
#

By chance, does anyone know how to activate an addon that requires the creator's key?

terse pulsar
#

How does the setLore works? The lore goes above the display_name

nova flame
terse pulsar
nova flame
#

yes

terse pulsar
dim tusk
terse pulsar
terse pulsar
dim tusk
terse pulsar
#

Hmmm

nova flame
fathom hemlock
#

can someone help me?

#

or just nvm

terse pulsar
#

This will work? {translate: 'text.evolution.success', with: ['item.ne:sharingan1' + ' -> ' + 'item.ne:sharingan2']}?

meager pulsar
#

is startup on beta?

thorn flicker
meager pulsar
#

system.beforeEvents.startup.subscribe(({ blockComponentRegistry, itemComponentRegistry }) => {

meager pulsar
#

i heard it was deprecated, but if startup is in beta

#

idk which to use

thorn flicker
#

you have to switch to it.

#

when using 2.0.0

meager pulsar
#

or wil, it be fine if i don tuse 2.0.0?

thorn flicker
#

if you stay on 1.18.0 no.

meager pulsar
#

ok thanks

#

world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry, itemComponentRegistry })

#

what's wrong now?

meager pulsar
lyric kestrel
#

Ye, it's deprecated

#

these are the only ones accepted

meager pulsar
lyric kestrel
dim tusk
lyric kestrel
dim tusk
#

fuck wrong reply.

#

Mbmb

gilded shadow
#

is it possible to make a chest-GUI with script api?

#

like know when player takes out an item and cancel

meager pulsar
dim tusk
dense skiff
#

Anyone know how to set an armor stand pose via script?

weary umbra
#
world.afterEvents.itemUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;
    const playerData = PlayerData.load(player.name);
    for (const quest of QUESTS) {
        let isCrafted = item.getDynamicProperty("crafted") || false
        if (quest.type === "craft" && quest.itemTypes.includes(item.typeId)) {
            if (!isCrafted) {
                playerData.updateQuestProgress(quest.id, playerData.questProgress[quest.id].progress + 1);
                item.setDynamicProperty("crafted", true);
            }
        }
    }
});

can someone please tell me why the dynamic doesn't work?

wary edge
weary umbra
#

ohhh

#

bruh I forgot thx

lyric kestrel
fallen cape
#

The deprecated thing is just a reminder to prepare for it's removal in v2

tropic geyser
dim tusk
vast rune
#

How do I set my scripts to TS in bridge. v2?

lyric kestrel
#

change .js to .ts

vast rune
#

idk how to specify that

#

like, right here

#

do i just change the entry point?

terse pulsar
#

The itemStack.hasTag uses 'minecraft:tags' item component?

vast rune
#

id guess so

#

because items are like floating entities when dropped

#

so you can tag them

terse pulsar
vast rune
#

its not a valid value tho

terse pulsar
vast rune
#

it just says now, as i change it to "typescript" and entry point to "main.ts" that it is usng an unsupported runtime

terse pulsar
vast rune
#

alr, i found out that the only language supported is js

vast rune
dim tusk
dim tusk
terse pulsar
dim tusk
terse pulsar
weary umbra
#

any ideas?

cold grove
#

and you trigger an event for the entity using scripts

weary umbra
weary umbra
#

I'll just wait until the custom component is in stable maybe with that I can change the scale

terse pulsar
cold grove
meager pulsar
#

Is there a way to detect if a player is starving?

thorn flicker
#

theres no hunger apis

dense forge
#

Right so what things in scripting is currently deprecated just so I know?

woven loom
#

why

dense forge
shy leaf
#

worldInitialize before/afterEvents (changed to worldLoad)

#

and iirc there also was a few changes in custom component registery?

woven loom
dense forge
shy leaf
#

oh and there has been a change in applyKnockback too

dense forge
#

Are there work arounds for the script components theyve deprecated @woven loom?

warped blaze
warped blaze
#

world.beforeEvents.worldInitialize.subscribe -> system.beforeEvents.startup.subscribe

warped blaze
#

beforeEventsStartup

dense forge
#

What about the item use

warped blaze
#

world.afterEvents.itemUse

#

@dense forge do you mean itemUseOn?

#

it is not the same as itemUse

dense forge
warped blaze
#

and use playerInteractWithBlock to replace itemUseOn

#

@dense forge
itemUse = using an item
itemUseOn = using an item ON a block
this was the same as playerInteractWithBlock, that's why it got deprecated

dense forge
#

Still concerning how much has been deprecated

#

And your saying the button after and befire events will also now have to be system @warped blaze ?

humble lintel
#

Yeah I currently just have the server options managed by admins only

prisma shard
#

DimensionTypes.overworld/nether/end

#

It was removed hmm

#

so are we forced to use the string one

random flint
#

just use (Entity || Block).dimension

prisma shard
#

ikr

floral vessel
#

Is there a good way to calculate damage done to an entity taking into account armor, status effects, sheilds, etc?

random flint
#

Map each item what they do

shy leaf
#

you could try reverse engineering the damage

#

reduced damage * whatever the armor and enchantment they have

#

but it sounds way too painful

random flint
#

The hard part was to make it compatible with custom armor 😭

shy leaf
#

yeah that too

#

we dont have access to armor attributes

random flint
#

-# I've done it. Checking each item attributes 😭

floral vessel
#

I can't beleive that we still can't make a single complete feature with addons

shy leaf
#

bruj

shy leaf
#

man why dont we have attack damage attribute and other stuffs

#

when theres lava movement for whatever reason

random flint
#

We need EntityAttributeComponent expansion

shy leaf
#

especially attack damage attribute, its relatively simple in bedrock since items add damage on top of players' attack damage value

random flint
#

waiting applyDamage() to have itemStack options

prisma shard
#

me waiting for entityHurtBeforeEvent

floral vessel
#

the options for applyDamage should include toggles for what factors should be included in the calculation

shy leaf
#

ikr

floral vessel
#

actually it would probably be better to have a separate calculate damage function

#

so that you can apply any additional modifications as needed

shy leaf
#

whats worse is that applyDamage has way too many unbearable stuff when you look inside

#

like mace's breach actually affecting damage done by applyDamage

floral vessel
#

yeah that's pretty egregious

random flint
prisma shard
#

wait

shy leaf
#

some damage type factors have stuff like ignoring totems, shields, etc

#

its hard to figure out which does what stuff

prisma shard
#

(I was very sleepy when I saw so i could be wrong) When i checked Script API general Minato was saying in this chat, something like IAfterEvent. Like is there even a I variant of events?!

random flint
shy leaf
#

and magic ignores everything except protection

#

entityExplosion not causing shield knockbacks

tropic geyser
#

@valid ice does the chest gui work with 2.0.0-beta, I cant get it to work

prisma shard
shy leaf
#

also why tf does mace smash attacks (not applyDamage) work by adding on top of player's attack damage attribute???

#

im so confused

random flint
shy leaf
#

yeah at least those follow how its supposed to work like

#

but it gets mad confusing when its used in applyDamage

#

or damage command

#

heres another funny thing

random flint
#

Lots of stuff needs to be experimented on. Still, this small difference in mechanics could be utilized to approximately guess how many armor points, resistance, and enchantments an entity has.

shy leaf
#

damage command can apply 0 damage while causing knockback and iframes

#

but applyDamage doesnt

#

and applyDamage's boolean return only checks if the entity was truly damaged instead of checking whether the entity can take damages

#

meaning that armor stands return false

random flint
shy leaf
#

i dont really like doing that

random flint
#

Too bad, being picky will starve you

#

What is this reaction lmao

tropic geyser
random flint
tropic geyser
floral vessel
#

Is there a way to detect if a player is riding a mob in script api?

shy leaf
#

hold on

#

i have the code

shy leaf
#

that

#

for 2.0.0-beta since it uses .isValid

Object.defineProperty(Entity.prototype, "isRiding", {get: function() {
    return this.getComponent("riding")?.isValid??false;
}})
#
if (player.isRiding == true)
random flint
#

could've removed that == true 😔

shy leaf
#

shhh

tropic geyser
# shy leaf shhh

do you what the component is too acess the ender chest of a player

shy leaf
#

no sorry

tropic geyser
#

alr

dim tusk
#

Tho commands can

#

I forgot but someone made a way to check what the item has in that slot using replaceitem

tropic geyser
prisma shard
# shy leaf for 2.0.0-beta since it uses `.isValid` ```js Object.defineProperty(Entity.proto...
/**
 * Checks if a player is riding a specific entity type.
 * @param {Player} player Player to check if riding an entity
 * @param {string} entityType Type ID of the entity to check, example: "minecraft:horse"
 * @returns {boolean}
 * @example
 * import { world } from "@minecraft/server"
 * 
 * const player = world.getPlayers()[0];
 * const isRidingPlayer = isRidingEntity(player, "minecraft:horse");
 * @throws If player is not a Player.
 * @throws if Player doesn't have a `riding` component
 */
function isRidingEntity(player, entityType) {
    if (!player || typeof player.getComponent !== 'function') {
        throw new Error('Invalid player object provided. Player must have a `getComponent` method.');
    }
    const riding = player.getComponent('riding');
    if (!riding) {
        throw new Error('Player does not have a `riding` component.');
    }
    if (!riding.entityRidingOn) {
        throw new Error('Player is not riding any entity.');
    }

    return riding.entityRidingOn.typeId === entityType;
}```
#

Muauahah

shy leaf
prisma shard
#

xd jk I just had this in my code

prisma shard
#

why

#

It doesnt detects if riding any mob. It detects with a specified entity typeId

shy leaf
#

but why throw

#

thats like

prisma shard
#

lol

shy leaf
#

nevermind i lost my words

prisma shard
#

ikr I needed it as of my use case

dim tusk
prisma shard
shy leaf
#

its like looking for troubles

#

like really

prisma shard
#

Yo bro I saw you asking already before apple_skull

tropic geyser
#

nvm

prisma shard
tropic geyser
nova flame
#
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
    const Interacter = ev.player;
    const location = Interacter.location;
    if (isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132})) {
        ev.cancel=true;
    }
})```
what this does is stop people interacting with blocks like enchantment tables & more but i need players to be able to open chests and shulkers, any ideas?
#

im quite new to scripting so

random flint
nova flame
#

nono i need some blocks to be interactable

#

like chests

#

but not other blocks

dim tusk
#

block.location

random flint
#

const interactable = [
"minecraft:chest",
"minecraft:barrel"
]

if (interactable.includes(ev.block.typeId)) return;

dim tusk
#

Not player.location, maybe you meant that?

shy leaf
nova flame
#

how exactly do i integrate this to the existing one?

dim tusk
#
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
    const Interacter = ev.player;
    const location = Interacter.location;
    if (isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132})) {
        if (interactable.includes(block.typeId)) {
          ev.cancel = true;
        }
    }
})```
nova flame
#

i done it a diffrent way and it still worked

#
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
    const Interacter = ev.player;
    const location = Interacter.location;
    const interactable = [
        "minecraft:trapped_chest",
        "minecraft:barrel"
    ]
    if (isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132})) {
        if (interactable.includes(ev.block.typeId)) return;
        else ev.cancel=true;
    }
})```
#

anyone see a flaw that will come back to bite me?

random flint
#

block outside bounding box [ 103 -38 21 ] — [ 22 35 132 ] is still interactable

shy leaf
#

and use !

random flint
#

he wants to make other block, except chest and shulkerbox can't be interacted

random flint
#

Ig you mean like this?

if (!checkExpression) ev.cancel = true;

shy leaf
#
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
    const Interacter = ev.player;
    const location = Interacter.location;
    
    const interactable = [
        "minecraft:trapped_chest",
        "minecraft:barrel"
    ];
    
    const condition = isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132}) && !interactable.includes(ev.block.typeId);
    
    if (condition) ev.cancel = true;
})```
#

or

#
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
    const Interacter = ev.player;
    const location = Interacter.location;
    
    const interactable = [
        "minecraft:trapped_chest",
        "minecraft:barrel"
    ];
    
    if (interactable.includes(ev.block.typeId)) return;
    
    const condition = isPointInBoundingBox(location,
        { x: 103, y: -38, z: 21 },
        { x: 22, y: 35, z: 132 }
    );
    
    if (condition) ev.cancel = true;
})```
past coyote
#

The ItemStack constructor is defined as:

constructor(itemType: ItemType | string, amount?: number);```

   ` itemType` is either an `ItemType` object (from `@minecraft/vanilla-data`) or a string ID (e.g., `"minecraft:bed"`).
    It doesn’t accept a data value or auxiliary parameter to specify data = 14 correct?
near siren
#

Is there a new way to register block custom components? WorldInitalize seems to be depricated in stable

uncut sail
#

🍌

dim tusk
dim tusk
gaunt salmonBOT
carmine cloud
#

yall know how to convert the type id of an entity to its display name? e.g. minecraft:panda -> Panda

stuck ibex
cold grove
#

Just items has weird keys

stuck ibex
stuck ibex
#

What i said

lyric kestrel
#

I'm guessing making recipes with js is not possible?

unique acorn
#

in crafting table, no

#

i did try this before and it works on brewing stand with iventory component

#

which means it may be possible with furnace?

distant tulip
unique acorn
#

what even is the difference between IPlayerSpawnAfterEventSignal and PlayerSpawnAfterEventSignal?

#

I've had this question for a while but keep forgetting to ask xd

distant tulip
#

They are the same, they rename it

#

Or are you asking what the i for

unique acorn
#

yeah

#

what is the I for

distant tulip
unique acorn
#

i see

random flint
#

"I" see

distant tulip
#

lol

prisma shard
dusky flicker
#

what is the limits of a string dynamic property?

#

how much can i write? and is it by char or byte?

#

and is the string formatting utf16?

woven loom
#

32k bytes

dusky flicker
#

most js engines use utf16 for formatting

distant tulip
dusky flicker
#

utf8 can go up to 4bytes per char, i dont know about utf16

#

and if a char which is more than 1 byte, minecraft would still expect a string of length 0x7fff or not

woven loom
#

dp uses utf8

honest spear
#

yea, NBT

#

but doesn't really matter bc it counts bytes

#

in most cases is one byte for ANSCII chars

woven loom
#

avoid tricks to make life easier 👍

woven loom
honest spear
#

so all ANSI chars are in one byte for utf

woven loom
#

yeah

#

i wonder if it breaks the structure when we use any control chars

#

have u tried doing that ?

honest spear
#

i know zero at the end is trimming char in C++ so sometimes it breaks in api as well

honest spear
woven loom
#

like saving a string with all 0-127 chars

#

Key stores normally uses control chars to function

honest spear
#

Well i have no idea

distant tulip
#

no error either

woven loom
#

can u try filling 32k

distant tulip
distant tulip
#

@woven loom
can't really tell
they all pass but u+0000 (Null)

Null key do appear to be saved but it is either empty or the app i used can't display it

grim raft
#

is there a way to detect left click with scirpts instead of using animation controllers? I dont want to modify my player.json so my mod works with other mods

distant tulip
#

no

#

only if it is on a block or entity

grim raft
#

I've been searching everywhere on this server with the search feature lol

grim raft
#

cuz thats what not letting me do that methode

woven loom
distant tulip
distant tulip
#

[Scripting][error]-Error: Maximum string size exceeded (131072/32767) bytes for dynamic property 'test' at <anonymous> (index.js:11)
all of them trigger it

woven loom
#

what u did

distant tulip
#

0x0000 didn't trigger it

woven loom
#

yea u gotta -1 first

#

32767

distant tulip
#

didn't you want to see if they can break the limit

woven loom
#

yea but chars should be -1

#

try with that too

distant tulip
#

yeah they save fine with 32677

#

uh

woven loom
#

hm

loud frigate
#

does anybody know what are the molang variables to put in the MolangVariableMap to spawn a block breaking particle with a certain block ID?

woven loom
#

thats not for that

#

u can make custom particle tho

loud frigate
#

is texture atlas deterministic?

dim tusk
#

MolangVariableMap just provides colors and changes the value of the variable as number and block breaking particles are based on block texture

#

but you can make your own custom particle.

loud frigate
#

yes but the block textures atlas coordinates ARE molang variables

#

if i could see the vanilla particle json, making a custom one with exact same physics would be easier

dim tusk
loud frigate
#

by giving the right UV. if atlas is constant in its vanilla section the it should work

#

thats a big if however

distant tulip
#

look into the warden dig particle

loud frigate
#

is there a place to see all the vanilla definitions?

drifting ravenBOT
loud frigate
#

thanks

past coyote
#

how do I get the block a player placed?

Like the vector location of it

#

I tried doing blockFace with offsets but there has to be a better method

wary edge
past coyote
#

duh

drowsy scaffold
#

is there a means to check if a player is in a lava block? there's Entity.isInWater but there's nothing like it for lava, and just checking their location for lava typeId doesn't work quite right because of corners

wary edge
#

Understandable, Bedrock either requires you to overengineer for a simple solution but have an easy thing for a complex problem.

wary edge
drowsy scaffold
#

aw that is not what I wanted to hear, alright

past coyote
#

Is there a way to make this visually faster?

wary edge
# past coyote

Are you willing to use Beta? Assuming this is a vanilla block.

past coyote
#
import { world, Direction, BlockPermutation, system } from '@minecraft/server';

// --- Configuration ---
const restrictedBlockIds = new Set([
    'minecraft:stone_button',
    'minecraft:lever'
]);

const restrictedSlabs = new Set([
    'minecraft:cobblestone_slab',
    'minecraft:oak_slab'
]);

// --- Script Logic ---
/**
 * Handles the playerInteractWithBlockBefore event to restrict ceiling placement for buttons/levers.
 * @param {import('@minecraft/server').PlayerInteractWithBlockBeforeEvent} event
 */
function checkCeilingPlacement(event) {
    const { itemStack, blockFace } = event;
    if (!itemStack) return;


    if (restrictedBlockIds.has(itemStack.typeId)) {
        if (blockFace === Direction.Down) {
            event.cancel = true;
        }
    }
}

/**
 * Handles the playerPlaceBlock event to enforce bottom placement for specified slabs.
 * @param {import('@minecraft/server').PlayerPlaceBlockAfterEvent} event
 */
function enforceSlabBottomPlacement(event) {
    const { block } = event;


    if (!restrictedSlabs.has(block.typeId)) return;


    system.run(() => {

        const permutation = BlockPermutation.resolve(block.typeId, {
            'minecraft:vertical_half': 'bottom'
        });


        try {
            block.setPermutation(permutation);
            console.log(`Set slab at ${block.location.x}, ${block.location.y}, ${block.location.z} to bottom`);
        } catch (error) {
            console.warn(`Failed to set slab to bottom: ${error}`);
        }
    });
}

// Subscribe to the events
world.beforeEvents.playerInteractWithBlock.subscribe(checkCeilingPlacement);
world.afterEvents.playerPlaceBlock.subscribe(enforceSlabBottomPlacement);

console.log("Ceiling Placement and Slab Restriction Script Loaded!");```
#

Its a vanilla block yeah, and beta

wary edge
#

I would use PlayerPlaceBefore event and change the permutationToPlace

past coyote
#

I'm trying to recreate the Minecraft Beta 1.7.3 slab placement

past coyote
unique acorn
wary edge
#

I haven't the foggiest clue why it still is in beta but stable for Custom Blocks.

past coyote
#

How can I make it so all blocks never get waterlogged?

#

I can think if a really bad way to do it, but I assume there is an easier way 😭

wary edge
past coyote
#

thats what I am trying to prevent

wary edge
thorn flicker
#

maybe you can just check if its being placed in water, then set it not to be waterlogged

past coyote
#
function enforceSlabBottomPlacement(event) {
    const { permutationToPlace, block } = event;

    if (!permutationToPlace || !permutationToPlace.type?.id) {
        console.warn(`Invalid permutationToPlace: ${JSON.stringify(permutationToPlace)}`);
        return;
    }


    if (!restrictedSlabs.has(permutationToPlace.type.id)) return;


    try {
        const newPermutation = BlockPermutation.resolve(permutationToPlace.type.id, {
            'minecraft:vertical_half': 'bottom'
        });

 
        event.permutationToPlace = newPermutation;
        console.log(`Set slab at ${block.location.x}, ${block.location.y}, ${block.location.z} to bottom before placement`);
    } catch (error) {
        console.warn(`Failed to set slab permutation: ${error}`);
    }
}

world.beforeEvents.playerInteractWithBlock.subscribe(checkCeilingPlacement);
world.beforeEvents.playerPlaceBlock.subscribe(enforceSlabBottomPlacement);

console.log("Ceiling Placement and Slab Restriction Script Loaded!");```

I think im doing this wrong...
wary edge
past coyote
#

TypeError: 'permutationBeingPlaced' is read-only

wary edge
#

PE_PandaOhshit Wait what...

past coyote
#

I think im dumb hold on

thorn flicker
#

you cannot reassign it like permutationToPlace

distant tulip
past coyote
#

I think its because im canceling the event? maybe instead I need to pass the permutation when its placing? idk

#

There is still a pretty decent visual delay, and I dont think thats supposed to happen

distant tulip
#

assign the new permutation to permutationToPlace

past coyote
wanton cedar
#

Is there a way via scripting to check what armor a player or entity has equipped? Specifically, I'm trying to check if any given player has the custom head armor that I'm working on.

distant tulip
distant tulip
past coyote
#

BlockComponentPlayerPlaceBeforeEvent is for custom block components, not the vanilla world event

distant tulip
#

you are right, my bad

dusky flicker
#

damn working with utf8 is hell

#

but i really prefer that over the web

#
///Gets the size of the char by seeing its first byte considering it as a utf8 byte
pub fn char_size_init(mut b: u8) -> u8 {
    if b < 0x80 {
        1
    } else {
        b &= 0b1111_0000;
        let mut n = 0;
        while b != 0 {
            n += 1;
            b <<= 1;
        }
        n - 1
    }
}
///Gets the size of the char at the given start point backwards
///Example
///rust
///let v = vec![b'a', 0xc3, 0xa0, 0xc3, 0xa7]; //'aàç'
///char_size_backwards(&v, v.len()-1); //2
///char_size_backwards(&v, v.len()-3); //2
///char_size_backwards(&v, 1); // 0; Invalid Byte
///char_size_backwards(&v, 0); //1
///
pub fn char_size_backwards(vec: &GapBuffer<u8>, spoint: usize) -> usize {
    if vec[spoint] < 0x80 {
        1
    } else {
        let mut bcount = 0;
        while bcount < 4 {
            //These 2 lines check if some of the 3 first bits in the byte are 1, if so, theyre a continuation byte defined
            //by utf8. Check https://en.wikipedia.org/wiki/UTF-8 for more information
            let mut c = vec[spoint - bcount] & 0b1111_0000;
            if c > 0b1000_0000 {
                let mut n = 0;
                while c != 0 {
                    n += 1;
                    c <<= 1;
                }
                return n - 1;
            }
            bcount += 1;
        }
        0
    }
}```
dusky flicker
wanton cedar
# distant tulip for player use equipment component for entities use testfor command with hasitem...

It looks like you're talking about the EntityEquippableComponent class (https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/entityequippablecomponent?view=minecraft-bedrock-experimental), but that class doesn't seem to exist on entities or players that I have been able to find...

Contents of the @minecraft/server.EntityEquippableComponent class.

distant tulip
thorn flicker
#

it used to work for entities I believe

#

they disabled it though because there were issues? I forgot.

distant tulip
#

no sure, i am kinda new
maybe in the old api

thorn flicker
#

same here.

#

maybe.

wanton cedar
# thorn flicker works for players only right now.

Players is exactly what I'm interested in. Any idea why this is throwing a TypeError?

    system.runInterval(() => {
        const players = world.getAllPlayers()
        players.forEach((player) => {
            world.sendMessage(String(player.getComponent('equippable').getEquipment('head')))
        })
    }, 20)
thorn flicker
#

capitalize the H

wanton cedar
#

Perfect, that worked. Thank you!

past coyote
#
function enforceStairsBottomPlacement(event) {
    const { block } = event;
    if (!restrictedStairs.has(block.typeId)) return;
    try {
        // Get the current permutation to preserve other states
        const currentPerm = block.permutation;
        // Create a new permutation based on current states, only changing upside_down_bit
        const newPermutation = currentPerm.withState('minecraft:upside_down_bit', false);
        block.setPermutation(newPermutation);
    } catch (error) {
        console.warn(`Failed to set ${block.typeId} to bottom: ${error.message}`);
    }
}
#

For some reason this doesn't set the permutation correctly

echo tinsel
#

Is it possible to make script only run when someone logs in?

dusky flicker
woven loom
dusky flicker
#

for performance i had to store things in a Vec<u8>, the equivalent to Uint8Array

#

in case it was a gapbuffer as you can see in the params

lethal bramble
#

i just want to know:
when should you use commands/functions and when should you use scripts

#

like cus scripting can do all the stuff commands can do

#

but ppl still use functions in scripts for some reason

#

so is there any benefit?

woven loom
#

People use it because it is simple, while those who are lazy or do not want to write too much use commands. Others use it because there is no API available for that specific thing.

#

Performance varies according to the use case.

lethal bramble
distant tulip
#

the only case i can recommend commands for is where there is no native functions for it, most stuff do
as waveplayz said, sometimes commands can be shorter like the hasitem property

thorn flicker
#

yall think we are ever going to get block dynamic properties?

distant tulip
#

doubt

thorn flicker
#

would be nice.

lethal bramble
#

itll be too much info to store in the db

distant tulip
#

it is not about that

thorn flicker
#

okay instead of that, I hope we get to be able to edit vanilla blocks in the future so we can add states to them.

lethal bramble
#

yeah

dusky flicker
#

if that's the case, they could do some kind of lazy loading

thorn flicker
lethal bramble
#

maybe world data?

#

i dunno

dusky flicker
#

just load the ones on the loaded chunks

#

but i really think a db could handle it easily

thorn flicker
#

theres a dynamic property limit right?

#

im not talking about how many chars

dusky flicker
#

is there?

lethal bramble
#

so maybe

dusky flicker
#

it would cost lesser

lethal bramble
thorn flicker
#

because if theres no limit, you can just store each vector3 as a property

distant tulip
# thorn flicker what do you think its about?

how will the game handle that, does breaking the block remove the dp? what if you moved it with piston? lot of things to consider and it is not even that good of a thing, just give us onBlockUpdate and let us handle it our self

dusky flicker
#

and getDynamicProperty just gets it from the db

#

and set just sets

thorn flicker
lethal bramble
#

so just look inside

#

��ξ:<��������� ��������,( ��������1�
��
�config�activation_range���@�deactivation_range���@
�key_item�Count�Damage���Name�minecraft:trial_key �WasPickedUp��
�loot_table-�loot_tables/chests/trial_chambers/reward.json�override_loot_table_to_display���
�data �items_to_eject����� �rewarded_players������state_updating_resumes_at��������id�Vault �isMovable�x�����y�����z���� ��������6���� ��������9 �������,( �������1�
���Findable� �Items����� �LootTable:�loot_tables/chests/trial_chambers/intersection_barrel.json
�LootTableSeed�����id�Barrel �isMovable�x#����y�����z�����
�� �Items����� �LootTable2�loot_tables/dispensers/trial_chambers/chamber.json
�LootTableSeed�����id �Dispenser �isMovable�x$����y�����z�����
��
�config�activation_range���@�deactivation_range���@
�key_item�Count�Damage���Name�minecraft:ominous_trial_key �WasPickedUp��
�loot_table5�loot_tables/chests/trial_chambers/reward_ominous.json�override_loot_table_to_display���
�data �items_to_eject����� �rewarded_players������state_updating_resumes_at4��������id�Vault �isMovable�x$����y�����z�����
�� �Items����� �LootTable2�loot_tables/dispensers/trial_chambers/chamber.json
�LootTableSeed�����id �Dispenser �isMovable�x.����y�����z�����

#

uh

thorn flicker
#

does anyone know the limit?

lethal bramble
#

that was in a folder in db

dusky flicker
#

í tՙÇï•åDJl%1bB҄BŽ)8à¤X9’˜Ä1Þ¼0]˲,ÛJl)–H8gKvi“@ȓ¤…hx„÷£°”N·g—Çò(Â)]Ø
…´Ûn—.»Ý-^!Ú¹óî<£—-{þó$ùÓ½#i&óûï#UD]’jè);ä—‘zɼò¿™­^¯‰·ÿ~s÷{Uëßkä÷
֟Oô§ûx¿±×Û¯Oñ÷çÍߨ[Ú tÿ$¸¥ÂMgÒ1ʾ2£bԃîY„Þ±]~馄íSMªVd¡•œ£ý
]{“÷ž«Ê°,Úö‘ËgGû¶ϧRißä„öeÒ?£q9IØß¬$½¡p0õwÆëü¡è¨$÷ǃ1R6’\ŒÆB‘ðÔùU”k1žkwøbñH8h¡‡Dâ±
ëBuC=¡
½¾H4s«J÷|JhǬÜ×.õã wjý8òèçcw»Cí¨ŒDJ:¦j³$¯EiË1’}{~ɧ-QÛåò¹µÅj;£¶Ù´Ï´Dûþ–b·7[ŠÙÞʒOÛb´Ïvɧ­EåHÌþàëáZ´;¢‘Àºd+z
…;CáPû†hØ×ŠÓÌýLÐ}âõ‘hÜßÓÏñïcœÔ£ÿœ#–¸´Ÿ°˜K[‘ûǂ ,¥º”“ü+…â実x$èNöâ:•Èðuú¡p—¯#
âRå$,Aµ» }:ÉuÁXÜÖ;¢þ®HØìêÊø;U¸w•]@Ç)Xg½8H¨ÃM.w4Éñ�u“PlYäZ{O–Q²Ñ!½OzÜT¯<^OsmhyT×БkCË•äÚP¿FËßQ¿Fù;V¸µt‚²iòkW==¨esð¥±Þg—+Ü/½[ùYᦠèÌ[”W.÷g
m»Q~á„ÙÚ(Û5Ƌ‹Íû•ýd†kÔ®±³NÐv奛ž±øéÞIGŸ™ê9úLï¤IãØó^×[Òó£[²ç“à‡~øá‡?w?%#„@?«°dއOáãáP4naÄPÅ5éŠúc1_{¿úBÎæ×‰Gý¡Ô$­Ð܁h$&uS©½†ƒÑ®MòÕEê›ôíbiàÆdDJ<.m˜VO“Ÿ,øÕï?]õ弘‹E¦‹Ç©‘©‹E¦wt(¯œ9a=, 7mÂUÂU˜…pÕ§…«v³pÕ§…«Î}Ò[ ²§ÄórÃ:Œq\ߙı‹Mu(‡Â«Ÿ8zñÖ»ý¿d}<†½I;’Þ*øAfÉ~† È~žÞ¦;äQñ£8~LÀñÙmŽ+8ٕ™54úÂ,Ð7"Òw=è AýèÛçÁQêÆêÆ})ꎔ©ûÝ6PfNÝÚênnu!²uÿ¶M¤îßµ¥S÷Fut;’x¨òÈf›¿ÇyÝ2}ïl}aæô½«U ï[A_‚lG߃­"}ïnM§ï=­ü˜÷ÞVºt¬ŒážÖ†?‘~Âúï^fŽá?]&ø^‚ Ûaø£ËDÿћŽáÿôòþo¥!žòܟ&yyaÈû¸W ï /Aö#ïÿêÈû¤yŸÈû—¥Æ»ÇŒº‘… .̜ºçˆÓÎ} A]‚lGݺiçØÂtêÆòÔÅÍ2žÔ·
ԅ™Sw¾²ŸÌ ãv±„í=}¿½M£/’ÓÀ?üðsþWeÿôtÿޞö?Øß¯@ý?e¥=’Ó(L1ßÈÑé¥ÛÄè´5
¿_ÙâÙ9åHú¢|tÚME§ÈÑéÞ¢S˜ytzkL›’S&î‹!…~øá/Y¿AT\Œõ[Š‘2Ñ.Qéþ˜•nUbN!Uâ‡+ø¨4°&•~)G¥¤Q)Ì<}·A8Sé¨Ã™J‚lw¦òÍÕIêª)™I멳.ýŒeyOß#«SôýÁè{s3è 3§ïöf¾·4ƒ¾َ¾w^-Žyw6§SwW3OÝ»®V©ë¡'¤LÉKüž—xr03Çð¬FÃS€a‚l‡á¯VˆþFƒ€a⑇nj·^:­Çñ‰IÐp<Z(.9w<p³P& EÀñ%ãc‚l‡ã{ÛEÏŸ>*ž?žÇð}íIŸLhþJ_XüÛiÊ Þ®ÿ3ysý…úxËþÓYûô¹~GS´MÃp‚]°8{ˆÞF³w£ìßsXöOγÿêLþ›ÈIù~~ƒßÇà2ÿßÉ~7ï_Røïç~¿ ¿OŸ¥í_´þtû—¼?ãÿù|¶ò¿W⟯¿Ù'ÜKµ˜Àµ¸®;ú®‹Dz,4Ç5Œ´ÇB!xx^ 9GwÛNÃùµv¤:KÅâ_/]TɇÇ/$ÃãƒÎ„×ÐSwȼt­^²ÌžzC½Îúó‰~#o½‰×ª?“·ÞÄkn^ÉÌߓû;(Ë-¯û‡Š+XT<QÙWfTŒzÐ=‹Ðû¶«Q1a{kTD9²{ÿ(NòßFeßßk»9‡ö¼6 뚒GÛs%=˜GçªÊuý®ú2l'UÙ´aÕó»S!

#

just a lot of bytes

lethal bramble
#

yeah

#

it doesnt seem too hard to store data on db

distant tulip
#

surprised you didn't get a auto timeout

dusky flicker
lethal bramble
#

if ur asking for the filename

dusky flicker
#

yeah

lethal bramble
#

0046.log

thorn flicker
distant tulip
dusky flicker
#

the database file is the ldb

distant tulip
#

you guys are way off

dusky flicker
#

yeah we probably are

distant tulip
#

it is stored as nbt in the world

lethal bramble
#

oh it is ?

#

nbt is like

#

complicated to me

deep quiver
woven loom
thorn flicker
#

like how many properties that can be stored.

lethal bramble
#

dynamic property limit?

deep quiver
#

Theres no limit I think

woven loom
#

If the key size is 32k bytes u can have 127^32k porperties

#

For 1 byte

lethal bramble
#

it doesnt seem like there is a limit

thorn flicker
#

would this be less laggy than entities

distant tulip
woven loom
#

You cannot go beyond combination.

lethal bramble
#

but no property limit

dusky flicker
distant tulip
#

same with keys

woven loom
#

Number of possible keys = 127^32k max

thorn flicker
#

alr I guess just have to wait until we can edit vanilla blocks.

dusky flicker
#

cant you do it with permutations?

thorn flicker
#

vanilla

#

blocks

lethal bramble
#

u cant

deep quiver
dusky flicker
#

isnt there a way to modify vanilla blocks the same as items?

thorn flicker
#

you cant do that with all items, only some

lethal bramble
#

BP Entities
RP Entities
Animations
Models
Animation Controllers
Spawn Rules
Recipes
Particles
Render Controllers

#

not blocks

wanton ocean
#

Is there a way to add lore to an item BEFORE it enters the player's inventory??

lethal bramble
wanton ocean
thorn flicker
#

you can get the entities on ground

thorn flicker
distant tulip
# dusky flicker that does not help much

the game save them to level.dat file as nbt
it uses the current addon uuid as a reference to the set of dp that addon is storing

just look into mcbe nbt files for more in depth stuff

wanton ocean
wanton ocean
#

the item entity I assume right

lethal bramble
thorn flicker
#
entity.getComponent('minecraft:item').itemStack
distant tulip
#

not with dp

thorn flicker
wanton ocean
#

oh alright

#

thanks

thorn flicker
#

np

dusky flicker
#

i really dont want to install wine just to run it

lethal bramble
#

do entities with dynamic properties despawn

thorn flicker
distant tulip
lethal bramble
lethal bramble
distant tulip
distant tulip
shy leaf
#

its super great

#

it made me less insane when i was trying to develop an addon that depends on hardcore

distant tulip
#

how did that help

shy leaf
#

even with scripts

#

i thought i was driving crazy or was wondering if the scripts werent working so i disabled hardcore with that

#

and i was able to change gamemode

distant tulip
#

bruh what

#

even with scripts....

#

that is weird and unnecessary

thorn flicker
#

they dont want people cheating

#

but yeah, apparently we can enable achievements now lol

thorn flicker
dim tusk
#

I have tested it before but I'm sure it's not after that, I will test it later

shy leaf
#

im going mad crazy because of how different 2.0.0 is in stable and preview

thorn flicker
#

whats different?

shy leaf
#

an async function which has world.getDynamicProperty()

#

works in stable's 2.0.0 but not in preview because its in early execution

dim tusk
#

Ehh? You mean the opposite?

shy leaf
dim tusk
#

I can literally put global variables and no privilege error if that's what you meant.

shy leaf
#

it spits out an error log when i load up or reload in preview world

#

but it doesnt in stable

dim tusk
#

ehh? Tbh I don't have both errors creating global variables both in .70 and .80

shy leaf
#

give me a second

dim tusk
#

meh you don't need to

vast rune
#

Why doesn't switch(block) { case block.typeId == "minecraft:grass_block": // blah blah blah } work?

shy leaf
#

oop i forgot to include lines

vast rune
#

context: i have a getBlock function which is stored in variable block

shy leaf
#

there

#

at line 41, theres world

dim tusk
vast rune
#

oh yeah that makes sense

thorn flicker
#

lol

vast rune
#

i forgot how they work lol

shy leaf
# shy leaf

i dont have access to my laptop rn so i cant really show what happens

#

but its

#

seriously driving me crazy

dim tusk
#

I dunno 🤷 never had had issue with global function or variable in both preview and stable.

shy leaf
#

yeah its super weird

#

i might have to wrap it in worldLoad

#

or use await null

dim tusk
#

just make separate file.

shy leaf
#

yk

dim tusk
#

and the one you connect in manifest, you do the import(); BLA BLA BLA

shy leaf
#

i do that

thorn flicker
#

ive seen this being recommended

shy leaf
#

but well

thorn flicker
#

whats the problem with it

shy leaf
#

the scripts have to load before world loads

valid ice
#

Anyone know why isSolid returns false for a custom block, or how I could fix it?

shy leaf
#

i think i saw someone having the same issue

#

with isSolid

#

or something

valid ice
#

fr? ong? no cap?

thorn flicker
#

we cant set if a block is solid or not, and it defaults to not solid?

shy leaf
#

gimme a sec

valid ice
#

idk what I need to change if there's a thing to make it register as solid, but

thorn flicker
#

so limited

shy leaf
#

#add-ons message

thorn flicker
#

?

shy leaf
#

im not sure if thats related with blocks being solid

valid ice
#

Like the block is pretty damn barebones lol

thorn flicker
#

that just has to do with collision.

shy leaf
#

oh

#

nevermind then

thorn flicker
shy leaf
#

whar

thorn flicker
#

Smokeystack told me that

#

let me find the message.

shy leaf
#

that

#

doesnt make sense how does it even

valid ice
#

I stg if I have to make a long-ass includes for my custom blocks

shy leaf
#

i feel you

thorn flicker
valid ice
#

ah, blocks.json

#

weird

woven loom
#

Can someone list complex addons created with API?

wary edge
#

😔 I would...unfortunately they're NDA currently.

woven loom
#

What are they about

stuck ibex
woven loom
#

Which

stuck ibex
#

#1154250586896744498 message

#

oh well it uses gpt so

woven loom
#

Ye

humble lintel
#

anyone know how long mcpedl take sto approve ur submissions

shy leaf
vast rune
#

is there any way to do this faster

#

like i need to detect if a curved track block is underneath and then rotate the train entity the right way depending on its cardinal direction

#

minecraft:grass_block will be replaced btw

#

also since I have like 3 curve blocks to do this code would be repeated 3 times over...you can see the issue

woven loom
#

wjybu doing like that

shy leaf
vast rune
shy leaf
#

nah uh

woven loom
#

i hate switch so no from me :p

shy leaf
#

theres .includes() method for arrays

vast rune
#

ooh

#

ok

#

well

shy leaf
#

yeah give me a second im terrible at explanation

vast rune
#

I dont see how that would work considering its just searching for items in an array

vast rune
shy leaf
vast rune
#

there is also .matches()

wanton ocean
humble lintel
dim tusk
# vast rune is there any way to do this faster
switch (block?.typeId) {
  case 'minecraft:furnace':
    const perm = block.permutation.getState('minecraft:cardinal_direction');
    switch (perm) {
      case 'north': break;
      case 'east': break;
      case 'south': break;
      case 'west': break;
      default: ;
    }
    break;
}```
#

I hate the format ngl.

shy leaf
#

you should use curseforge instead

humble lintel
#

okay soudns good

#

so my submission won't get submitted at all?

shy leaf
#

uhhhh i dunno

humble lintel
#

alright thanks

thorn flicker
vast rune
floral vessel
#

how efficient is dimension.getBlocks()?

valid ice
#

Hmmm (BDS console errors)

dense skiff
#

How can you use system.runJob() to return a value?

meager zenith
#

can we detect how much hunger a player has?

#

not the effect but the amount shown in the hunger bar

dim tusk
#

Both json ui and behavior pack can't detect it.

meager zenith
#

awww ok thx

prisma shard
distant tulip
#

runJob expect nothing in return

#

just handle all your stuff inside the function

#

or use promises

dense skiff
#

Yeah I'm going with promises

shy leaf
meager zenith
#

yea

dense skiff
#
async runVerifier() {
    return new Promise((resolve) => {
        system.runJob(this.verifyBlocks.bind(this));
    });
}

*verifyBlocks() {
    for (const block of this.instance.getBlocks()) {
        this.blockVerificationLevels[block.location] = this.verifyBlock(block.location);
        yield;
    }
    resolve();
}

Huh?

[Scripting][error]-Unhandled promise rejection: TypeError: Native type conversion failed. Function argument [0] expected type: Generator<unknown, unknown, unknown>    at <anonymous> (classes/StructureVerifier.js:21)
    at Promise (native)
    at runVerifier (classes/StructureVerifier.js:22)
    at ...
#

also i didn't pass the resolve but that's not the issue

prisma shard
#
import {} from "@minecraft/server";

declare module "@minecraft/server" {
    interface WorldBeforeEvents {
        readonly entityHurt: EntityHurtBeforeEventSignal;
    }

    export class EntityHurtBeforeEventSignal {
        private constructor();

        subscribe(
            callback: (arg0: EntityHurtBeforeEvent) => void,
        ): (arg0: EntityHurtBeforeEvent) => void;

        unsubscribe(
            callback: (arg0: EntityHurtBeforeEvent) => void,
        )
    }
    export class EntityHurtBeforeEvent implements EntityHurtAfterEvent {
        readonly cancel: boolean;
        readonly damage: number;
        readonly damageSource: EntityDamageSource;
        readonly hurtEntity: Entity;
        constructor(data: EntityHurtAfterEvent);
    }
}

declare export class EntityHurtBeforeEventSignal extends EntityHurtAfterEventSignal {
    private constructor() {}
    
    subscribe(
        callback: (arg0: EntityHurtBeforeEvent) => void,
    ): (arg0: EntityHurtBeforeEvent) => void;

    unsubscribe(
        callback: (arg0: EntityHurtBeforeEvent) => void,
    )
}```
Any typescript developers out there?
I am making a custom event,  entityHurt BeforeEvent
I asked him, that i want typings for my custom event 
and he gave me this, is that right?
dim tusk
#

How would you even implement it?

prisma shard
remote oyster
# prisma shard ```ts import {} from "@minecraft/server"; declare module "@minecraft/server" { ...

You cannot create an event that doesn't exist in the API to communicate with the game in a way it is not designed or exposed to communicate. You are trying to create a beforeEvent for when a Entity is hurt in hopes to handle such cases in a "before event" context but unfortunately that won't work. Unless the developers implement that sort of logic themselves and expose it in the game then the answer is no. You can create custom events but it's not the way you think it is.

prisma shard
#

oh dude. i forgor to tell this.

So
mojang still havent added entityHurt beforeEvent, so we can't cancel entity damages.
But i found a workaround, applying instant health max, gives them invincibility, so i thought of making it custom event, so that we can make a custom event and extend afterEvent to add event.cancel property to apply the instant health effect and act like cancel damage.

I am using prototypes, to extend the beforeEvents class and make a custom event.

WorldBeforeEvents.prototype.entityHurt = {
    subscribe(callback) {
        listeners.add(callback)
        return callback
    },
    unsubscribe(callback) {
        listeners.delete(callback)
    }
}```
#

That's just the typings i provided before.. Yeah everyone is confused without the main javascript file

remote oyster
# prisma shard

You are creating an instance in the afterEvent and simply passing it's data over to your mockup beforeEvent.

world.afterEvents.entityHurt.subscribe((ev) => {
    const data = new EntityHurtBeforeEvent(ev);
    entityHurtEvent.run(data);

    if (data.cancel) {
        // event cancel code
    }
})

Unfortunately this is pointless because the data is still "after" it happens. So even though you may have created a prototype for this beforeEvent logic of yours, the data is still not transferred to it until after it happens. The code is simply going to confuse someone as it's solely pretending to do something it cannot actually do.

prisma shard
#

hmmmmmmmmmmmm

#

I dont understand

#

If you mean my script will not work, can you just add the fix, to my whole script?

remote oyster
#

The logic you have for creating a "beforeEvent" regarding "EntityHurtAfterEvent" available in @minecraft/server is like getting a receipt after you've bought something, and then pretending that you're reviewing the items before checkout

prisma shard
remote oyster
#

No, I'm saying you have made a prototype for a "EntityHurtBeforeEvent" that doesn't exist in the API. Your idea is misleading. Your objective may work, but the notion that this "beforeEvent" is handling the hurt entity "before" they are hurt is still false as it's not being dealt with until after it happens.

prisma shard
#

Yeah you said it "The code is simply going to confuse someone"

#

So i think that you mean

#

The script appearantly doesnt make sense and confuse someone but work

#

im assuming

remote oyster
#

It's possible to handle an entity after they are hurt. You can use purely scripts to do it, but since we are talking about damage that occurs after the event there are many things to check for and it can be tedious when you consider the environment in Minecraft. The other option is to modify the entity file and utilize that in combination with your script.

I think your idea for creating a prototype for "EntityHurtBeforeEvent" should be changed to something else because it's not "before" they are hurt. You are still getting the data from the EntityHurtAfterEvent and then passing it to your prototype. So it's not truly a "EntityHurtBeforeEvent". It's just "EntityHurtAfterEvent" duplicated.

prisma shard
# remote oyster It's possible to handle an entity after they are hurt. You can use purely script...

okay i might know what you meant here. My purpose here is not to make a real EntityHurtBeforeEvent, but to make a workaround. It's just not possible unless mojang does it, how can you even get it before it'll fire? I'm just trying to make entityHurt beforeEvent prototype because it would be easier to cancel damage in scripts, instead of entity.json and damage_sensor component. Its just better than nothing.

prisma shard
remote oyster
# prisma shard okay i might know what you meant here. My purpose here is not to make a real Ent...

Unfortunately, you can't truly create a new "beforeEvent" like that. The API acts like a phone line between us and the game engine, we can only use the lines the developers have exposed. While we can build wrappers and simulate certain behaviors, we can't invent new communication channels that the game will recognize. Only Mojang can expose actual beforeEvents with the ability to affect the game's internal logic.

cold grove
#

Well its an API

prisma shard
#

yeah i already said i dont want to create "truly" a new "beforeEvent"

remote oyster
prisma shard
remote oyster
# cold grove Well its an API

Correct, but im trying to help the other person understand that so they don't fall into a false premise that something can be achieved which cannot.

prisma shard
#

Yep thanks for putting the effort to make me understand

remote oyster
#

I did my best. If you still don't understand anything I said then I guess copy and paste it in ChatGpt and have it dumb it down in a way you can comprehend it. Wish you the best though.

cold grove
prisma shard
dusky flicker
prisma shard
#

but experimenting and finding out new things is cool.
Just wanted to see if what about doing it in scripts and creating new event instead of damage sensor component

remote oyster
dusky flicker
#

you should simply call the method and pass the generator to runJob

cold grove
#

I hope some day they implement a fs like nodejs

dusky flicker
#

if they do something, probably will be like fs on the web

#

and damn node fs sucks

#

how could one like that?

dusky flicker
#

just to pass a wrapper that executes fopen, fgets, fclose and stuff like that

loud frigate
#

is there any trick to make blocks behave like hay? negate/reduce fall damage?
All i can think of is heal the player back up, that sill wont prevent death when height is too much

#

i have a proper solution but would be expensive

pine grove
#
if (!heldItem || heldItem.typeId !== "minecraft:stick") return;```

I'm trying to detect if the player is holding an item on their right hand. What component can I put here?  "minecraft:inventory" and "minecraft:equippable " don't work.
cold grove
#

Wdym with "dont work"

#

Show your code, content logs, anything..

cold grove
#

Try this:

const equippable = player.getComponent(EntityComponentTypes.Equippable);

const item = equippable.getEquipment(EquipmentSlot.MainHand);
pine grove
broken dagger
#
player.applyKnockback(0, 0, 6, 0.9);
sharp elbow
#

In 2.0, applyKnockback now takes two parameters: a Vector2 XZ-fitting object (for x and z), and a number (for y).

player.applyKnockback({x: 0, z: 0}, 0.9);
weary onyx
#

i was trying to add an effect, but i don't know what's the variable for it

idle dagger
#

How to choose version in @gaunt salmon ?

warped blaze
#

@ivory bough lmao

ivory bough
#

Cause who tf is trolling for this long?

warped blaze
warped blaze
untold garnet
#

how to fill 0 2 0 to 7 2 7 with air using js api

#

very confused with fillBlocks function

untold garnet
warped blaze
#

I can't even say anything abt that guy cuz u don't want to be banned for some dumb reason

untold magnet
untold garnet
#

I prefer use the js api functions

untold magnet
#

then use fillBlocks

untold garnet
#

can you give me a example of fillBlocks?

#

dimension.fillBlocks({x: 0, y: 2, z: 0}, {x: 7, y: 2, z: 7}, "minecraft:air")

untold magnet
#

sadly i dont have it.

untold garnet
#

this is what i have rn

untold magnet
#

im pretty sure Herobrine64 [@] have it.

valid ice
# untold garnet very confused with fillBlocks function
const initialVol = new CompoundBlockVolume();
initialVol.replaceOrAddLastVolume({ action: 0, locationRelativity: 1, volume: new BlockVolume({x: 0, y: 2, z: 0}, {x: 7, y: 2, z: 7}) });
dimension.fillBlocks(initialVol, 'minecraft:air')
#

I think

#

Kinda spliced it from my original code, so if it works, great

untold garnet
#

this would require me importing CompoundBlockVolume?

untold magnet
valid ice
#

And BlockVolume

untold garnet
#

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

#

imported both

#

doesnt seems to work

honest spear
#

What is your error tho?

untold garnet
#

is there a way for me to debug in console?

#

sorry havent messed with miencraft js in a hot minute

honest spear
#

syntax error is showed in content log already when loading script

valid ice
#

Note that I just put “dimension” off the fillBlocks, not the actual code needed

untold magnet
#

uh, is it possible to now show the other numbers?
Math.floor(x*10) / 10 will show the player X location but with other numbers ( X: 63.4 )
like is it possible to show the 63 only?

untold magnet
#

huh

distant tulip
#

it is

unique acorn
wise raft
#

Is it possible to change the bone visibility from a specific block?

wary edge
wise raft
#

how?

dim tusk
#

Block permutations

dim tusk
wise raft
#

Is this possible without states?

dim tusk
#

No.

#

Either use entity or animated textures or multiple blocks.

pine grove
#
  onPlayerInteract(event) {
    const { block, player, block: { location }, dimension } = event;
    const validIds = ["mgp:custom_block1", "mgp:custom_block2"]; 

    if (!block || !validIds.includes(block.typeId)) return;

    const equippable = player.getComponent(EntityComponentTypes.Equippable);
    if (!equippable) return;

    const item = equippable.getEquipment(EquipmentSlot.Mainhand);

    if (item && item.hasTag("minecraft:wool")) {
      const permutation = block.permutation;
      const currentVariant = permutation.getState("mgp:variant") ?? 0;
      const nextVariant = (currentVariant + 1) % 7;

      dimension.runCommand(`playsound dig.cloth @a ${location.x} ${location.y} ${location.z} 0.5`);
      block.setPermutation(permutation.withState("mgp:variant", nextVariant));
    }
  }```

I use this event. Currently, it correctly changes the block state of custom block when holding a wool block. But it does not allow placing any block on the custom block when the player is not holding a wool block. Does onPlayerInteract override default interactions? Can I stop it from doing that when the condition is false?
open urchin
pine grove
#

Ah, that's a shame. Thanks for the info.

scarlet lynx
#

What is 2.0.0?