#Script API General

1 messages ¡ Page 108 of 1

wary edge
#

Not what I meant.

#

I meant did you wait 1 tick after setProperty before calling getProperty?

loud brook
wary edge
#

Yes.

#

SetProperty takes 1 tick.

loud brook
#

Oh, I will try it rq then

loud brook
wary edge
#

No idea. It's been like that for as long as I know.

loud brook
#

TYSM!!!!!

#

I Literally was stuck on this stupid problem for like 4 hours

#

Tysm so much!

subtle cove
#

Some rider component check, perhaps...

rose light
#

If I double-click quickly to use the shortcut to store the item effectively from the inventory, it executes the event 4 times. How could I solve this effectively?

subtle cove
#

But idk how that's doubled

#

Try troubleshooting how many times that method got triggered

#

If idk where that's triggered i just put a stack tracer inside the event

console.error(new Error("trace").stack)
rose light
frozen vine
#

player.addEffect supports infinite time?

warped blaze
#

you must use commands

shy leaf
frozen vine
shy leaf
#

i havent touched addons for a while so i forgot

#

by the way, since item lore supports RawMessage, how does text limit work now?

warped blaze
#

oh sorry

#

i thought you were asking since when we had support

shy leaf
#

np

warped blaze
#

btw, wasn't the limit increased to 255 characters per line?

#

i remember something like it

shy leaf
#

100 lines i think?

#

and/or 1000 characters per line

#

the docs probably didnt update

cursive fog
#

Guys

#

Is it possible to change the player rot using scripts?

#

Because tp is kinda janky

#

And i cant change the camera rot for first person

sudden verge
#

player.setRotation

#

most of the time, your question can be answered by simply looking in the docs

distant tulip
cursive fog
cursive fog
sudden verge
#

Damn that is very odd, after testing both lookAt & the setRotation methods are unsupported for players. So yeah I guess theres really no better solutions

#

and keepVelocity in teleport options are also unsupported, lovely

loud brook
#

Guys, I have a question
Does running system.runInterval causes lag?

shy leaf
#

if you have multiple runInterval running at once filled with cost intensive works, then it will cause lag

halcyon phoenix
#

I love scripts

vast comet
#

is there a way to know pushed blocks previous location?

civic nest
#

BlockPistonComponent does have getAttachedBlocksLocations function, you can use those

distant tulip
#

locations and the piston location and isExpanding and do a bit of math to get the previous location.

lapis heart
#

but that fail if the block is pushed from behind the piston (using slime blocks)

barren willow
vast comet
#

What about the beforeEvent, iirc there is a before event for piston event

civic nest
#

No there isn't

distant tulip
#

It got removed

vast comet
#

Bruh

lapis heart
#

yes, A while ago

unique acorn
#

why is there 3 Minato's

#

who's the real one

distant tulip
#

Who

lapis heart
#

me

barren willow
#

Idk

civic nest
#

me

civic nest
unique acorn
#

there's a fourth one???

civic nest
#

Not YET

distant tulip
#

Where

lapis heart
unique acorn
shut sapphire
unique acorn
#

-# a fifth one??

lapis heart
#

Maybe we have a sixth one 👀

distant tulip
#

Oh no

shy leaf
#

what in the gods green earth is this shir

#

t

woven loom
#

wth

lapis heart
#

what's going on here ???

distant tulip
#

You should ask your self

#

Or ask me

#

Or the other ones

civic nest
#

You're right

lapis heart
#

100‎%‎

halcyon phoenix
#

wth

#

do you have 2 acccounts?

lapis heart
#

No

halcyon phoenix
civic nest
distant tulip
#

You guys should this to #off-topic

#

Or i should

harsh robin
warm mason
warm mason
harsh robin
warm mason
#

oh..

harsh robin
#

?

loud brook
warm mason
#

you can't use getScoreboard right after running code in V2

shy leaf
harsh robin
#

i didnt even make this

#

🙏

loud brook
warm mason
harsh robin
warm mason
harsh robin
#

how do i

#

change that

#

what to change it with

warm mason
#

just put this file instead of yours

harsh robin
#

im not a scripter

#

i literally payed 5$

warm mason
drowsy scaffold
#

why is there 7 minato's 💀

harsh robin
#

bc

drowsy scaffold
#

sorry, 6

harsh robin
#

they're all gay

drowsy scaffold
#

someone skipped a number

harsh robin
#

right @shut sapphire ?

#

IT ISNT WORKING

warm mason
#

If you're not going to do something yourself, go to the guy who made it.

harsh robin
#

but he blocked me

#

ill just ask chatgpt

#

im sure it wont make it 10x worse

shy leaf
#

instead of dealing with the codes all at once (with only one runInterval)

dusky flicker
#

supposing each runInterval runs in parallel or in multi threads, which the implementors can do if they want, no it wont

#

but i got no idea how that is implemented

#

the thing is that runninh with a lot of intervals you have to paralelize them all

#

while making simply a single 1 it will judt execute that single one without the need to paralelize

#

so in theory and so far as i know about the scripting, yeah it would lag

#

maybe cause more overhead actually

#

the lag would be caused due to your function implementation

warm mason
#

runInterval simply runs a function every X ticks. That is, if you have two intervals with a delay of 1 tick, then the functions in them will be executed in turn every tick.

dusky flicker
sly valve
#

I wish PlayerLeaveBeforeEvent had the cancel: boolean property

dusky flicker
#

what it can do is stop 1, go to another, stop that, go back, and keep like that

sly valve
#

😿

warm mason
#

whole script is executed in one thread

#

one by one

sly valve
#

Microsoft is able to train its own AI but not able to Minecraft's Script API better

#

based

dusky flicker
sly valve
#

Yessir

round bone
sly valve
#

Why dont they just add

  • Workers
  • readJSON function
  • fs (but kinda downgraded ofc)
#

so much goof things they could do

dusky flicker
# warm mason

so something like

runInterval(a);
runInterval(b);
runInterval(c);
is no different than
runInterval(()=>{
a();
b();
c();
});

isnt it?

dusky flicker
#

like, your addons could literally write other addons

sly valve
dusky flicker
dusky flicker
sly valve
#

right quickjs...

dusky flicker
sly valve
#

just a basic readJSON(path: string): Promise<Object> function

dusky flicker
#

