#Script API General

1 messages · Page 75 of 1

scarlet lynx
#

Is there big changes?

valid ice
#

Yes

dusky flicker
valid ice
#

Mainly how the world is loaded up with respect to script s

wise raft
#

How can I get traits?

woven loom
#

what?

wise raft
# woven loom what?

these things from blocksjson "traits": { "minecraft:placement_position": { "enabled_states": ["minecraft:vertical_half"] }, "minecraft:placement_direction": { "enabled_states": ["minecraft:cardinal_direction"], "y_rotation_offset": 180 } }

open urchin
#

why

wise raft
#

because I need it

open urchin
#

which information

wise raft
#

the rotation

open urchin
#

block.permutation.getState("minecraft:vertical_half")

wise raft
#

oh

#

I wrote placement_direction instead of cardinal_direction

#

thanks

verbal yew
#

I need some help

untold magnet
thorn flicker
#

turns out that was the case, if you read above.

thorn flicker
thorn flicker
dense skiff
#

Can someone give me an example for how to set particle colors using MolangVariableMap.setColorRGBA()? I'm having trouble actually changing the color value. Here's what I've got so far:

{
    "format_version": "1.10.0",
    "particle_effect": {
        "description": {
            "identifier": "structool:outline",
            "basic_render_parameters": {
                "material": "particles_blend",
                "texture": "textures/particle/particles"
            }
        },
        "components": {
            "minecraft:emitter_rate_instant": {
                "num_particles": 1
            },
            "minecraft:emitter_lifetime_once": {
                "active_time": 1
            },
            "minecraft:emitter_shape_point": {},
            "minecraft:particle_lifetime_expression": {
                "max_lifetime": 1
            },
            "minecraft:particle_appearance_billboard": {
                "size": [0.2, 0.2],
                "facing_camera_mode": "rotate_xyz",
                "uv": {
                    "texture_width": 16,
                    "texture_height": 16,
                    "uv": [6, 11],
                    "uv_size": [1, 1]
                }
            },
            "minecraft:particle_appearance_tinting": {
                "color": [1, 1, 1, 1]
            }
        }
    }
}

Attempting to set color like this:

molang = new MolangVariableMap().setColorRGB("minecraft:particle_appearance_tinting",{ red: 1, green: 1, blue: 0, alpha: 1 });
overworld.spawnParticle("structool:outline", location, molang);
dim tusk
dense skiff
#

Mmm now they're flickering

#

Got it working thanks 👍

#

It was because I was expecting setColorRGB() to return the molang map but it's just void

dusky flicker
valid ice
#

Was in the script v2 video on the creator channel

sand saddle
#

How can I filter players based on scores?

#

Help please

gilded shadow
#

anyone knows what is the difference between applyImpulse and applyKnockback?

simple zodiac
#

knockback is affected by side effects such as the knockback resistance from netherite armor

winged root
#

Speaking about this subject, I just posted a question about it. But since it’s more a discussion based subject rather than a question it might be more fitting for this chat. I am trying to find the best way to smoothly adjust the player position by applying momentum. https://media.discordapp.net/attachments/1361837344755552469/1361837346198257944/Minecraft_2025-04-16_00-50-44.mp4?ex=6800355d&is=67fee3dd&hm=ca2762aafacf9e0f1b4bd0f3e8b5ecf7f9b98aecae238dbb37d38c6a5f2bfb2a&

this is what I got so far using applyKnockback.

woven loom
#

that is really nice

remote oyster
#

I'd be curious if it can be done better.

winged root
#

It’s certainly usable but it is a bit jittery and player movement is not completely predicable. This is more apparent when actually playing of course.

remote oyster
#

I can see how the jitters would be bothersome.

scarlet lynx
# valid ice

Are they tryna switch people all to before events and stuff

valid ice
#

It doesn’t change current event firing; it just adds extra events and how data is handled when the world is first loaded up

scarlet lynx
thorn flicker
#

no

valid ice
#

I don’t see how that’s related to the world loading… if you’re asking if it’s still possibly being added, then yeah, no reason it can’t be added

thorn flicker
#

entityHurt beforeEvents would be really nice

valid ice
#

Yar

thorn flicker
#

modifying damage would be great for configuration menus

shy leaf
cinder shadow
#

Took me 2 days to realize that my code wasn't working because I used inventory.length and not .size 😔

cold grove
dusky flicker
cold grove
#

Mmmm Typescript flashitoOjitos

cinder shadow
#

Try using assembly next time

#

It's way better

wary edge
cinder shadow
wary edge
dusky flicker
valid ice
cinder shadow
#

Why would I ever give attention to a language named after old and errodded metal smh

scarlet lynx
#

whst language

terse pulsar
#
player.sendMessage({translate: 'text.ne:evolution', with: ['text.ne:sharingan1', 'text.ne:sharingan2']})

text.ne:sharingan1=Sharingan §4[1 Tomoe]
text.ne:sharingan2=Sharingan §4[2 Tomoe]
text.ne:evolution=§bYou Have Evolved! %%s -> %%s

#

Why inst working?

#

The menssage says You Have Evolved! %text.ne:sharingan1 -> %text.ne:sharingan2

shy leaf
#

you need to do translate for with too

#

youre using normal strings in that code