but probably they won't because i dont think it is spec of js

#

that would probably be a thing quickjs would have to implement

stuck ibex
dusky flicker
#

no reason to import json files

#

like no other language does that

stuck ibex
#

its a great config file ig

dusky flicker
stuck ibex
#

but webdev usually lacks those

stuck ibex
dusky flicker
dusky flicker
#

literally no other language have an issue like this

#

i dont see any std on any other languages importing specifically json

#

or files for configs

subtle cove
#

having access to nbt is already a no-no for the devs

stuck ibex
dusky flicker
round bone
#

😳

dusky flicker
#

and not force json

#

what if i want to use toml instead?

round bone
dusky flicker
#

yml is based

round bone
#

PNPM is using YAML, PNPM is based, so YAML is also based.

stuck ibex
dusky flicker
#

i use a lot of code written in rust and c++, they dont use json

stuck ibex
dusky flicker
#

ghostty, kitty and alacritty, 3 terminals, none of tjem use json

stuck ibex
#

js is its own system

#

it can break the tradition whenever it wants

#

bottom line

dusky flicker
stuck ibex
#

try it, let us know

distant tulip
#

it doesn't

sly valve
#

fuck

shut vessel
round bone
unreal saddle
#

Is there a way to detect when an item is crafted? And block it

unique acorn
unreal saddle
unique acorn
#

that works but you can use playerInventoryItemChange event

unreal saddle
unique acorn
unreal saddle
unique acorn
#

well you can remove it

quiet magnet
#

Good afternoon, does anyone know if I can register Minecraft:timer with Scripts API?

#

And mark_variant values

#
"egg:pre_hatch_timer": {
          "minecraft:mark_variant": { "value": 2 },
          "minecraft:timer": {
            "looping": false,
            "time": 10,
            "time_down_event": {
              "event": "egg:spawn_state",
              "target": "self"
            }
          }
        },
#

Example, this one is 10 seconds and Mark Variant 2

round bone
#

Timer you can modify only via component groups.

harsh dawn
#

hey guys im a little new to scripting and i wanted to make something simple where if a certain player broke a block the world would send a message but everytime the player breaks something the message will say the block broken is minecraft:air (btw i changed "username" to a real username)

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

world.afterEvents.playerBreakBlock.subscribe((event) => {
const block = event.block;
if (event.player.nameTag === "username") {
world.sendMessage(user just broke ${block.type.id}!);
}
})``

warm mason
#

use event.brokenBlockPermutation.type.id

harsh dawn
# warm mason use ``event.brokenBlockPermutation.type.id``

o awesome tysm
do yk how i could change it so the text is a little nicer and js says the block isntead of minecraft:oak_leaves
also js to get a better understanding what does permutation do and how could i find that in the documentation

cinder shadow
#

Is there a restriction in format version for "minecraft:cooldown" in scripting? I'm trying to get an item's cooldown component but it's format version 1.10

warm mason
cinder shadow
#

I wonder if it's freaking out because it's a vanilla food item

#

It only returns the compostable component

#

ah

#

this component only gets the cooldown when it's attached to food

#

not the "minecraft:cooldown" component

silver agate
#

How can I detect if player isn’t holding an item?

const heldItem = player.getComponent(“minecraft:equippable”)?.getEquipment(EquipmentSlot.mainhand);
if (!heldItem) {
…
}```
Or

```js
const heldItem = player.getComponent(“minecraft:equippable”)?.getEquipment(EquipmentSlot.mainhand);
if (!heldItem.typeId === “minecraft:air”) {
…
}```
?
cinder shadow
#

try it

cinder shadow
#

so this cooldown component is useless in scripting

#

food has a built in animation that you can't get rid of, it's cooldown is automatically applied when you start eating, not when you've finished eating the item

#

I can't even disable it with "can_always_eat": false because it's forced to true when in peaceful

#

crashing out on Minecraft food

jagged gazelle
#

I'm back!

warm mason
#

hmmm

jagged gazelle
cinder shadow
#

oh SICK, getCooldownTicksRemaining DOESN't EVEN WORK

#

nvm it does, eventData.cancel makes it so getting the cooldown will be 0, but it will still set the cooldown

cinder shadow
#

I'm kinda out of options, I tried syncing the timing of the food cool down to a dynamic property, but they are incredibly inconsistent for some reason

#

Why we can't just get the cool down component and why it's locked to food that always triggers before you've eaten it is beyond me

halcyon phoenix
#

bro calm down

#

stop it

#

get some help

harsh dawn
#

hey guys im a little new to scripting and i wanted to make something simple where if a certain player eats food the world would send a message but i cant seem to get the food detection quite right (btw i changed "username" to a real username)

world.afterEvents.itemCompleteUse.subscribe((event) => { if (event.source.nameTag !== "username") return; if (event.itemStack.hasComponent("minecraft:food")) { const item = event.itemStack.typeId world.sendMessage(`user just used ${item}!`); } });

warm mason
halcyon phoenix
#

oh lol

warm mason
#

also do this when you want to send a code

halcyon phoenix
warm mason
#

hm?

full idol
#

Taking shots in the dark here, but would it be possible to detect Horion commands through detecting when players open chat or send a message which doesn't reach the server somehow? Any ideas appreciated!

valid ice
full idol
valid ice
#

And the client can’t pass data to the server, save for very specific instances, so seeing UI buttons pressed or testing chat being opened would always be very inaccurate

full idol
#

There has to be something out there to catch it. I know any large scale release would let them patch it rapidly to avoid detection, but I'm working small scale here

#

I have even considered "captchas" which require them to type .eject while joining as I've heard it must be injected from the main menu before doing anything? This fell apart because people can change prefix

harsh dawn
valid ice
warm mason
#

I don't remember exactly what the tag should be

cinder shadow
#

wait the cooldown component can't even be read in a before event, so it's impossible to actually check whether the item is being used off of it's cooldown

#

I give up

#

this components a mistake

cinder shadow
#

mk I got it finally.. had to use the itemCompleteUse event

harsh dawn
cinder shadow
#

you could just make an array of every food item

harsh dawn
cinder shadow
#

yes

#

that's what I've done

#

at least every food item I care about

harsh dawn
#

ehhh i js feel liek theres gotta be a better way to do it

stark kestrel
harsh dawn
halcyon phoenix
halcyon phoenix
#

??

cinder shadow
#

did you try it and see if it works?

halcyon phoenix
hazy kraken
hazy kraken
halcyon phoenix
#

I have no idea but if there's a will there's a way

hazy kraken
#

ohhhh ok

#

I thought u ment there was one and u knew it lol

halcyon phoenix
#

if it's not doable then list all food manually

hazy kraken
#

i js made a fat list with all the food types

halcyon phoenix
cinder shadow
#

now just do const isFood = foodItemTypeIds.includes(item.typeId) and you're done

harsh dawn
#

o cool

hazy kraken
grand needle
#

Does anyone know if it is possible to detect items in the crafting table slot?

subtle cove
#

only inventory, equipment and cursor

stark kestrel
#

is it possible to get if a block was stopped mining?

shy leaf
#

has anyone figured out how to check for duplicate lines on item lore with RawMessage?

#

im currently fiddling with the new RawMessage argument for item lore and i cant seem to filter out existing lores and avoid interfering with other lore texts

#

since its a RawMessage and not just string, i cant compare it nor use .filter() or .includes()

#

or should i just stringify an object in RawMessage and compare with that? i dont know if stringifying existing lore works

shy leaf
#

OH WAIT

#

getRawLore EXISTS

#

😭

harsh dawn
#

hey guys im a little new to scripting and i was wondering what the difference was between event and eventsignal classes because i see this pattern a lot

shy leaf
#

also some event subscribes have interfaces for filtering options

stark kestrel
shy leaf
#

hopefully soon

#

one day

stark kestrel
#

i dont even think they will add support for bedrock so make a block stay in its broken state if it was being mined

#

:/

shy leaf
#

cant say theyll never do it

#

it might not be their top priority

#

but it could happen one day

jagged gazelle
stark kestrel
halcyon phoenix
warped blaze
#

poor guy

halcyon phoenix
#

change his name

#

*Name your self Script API

*gets asked about Script API

*angry because he got pinged

hazy nebula
#
const view = target.getViewDirection();
            const pos = target.location;

            const forwardX = Math.floor(pos.x + view.x * -3);
            const forwardY = Math.floor(pos.y);
            const forwardZ = Math.floor(pos.z + view.z * -3);
            target.runCommand(`tp @s ~~0.1~`)
            player.teleport(forwardX, forwardY, forwardZ, {
                dimension: dim,
                rotation: target.getRotation()
            });``` what wrong with `player.teleport` ?