idle dagger
#
const objectiveNames = ["money", "top]

system.runInterval(() => {
  for (const objectiveName of objectiveNames) {
    const obj = world.scoreboard.getObjective(objectiveName);
    if (!obj) continue;

    for (const player of world.getAllPlayers()) {
      const realScore = obj.getScore(player.scoreboardIdentity);
      if (realScore === undefined) continue;

      world.scoreboard.setScore("fake_" + player.name, objectiveName, realScore);
    }
  }
}, 100);

Error:
native variant type conversion failed. Function argument [0] expected type: ScoreboardIdentity | Entity | string at <anonymous> (index.js:31)
error is at obj.getScore() line
how to fix it?

woven loom
#

chek for null

shy leaf
analog salmon
#

Is it possible to suppress vanilla blocks loot?

random flint
#

gamerule doTileDrop false

#

-# (pls laugh)

dim tusk
half drum
lyric kestrel
# valid ice

I wonder if they're changing how API world loads work to prepare for dimensions and custom biome generation through scripting

stuck ibex
#

why would they implement those via scripting

random flint
#

Guys, how do I specify the players if they accept string[] in PlayAnimationOptions

#

using player.id does nothing

dim tusk
distant tulip
safe stream
#

can entities not be tamed by non-player entities via scripting?

dim tusk
safe stream
#

Idk

#

wandering trader? no idea

obsidian coyote
#

I don't think non-player entities can tame other entities

random flint
distant tulip
#

hmm

dim tusk
random flint
distant tulip
#

that is a weird way of doing it

random flint
#

Weird choice to use player name moyang

obsidian coyote
#

Providing the player instance imo would be better. hopefully changed in Scripting v2

dim tusk
#

Zombie apocalypse oh no.

safe stream
#

doesnt player.id return a long ass number just like any other entity

dim tusk
safe stream
#

does the player.id change from world to world is it unique to the account

prisma shard
prisma shard
random flint
#

You're probably looking for "XUID"

glacial widget
obsidian coyote
obsidian coyote
scarlet lynx
#

If your trying to grab offline scores and names I have a system for that

gilded shadow
#

is there an event for when an entity dies?

devout dune
#

Hey for some reason onTick is not invoking on my custom_component. The block has tick component. loop, etc.
OnPlayerInteract is working...

#

Not sure why at all. I figured if OnTick wasnt working, onPlayerInteract wouldnt either.

dawn zealot
#

can 2.0.0 be used on realms?

valid ice
#

Yes

devout dune
#

@wary edge Hey! Any idea why a blocks custom_component may not register onTick, when the world is loaded!

wary edge
devout dune
#

to be more specific. I am placing a block in v1.0.0

#

loading the world again with the pack on v1.1

#

exact same block

#

but with a custom_component

#

the custom_component is registaering properly. because onPlayerinteract worls

wary edge
#

That seems like a bug.

devout dune
# wary edge That seems like a bug.

damnnnn. ive noticed it a few other times in other instances as well. For example. i spawn a bunch of single blocks, via feature rules. All of the blocks work with onPlayerInteract. But only half or so are invoking OnTick. Should i make a ticket

wary edge
#

Yeah, onTick has a 50/50 chance of actually ticking when placed via world gen.

devout dune
wary edge
#

I know random tick still works so you could random tick and set the block again.

scarlet lynx
#

Hey would this delete any dynamic property that has the string Voter:"random like a player id"

    world.getDynamicPropertyIds().forEach((id) => {
        if (id.startsWith(`Voter:`)) {
            world.setDynamicProperty(id, undefined)
        }
    })
broken osprey
#

Can someone explain this error? [Scripting][error]-TypeError: not a function at <anonymous> (chat_cmds.js)

#

Side note, how to you add a new line on discord?

grim raft
#

is there a way to make a custom projectile entity to rotate to the player view?

#

im using this

let launchVel = 5;
        const velocity = player.getViewDirection();
        let headLoc = player.getHeadLocation();

        const proj = player.dimension.spawnEntity('ultra:revolver_bullet', {
            x: headLoc.x + velocity.x,
            y: headLoc.y + velocity.y,
            z: headLoc.z + velocity.z
        });

        const projComp = proj.getComponent('minecraft:projectile');
        if (projComp) {
            projComp.shoot({
                x: velocity.x * launchVel,
                y: velocity.y * launchVel,
                z: velocity.z * launchVel
            });
        }```
#

tried the methode that uses animations but it just rotate to the x axis for some reason

odd path
#

Does anyone know how to increase the scale of an entity via script? 😔

scarlet lynx
#

ty

dim tusk
#

Scale's value property is read-only

odd path
#

But I think I got it wrong 😔

dim tusk
#

Tho you could try it.

#

I may be wrong tho... :)

gloomy wolf
dim tusk
grim raft
gloomy wolf
dim tusk
# grim raft Elaborate

I don't need to elaborate, you're adding the value of the head and the value of the view direction of olayer

grim raft
dim tusk
#
let launchVel = 5;
const view = player.getViewDirection();
const head = player.getHeadLocation();

const entity = player.dimension.spawnEntity('minecraft:snowball', { ...head, y: head.y + 0.1 });

const projectile = entity.getComponent('projectile');
projectile.shoot({ x: view.x * launchVel, y: view.y * launchVel, z: view.z * launchVel });
gilded shadow
#

how to get a player from playerid

dim tusk
gilded shadow
grim raft
# dim tusk Noo?

It was working normally with arrows then when I switched to custom projectile it broke

dim tusk
#

Not the scripts...

gilded shadow
# dim tusk getPlayers()
interface EntityQueryOptions {
    closest?: number;
    excludeFamilies?: string[];
    excludeGameModes?: GameMode[];
    excludeNames?: string[];
    excludeTags?: string[];
    excludeTypes?: string[];
    families?: string[];
    farthest?: number;
    gameMode?: GameMode;
    location?: Vector3;
    maxDistance?: number;
    maxHorizontalRotation?: number;
    maxLevel?: number;
    maxVerticalRotation?: number;
    minDistance?: number;
    minHorizontalRotation?: number;
    minLevel?: number;
    minVerticalRotation?: number;
    name?: string;
    propertyOptions?: EntityQueryPropertyOptions[];
    scoreOptions?: EntityQueryScoreOptions[];
    tags?: string[];
    type?: string;
    volume?: Vector3;
}

i dont see id

grim raft
dim tusk
gilded shadow
#

will getEntity work?

dim tusk
#

that's much better tbh

gilded shadow
dim tusk
#

I just suggested

gilded shadow
#

thanks tho

grim raft
#

Should I ask in entities channel?

dim tusk
#

Try checking arrows animation and models.

grim raft
dim tusk
grim raft
#

Not affected by gravity

#

Like a bullet

dim tusk
grim raft
#

Other other question, how can I modify its speed?

#

Wait nvm

dim tusk
#

the velocity in scripts

dim tusk
grim raft
#

Ty for your help

past blaze
#

I finally started using the new custom command APIs. I really hope they come around to fixing the command descriptions, and adding the ability to type the command without the namespace

distant tulip
past blaze
distant tulip
#

give me a sec to look for navi comment

past blaze
#

Oh you were just talking about the namespace requirement

distant tulip
#

yep

untold magnet
midnight ridge
#

does script api has isRiding an entity?

distant tulip
untold magnet
#

getComponent

midnight ridge
midnight ridge
untold magnet
neat hazel
#

How to set item in hotbar with "Item Lock" and "Keep on Death"?

distant tulip
untold magnet
distant tulip
#

<slot|item>.lockMode = "inventory"
<slot|item>.keepOnDeath = true

neat hazel
#

Thanks

thorn flicker
# neat hazel Thanks

"inv" being a variable that stores the container class.

const inv = player.getComponent('inventory').container
thorn flicker
dim tusk
loud frigate
#

is there any good reason why BlockComponentPlayerPlaceBeforeEvent doesnt fire if you have a block that has an item?

leaden elbow
#

can i lock chests using script api or like cancel the chest ui

valid ice
past blaze
dim tusk
random flint
#

I want translation key on item Lore 😔

dim tusk
#

Didn't confirmed it yet tho.

dim tusk
#

I'm starting to be a bit OA in making these custom commands better and easier for me to add instead of manually adding registerCommand().

chrome gyro
#

I keep getting undefined from this, I am trying to target a certain entity and find out if it's holding an item. I've tried several different ways from the wiki to try and target the item, but nothing is working, any ideas what I'm doing wrong:

    for (const entity of world.getDimension("overworld").getEntities({
        families: ["cnb_ppl_emitter"]
        })) {

    
        const entityId = entity.id;
        const equippable = entity.getComponent('equippable');
        console.error(equippable)
        if (!equippable) return;
        const mainhand = equippable.getEquipment('Mainhand');
        console.error(mainhand)
        if (!mainhand) return;

        if (mainhand.typeId === `cnb:cnb_ppl_particle`) {
        const lore = mainhand.getLore()[0];
        if (!lore) return;
//...
dim tusk
#

The best thing you can do is the hasitem command or molang query in animation controllers

chrome gyro
#

Oooooh ok

chrome gyro
chrome gyro
dim tusk
dim tusk
#

And it's better if you use animation controllers or function to run the command.

#

Not thru scripts.

prisma shard
chrome gyro
chrome gyro
dim tusk
#

And you'll be surprised at me having a blank display name lol

prisma shard
#

💀

dim tusk
#

nvm, just did it.

prisma shard
#

bro just changed his name llmao

chrome gyro
#

What the what??? lol

prisma shard
#

uh

dim tusk
#

I hate not having one Soo yeah, I'll be reverting it.

prisma shard
#

Debug scripts bot not working :((

chrome gyro
#

haha, Aaah there we go. That's the one I know. Anyway, thank you! I should have thought of that solution sooner.

dim tusk
#

Just one by one read your script.

prisma shard
#

can u respond in DMs

dim tusk
#

Y...?

prisma shard
#

i need some help w/ scripts

chrome gyro
chrome gyro
loud frigate
#

No but I can answer myself. It's because the scripting API is a total mess

untold garnet
#

how to disable watchdog

distant tulip
untold garnet
#

it does require a lot of computation power lol

#

im aware of the problem

dim tusk
#

Chess? Shyt I got PTSD on that

distant tulip
untold garnet
#

so how to bypass the watchdog lol

#

i know its not a good practice but thats how chess engine works

distant tulip
#

The only knowledge i am bot sure to share lol
How much spike hangs do you get

#

Iirc there is a watch dog event under system.beforeEvents

#

Should be watchDog

untold garnet
#

system.beforeEvents.watchdogTerminate.subscribe?

distant tulip
#

Probably, try and see

untold garnet
#

for some reason when I add this event to the script it straight up wont load

#

I already imported from "@minecraft/server"

#

is it only in experimental?

#

running on stable

loud frigate
#

also checking for a block face is solid is absolute garbage, such a basic thing and yet not decent way to do it (efficently)

#

was this reported? dont even know wheer this stuff could be reported

#

similar to .getRedstonePower() not returning power when block is next to a redstone block... scripting api is really a mess seems amateurish too there are way more of these quirks

distant tulip
prisma shard
loud frigate
#

so you do stuff twice if you for example place a block with item used

distant tulip
loud frigate
#

and cant even remove the block placer compoent as i need an item for 2d sprite and other item components stuff

#

and dont get me started on all the events.. if you add beforePlayerPlace component the player will swing its hand when clicking on the block empty handded... for some reason

prisma shard
loud frigate
#

and the onUseOn will make the hand swing ALL the times regardless of what player does. no context whatsoever...

loud frigate
# prisma shard Scripting is a mess indeed

not just scripting.
Ask the game for a minecraft:white_wool[color=red]
ah yes red wool that is....
oh animal mob family? yes that just contains goats
hardened clay? yup thats terracotta...

#

mob family? that has abunch of stuff including armor stand and NOT goats...

#

and why need for family whenthere are tags..
sorry for the rant but thisis all BS

distant tulip
#

Hey @spring axle , sorry for the ping.
Can you guys do something about this?
I am referring to the block placer component, It doesn't trigger BeforeEventPlayerPlaceBlock or Custom Components, it will be cool if it did or if not possible altar the placed block in the itemUseOn event? Either way we really need something done regarding this

wary edge
fathom hemlock
#

is it possible to make custom events?

#

I think yea

#

its impossible

open urchin
open urchin
#

I haven't made a bug report for it not working at all on BDS/Realms

open urchin
#

the arm still doesn't swing though

distant tulip
open urchin
#

I haven't tested replace_block_item yet

open urchin
# open urchin the arm still doesn't swing though

the client clearly isn't recognising that the player has placed the block so it's not fully fixed but at least the code in beforeOnPlayerPlace is running
makes building with the blocks difficult since too many get placed

distant tulip
#

it is only when replace_block_item set to true?

#

same with the beforeevent?

open urchin
#

what

#

the issue that has been fixed is beforeOnPlayerPlace being broken (not ever triggering) on BDS

distant tulip
#

ah, you were talking about BDS

open urchin
#

it is still broken with replace_block_item

prisma shard
#

How can i link my TS file to JS ?

#

the TS shows error when JS file is not open at the same time + the typings in JS don't show when TS file is not open at the same time

terse pulsar
#

Whent i use getComponent()? it returns a bool?

drowsy scaffold
#

something like:

/** @type {import("./BattlePassTypes").reward[]} */
const rewards = [
    {
    //assume a rewards object here
    }
]
lyric kestrel
terse pulsar
#

itemStack.getComponent('minecraft:cooldown')?.getRemaingTicks

drowsy scaffold
terse pulsar
drowsy scaffold
#

does the item have a cooldown component to begin with?

terse pulsar
#

Sometimes it has

#

But when not it send a error to console

drowsy scaffold
loud frigate
midnight ridge
wanton cedar
#

Can anyone tell me why trying to set an entity enum property isn't working in this script?

theEntity.setProperty('wfir:prop', 'east')

It's trying to change the value of this property in the BP:

"properties": {
    "wfir:prop": {
        "type": "enum",
        "values": ["north", "south", "east", "west", "up", "down"],
        "default": "north",
        "client_sync": true
    }
}

I know the script is running, because there's another property that it's setting just fine. It's just the enum property that's causing problems. It stays the default and using setProperty doesn't seem to change it.

chrome gyro
# chrome flint itemStack.getLore()

This doesn't seem to work with entities since items are equipped to hand once given to them. And it doesn't seem like there's a way to unpack Lore within their container. Maybe I'm missing something though, here's my code just incase:

        const { container } = entity.getComponent('inventory');
        console.error(container)
        const itemStack = container.getItem(0);
        console.error(itemStack)
        const mainhand = itemStack.getLore()[0];
        console.error(mainhand)
        if (!mainhand) return;
wanton cedar
wanton cedar
#

How do I access the name of a block in scripting? For example, I'm after Oak Stairs, not minecraft:oak_stairs.

deep yew
#

You can just convert it using a function. Split the words by _ and then capitalize the start of each word.

#
export function getItemName(item) {
    return item?.nameTag ??
        item?.typeId.replace(/.*(?<=:)/, '').replace(/_/g, ' ').replace(/(^\w|\s\w)/g, m => m.toUpperCase());
}
wary edge
wanton cedar
warped blaze
wanton cedar
#

Any idea where the documentation is for it?

loud frigate
#

is there a way to add features to vanilla biomes?

#

pretty sure ive seen addons do it, even if i imagine they were using hacks likespawning entities and such

#

what is the goto way?

wary edge
loud frigate
#

ah so this must mean there is a proper way of doing it nice

chrome flint
#

you can only get their inventory

echo tinsel
#

how could i check if a entity a player kills has over 80 health to then drop an item?

chrome gyro
dim tusk
#

Current health or max health?

echo tinsel
#

i think thats the only none boss type mob that spawns with over 80?

thorn flicker
#

to exclude the iron golem, just check if the typeId of the entity is not iron golem.

echo tinsel
#

Thank you!

echo tinsel
prisma shard
prisma shard
deep yew
#

Honestly sounds silly but I just want to ask:
Is it useless to just get the block permutation of each block in a structure and take a specific coordinate and use the structure blocks' relative locations to set each block using commands or scripts?

#

And if I wanted to use it for more controlled structure placement/animation, would it then be okay?

dim tusk
deep yew
#

I know it would be slow, but I was just wondering if it'd be better that way if you'd want it slow. Purposefully slow wouldn't hurt the server with more complex structures, even custom sized ones, I'd assume

lethal bramble
#

I'm trying to get the block a player is looking at but it seems to be getting the wrong block

const blockRaycast = player.dimension.getBlockFromRay(player.location,player.getViewDirection());```
when i use the code it does not return the block that the player is looking at
#

pls help

#

oh wait nvm i fixed it

#

i was using the position of the feet 😆

distant tulip
lethal bramble
distant tulip
#

now you know

dusky flicker
#

people dont have autocomplete xd

fathom hemlock
# prisma shard ye

ye its possible, but I mean word.after - beforeEvents. thtas prob impossible

prisma shard
#

afterEvents are posible, if you need, i can give you my custom event script

fathom hemlock
#

yea

prisma shard
#

u need?

fathom hemlock
#

yes

prisma shard
prisma shard
# fathom hemlock yes
export class EntityHurtBeforeEventSignal extends EntityHurtBeforeEvent {

    /** @type {Map<(data: import('@minecraft/server').EntityHurtBeforeEvent) => void>} */
    listeners = new Map();

    constructor() { }

    subscribe(cb) {
        const id = system.currentTick;
        this.listeners.set(id, cb);
        return id;
    }

    unsubscribe(id) {
        return this.listeners.delete(id);
    }

    run(data) {
        for (const cb of this.listeners.values()) {
            cb(data);
        }
    }
}```
#

class EntityHurtBeforeEvent {
// properties
    /**
     * @type {boolean}
     */
    #cancel = false;
    get cancel() { return this.#cancel };
    set cancel(v) {
        if (v == true){
            // code here to 'cancel'
        }
        return this.#cancel = v;
    };

    /**
     * @type {number}
     */
    damage;

    /**
     * @type {import('@minecraft/server').EntityDamageSource}
     */
    damageSource;

    /**
     * @type {import('@minecraft/server').Entity}
     */
    hurtEntity;

    constructor(data) {
        this.damage = data.damage;
        this.damageSource = data.damageSource;
        this.hurtEntity = data.hurtEntity;
    }
}
#

const entityHurtEvent = new EntityHurtBeforeEventSignal();
WorldBeforeEvents.prototype.entityHurt = entityHurtEvent;


world.afterEvents.entityHurt.subscribe((ev) => {
    const data = new EntityHurtBeforeEvent(ev);
    entityHurtEvent.run(data);
    data.cancel = true;
    if (data.cancel) {
  // code here to cancel
    }
})```
fathom hemlock
#

ohhh

prisma shard
#
// Usage
world.beforeEvents.entityHurt.subscribe((event) => {
    const { damage, damageSource, hurtEntity } = event

    event.cancel = true;
})
fathom hemlock
#

but wait

#

what does typescritp do?

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

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

    export class EntityHurtBeforeEventSignal extends EntityHurtAfterEventSignal {
        private constructor();

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

        unsubscribe(
            callback: (arg0: EntityHurtBeforeEvent) => void,
        )
    }
    export interface EntityHurtBeforeEvent extends EntityHurtAfterEvent {
        cancel: boolean;
        readonly damage: number;
        readonly damageSource: EntityDamageSource;
        readonly hurtEntity: Entity;
        constructor(data: EntityHurtAfterEvent);
    }
}```
Typescript for custom Events
#

for typings

fathom hemlock
#

test.d.typescript

#

why that "d"

prisma shard
#

idk

#

i am not that fimilliar with TS

fathom hemlock
#

I use it everytime but I can't import it

prisma shard
prisma shard
fathom hemlock
#

typescript is so much easier

prisma shard
#

really really false.

fathom hemlock
#

why do I see in libaries ts files

prisma shard
#

?

#

lib?

#

wat libs

fathom hemlock
#

patchy api

prisma shard
#

patchy api?

#

what that

fathom hemlock
#

mc bedrock api

prisma shard
#

idk

#

I dont know much about TS

fathom hemlock
#

but I think it does smth

#

forms.js
forms.d.ts

#

but is it possible to make world.afterEvents.LOL

loud zenith
#
// for example, lets say this file is called "functions.js"

export function test() {

}

import { test } from './functions'

test()

With the new way minecraft load its world how can i make it run like so with worldLoad but i dont see how can someone show me an exemple

loud zenith
#

When i try to import it it make the all thing bug

#

For exemple

sharp elbow
#

When you import code from another file, it imports the entire file. If you are invoking anything in the scope of that imported file, that is your problem

#

e.g.

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

// This line may throw in 2.0 when this file is imported
const overworld = world.getDimension("overworld");

export function init() {}
# main.js
import { init } from "./a_thingy.js"

init();
loud zenith
#
import {world} from "@minecraft/server"

world.afterEvents.worldLoad.subscribe( () =>
World.sendMessage("test")
})

import "file.js"
import { test } from "./function.js"

test()```
loud zenith
sharp elbow
#