shy leaf
#

but in that code, youre giving three Number objects, which is wrong

#

so you should be doing

player.teleport({
    x: forwardX,
    y: forwardY,
    z: forwardZ
}, {
    dimension: dim,
    rotation: target.getRotation()
});
stark kestrel
stark kestrel
#

Does anyone have formula to minecraft bedrock's strength extra damage formula

granite cape
#

wanna made teaser

warm mason
granite cape
#

but this work

world.beforeEvents.itemUse.subscribe(function tes(e) => {
  const {source,itemStack:item}=e;
  if(item?.typeId==="minecraft:stick")system.run(async()=> {
    const hud=source.onScreenDisplay,cam=source.camera
    const lpos1= {x:-199,y:126,z:536};
    source.onScreenDisplay.hideAllExcept()
   cam.fade({fadeTime:{
     fadeInTime:1,
     holdTime: 1,
     fadeOutTime:1
    }})
    await system.waitTicks(30)
    cam.setCamera("minecraft:free",{location:lpos1,rotation:{x:0,y:150}})
    await system.waitTicks(10)
    cam.setFov({fov:30,easeOptions:{easeTime:3,easeType:"InOutCubic"}})
    await system.waitTicks(50)
    source.sendMessage("what is that??")
    await system.waitTicks(40)
    cam.setFov({easeOptions:{easeTime:3,easeType:"InOutCubic"}})
    await system.waitTicks(70)
    cam.setDefaultCamera("minecraft:third_person",{easeType:"InOutCubic",easeTime:2})
    await system.waitTicks(40)
    source.onScreenDisplay.resetHudElementsVisibility()
    cam.clear()
    world.beforeEvents.itemUse.unsubscribe(tes)
  })
})
granite cape
naive tinsel
#

is it possible to get the current ticking areas in the world?

warm mason
#

No

warm condor
#

how do i freeze a player in place?

#

like

distant tulip
#

tp or input permission

warm mason
warm mason
#

Hm

distant tulip
#

system.runInterval(() => {
    const overworld = world.getDimension('overworld');
    const nether = world.getDimension('nether');
    const the_end = world.getDimension('the_end');
    
    const entities = [...overworld.getEntities(), ...nether.getEntities(), ...the_end.getEntities()];
    for (const e of entities) {
        if(e.typeId === "minecraft:player") continue
        e.clearVelocity()
    }
});
#

stable module

halcyon phoenix
jagged gazelle
#

Guess what I am doing with this function only.```js
function parseLocation(location) {
let [left, right] = location.split(':');

if (left.includes('.')) {
const [namespace, value] = left.split('.');
left = ${namespace}:${value};
} else if (!left.includes(':')) left = minecraft:${left};

if (right) {
if (right.includes('.')) {
const [namespace, value] = right.split('.');
right = ${namespace}:${value};
} else if (!right.includes(':')) right = minecraft:${right};
} else right = left;

return [left, right];
}```

jagged gazelle
#

no...

#

not even close lol

normal wing
#

lol you said guess, so...

warm mason
jagged gazelle
warped blaze
warped blaze
distant tulip
distant tulip
warped blaze
#

oh mb

warped blaze
distant tulip
#

seem so
altho Serty is talking about beta api (it is the one that have player support for clearVelocity)
i was using stable model so that what i was able to test at that time

subtle cove
snow apex
#

Ending up learning a bit to write one myself lmao, but thank you

halcyon phoenix
snow apex
#

No i just used the built in detection with scripts

#

Works great

distant tulip
#

How to use rawText


           { text: `§rDimension: §5`, translate: dpDim1},

This doesn't show the dimension text, only the translation

prisma shard
#

how can I get strings parts in custom commands?
I need the radius in code
as a variable
like get the input

woven loom
#

after the first param

round bone
sullen heart
#

Custom components V2 is already in stable?

prisma shard
#

also how to filter out player's id

#

like get the player according to player id i have