You need to write more import-friendly code. I can only offer suggestions if you can share what error you are getting

prisma shard
#

global variables fix the overworld constant issue

#

which returns a have not required priviliges error

sharp elbow
#

This works. That pattern can get repetitive, however. I would personally place those dimensions into another module that can be imported from elsewhere

woven loom
#

anyone know how to make VS Code use globally installed types

prisma shard
woven loom
#

ye, I know how to install it

prisma shard
woven loom
#

but vsc isn't detecting that

prisma shard
#

oh wait

#

uhhhh

prisma shard
#

I just realized

#

Does anyone know why my globally installed types don't work?

onyx lantern
#

does anyone knows if Mojang has any plans to make scripts able to intercomunicate with scripts from other add-ons?

#

would be extremely useful

woven loom
#

you can do that withscript eventss

prisma shard
#

yea

onyx lantern
#

wait, how?

prisma shard
woven loom
#

trigger event and listen to the event

prisma shard
#

/scriptevent se:example

onyx lantern
#

but I cant like:
addon 1 with an input
addon 2 with the function, returns the result to addon 1

woven loom
#

u can also filter based on source

onyx lantern
#

and import files from other addons

prisma shard
woven loom
#

u can pass basic string args

onyx lantern
#

instead of just one

onyx lantern
prisma shard
wary edge
prisma shard
#