woven loom
sullen heart
distant tulip
naive tinsel
thorn flicker
prisma shard
#

also

#

how to get the player according to player id i have

round bone
round bone
prisma shard
#

huh

#

getEntity?

#

that even exist?

#

INTERESTING, i never knew this existed.....

sharp elbow
#

It's a fascinating method. Very useful

prisma shard
#

@warm mason If i remember correctly... You shared a stomp mechanic function, Which applies knockback like stomping. Is that script still being shared? I can't find

dusky flicker
round bone
somber cedar
#

nvm it says Playfab there

round bone
#

If you can't use XUID, use entity's identifier.

somber cedar
#

I’m trying to download an addon for editor. How do I add the addon to editor mode

wary edge
prisma shard
# warm mason https://discord.com/channels/523663022053392405/1310147379361615872
function getDirection(vector1, vector2) {
    let distance = Math.sqrt((vector1.x - vector2.x) ** 2 + (vector1.y - vector2.y) ** 2 + (vector1.z - vector2.z) ** 2) || 0.001
    let direction = {
        x: (vector2.x - vector1.x) / distance,
        y: (vector2.y - vector1.y) / distance,
        z: (vector2.z - vector1.z) / distance
    }
    return direction
}

/**
 * @param {Entity} entity 
 */
function bossStomping(entity) {
    const entities = entity.dimension.getEntities({ location: entity.location, maxDistance: 5 }) ?? []

    for (let target of entities) {
        let direction = getDirection(entity.location, target.location)
        applyKnockbackUpdated(target, direction.x, direction.z, 5, direction.y * 0.5 + 0.5);
        target.applyDamage(5, { cause: "entityAttack", damagingEntity: entity })
    }
}

world.afterEvents.itemUse.subscribe(event => {
    if (event.itemStack.typeId !== 'minecraft:stick') return;
    bossStomping(event.source)
})


function applyKnockbackUpdated(target, dirX, dirZ, horizontalStrength, verticalStrength) {
    const horizontalForce = {
        x: dirX * horizontalStrength,
        z: dirZ * horizontalStrength
    };

    target.applyKnockback(horizontalForce, verticalStrength);
}

This also launches up the player.. and sometimes, It can't find the entity.
In my case, i am using player as the target entity, and stick as a stomper

#

help

prisma shard
#

npm bot not work

round bone
# prisma shard npm bot not work
jagged gazelle
#

which one you guys prefer?

// v1
const at = Player.stat.at('<location>');
at.set(10);
at.add(); // optional values inside
at.sub(10);``````js
// v2
const get = Player.stat.get('<location>');
Player.stat.set('<location>', 10);
Player.stat.add('<location>');
Player.stat.sub('<location>', 5);```
cinder shadow
#

when you aren't looking at anything while typing and look up to see ```js
dimension.setBlockType(blockLocation, 'mciniweacft'syr)

zealous wing
#

What is the best approach to tick a water source block after placing it?

#

right now I just get a cube of water that isn't flowing

open urchin
#

try placing flowing water instead

wary edge
warped blaze
#

we can use it as a variable name?

#

or is it just for an example

unique acorn
#

obviously its just an example

solar dagger
#

is there a way to add a crosshair for a player while riding an entity?

warped blaze
#

maybe using json ui

#

with hud screen

noble pecan
#

how would i make this script make it so that a particle is constantly emitting a particle on a block. The wiki was no help and i have zero experience with scripts at all

solar dagger
sly valve
#

SourceEntity is the player, when executen by ins

distant tulip
#

Is there a way to detect player pressing sneak while he is riding an entity? With the dismount disabled.
both the event and player.isSneaking do nothing

small cloak
#

Does setPropertyOverrideForEntity() persist between reloads?

#

I feel like it wouldn't.

shy leaf
#

RawMessage support for item lore is one of the best thing that could ever happen in the histroy of scripting api

#

i really love it

narrow lintel
#

Hello everyone, can we defined the item arrow identifier and projectile arrow identifier separately, using api?

Please help

halcyon phoenix
shy leaf
#

what do you mean by default text?

halcyon phoenix
#

english->korean via rawmessage set item lore?

shy leaf
#

well uh

shy leaf
#

which has translation and other stuff

halcyon phoenix
#

that's very helpful I should try and make that

halcyon phoenix
shy leaf
#

the layout?

halcyon phoenix
#

how is the lore structured? from the name to the status

#

I want to to extend the when in main hand part

shy leaf
#

oh

halcyon phoenix
#

add another custom status for the item

shy leaf
#
  const damage = stats.damage ?? 0;
  const atkSpeed = stats.attackSpeed ?? 0;

  let existingLore = item.getRawLore() ?? [];

  const mainhandStr = { rawtext: [{ text: "§r§7" }, { translate: "sweepnslash.item.modifiers.mainhand" }] };
  const damageStr = { rawtext: [{ text: ` §r§2${damage} ` }, { translate: "sweepnslash.attribute.name.attack_damage" }] };
  const atkSpeedStr = { rawtext: [{ text: ` §r§2${atkSpeed} ` }, { translate: "sweepnslash.attribute.name.attack_speed" }] };

  function isOurLine(raw) {
    const str = stringifyRawMessage(raw);
    return (
      str.includes("sweepnslash.item.modifiers.mainhand") ||
      str.includes("sweepnslash.attribute.name.attack_damage") ||
      str.includes("sweepnslash.attribute.name.attack_speed")
    );
  }
  const itemLore = existingLore.filter((line) => !isOurLine(line));

  if (existingLore.length >= 100) return;

  if (stats.skipLore) {
    itemSlot.setLore([...itemLore]);
  } else {
    itemSlot.setLore([...itemLore, mainhandStr, damageStr, atkSpeedStr]);
  }
#

this is how its structured

nimble schooner
#

How do I get the dimension name from the dimension an entity is in? entity.dimension returns [object Object]

#

Is there sth like entity.getDimension()?

halcyon phoenix
#

JSON.stringify(entity.dimension)

nimble schooner
#

Ty

halcyon phoenix
#

that just turns it into string

nimble schooner
#

It returns {"id": "overworld"} so I guess I can just do entity.dimension.id to get the string I need right away

#

I mean I don't just guess

halcyon phoenix
#

yeah you can do that

nimble schooner
#

Ty for your help dude

#

Or not dude, idk

halcyon phoenix
shy leaf
#

idk how to make this better but it works for now

#

...actually, hold on

#

ok nvm it didnt work

#

youre passing an object that dimension argument does not take

subtle cove
#

it needs a Dimension prototype so ```js
const dimension = world.getDimension(target.dimensionId)
player.teleport(target.location, {dimension})

subtle cove
#

or that way

broken pawn
#

i don't really understand how to utilize playerSpawn and playerJoin.

i just want the command executed once the player join or respawn

open urchin
#

the player isn't in the world yet on playerJoin

#

playerSpawn is when the player actually spawns in the world

broken pawn
#

well, how to correct it?

#

wait

open urchin
#

put everything in playerSpawn

broken pawn
#
world.afterEvents.playerJoin.subscribe((player)=>{
    const X = player.source;
    if(X.hasTag("Custom.Member")){
        X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
    }else{
        X.addTag("Custom.Member");
        X.runCommandAsync("Effect @s Resistance 15 4 True");
        X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
        X.runCommandAsync("Function Custom/World_Config");
        X.runCommandAsync("Function Custom/Settings");
    }
});

world.afterEvents.playerSpawn.subscribe((player)=>{
    const X = player.source;
    if(X.hasTag("Custom.Member")){
        X.runCommandAsync("Effect @s Resistance 15 4 True");
        X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
        X.runCommandAsync("Function Custom/Settings");
    }
});

world.afterEvents.itemCompleteUse.subscribe((event_data)=>{
    const X = event_data.source;
    const item = X.getComponent('equippable').getEquipment('Mainhand');
    if(item?.typeId=='minecraft:milk_bucket'){
        X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
        X.runCommandAsync("Effect @s Regeneration 10 4 True");
        X.runCommandAsync("Effect @s Saturation 5 0 True");
        X.runCommandAsync("Function Custom/Settings");
    }
});
#

only the itemCompleteUse is working

shy leaf
#

have you tried having content logs on

broken pawn
#

haven't enabled it, cuz it's my first time doing this

subtle cove
broken pawn
runic maple
#

Does anyone know a way to set the dynamic property of stackable items?

latent wing
#

Does anyone know how I can register a custom component? I'm using the 2.0.0 API, but the script I had no longer works.

import * as mc from '@minecraft/server';
import * as ItemComponent from "./test/sistema/items.js";
import "./test/sistema/title.js";
import "./test/sistema/commands.js";
import "./test/sistema/menu.js";
// import "./test/sistema/chat.js";


import "./test/tree_stats.js";

import "./combat/basics.js";



mc.world.beforeEvents.worldInitialize.subscribe(event => {
    const itemComponentRegistry = event.itemComponentRegistry;

//Kagune
    itemComponentRegistry.registerCustomComponent("ts:system",{onUse: arg => {ItemComponent.menu(arg.source);}});
    
    itemComponentRegistry.registerCustomComponent("ts:kagune_kaneki",{onUse: arg => {ItemComponent.kagune_kaneki(arg.source);}});
    itemComponentRegistry.registerCustomComponent("ts:kagune_touka",{onUse: arg => {ItemComponent.kagune_touka(arg.source);}});
    itemComponentRegistry.registerCustomComponent("ts:kagune_tsukiyama",{onUse: arg => {ItemComponent.kagune_tsukiyama(arg.source);}});
});
warm mason
latent wing
runic maple
round bone
# runic maple 😞

The closest thing you can approach is by using item's lore and saving it with paragraphs (§).

stark kestrel
#

I didn't even know @minecraft/client is a thing

stark kestrel
unique dragon
#

Just an internal thing

#

We can't use it

#

The things that we can use are in the wiki

runic maple
#

I could loop through all the slots but this would prolly cause lag as the function runs every second

round bone
runic maple
#

Aight

nimble schooner
#

Why does this send me to the same dimension I'm in everytime even tho I was in the overworld but the console warning said target.dimension is "minecraft:nether" js console.warn(target.dimension) player.teleport(xyz, world.getDimension(target.dimension));

warm mason
merry cove
#

opa oi ?

#

foi mals mano tava meio afastado kkkk

warped blaze
#

like

warped blaze
warm mason
warped blaze
#

oh

#

ig target isn't an entity

round bone
warped blaze
#

i supposed it was

halcyon phoenix
#

client sided stuff

jagged gazelle
#

I complained about this way way back and there's no fixed yet.

jagged gazelle
#

Oof, not wouldn't more like don't...

distant tulip
jagged gazelle
#

it's like they literally separated the dismount button ID to the sneak button itself.

distant tulip
#

Was this when they made the player hitbox shorter on sneak

jagged gazelle
#

I'm not entirely sure but there's a chance that it is...

#

I need a professional to actually say the reason why they did that 😭😭

#

It's frustrating asf...

distant tulip
#

Let's mass ping navi
-# jk

cinder shadow
#

I feel scammed

#

It may be incorrect because it's not actually checking if the entity is on the ground, it's just checking if their velocity is 0

halcyon phoenix
#

scammiest method

cinder shadow
#

Well I'm trying to use it for my custom falling block

#

But entities do not fall at the same speed as the falling block entities

#

So I'm trying to set gravity to false and appy impulse at a close equivalent

#

Not to mention the entity desync this game has throws off all of the position checks

stark kestrel
unique acorn
#

whats the difference between ItemStack.type.id and ItemStack.typeId

halcyon phoenix
unique acorn
#

thanks

acoustic basin
#

guys, i need some help. so i have a block, let's call it block A, and i have block B. when block B is destroyed, i spawn a particle, and i want that particle to travel to the block A, if it's present in a 48 block radius from block B, kind of how particles go to creacking heart when you hit the creacking

#

is there any way to do this without any lag?

shut citrus
#

What's onswing event and how to use it?

lapis heart
wintry bane
#

What do you guys think about using block class for server ui icons?

#

so instead of using individual isometric screenshots, it uses what the inventory uses

warm mason
wintry bane
#

like form.button("Crafting", craftingTableVariable);

warm mason
wintry bane
#

block class

open urchin
#

i think a BlockType would make more sense

warm mason
#

you will get an error

wintry bane
#

yeah blocktype

#

What about blocks with different states

warm mason
# warm mason you will get an error

Technically you can do this by modifying JsonUI so that it supports rendering items via AuxId, but you can't get the exact ID of a block/item so you can't do this.

warm mason
chilly fractal
#

i have a question

#

if anyone has tested this case, please tell me so

#

anyway so if you register custom commands with synchronous functions as their handlers, but they require some asynchronous logic, and you have to wait for that logic before returning a CustomCommandResult (or undefined)

#

and you use a .then/.catch block to do this

#

does the API accept this or only strict synchronous results?

subtle cove
#

In my case, I tried to do awaition there, it's my 1st encounter where awaition cannot be done in there so gota use system.run

shut citrus
distant tulip
#

when the player swing his arm

lapis heart
woven loom
#

it triggers everytime the player's hand moves

halcyon phoenix
untold magnet
#

umm, is it possible to take an ingame screenshot using commanda or scripts?

untold magnet
#

ig

round bone
untold magnet
#

i see

chilly fractal
#

thanks for letting me know tho

prisma shard
#

@granite badger
@minecraft/server-gametest documentation link takes you to @minecraft/server-ui

shut citrus
#

what new feature is that?

prisma shard
#

wha-

somber sundial
granite badger
cyan basin
somber sundial
#

yeah would be nice, now they've made skin apis for bedrock i don't see why they couldn't do it at some point

#

i guess the fact they're not storing user-uploaded skins is a big reason as to why they probably wouldn't

#

half the time it'll just resolve to a default character

warped blaze
somber sundial
warped blaze
#

yeah but i mean with just the @minecraft/server module

somber sundial
#

cant really do much with it sadly if you cant show it in forms or set skins

north frigate
#

Imagine JavaScript without async or promises

round bone
rigid torrent
#

Is saving an entity's inventory possible with stable API?

wary edge
rigid torrent
#

But how can I make it modular kinda without making the size of the world go up crazy

cyan basin
#

Where do I get MinecraftEffectTypes from?

#

I see other people importing files like "./vanilla-data.js" and I heard there was a way of getting the vanilla data from the minecraft server but it's a pain to figure out unless I'm just not seeing it

#

I thought there was a package like "@minecraft/vanilla-data" or something

#

nevermind i guess it is a thing.. i just tried it in npm 🤷‍♂️

somber sundial
#

it's not a package that ships with the client, so you'll need to compile it into your source if you intend on using it

cyan basin
#

How would I compile it into it?

somber sundial
#

using some form of bundler is the easiest way

cyan basin
#

so i do actually have to make it into a script file?

#

i have typescript.. it's just weird that i can install it as a npm package but i have to bundle it?!

round bone
cyan basin
#

alr yeah, i just moved it into my project.. easier way i guess

round bone
alpine wigeon
#

is world.beforeEvents.chatSend.subscribe() still beta?

wary edge
#

Yes.

nova flame
#

theres no error and the commands are not showing up in chat

#

not useable either

#

it is imported to my main file too

#

it used to work

#

now i was coding other stuff and realised its broken now

unique acorn
north frigate
halcyon phoenix
warm mason
wintry bane
halcyon phoenix
warm mason
warm mason
wintry bane
#

player hunger component

halcyon phoenix
wintry bane
#

It's out of beta?

warm mason
warm mason
wintry bane
#

tf im so ootl

#

since when??

round bone
# wintry bane since when??

It's out of beta for a longer time, it's not that hard component to implement, also it does not really change through the time.

round bone
#

I thought it's been a long time.. uhhh.

distant tulip
#

yeah, first introduced in 1.21.90.26

round bone
distant tulip
#

and it got stable between tow releases

#

meanwhile blockSignComponent

#

1.19.20.20

lapis heart
warped blaze
#

uhm, does a custom slash command function count as a read-only mode?

#

i tried to use spawnSimulatedPlayer() inside it and got a privilege error

halcyon phoenix
runic maple
wintry bane
#

Is it using "subject": "target"?

runic maple
#

Basically if you remove (i forgot I'd check my PC later), the is it attack behaviour component of the entity with an event and add it later it looks for the last entity that hurt it

#

So I use like entity.hurtafter event,to check whether it was it's target that hurt it, and it's random depending on damage

wintry bane
#

What's the usecase for this?

#

Setting targets?

runic maple
wintry bane
#

huh

runic maple
# wintry bane Setting targets?

You can also use the reset_target in events property to remove the entities target and apply a damage of 0 from it's new target to it

wintry bane
#

I like the idea but I use entity.target for other things like monsters hurting you remotely.

prisma shard
nova flame
spice finch
#

is there any way to force a player to open an inventory from like an entity or something?

spice finch
#

ok thx

lavish surge
#

Is there any way to make a custom command capture the entire string, even with spaces, without needing to use quotes, like /tell <player> <message>?

wary edge
#

No.

runic maple
#

If I am setting the target by causing the damage without the target hurting the entity first I apply a knockback of 0 in all directions - it cancels the bounce that happens when an entity is hurt

nova flame
wary edge
shy leaf
#

oh wait

#

i was thinking of somethjng else nvm 😭

proper perch
#

Does anyone know if it’s possible to make it so when a player places any door in water it will not water log it like in Java and if possible to do it using stable scripts or changing the door behavior so it can’t be water logged

loud zenith
#

hey i got a quick question about custom command
can you do them in js are they only in ts ?
also is it available in 2.2.0-beta ?

prisma shard
lethal bramble
#

gugugua

shy leaf
lethal bramble
#

do u understand what ts is

shy leaf
lethal bramble
shy leaf
#

soz

loud zenith
lethal bramble
# loud zenith not really

It’s basically an extension of js that adds explicit types and enums interfaces and a lot of other stuff

#

it compiles to js

loud zenith
#

Oh okay

#

i understand thanks

shy leaf
#
function configFormOpener({ sourceEntity: player, sourceType }) {
  if (!(player instanceof Player && sourceType === CustomCommandSource.Entity)) {
    return {
      status: CustomCommandStatus.Failure,
      message: "Target must be player-type and command executor must be entity"
    };
  }
  system.run(() => configForm(player));
  return {
    status: CustomCommandStatus.Success
    //message: "Successfully opened Sweep 'N Slash configuration menu for " + player.name
  };
}

system.beforeEvents.startup.subscribe((init) => {
  const configMenuCommand = {
    name: configCommand,
    description: "sweepnslash.commanddescription",
    permissionLevel: 0,
    cheatsRequired: false
  };
  init.customCommandRegistry.registerCommand(configMenuCommand, configFormOpener);
});

function configForm(player) {
  //...
};
#

this is my take on custom commands

#

making the custom command to run codes directly rather than making it run a function kinda caused an issue where i couldnt reload to debug it

#

since registered stuff cant be reloaded mid game

#

so i just slapped functions here and there

prisma shard
shy leaf
#

how is the new swing event? its obviously more reliable than AC method, but how does it compare?

shy leaf
#

what about the delay?

thorn flicker
#

theres some issues with it though, such as, if you break a block, it'll trigger 20 times.

shy leaf
#

odd

thorn flicker
#

i cant report it: #1407392112588230676 message

#

maybe you can, if its not reported already.

floral timber
#

did u work it out?

distant tulip
thorn flicker
#

I mean in creative

distant tulip
#

same

thorn flicker
distant tulip
#

creative is the same as survival

thorn flicker
thorn flicker
distant tulip
#

the swing animation run in an interval

thorn flicker
#

that does not help

distant tulip
thorn flicker
#

I dont see why this would be intended.

distant tulip
#

cause the swing is running in a loop

thorn flicker
#

it spamming it 20 times when breaking a block is not a good thing.

gray tinsel
#

would anyone know how to detect if an itemstack is a block?

thorn flicker
#

import BlockTypes from server

gray tinsel
#

ah sweet ty

open urchin
#

you'll have to do some manually since not all of the IDs are the same
e.g. the item is minecraft:sugar_cane and the block is minecraft:reeds

thorn flicker
#
function isBlock(id) {
    const types = BlockTypes.getAll().map(type => type.id)

    if (types.includes(id)) {
        return true
    }
}
open urchin
gray tinsel
#

we love mojang :P

thorn flicker
thorn flicker
distant tulip
#

you can just try block.setType and see if it throw error

thorn flicker
warm mason
thorn flicker
thorn flicker
warm mason
#
function isBlock(id) {
    return BlockTypes.get(id) != undefined;
}
warm mason
warm mason
thorn flicker
warm mason
thorn flicker
distant tulip
thorn flicker
shy leaf
thorn flicker
woven loom
#

Does anyone have a fake spectator addon

#

Using camera api

dusky flicker
round bone
dusky flicker
round bone
distant tulip
#

what am i missing here

[Scripting][inform]-true std:mob_id
[Scripting][inform]-["mob_family"]

why is it showing in the log if the condition is true

#

...
nvm

shy leaf
#

LMAO

thorn flicker
shy leaf
#

didnt update preview yet

thorn flicker
distant tulip
#

"isMnoster"

#

i have the extension disabled

prisma shard
distant tulip
#

🙄

round bone
prisma shard
#

ok bro is fr obsessed with webstorm

subtle cove
subtle cove
distant tulip
round bone
round bone
distant tulip
prisma shard
round bone
distant tulip
round bone
round bone
distant tulip
#

i would use sublime text if i could

prisma shard
prisma shard
distant tulip
prisma shard
distant tulip
subtle cove
#

mine's just 1.8G

distant tulip
#

i usually work fine with my hardware.
but sometimes some projects require a lot of performance like my current project
opening the game + vs code + blockbench with a 1000 cube model and 1mb animation file

simple zodiac
#

Jedbrains IDE's are peak but they somehow manage to hog up more resources then vscode. It is however faster when it comes to like auto completion suggestions and intellisense

round bone
round bone
amber nest
#

how do i fix this

unique acorn
#

@minecraft/vanilla-data isn't an actual module included in the game, you have to include it yourself

amber nest
#

i mean i did but if i dont add it to the manifest it tells me to do it

unique acorn
unique acorn
# amber nest

it says "if this is a native module, add it to manifest.json".
and if you haven't guessed it, vanilla-data isn't a native module!!!

amber nest
#

oh right i didnt read that part

unique acorn
empty quail
#

How can I tag a player when they spawn an entity with an entity placer (spawn egg, armor stand, end crystal, custom placers, etc)?

chrome flint
#

does anyone have a latest typeId.js from herobrine chest UI? the one on his github seems to be outdated

slender bolt
#

how to keep entityDieAfterEvent from throwing errors when using command /kill?

hidden perch
#

does anyone know how do i give player spawn_egg 1 51 by do new ItemStack thrn add to player container?

#

new ItemStack(spawn_egg, 1)

shy leaf
shy leaf
hidden perch
#

okay i’ll try

shy leaf
#

also, container has a method for adding item

#

iirc

hidden perch
#

ik but im curious about itemid

#

cuz i do “minecraft:spawn_egg 1 51” so it throw me an error

#

but thanks for advice 🙏🏻

shy leaf
slender bolt
shy leaf
#

also what error is it throwing?

shy leaf
#

you can do a workaround by using runCommand to give the item if you want it to drop from full inventory

hidden perch
#

i’m helping that guy who trying to make admin panel

#

“He knows 🤓”

slender bolt
# shy leaf can you post the code here?

Cannot read 'typeId'

                    const deadEntity = event.deadEntity;
                    const damager = event.damageSource.damagingEntity;
                    const damagingProjectile = event.damageSource.damagingProjectile;
                    const loot = deadEntity.typeId === "gg:scar_mag_loot" || deadEntity.typeId === "gg:scar_mag_empty_loot" || deadEntity.typeId === "gg:deagle_mag_loot" || deadEntity.typeId === "gg:deagle_mag_empty_loot";

                    
                    if (deadEntity.typeId === "minecraft:player" && damager.typeId === "minecraft:player" && gotHit.hasTag("shot") && !loot ) {
                        player.addTag("dead");    
                        return;                    
                    } else if (!loot && damager.typeId === "minecraft:player") {
                        player.setProperty("gg:is_hitting", 2);
                        player.runCommand(`/playsound random.orb @p ~ ~ ~ 1 2`);
                        return;
                    }
                    
                });```