Yeah

onyx lantern
#

thats it

prisma shard
#

lol

onyx lantern
#

I wanted to make a library for my projects

wary edge
#

I've done so with my adk-scripts-server library.

woven loom
#

u will need to sync that across packs

prisma shard
#

by the way
is constant arrow function better than functions

onyx lantern
woven loom
#

doesn't matter

#

check npm site

#

its very easy

onyx lantern
#

but like how do you use this on a minecraft addon

woven loom
#

but u will need to install lib to every project

wary edge
#

And then bundle it.

prisma shard
#

you use like that in your addon

#

import your custom lib

onyx lantern
#

I never knew this was possible lol

#

I'm going to check more about this

#

if any of you guys have any tips or idk, youtube tutorials or websites that teach this it would be extremely useful

onyx lantern
#

but either way thank you all very much for all the info!!

woven loom
patent bane
#

how do i modify the durability of an item using scripts?

remote oyster
patent bane
# thorn flicker get the durability component.

it doesnt seem to be workin

import { world } from '@minecraft/server';
import { hasLoreInHeldItem } from '../../../utils/utils.js';

const potato = true

function tryApplyReinforcement(player) {
        if (!hasLoreInHeldItem(player, 'reinforced')) return;

        if (potato) {
            const inventory = player.getComponent('minecraft:inventory')?.container;

            if (!inventory) return false;

            const selectedSlot = player.selectedSlotIndex;
            if (typeof selectedSlot !== 'number') return false;

            const item = inventory.getItem(selectedSlot);
            const durability = item.getComponent('minecraft:durability');
            console.log(durability.damage)
            durability.damage -= 1;

            player.playSound('random.orb');
            player.onScreenDisplay.setActionBar('§r[§bReinforced Item§r]');
        }
}