shy leaf
#

of undefined?

slender bolt
#

this line throws the error else if (!loot && damager.typeId === "minecraft:player")

shy leaf
#

if the entity dies without a damaging entity, it will be undefined

#

hence the error

slender bolt
shy leaf
#

just add a check if the damager is valid

slender bolt
#

how?

shy leaf
#
if (!damager) return;
#

or something like that

slender bolt
#

It works thank you

prisma shard
#

@granite badger jayly bot not working again....... :<
the /docs info
.

#

is getBiome and getLightLevel still preview ?

round bone
prisma shard
#

the bot is down

round bone
prisma shard
#

wait whar

#

1.21.102 released?

granite badger
lapis heart
distant tulip
round bone
# lapis heart Tip: In any event, use `?.` after each property of the event to avoid errors. L...
import { Entity } from "@minecraft/server"

class EntityLootable {
    private constructor() {}
    private static readonly LOOTABLE_ENTITIES: Readonly<Set<string>> = new Set<string>([
        "gg:scar_mag_loot",
        "gg:scar_mag_empty_loot",
        "gg:deagle_mag_loot",
        "gg:deagle_mag_empty_loot",
    ])

    public static isLootable(entity: string | Entity): boolean {
        return this.LOOTABLE_ENTITIES.has(entity instanceof Entity ? entity.typeId : entity)
    }
}

export { EntityLootable }
lapis heart
distant tulip
#

It is not a good practice, use it when it matters, and when it is better than the alternatives.
An early return well work better in such a case

shy leaf
#

yeah, cases like damagingEntity not existing and throwing error can be resolved by early return

lapis heart
lethal bramble
#

how would i get the block to an arbitrary direction of another block, without using a large if-else structure or switch statement? for example, i want to know if there is a function thet can do something like this:

block::getBlockFromDirection(Direction): Block
lethal bramble
#

there doesnt seem to be a method for using a direction

round bone
#

You can use a hashmap to get a vector from a directory, then apply it to a method.

round bone
#

Are you using JS or TS? Just asking if you need any code example, so I can write a simple one for you.

round bone
# lethal bramble ts

Nice, I like using TS over JS.

import { Direction, type Vector3, Block } from "@minecraft/server"

const directoryOffset: Readonly<Map<Direction, Vector3>> = new Map<Direction, Vector3>([
    [Direction.Down, { x: 0, y: -1, z: 0 }],
    [Direction.East, { x: 1, y: 0, z: 0 }],
    [Direction.North, { x: 0, y: 0, z: 1 }],
    [Direction.South, { x: 0, y: 0, z: -1 }],
    [Direction.Up, { x: 0, y: 1, z: 0 }],
    [Direction.West, { x: -1, y: 0, z: 0 }],
])