world.afterEvents.playerBreakBlock.subscribe(({ player }) => {
    if (player?.isValid()) {
        tryApplyReinforcement(player);
    }
});

world.afterEvents.entityHurt.subscribe(({ damageSource }) => {
    const attacker = damageSource.damagingEntity;
    if (attacker?.isValid() && attacker.typeId === 'minecraft:player') {
        tryApplyReinforcement(attacker);
    }
});
thorn flicker
honest spear
thorn flicker
#

put it after the changes

#

looks like sprunkles suggested the same 2 mins ago.

patent bane
thorn flicker
warm mason
#

And remove this useless line

fathom hemlock
#

how to make floating text?

random flint
# fathom hemlock how to make floating text?

The easy way is to use an entity with a nameable component: always_show to true.

  • A custom entity is preferable. But that'll require a resource pack to be rendered correctly.
  • A vanilla entity could work without any new resource pack, but you'll be editing a vanilla file.
prisma shard
#

why Math.clamp() isnt a thing

random flint
#

Shouldn't be hard to implement using max() and min()

prisma shard
#

ikr

#

but why it isnt just a native method

#
const clamp = (val, min, max) => Math.min(Math.max(val, min), max)```
#

we have to do this for clamp

#

atleast even a 1 line matters

#

Math.clamp() would be lot simpler

random flint
#

Math utils class

prisma shard
random flint
#

*make

prisma shard
#

lol

cold grove
granite badger
random flint
#

You can actually delay players' clients to update their surroundings lol.

By overloading the client by sending and using player.spawnParticle, you can have them see a few seconds ago in the past.

Other player's perspectives would be normal. And it doesn't have any significant impact on TPS

prisma shard
prisma shard
shut vessel
#

what is the error ?

random flint
# shut vessel what is the error ?
  • world.getAllplayers() return an array of all online players... basically [ player, player, player ]

You fed that to the objective.getScore()... it doesn't want array

warm mason
prisma shard
#

lol

#

1.999999

warm mason
full idol
#

Is it bad to have lots of global properties on a world?

#

I'm not sure if there is such thing as badly polluting the global scope

warped kelp
#

Mb I'll make a post

fathom hemlock
#

the particles won't show

prisma shard
prisma shard
fathom hemlock
#

uhh

#

type error not a function: const dimension = world.getDimension("overworld");

random flint
#

is world defined?

fathom hemlock
random flint
#

The line before it?

thorn flicker
#

show the full code

fathom hemlock
distant tulip
#

world.getDimension("overworld");
what does this throw in V2 if it is in the global scope

random flint
#

interesting... 🍿

thorn flicker
fathom hemlock
# thorn flicker show the full code
        const dimension = world.getDimension("overworld");

        const startX = plot.pos1.x;
        const startZ = plot.pos1.z;
        const endX = startX + plot.size - 1;
        const endZ = startZ + plot.size - 1;
        const y = PlotAPI.baseY;

        for (let x = startX - PlotAPI.roadSize; x <= endX + PlotAPI.roadSize; x++) {
            for (let z = startZ - PlotAPI.roadSize; z <= endZ + PlotAPI.roadSize; z++) {
                const inPlot = (x >= startX && x <= endX && z >= startZ && z <= endZ);
                const isEdge = (x === startX || x === endX || z === startZ || z === endZ);

                const block = dimension.getBlock({ x, y, z });
                if (!block) continue;

                if (inPlot) {
                    block.setType(PlotAPI.groundBlock);
                    if (isEdge) {
                        const fenceBlock = dimension.getBlock({ x, y: y + 1, z });
                        fenceBlock?.setType(PlotAPI.fenceBlock);
                    }
                } else {
                    block.setType(PlotAPI.roadBlock);
                }
            }
        }
    }```
distant tulip
random flint
fathom hemlock
random flint
#

where are you calling class.generatePlotArea()

fathom hemlock
#

lol no where

#

oh no

#

PlotAPI.generatePlotArea(plot);

random flint
#

Is it on early execution scope?

distant tulip
#

"whats that"

thorn flicker
fathom hemlock
random flint
#

Have you tried system.run()

fathom hemlock
#

no

distant tulip
#

not sure that will do anything

#

use world load event

random flint
distant tulip
#

hmm? no

#

system.run evaluate the call to the next tick
world load wait for the world to actually load

gilded shadow
#

await null;

prisma shard
fathom hemlock
#

now here: PlotAPI.createPlot("plot_" + Date.now(), player.name, pos1, pos2);

thorn flicker
random flint
prisma shard
fathom hemlock
#

or nvm

fathom hemlock
#

its just broken everything

#

my minecraft is broken