const newBlock: Block | undefined = someOtherBlock.offset(directoryOffset.get(yourDirection)!)
lethal bramble
round bone
untold magnet
#

umm, is it possible to extract a number from a string?
the text is from a custom item tag, it will look something like this customtag:4000 so i just want to see if it is possible to get that exact number or not.

woven loom
#

+'wave4000'.match(/\d+/)[0]

untold magnet
# dusky flicker text.split(":")[1]

umm, how can i use the tag string?
like i need to detect if the tag starts with customtag: for example and extract the number that will be after the tag.

warm mason
untold magnet
untold magnet
warm mason
dusky flicker
untold magnet
sly valve
untold magnet
#

oh my bad

shy leaf
#

@thorn flicker apparently my preview is refusing to install so i might have to try it again after i get back to college dorm

shy leaf
#

thinking about it...

#

i wonder if the event triggering 20 times is the reason why v.attack_time has a delay

#

wait

#

i dont know if the event triggers 20 times at once

#

or on every tick

thorn flicker
#

it only triggers 20 times when you break a block.

untold magnet
#

umm, player?.setDynamicProperty('xHydration:hydrationValue', hydValue + eHydValue); will set the hydrationValue to 206 for some reason, like it just looks like this: hydValueeHydValue

shy leaf
untold magnet
#

hydValue = 20
eHydValue = 6
instead of 26, it returns 206

shy leaf
#

thats probably because the number is actually string and not number

#

string + string results in stringstring

untold magnet
#

it is a string, then how can i turn it from sting to number?

shy leaf
#

maybe try converting it to number first

thorn flicker
#

Number(string)

shy leaf
#

yeah, theres a native class in javascript

#

like how it has Math and Date

thorn flicker
#

why is it a string though in the first place

shy leaf
#

theyre extracting number from tag

#

iirc

thorn flicker
#

oh, I see.

untold magnet
shy leaf
thorn flicker
#

why arent they using custom components

#

with params

shy leaf
#

wow

#

thats super odd

#

i cant even guess why that happens

#

😭

thorn flicker
#

idc why it happens

#

I just want it fixed lol

shy leaf
#

same

#

it sounds like an annoying issue

thorn flicker
#

only issue with it, far as I know

#

other than that HELL YEAH, SWING AFTER EVENT WOOOO

#

FINALLY

#

and there's no delay, I think

shy leaf
#

my addon is one step closer to be player.json free

thorn flicker
#

why do you need it for?

shy leaf
#

for checking player attacking in general

#

and uh

#

for custom damage mechanics

thorn flicker
#

long range weapon swing?

shy leaf
#

nope

thorn flicker
shy leaf
#

i should prob explain what i did

#

gimme a second

thorn flicker
#

alr

shy leaf
#

right so you know that entities have minecraft:attack component, right?

thorn flicker
#

oh this?

shy leaf
#

oh

#

you know it

#

lmao

#

yeah

thorn flicker
#

no

#

I just saw it on your profile

shy leaf
#

yeag ill still explain it

thorn flicker
#

I dont download addons

#

so yeah

thorn flicker
#

I dont know whats popular if it is

thorn flicker
shy leaf
#

that entirely disables damaging entities

thorn flicker
#

okay so, no damage

shy leaf
#

yeah, no damage

#

but entityHitEntity still fires

#

and i made use of that

thorn flicker
#

and you use applyDamage?

shy leaf
#

yep

#

its not perfect tho, cuz that whole thing is probably a bug

thorn flicker
#

how does this support custom items?

#

weapons, I mean

shy leaf
#

it doesnt clueless

#

but

thorn flicker
#

you should add a config

shy leaf
#

the stats are data driven

thorn flicker
#

that allows people to setup damage models

shy leaf
#

yeah thats what i added

thorn flicker
#

you said it doesnt support it

#

oh you mean off the bat

shy leaf
#

i mean

#

yeah

thorn flicker
#

my bad

shy leaf
#

its ok