gilded shadow
gilded shadow
thorn flicker
fathom hemlock
#

I need ideas for my libary

#

plotAPI is done

random flint
#

-# And win this 1:00 am issue later

wheat condor
gilded shadow
fathom hemlock
fathom hemlock
wheat condor
fathom hemlock
#

I added the plot system

wheat condor
#

i miss read done with gone

gilded shadow
#

💔

wheat condor
gilded shadow
#

🫸 🫷

wheat condor
#

brainrot final boss

prisma shard
#

How do i make a function act like callback with properties

random flint
#

Visual example pls because my brain can't comprehend the ambiguity

prisma shard
prisma shard
#

How do i

gilded shadow
#

variable = function ((player) => {
player.jump();
}

warm mason
distant tulip
warm mason
random flint
distant tulip
random flint
gilded shadow
distant tulip
# random flint is that gud or nah

You win this time

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

console.warn(`world loaded at ${system.currentTick}`);

try {
    world.getDimension("overworld").runCommand("say Hello World!");
    console.warn(`world.getDimension() at ${system.currentTick} with no errors`);
} catch (error) {
    console.warn(`world.getDimension() at ${system.currentTick} with errors`);
    console.warn(error);
}

try {
    system.run(() => {
        world.getDimension("overworld").runCommand("say Hello World!");
        console.warn(`system.run() at ${system.currentTick} with no errors`);
    });
} catch (error) {
    console.warn(`system.run() at ${system.currentTick} with errors`);
    console.warn(error);
}

world.afterEvents.worldLoad.subscribe((event) => {
    console.warn("World Initialized");
    world.getDimension("overworld").runCommand("say Hello World!");
});

random flint
#

Yay.

prisma shard
#
function detectJump(callback) {
  world.afterEvents.playerSpawn.subscribe((event) => {
      const { player } = event;
      callback({ player: player })
  })
}
warm mason
random flint
prisma shard
gilded shadow
distant tulip
prisma shard
#

So that the properties of the event inside function, can be used in the callback like that:

detectJump((event) => {
  const player = event.player
})```
warm mason
prisma shard
#

oooooooooo

#

I see

gilded shadow
#
function detectJump(callback) {
 let player = undefined; world.afterEvents.playerSpawn.subscribe((event) => {
      const { source } = event;
       player = source;
  });
   player.jump();
}
prisma shard
#

Thanks

thorn flicker
prisma shard
warm mason
thorn flicker
#

damn.

prisma shard
#

also why set player undefined?

gilded shadow
#

you can set default

distant tulip
#

event listener inside a function without unsubscribe
sound like a bad idea

random flint
#

One way road

distant tulip
#

well, the game crashing is the unsubscribe

distant tulip
#

Some of my global types do work for some reason tho

woven loom
#

can we export global part

dim tusk
#

-# blind?

#

I forgot, high serty.

bronze pulsar
#

What is the best way to visualize a shrinking border?

  1. Singular Particle Walls (billboard)
  2. Individual particle effects
  3. Custom Barrier Blocks
  4. Other method haven't listed

Thank you.

real whale
#

Can you send me an example of creating a manifest.json file for the script. I can't find it anywhere and I can't do it, it gives an error

dim tusk
#

tho not individual, just use one particle where it adjusts in xyz

real whale
#

Thanks again

dim tusk
#

from com_project into manifest_generator lol

real whale
#

lol

bronze pulsar
woven loom
#

how do i make vsc auto compile

remote oyster
# woven loom how do i make vsc auto compile

tsc --watch will compile automatically when files change. If you use package.json in your project then you can add that as a script:

"scripts": {
    "watch": "tsc --watch"
}

Then excute in your terminal npm run watch. Or just execute the command itself, but that script is good to have if others contribute.

loud frigate
#

Is there an entity animation event thing that can be triggered to make player swing it's hand?

shut vessel
#

hello, you knew how I can put my effects in percentage from 1 to 100% then make it so that when I put the scoreboard streng to 5 it gives 5% easily

prisma shard
gilded shadow
#

is there a way to load/unload chunks?

dim tusk
#

And no it can't detect hitting the air, either animation controllers or use old versions of script.

#

which I doubt you wil

loud frigate
loud frigate
dim tusk
loud frigate
round bone
dim tusk
#

wait, lemme look

#

I have the hardcoded values made by Minato before.

#
{
    "format_version": "1.8.0",
    "animations": {
        "animation.steve.swing": {
            "loop": true,
            "animation_length": 0.2917,
            "bones": {
                "rightArm": {
                    "rotation": {
                        "0.0": [0, 0, 0],
                        "0.0833": [-5.41199, 23.06265, 5.38894],
                        "0.125": [-13.31634, 36.7612, 56.32978],
                        "0.1667": [-58.11073, 6.44931, 8.72102],
                        "0.25": [-28.77157, -5.28699, -10.94791],
                        "0.2917": [0, 0, 0]
                    }
                },
                "leftArm": {
                    "rotation": {
                        "0.0417": [-8, 0, 0],
                        "0.1667": [-16, 0, 0],
                        "0.2917": [-8, 0, 0]
                    }
                },
                "body": {
                    "rotation": {
                        "0.0417": [0, 0, 0],
                        "0.1667": [0, 7.5, 0],
                        "0.2917": [0, 0, 0]
                    }
                }
            }
        }
    }
}```
#

y'know how to use Blockbench right?

loud frigate
#

Can addons modify the player like that tho? I thought we couldn't alter vanilla stuff

drifting ravenBOT
#
What Vanilla Things Can We Modify?

Can

  • Entities
  • Certain Items(Any food items or those found in the windowsapp folder)
  • Entity loot tables
  • Features
  • Feature Rules
  • Biomes

Can't

  • Blocks
  • Block loot tables
  • Items not found in the windowsapp folder
  • Dimensions
loud frigate
#

Let me clarify, addons for the marketplace, I thought there was a policy where vanilla stuff shouldn't be overwritten and in my understanding to add an animation I would need to overwrite something no?

dim tusk
#

You can just add animation in the animations folder and play it using the playanimation command or playAnimation() API in scripts

loud frigate
#

Oh I see I see

#

I barely did anything outside of scripting, I need this because the interact events are so dumb and either always play the swing anim unconditionally or just don't play it at all

wheat condor
#

is there any way to check the effect of a potion itemStack?

warm mason
real whale
#

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

world.beforeEvents.worldSave.subscribe(() => {

prisma shard
gilded shadow
prisma shard
#

it has no native method for add ticking areas

#

you do

runCommand(`add tickingarea ~~~ true`)```
#

smth like that it was

gilded shadow
#

how will i remove it

lyric kestrel
#

It's saying that worldSave is undefined

#

/ not correct

prisma shard
#

what is even a worldSave event 💀

#

chatgpt ahh moment

lyric kestrel
#

There's worldLoad in 2.0.0-beta, but no worldSave

#

If you're using AI. I suggest using Mistal AI's Le Chat

#

It doesn't make stuff up (most of the time)

real whale
distant gulch
#

Guys Help

#

How can I create a ItemStack with a Specified Potion, Like a regeneration potion??

distant gulch
distant gulch
#

Well, im using the 2.0.0-neta and installed the npm of it but it doesnt gets shown

#

maybe the npm is wrong, i got:

#
@minecraft/server-ui@2.0.0-beta.1.21.70-stable
@minecraft/server@2.0.0-beta.1.21.70-stable
#

wait

#

ughhh

#

I see it

distant gulch
random flint
#

Heh, it's always been a static method. Everyone falls for that

full idol
#

I'm currently storing logs for my chestlog addon in global properties, 1 property per chest. How bad is this, and is there a better way to store it? It's on a realm or I'd store it externally...

fast lark
#

how do i cancel whatc dog thing with script

warm mason
fast lark
#

thx serty

prisma shard
fervent topaz
#

guys

#

look

#

no namespace

unique acorn
#

how

prisma shard
#

Post that on #1067535712372654091

#

We need it

fervent topaz
#

its really scuffed

#

u wouldnt want ti

unique acorn
#

just say how

prisma shard
#

Yeah

#

Thats so crazy how would you do without namespace

#

Just tell us how

wheat condor
fervent topaz
#

^facts

unique acorn
#

that's it...?

wheat condor
#

i think

fervent topaz
#

but no

#

i didnt do that

#

its scuffed

unique acorn
#

doesn't it return an error when you don't write a namespace?

fervent topaz
#

it does

unique acorn
#

then how did you do that

fervent topaz
#

ok ima reveal the method

#

u just do this

    const command = {
        name: "hello::::world",
        description: "bruh",
        permissionLevel: 0
    }```
#

and make the colon invisible

unique acorn
#

good to know.

random flint
gilded shadow
gilded shadow
fervent topaz
#

just do

fervent topaz
random flint
#

Does that automatically get parsed to be invisible?

gilded shadow
#

uhh

gilded shadow
unique acorn
fervent topaz
#

yeah

#

defo

random flint
#

or you change the glyph texture?

fervent topaz
#

seems smart

#

but fr tho

#

just put this in ur font folder

random flint
#

ig you did...

gilded shadow
fervent topaz
#

yes

#

i just pasted it in

#

so it looked like a space

prisma shard
#

mhm

#

Indeed very scuffed

fervent topaz
#

yes

warm mason
fervent topaz
#

they sure will

scarlet sable
#

is chatSend not a stable thing?

random flint
scarlet sable
#

brah

#

is there any way to read chat messages in stable api ?

random flint
scarlet sable
#

nvm

#

I think you've killed some of my braincells

#

(I don't have many 💀 )

prisma shard
#

cool

random flint
#

Ah, yes, the obviously redundant and ridiculously stupid concept is being approved. I'm so proud of myself

snow jungle
#

Set a players hunger, is that something accessable through the components?

unique acorn
#

however you can add the saturation effect or hunger effect to the player

#

saturation might heal them up to full hp tho

snow jungle
#

Thank you

snow jungle
fathom hemlock
#

how do I import a ts file

unique acorn
#

you don't

#

you gotta compile the ts file into js

fathom hemlock
#

why libaries are using ts files?

#

like test.d.ts

distant tulip
#

declaration files

dim tusk
snow jungle
fathom hemlock
dim tusk
#

try reading typescript

fervent topaz
snow jungle
#
import {
    system,
    world,
  } from "@minecraft/server";


system.beforeEvents.startup.subscribe((init) => {
    const helloCommand = {
      name: "creator:hellocustomcommand",
      description: "Celebration super party hello",
      permissionLevel: 0,
      optionalParameters: [{ type: 1, name: "celebrationSize" }],
    };
    init.customCommandRegistry.registerCommand(helloCommand, helloCustomCommand);
})

function helloCustomCommand(origin, celebrationSize) {
    world.sendMessage("Hello Custom Command!");

    if (celebrationSize) {
      system.run(() => {
        for (const player of world.getPlayers()) {
          player.dimension.createExplosion(player.location, celebrationSize);
        }
      });
    }

    return {
      status: 0,
    };
  }
#

Seems to not roll any dice for me

fathom hemlock
snow jungle
#

your probably looking at the type bindings

fathom hemlock
#

if u can't import it

snow jungle
#

Which helps you see how functions are used

distant tulip
dim tusk
snow jungle
distant tulip
# fervent topaz

i thought you are into something, lol
scuffed is an understatement

fathom hemlock
#

lol I can import ts files

distant tulip
#

you are talking about minecraft or third party software

dawn zealot
#

When i break a block how can i test if the crop was fully grown or not

prisma shard
#

growthState

#

myb the max growthState is 7

#

Check if its 7 so that can u know if its fully grown

dawn zealot
#

So block.permutstion.growth() ?

fervent topaz
dawn zealot
#

My intrnet bkx broke so doin this shit on phone is aids rn

prisma shard
prisma shard
#

check docs

#

about permutations

dim tusk
prisma shard
#

ya i was talking abt that lol

dim tusk
#

And yes, I used the font and 4 :

dawn zealot
#

Says getState of undefined im lost

prisma shard
#

@dawn zealot

dim tusk
#

Check the state block has.

dawn zealot
#

getAllStates is undefined

prisma shard
#

i remember u as i seen you as a Command guy somewhere, Osuea

dawn zealot
#

?

prisma shard
#

idk ignore it

dim tusk
dawn zealot
#

But it is

prisma shard
#

Or getBlock() if outside event

#

Pretty sure your just trying to detect growth when broken

dim tusk
#
world.beforeEvents.playerInteractWithBlock.subscribe(({ block, player }) => {
  console.error(JSON.stringify(block.permutation.getAllStates()));
});```
prisma shard
dawn zealot
#

Its on my pc

#

My wire to my internet box broke waiting to get replaced

#

So using data

dim tusk
prisma shard
#

block.permutation()
and brokenBlockPermutation property
Isnt it same thing it returns?

dawn zealot
#

4k quality

dim tusk
snow jungle
#

17k subs and no screenshot button

dawn zealot
#

Cannot read property getAllStates of undefined at anon

dawn zealot
snow jungle
dim tusk
#

console.error(JSON.stringify(brokenBlockPermutation.getAllStates()));

prisma shard
#

block property dont exist anymore?

dim tusk
#

Read first...

prisma shard
#

Oooh

#

OK I SHOULD SLEEP

#

ITS ALL BCOZ IM BEING SLEEPY

dawn zealot
#

But what if its broken

snow jungle
#

its a afterevent

dawn zealot
#

I only need broken

snow jungle
#

how are you going to get data from a block thats already broken

#

🤔

dim tusk
dim tusk
dawn zealot
dim tusk
#

Are you sure you're editing the right file? Are you sure that the block has permutation?

snow jungle
dim tusk
#

Since in the first place it should work, you can't tell me otherwise since I'm literally using it rn.

dim tusk
vast comet
#

what is your version

vast comet
#

and are you using the beforeevent

dim tusk
#

then what the fuck.

dawn zealot
vast comet
#

code?

dawn zealot
dim tusk
snow jungle
dawn zealot
dim tusk
#

It's under permutation, pls read docs first.

vast comet
dawn zealot
#

I already said

snow jungle
dawn zealot
#

Before

#

I fixed it

#

Lmao

#

block.permutation.getAllStates()

snow jungle
dim tusk
vast comet
dawn zealot
#

Thats old code

#

Jesus

dim tusk
# snow jungle

And? Doesn't change the fact it's under permutation not block my guy.

snow jungle
#

what are you talking about

#

like seriouslly

dim tusk
dim tusk
dawn zealot
#

Right do how am i supposed to test if its broken if im using interact event then

vast comet
#

huh

dim tusk
#

block.permutation.getAllStates() not block.getAllStates()

snow jungle
dawn zealot
dawn zealot
prisma shard
#

Just answer directly

#

Why argue

dim tusk
vast comet
#

lol

prisma shard
#

"" show me in docs where its stated ""
Like literally?

dim tusk
dim tusk
dawn zealot
dim tusk
snow jungle
#
world.afterEvents.playerBreakBlock.subscribe((event) => {

    const { player, brokenBlockPermutation } = event;

    console.log(JSON.stringify(brokenBlockPermutation.getAllStates()))

})```
dim tusk
#

since the console will return list of permutation available on blocks, if you find one use it in getState('<name>')

dawn zealot
dim tusk
dawn zealot
#

What

#

Bro does not understand what im asking

dim tusk
snow jungle
dim tusk
snow jungle
# dawn zealot Ty.

Np, dont worry about these other trolls, sometimes they feel like they are inherintely better than others for no reason

distant tulip
#

brokenBlockPermutation is not in the before event in V2

dim tusk
#

bro asks for source and gave him and I'm the one who's wrong? Oh noo.

north frigate
#

guys I'm bored what to code

dim tusk
#

Tbh, I talked to you properly but I guess you took it seriously? Then it's not my fault lol

snow jungle
#

Why are you being such a ass, just help the guy. Stop trying to bait me into a arguement thanks

distant tulip
#

-# that what he did

fathom hemlock
#

why is the item undefined?

  try {
    const currentId = event.itemStack?.typeId;

    console.warn(`[setItem] Used item: ${currentId}, target: ${itemId}`);

    if (currentId === itemId) {
      func();
    }
  } catch (e) {
    console.warn(`[setItem] Error: ${e}`);
  }
};
distant tulip
#

anyway @dawn zealot brokenBlockPermutation is in the afterevent
sorry about the misinformation

dawn zealot
#

I do have another question tho

dim tusk
#

wait, I can use the this. in the function() right?

dawn zealot
#

Is their an efficient way to check like lets say a 3x3 area around the broken crop instead of typing out each coordinate?

distant tulip
dawn zealot
#

Oh god lmao

dim tusk
#
world.afterEvents.playerBreakBlock.subscribe(({ block, player }) => {
  const { x, y, z } = block.location;

  for (let dx = -1; dx <= 1; dx++) {
    for (let dy = -1; dy <= 1; dy++) {
      for (let dz = -1; dz <= 1; dz++) {
      }
    }
  }
});```

-# oof, lag will say hi to you...
distant tulip
#

i mean... you could simplify that
const offsets = [];
for (let dx = -1; dx <= 1; dx++) {
for (let dz = -1; dz <= 1; dz++) {
if (dx === 0 && dz === 0) continue; // skip center
offsets.push({ x: dx, y: 0, z: dz });
}
}

#

-# not referring to what coddy sent

dim tusk
#

I guess it would be better, if I just make this into a class. Tbh

dawn zealot
full idol
#

Is there a place for all afterEvents and beforeEvents?

full idol
#

Thanks!

unique acorn
#

the links I sent u are not beta btw

fathom hemlock
#

light speed

unique acorn
distant tulip
#

lol

dawn zealot
distant tulip
#

add them to your block location and get those blocks

dawn zealot
#

I dont get it

#

Wait nvm

#

Yep im still lost

full idol
#
        const allClaims = getAllClaims();
        let insideClaim = null;

        for (const [name, claim] of Object.entries(allClaims)) {
            if (
                hasFlag(claim.flags, CLAIM_FLAGS.LOG_ENTRY_EXIT) &&
                isPositionInBoundary(claim.start, claim.end, { x, y, z })
            ) {
                insideClaim = name;
                break;
            }
        }
export function isPositionInBoundary(pos1, pos2, target) {
  const [xMin, xMax] = pos1.x < pos2.x ? [pos1.x, pos2.x] : [pos2.x, pos1.x];
  const [yMin, yMax] = pos1.y < pos2.y ? [pos1.y, pos2.y] : [pos2.y, pos1.y];
  const [zMin, zMax] = pos1.z < pos2.z ? [pos1.z, pos2.z] : [pos2.z, pos1.z];

  return (
      target.x >= xMin && target.x <= xMax &&
      target.y >= yMin && target.y <= yMax &&
      target.z >= zMin && target.z <= zMax
  );
}

For a claims plugin that logs whenever someone enters a claim, is this bad practice? I'm using some code from this chat way back. This runs on the playerButtonInput afterEvent so I'm not sure if this is bad... like I get tons of claims will cause issues, but say like 30 claims

distant tulip
# dawn zealot Yep im still lost
import { world } from '@minecraft/server';

world.afterEvents.playerBreakBlock.subscribe((event) => {
    const { brokenBlockPermutation } = event
    if (brokenBlockPermutation.type.id !== "minecraft:wheat") return;
    if (brokenBlockPermutation.getState('growth') !== 5) return

    const blocks = getHorizanal3x3Blocks(event.block)
    for (const block of blocks) {
        //...
    }
})

function getHorizanal3x3Blocks(block) {
    const { x, y, z } = block.location
    const blocks = [];
    for (let dx = -1; dx <= 1; dx++) {
        for (let dz = -1; dz <= 1; dz++) {
            if (dx === 0 && dz === 0) continue; // skip center
            Blocks.push(block.dimension.getBlock({
                x: dx + x,
                y: y,
                z: dz + z
            }))
        }
    }
    return blocks
}
full idol
#

I feel like I'm always reading the wrong docs, but is there a reason I can't use this on the beta? I just want to check if a player is in creative

#

(I'm running this inside the before block break event)

lyric kestrel
full idol
#

Thank you! I'll give it a go

shut citrus
#

any example using getBlocks method?

fathom hemlock
#

why is this not working?

    e.player.sendMessage("You wrote: " + e.message);
  });```
#

do I need to do const player = e;

#

oh wait its msg