#Script API General

1 messages Ā· Page 12 of 1

shy leaf
#

instead of runinterval and clearrun...

quasi meteor
#

Hey folk! Did minecraft worlds are the variables we set with the js kept in the world files or are all variables reset at each world entry?

cold grove
quasi meteor
#

Ohhh, thank you...

woven loom
#

anyone got a data structure with everything at O(1)

sudden nest
woven loom
#

if you look at the qjs api, it tells us to create a qjs context which runs our code, so what reload in game should be doing is that to create new context means everything ROM is cleared

quasi meteor
#

thanks folk

sudden nest
#

it's O(log n) for getting the nearest vector on the container based on the passed vector

woven loom
#

interesting

#

btw I had an idea of building global que which works across packs

#

using dps

#

still cant figure out how to make it work

#

need ideas

prisma shard
#

yeah i'm still alive, i had to take a little break from life, because my grandfather died....

#

so i was inactive for a month

sudden nest
woven loom
distant tulip
woven loom
#

I mean funcs

quasi meteor
#

Can we see total ram usage per world for scripting in bedrock?

distant tulip
# woven loom I mean funcs

hmm
you can make it depend on a scoreboard
before the function run it check a score if the queue is empty

valid ice
#

script debugger kinda shows that but not really

woven loom
woven loom
#

can someone give me js files of mojang modules

woven loom
#

no the other ones

prisma shard
#

can anyone gimme some iddeas

#

i am making a script for custom food

#

it gives you effect after eating

#

the script will be helpful for making custom food item

#

like

const customFood = {
typeId: "minecraft:steak",
applyEffect: "resistance",
runCommandOnConsume: "/give @s dirt",

// Give me more ideas i can add

}
#

@valid ice

valid ice
prisma shard
#

i can add ther

valid ice
#
  1. A food that, when eaten, stops the player from pinging me for random stuff
prisma shard
#

:(((

#

ok sorry for ping

#

ohh teleportOnConsume

#

but surely there might be more ideas

distant tulip
remote oyster
#

Lol

prisma shard
#

how you get my user ID

#

wtf

woven loom
#

ppl love hero so much

#

everyone keeps on pinging him

distant tulip
valid ice
woven loom
umbral scarab
prisma shard
#

how can i detect if some code throws error

woven loom
distant tulip
prisma shard
prisma shard
woven loom
#

try {} catch (err) {}

cinder shadow
#

@valid ice helo I ned your help

distant tulip
#

try {
//code
} catch(err) {
//if error
}

prisma shard
prisma shard
valid ice
#

I don't mind pings

But at the same time keep them slightly relevant

prisma shard
distant tulip
#

you don't need the if statement

prisma shard
prisma shard
distant tulip
#

but err do have some infos on the error if you want to use it

woven loom
#

I add prototype to function as I hate so many tries

distant tulip
#

i just avoid them if i can

prisma shard
#

how to detect if something is number?

#
if (!duration typeof number) return```
#

like that

#

?

woven loom
#

if ( ! isNaN( val ) )

prisma shard
#

dont understand

prisma shard
#
if (!duration typeof number) return```
woven loom
#

I use if (+val)

distant tulip
#

is the number a string? "1"

prisma shard
distant tulip
woven loom
#

nothing beats (+val)

#

if not zero

valid ice
#

Consider the following:
if (duration != 0 && duration != 0.1 && duration !== 0.021 && ...)

#

Yes, my addon is 54 gigabytes, why do you ask?

distant tulip
woven loom
#

hero have you ever created a keyframe system? i am trying to find to structure numbers in way where with any x i can find the nearest one

valid ice
#

šŸ¤”

woven loom
#

binary search would be first choice for this but I feel if we structure them differently to even improve the speed

distant tulip
#

how are the key frames stored

#

discord api should add that event tbh
lol

woven loom
#

in array rn

#

@distant tulip

distant tulip
woven loom
#

ye

distant tulip
#

sorry something came out
brb ...

woven loom
#

np

distant tulip
# woven loom np

you can start from the middle
check the left and right
and go to the closest side
start from the middle of it and redo the steps

#

re do that until you reach a side with length of 1

#

let me see if i can code that

misty pivot
#

is it possible to change the selected slot?

distant tulip
#

no

misty pivot
#

alright thanks

distant tulip
#

@misty pivot try
i was thinking selectedSlotIndex is read only
but it is not marked as one
so maybe
(sorry for the hasty response)

misty pivot
#

ah, right, lemme test it right now

distant tulip
#

@woven loom

//keyframes array structure

const keyFrames = [
  [10, "value"],
  [12, "value"],
  [14, "value"],
  [19, "value"],
  [22, "value"],
  [25, "value"],
  [37, "value"],
  [39, "value"],
  [49, "value"],
  [50, "value"],
];

function findNearestKeyframe(keyFrames, x) {
  let left=0;
  let right=keyFrames.length-1;

  while (left <= right) {
    const mid=Math.floor((left+right)/2);
    const midX=keyFrames[mid][0];

    if(midX===x) return keyFrames[mid];
       else if(midX<x) left=mid+1;
         else right=mid-1;
  }

  const leftFrame=keyFrames[Math.max(0,left-1)];
  const rightFrame=keyFrames[Math.min(keyFrames.length-1,left)];
  return x-leftFrame[0]<=rightFrame[0]-x?leftFrame:rightFrame;
}

//usage:
console.log(findNearestKeyframe(keyFrames, 15));
woven loom
#

yea that's binary

dense wraith
#

One message removed from a suspended account.

remote oyster
dense wraith
#

One message removed from a suspended account.

north rapids
#

How do I spawn the particle that appears when removing wax and oxidation from the copper block?

#

What is the function and ID of the particle?

distant tulip
# woven loom yea that's binary

probably less efficient
but you can push the test value with a fake frame to the array
sort it find it index and get the closest neighbor

const keyFrames = [
    [10, "value"],
    [12, "value"],
    [14, "value"],
    [19, "value"],
    [22, "value"],
    [25, "value"],
    [37, "value"],
    [39, "value"],
    [49, "value"],
    [50, "value"],
  ];

  
  const testArray = [...keyFrames,[15, undefined]].sort((a, b) => a[0] - b[0]);
  const frame = testArray.find((frame) => frame[0] == 15 && frame[1] == undefined);
  const index = testArray.indexOf(frame);

  const closest = frame[0] - testArray[index - 1][0] > testArray[index + 1][0] - frame[0] ? testArray[index + 1] : testArray[index - 1];

  console.log(closest);
  
#

yeah it is less efficient
complexity of O(n log n)
binary search only have complexity of O(log n)

#

Binary Search seem the best option
test of 1000 run

oak lynx
#

probably wrong channel but any way to get rid of the vanilla stuff below item name

valid ice
#

nope

oak lynx
#

Equipment is fine but +6 attack damage is annoying

#

i guess i can just copy all vanilla pickaxes and make my own items

valid ice
#

Many have asked, nobody has succeeded :(

oak lynx
#

just a matter of finding the mining stats

obsidian coyote
#

@valid ice hi

valid ice
#

allo

oak lynx
sharp elbow
#

Could look at the list of destroy times for blocks on the Minecraft wiki entry for Pickaxes and calculate their rough speed increase.

#

Although it's going to wildly differ depending on the block and whether that tool is eligible for harvesting the block or not.

#

It seems that on average, the following tools reduce destroy time by the following:

  • Wooden pickaxes by x2;
  • Stone pickaxes by x4;
  • Iron pickaxes by x6;
  • Diamond pickaxes by x8;
  • Netherite pickaxes by x9;
  • Gold pickaxes by x12.
    And mining speed is increased by an additional x3.33 if the tool can harvest the block.
#

So for example, Chain: With a destroy time of 25 seconds, a wooden pickaxe can harvest it in 3.75 seconds: 25 / (2 * 10/3)
And for another, Raw Iron: Also with a destroy time of 25 seconds, a wooden pickaxe can break it in 12.5 seconds: 25 / (2 * 1)

#

Is this useful @oak lynx

oak lynx
#

thanks for helping

distant tulip
thorn ocean
#

Does anyone wish there was a scriptEvent that happens when the player crafts something?

hybrid bobcat
#

same problem here, did you fix it?

thorn flicker
#

im using randomTick instead for now

hybrid bobcat
chrome flint
#

where can i find aux id list again

#

i forgot where is it

chrome flint
rigid torrent
#

Can you give lore to armor items?

#

Without it getting removed after unequipping

neat hound
amber granite
#

.

#

.

chrome flint
chrome flint
chrome flint
rigid torrent
#

Nevermind yeah, I forgot something

amber granite
#

.

#

.

subtle cove
#

慤

shy leaf
chrome flint
#

is this typo error or are these really the same ID values?

valid ice
#

Both are incorrect lol

misty pivot
valid ice
#

stained clay is 159, armadillo spawn is 720

chrome flint
#

how do get your IDs btw, do you test it one by one?

valid ice
#

I do

#

Names are ultimately a guess in the end. I try to map the ones I can based on /give or /setblock stuff, but some are unknown, so

neat hound
feral minnow
#

does someone have the order of clicks in script

#

beforeItemUse -> afterItemUse ->

#

like that

feral minnow
#

execution order?

#

ohh thanks

feral minnow
# wary edge https://github.com/Mojang/bedrock-samples/blob/main/metadata/engine_modules/engi...

found this

Events.* execution order
Hitting an entity
1 entityHit

Breaking a block
1 blockBreak
2 entityHit

Placing / pushing a block
1 itemStartUseOn
2 beforeItemUseOn
3 itemUseOn
4 blockPlace / buttonPush
5 itemStopUseOn

Hitting a block
1 beforeItemUseOn
2 itemUseOn

Using an item
1 beforeItemUse
2 itemUse

Using an item projectile
1 beforeItemUse
2 itemUse
3 entityCreate

Using an item charge start
1 beforeItemUse
2 itemUse
3 itemStartCharge

Using an item charge release
1 itemReleaseCharge
2 entityCreate
3 itemStopCharge

Using an item charged
1 itemCompleteCharge
2 itemStopCharge
shy leaf
#

im kinda wondering if i can heal a mob before the mob dies to a hit

wary edge
#

No

valid ice
#

Legit the only thing that fires before damage is a damage sensor lol

shy leaf
#

beforeEvents for entityHurt and entityHitEntity when

valid ice
#

Big Damage propaganda

modest oasis
#

Just asking, is there a way to whitelist a player using discord or a script?

shy leaf
#

using script, sorta

modest oasis
shy leaf
#

no

modest oasis
#

How?

shy leaf
#

you know how to script?

modest oasis
#

Yes kinda, i just learned few weeks ago

shy leaf
#

then try this

#

upon player join, check if the joining player's id (not name) matches with the whitelisted ids you set in script

#

if not, kick

#

keypoint here is 'id'

grave nebula
#

is there a way to stop the player from moving?

#

without constantly tping

#

like as a before or after event

wary edge
#

Disable their inputperms

grave nebula
#

what would be the world event

wary edge
#

No its a gamerule

grave nebula
#

ah ok

#

thanks

#

whats the gamerule name?

#

nvm

#

its a command

wary edge
#

OOps, my bad

grave nebula
#

nah ur good

viral plaza
#

world.beforeEvents.playerPlaceBlock.subscribe(evd => {
  const block = evd.block
  const player = evd.player
  const dimension = world.getDimension('overworld')
  const blockLocation = { x: block.x, y: block.y, z: block.z }
  const b = dimension.getBlock(blockLocation);
  const data = JSON.stringify(b)
  world.sendMessage(`${data} ${b.nameTag}`)
})

Anyone know why this just gets the block location? How can I get other things like the blocks name and stuff

wary edge
#

Wha...why do you need to use getBlock?

viral plaza
#

Because evd.block is just the location

wary edge
#

But...the event data already gives you the block broken

viral plaza
#

I’m trying to get the blocks name but all I get is the coordinates of it

#

And I’m trying to get the type id

shy leaf
viral plaza
#

It’s

#

Yea*

shy leaf
#

ill just make you one

viral plaza
#

Oh wait

#

Nvm

#

Idk why I might have been on the wrong event

shy leaf
#

its still on the wrong format

#

wait nvm

#

i just saw BlockEvent has smth

viral plaza
#

Ok

#

So

#

const block = evd.permutationBeingPlaced

shy leaf
#
world.afterEvents.playerPlaceBlock.subscribe(({player, block}) => {
  const loc = block.location;
  player.sendMessage(`${block.typeId} / ${loc.x}, ${loc.y}, ${loc.z}`);
});```
#

@viral plaza

prisma shard
viral plaza
#

I tried to do block.getItemStack().nameTag

wary edge
#

You cant get the name, only the id

shy leaf
#

you can make an array of block identifiers & block names (item names)

viral plaza
#

That sucks

shy leaf
#

and make the script to check if both matches

viral plaza
#

I mean it’s not a downside it’s just I can’t use the same block with different levels

#

I mean I can set lore right?

prisma shard
#

itemStack.setLore()

#

oh block?

#

get the block as a itemStack somehow

wary edge
shy leaf
#

can i set player's saturation (not hunger) in API

#

or does saturation effect do the job

thorn flicker
thorn flicker
shy leaf
#

i was asking cuz i kinda feel like saturation effect doesnt really fill saturation

#

only hunger

thorn flicker
#

ah

#

right

#

so you have no options for now

shy leaf
#

but does saturation effect do fill saturation

#

thats what i need

#

meh only one way to find out

neat hound
viral plaza
#

I don’t see anything listed about block data on the docs with before event playerBreakBlock

#

Can you not get the block?

wary edge
crude ferry
#

Wtf?

#

What's wrong with you huh? šŸ˜‚

remote oyster
feral minnow
crude ferry
remote oyster
prisma shard
# crude ferry What's wrong with you huh? šŸ˜‚

you might not know, but there is a fact.
in india, most of the people who make"addons" or mods are kids. mostly under 11-13 yr olds, they don't actually make it, but steal them and claim it as your own, which, makes me to be so furious at them. they beg/ask that how to make smth, or they just make hillariously bad addons in addon maker. i know the accent of them , i did expect to beg him ,and you see in that conversation, i litterly said that "are you from india" at the start of the conversattion , bcoz i know the behvaiour of them. they even DM me and disturb me for no reason and spam,

prisma shard
#

@valid ice how to send a error ?

crude ferry
prisma shard
#

like

if (typeof duration !== "number") {

// what sould i use  
console.error('duration must be a number');

//which one i should use
throw new Error("duration must be a nuumber")

}```
valid ice
#

idk

#

just uhhhhhhhhhhhhhhhhhhhhh don't make problems in the first place and you don't need errors yessir

sharp elbow
#

throw, since that interfaces with the try..catch syntax and can be caught

#

Erroring is not entirely a bad thing. But you do want robust errors

prisma shard
#

@woven loom see this screenshot

woven loom
#

just do throw e

prisma shard
crude ferry
simple zodiac
#

try {} catch (e) { throw new Error(e)} 🤭

sharp elbow
#

Is your sample here only for demonstration? Or is customFood going to be something else

crude ferry
simple zodiac
sharp elbow
#

You could design it so that customFood's effectDuration can only be a number when setting it. Then there would never be any need for error checking/throwing

prisma shard
cold grove
#

LOL

crude ferry
#

šŸ˜‚

ocean escarp
#

How easy would stamina meter be to create with scripts?

prisma shard
cold grove
sharp elbow
#

Ah, so these implementation details will be exposed. It is not abstracted away in any form

prisma shard
ocean escarp
sharp elbow
#

In other words—people will be setting values for customFood directly, and you are not providing other means to set values for it

ocean escarp
#

Actions that would consume hunger also consume stamina, and stamina only restores if not sprinting or attacking/mining etc.

sharp elbow
#

I'll present an example of what I mean by "abstracting" details

cold grove
#

But it can be just an slowness effect or edit player.json

ocean escarp
#

I have a strange implementation I wanna try

#

All actions are fine until you completely run out of stamina at which point you become ā€œfatiguedā€ until stamina is full again

#

I want the player to pace themselves

#

Not a hard implemented combat cooldown like Java but some mild guidelines

sharp elbow
#

Something like this, where only you control how the property is set. People cannot use myFood.effectDuration = 5 because effectDuration is private.

class CustomFood {
  #effectDuration
  constructor(duration) {
    this.setDuration(duration);
  }
  /** Sets the food duration.
   * @param {number} duration Duration in seconds
   */
  setDuration(duration) {
    if(typeof duration !== "number") {
      throw Error("Type was not number");
    }
    this.#effectDuration = duration;
  }
}

const myFood = new CustomFood(3); // Internally, #effectDuration = 3
myFood.setDuration("3"); // "Error: Type was not number"
#

You could probably make something with get and set but I find that syntax kinda ugly

prisma shard
#

lalalalalal

#

im making things harder

#

i should take it easy

#

why people would be that dumb to put "3" instead of 3

sharp elbow
#

It could happen on accident. For example: Reading input from chat messages, /scriptevent myevent:hi 3 the "3" is a string. It would need explicitly converted to a number, either by +"3" or Number("3")

prisma shard
#

PROBLEM SOLVED

sharp elbow
#

I'd at least make those JSDoc comments, so Intellisense will suggest those comments when looked at

#
const customFood = {
  /** Must be a string, or it will throw error */
  typeId: "",
  /** Must be a number, or it will throw error */
  effectDuration: "",
  // etc.
}
prisma shard
#

WAit wht

prisma shard
sharp elbow
#

number is a variable name. "number" is a string

#

For context: "number" in that line can be anything and it'd have the same effect: typeof 33 === foobar

prisma shard
#

oh ops

#

i was confused ;llol

#

yeah yeah

#

can i rem0ove unnecerary typings?

sharp elbow
#

Unnecessary how?

prisma shard
#

like i want to remove the SVGAnimatedNumberList

sharp elbow
#

Good question. I don't know

granite badger
#

Use typescript, setting tsconfig

simple zodiac
#

Create a tsconfig

#

But if you exclude DOM you also exclude console i think

prisma shard
#

i dont know ts

#

:((

simple zodiac
#

You dont need to

prisma shard
#

like nothing abt ti\

sharp elbow
#

Does VSCode work with a TSconfig out of the box?

prisma shard
#

then what do i need to wirte in tsconfig?

simple zodiac
sharp elbow
#

tsconfig is like a JSON file. Not too much to it, there should be a template somewhere

granite badger
woven loom
#

can we use server 2.0.0 alpha

prisma shard
subtle cove
iron jewel
#

why does it say @@ in the reply

#

but single in the message

#

huh

neat hound
#

That is a discord question, not a scripting question. Prob has to do with him already having the prefix of @ and their UI dealing with it.

woven loom
prisma shard
#

and another @ shows bcoz your pinging him

iron jewel
neat hound
thorn flicker
sudden nest
#

bao_foxxo_dead i am rewritting a Vector class utility wrapper i found in the script resources ā˜ ļø

#

Idk but is this inefficient?

#

Snippet

class SomeVector3Utility {
add(other: SomeVector3Utility | Vector3): Vec3 {
  return new SomeVector3Utility(this.x + other.x, this.y + other.y, this.z + other.z);
}
}
#

using this:
new SomeVector3Utility(player.location).add({x: 0, y: -10, z: 0})\

this creates two vector object instead of 1

#

imagine using this with 1000 loops or idk big loops

#

1000 * 2 = objects

#

and imagine the other methods from this which creates other new Vector instances which is unnecessary

#

oh, that's why xp

#

i wanna pass away ā˜ ļø, creating static methods and class methods

prisma shard
#
class Vec3 {
    constructor (x, y, z) {
        this.x = x;
        this.y = y;
        this.z = z;
    };
    static add(vecA, vecB) {
        return Vec3(vecA.x + vecB.x, vecA.y + vecB.y, vecA.z + vecB.z);
    }
};


const vectorA = player.location;
const vectorB = new Vec3(0, -10, 0);

Vec3.add(vectorA, vectorB)
#

@sudden nest

#

dont complicate things

sudden nest
#

yeah, it should be like that, but this one is 1000+ lines of code

prisma shard
#

turn interface into that class, like don't do {x: 0, y: -10, z: 0} , instead do new Vec3(0, -10, 0);

#

then it willl wokr

#

as i did

sudden nest
#

i meant this Vector class: #1235161895879839785 message

#

i saw it, and it was great and all, until i saw the add method

prisma shard
#

it great

sudden nest
#

the other unique methods are cool

prisma shard
sudden nest
#

like CatmullRom and stuffs

prisma shard
sudden nest
crude ferry
prisma shard
#

what?

crude ferry
#

Inefficient hmm šŸ¤”

sudden nest
prisma shard
#

after that return?

#

........... THATS HOW IT WORK

#

bruh

#

are you crazy

sudden nest
#

i mean like this vector calculations and stuffs

prisma shard
#

or are you high

sudden nest
prisma shard
#

thats how it work

sudden nest
#

oh bao_icon_entities bao_doggo_derp

neat hound
#

try ```js

  • @param { import("@minecraft/server").Vector3 } other``` to enforce proper usage
sudden nest
#

I transferred it into one typescript file instead of two javascript (vec3.js) with types (vec3.d.ts)

prisma shard
#

@valid ice how to remove a item in 1.4.0-beta api ?

distant tulip
fickle dagger
#

also if you want to ask someone, make sure you're using the proper language and manners, you can't just say "Hey user, how do this" unless they're okay with that

wary edge
#

Also, if youre gonna use an old version its best to read the docs

prisma shard
#

okaokay

#

i will not ping

#

how can i remove an item from inventory? (1.4.0-beta)

woven loom
#

1.4 beta ?

prisma shard
#

yes

distant tulip
prisma shard
#

Removing the specefic item from slot

distant tulip
#

container.setItem(slot, undefined or null)

#

-# or is not part of the code...

prisma shard
#

why there is not a removeItem method

prisma shard
#

would that work?

distant tulip
distant tulip
prisma shard
#

.....

#

In playerBreakBlock

#

there is itemStackAfterBreak

#
container.setItem(itemStackAfterBreak, undefined)```
#

would that work

#

but that slot want number

distant tulip
#

player.selectedSlotIndex is a number

celest fable
#

i feels like im using "as type" too much on my script especially at the formValues, is that normal?

let commandAmount = res.formValues[1] as number //formValues[1] is slider
misty pivot
#

how would i get all objects that start with "skill" inside an array?

sudden nest
#

But when it autocompletes i just ignore it

distant tulip
misty pivot
#

i forgor filter exist

umbral scarab
#

could someone give me a function that moves the armour from the player who activates the function to the nearest entity?

hazy nebula
#

Scripting][error]-Unhandled promise rejection: TypeError: Incorrect number of arguments to function. Expected 0-1, received 3 what is this error?

fiery solar
prisma shard
#

........

#

Its not related to scripting!

#

thats a JSON problem

umbral scarab
#

oh yeh mbmb

prisma shard
umbral scarab
#

I thought I was already in that channel from when I last left off lmao

prisma shard
#

i dont have the javascript OR operator, in my keyboard :(((

remote oyster
#

Now you can copy and paste it lol.

prisma shard
#

guh

#

ok

shy leaf
neat hound
#

Find the alt-code for it, so you can do it that way when needed

valid ice
honest spear
hazy nebula
# prisma shard show code
function giveItem(player) { 
        const {
            container
        } = player.getComponent("inventory");
        if (player.hasTag('PlayNodebuff')) {
    for(let i = 9; i < 36; i++) {
        container.getSlot(i).setItem('minecraft:splash_pointion', 64, 22)
    }
    for(let i = 3; i < 7; i++) {
        container.getSlot(i).setItem('minecraft:splash_pointion', 64, 22)
    }
    for(let i = 6; i < 9; i++) {
        container.getSlot(i).setItem('minecraft:splash_pointion', 64, 22)
    }
    container.getSlot(0).setItem('minercaft:diamond_sword')
    container.getSlot(1).setItem('minercaft:bow')
    container.getSlot(0).setItem('minercaft:fishing_rod')
    container.getSlot(9).setItem('minercaft:cooked_beef', 64)
    container.getSlot(8).setItem('minercaft:arrow', 64)
}
    if (player.hasTag('PlayCombo')) {}
}```
honest spear
#

you should upgrade to SwiftKey

shy leaf
#

i can add arrows

#

brb

honest spear
#

up and down?

shy leaf
#

up and down

#

left and right

honest spear
#

šŸ‘

shy leaf
#

its crazy how this is basically a built in feature

#

the devs went crazy with it

#

well not really built in but its semi official atp

honest spear
#

real

#

its really useful in mc tho

shy leaf
#

oh i can just sweep my keyboard for that

#

the down 'arrow' doesnt work though for some reason

sturdy ermine
#

real ik

#

it the same sound too

#

but there was a bunch of random shit in with it for like 2 diffrent addons

meager pulsar
#

Has the 1.14 version of the server API came out of betas?

quasi meteor
#

Hey folk! does player.id changes every world join?;
is it unique like UUID,

umbral dune
#

How do I install modules other than "@minecraft/..."?

#

And if I want to install an NPM module, what do I do?

granite badger
#

Bundling (works on modules that doesn't require nodejs or dom apis only)

viral plaza
#

system.runInterval(() => {
  world.getPlayers().forEach(player => {
    const playerInventory = player.getComponent("minecraft:inventory").container;
    for (let i = 0; i < playerInventory.size; i++) {
      const itemStack = playerInventory.getItem(i);
      if (itemStack && genMap[itemStack.typeId]) {
        const genMapData = genMap[itemStack.typeId]
        itemStack.nameTag = `§e§l${genMapData.clean}`
        world.sendMessage(`${genMapData.clean}`)
      }
    }
  });
}, 200);

How can i change the names of the items in peoples inventory’s? It works just the item doesn’t get renamed.

wary edge
viral plaza
#

Ok thank you

next sedge
#

why is it every time i come back to use my old code that none of it works and loads has changed

sturdy ermine
#

Freaky

#

I gotta change one thing and then i'm done so idk

next sedge
#

but even so i come back to work on some world every like few months and its all broken

valid ice
#

The perils of using beta APIs shrug

next sedge
#

fr

#

did ///text/// change or something anymore cuz im getting a lot of errors for it

valid ice
#

A comment?

next sedge
#

yeah

#

either that or im just reading it wrong

sharp elbow
#

Can you share a more specific example?

next sedge
#

think i fixed it

valid ice
#

Comments should never break, ever

shy leaf
#

unless you commented on extra lines

#

but yeah

#

no reason for those to break

viral plaza
#

How do I test that it’s the players first time joining the game, and if they leave and join it’ll run again, cause mine runs when someone dies

shy leaf
#

instead of playerSpawn

viral plaza
#

Alr thanks

valid ice
#

playerJoin only has player ID & name, not the actual player object

#

use playerSpawn but filter for event.initialSpawn- which is true when the player joins the world, and false when the player respawns after dying.

viral plaza
#

That’s what I was looking for

#

I have initial spawn but I didn’t know how to use it

valid ice
#

I just have if (!data.initialSpawn) return; at the top of my playerSpawn event

shy leaf
#

doesnt initialSpawn reset if the world restarts

#

not reload

valid ice
#

no?

shy leaf
#

wtf

#

what is this rng

valid ice
#

whar

shy leaf
#

i think there was that one time

#

where initialSpawn didnt work for me

valid ice
#

odd

#

It's an event parameter, it's independent of world state

shy leaf
#

yeah its weird

random flint
#

tag them

#

if they don't have the tag, then they truly joined for the first time.

shy leaf
#

yeah thats what i did

random flint
#

u can also use dynamicProperty

shy leaf
#

oh wait yeah i used that

#

not a tag

viral plaza
fallow rivet
#
world.afterEvents.worldInitialize.subscribe((event) => {
  const property = new DynamicPropertiesDefinition();

  property.defineNumber("test", 1);
  event.propertyRegistry.registerWorldDynamicProperties(property);
});

Not work, why?

random flint
fallow rivet
random flint
random flint
#

skip the "defining" part

hazy nebula
#
function giveItem(player) { 
        const {
            container
        } = player.getComponent("inventory");
        if (player.hasTag('PlayNodebuff')) {
    for(let i = 9; i < 36; i++) {
        container.getSlot(i).setItem('minecraft:splash_pointion', 64, 22)
    }
    for(let i = 3; i < 7; i++) {
        container.getSlot(i).setItem('minecraft:splash_pointion', 64, 22)
    }
    for(let i = 6; i < 9; i++) {
        container.getSlot(i).setItem('minecraft:splash_pointion', 64, 22)
    }
    container.getSlot(0).setItem('minercaft:diamond_sword')
    container.getSlot(1).setItem('minercaft:bow')
    container.getSlot(0).setItem('minercaft:fishing_rod')
    container.getSlot(9).setItem('minercaft:cooked_beef', 64)
    container.getSlot(8).setItem('minercaft:arrow', 64)
}
    if (player.hasTag('PlayCombo')) {}
}``` what wrong?
random flint
#

you can use it straight away now

random flint
hazy nebula
random flint
#

Data isn't supposed to be supported anymore in the future.

#

If you're looking for Durability, there's a Durability Component to manipulate it.

Else, if you're looking for more range of items, use the flattened identifiers.

north rapids
#

Is it possible to get an array with all item ids in the game + addons?

hazy nebula
random flint
#

for data, no

#

Well, you can still use commands

#

But it's advisable not to depend on commands. It's slow af

fallow rivet
random flint
#

What r u trying to do

random flint
#

You "skip" that process

#

you can use dynamicProperty straight away

fallow rivet
#

Hmm

#

1 sec

random flint
north rapids
#

Ok

#

When I replace a door with other using block.setPermutation() the door breaks. How can I avoid this?

umbral scarab
#

how would I find the closest entity to a player?

fallow rivet
#

@random flint

#

Working , thanks

distant tulip
fallow rivet
# random flint You remove that ( aka: defining the property )
world.afterEvents.worldInitialize.subscribe((event) => {
    const property = new DynamicPropertiesDefinition();
    const auction_Items = new Array();
    const data = JSON.stringify(auction_Items);
    property.defineString("listed_Items", 99999, data);
    event.propertyRegistry.registerWorldDynamicProperties(property);
   }); 

I need to do the same thing for this code

random flint
#

My monkey brain is unable to comprehend new Array()

fallow rivet
#

Ok

north rapids
random flint
#

new Array() is simplified to [] and skip stringifying it into "[]"

prisma shard
random flint
wraith peak
#

is there any way to detect the up and down buttons moving back and forth?

random flint
#

Do you mean scrolling?

#

or the WASD keys

wraith peak
#

WASD keys

random flint
#

No easy way. You can utilize the player's past position and current position (or just use velocity), then recalculate based on the player's head rotation if they move forward or somewhere else.

wraith peak
#

I understand a little, thank you..

fallow rivet
random flint
# fallow rivet Is there any information about this on the Microsoft website?

DynamicProperty didn't get centralized into a single documentation page.

For the summary, you can use setDynamicProperty & getDynamicProperty inside Entity, ItemStack, and World Class.

The values you can set are: Vector3, Boolean, Number, and String ( use undefined to clear a property )

World Class possesses utility method for dynamicProperty:

  • getDynamicPropertyIds
  • getDynamicPropertyTotalByteCount
  • clearDynamicProperties
fiery solar
fallow rivet
#

#1271915600855171112

fallow rivet
fiery solar
umbral scarab
#

how would I find the closest entity to a player?

prisma shard
prisma shard
#

You mean the closest entity?

umbral scarab
#

ye

prisma shard
#

Not all the closest entities?

umbral scarab
#

just THE closest entity

#

so 1

prisma shard
#

so doing [0] , it will return the first entitiy

#

maybe the most closest

umbral scarab
#

so longest entity is first?

remote oyster
# fallow rivet I don't know how to do this

Example:

script1.js

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

// Example player statistics object
const playerStats = {
    miniGame1Score: 1500,
    miniGame2Score: 3200,
    lastLoginTick: system.currentTick // Store the current tick
};

// Convert the object to a JSON string
const playerStatsJson = JSON.stringify(playerStats);

player.setDynamicProperty("playerStats", playerStatsJson);

script2.js

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

const playerStatsJson = player.getDynamicProperty("playerStats");

// Check if the property exists and is valid
if (playerStatsJson) {
    try {
        // Convert the JSON string back to an object
        const playerStats = JSON.parse(playerStatsJson);
        
        // Access player statistics
        console.log(`Mini-Game 1 Score: ${playerStats.miniGame1Score}`);
        console.log(`Mini-Game 2 Score: ${playerStats.miniGame2Score}`);
        
        // Calculate the time since the last login
        const ticksSinceLastLogin = system.currentTick - playerStats.lastLoginTick;
        console.log(`Ticks since last login: ${ticksSinceLastLogin}`);
        
    } catch (error) {
        console.error("Error parsing player stats:", error);
    }
} else {
    console.log("No player stats found.");
}
prisma shard
umbral scarab
#

alrighty npnp, thanks anyways!

umbral scarab
#

got me in the right direction

neat hound
#

Question: I don't suppose there is a way to get an entity's target block, like a bee, from the move_to_block component?

random flint
#

nah iirc

honest spear
random flint
#

Does the delay from ServerForm depend on the player's connection/pings or World tick?

neat hound
#

Woulda been nice... Making a tree spider and would like him to either replace a block with a web or put one in the air block he is in depending on the block... so guess I gotta just test. Using bee JSON as base with scripevent

neat hound
#

Yes he is

fallow rivet
# remote oyster Example: script1.js ```js import { system } from "@minecraft/server"; // Examp...

import { world, system } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";


world.afterEvents.itemUse.subscribe(data => {
const player = data.source;
const { x, y, z } = player.getViewDirection();
    if (data.itemStack.typeId !== 'minecraft:diamond') return;
    if (player.isSneaking == false ) {
    
    menu(player);
    } 
    
    if (player.isSneaking == true ) {
    testmenu(player);
    }
    
});

function menu(player) {
const stJson = player.getDynamicProperty("st");
        const st = JSON.parse(stJson);
    const form = new ActionFormData()


       form.title(`§eMenü`)
 
        form.body("")

form.button(st.text);


form.button('§eOK\n§r§rTıkla')

          form.show(player).then(result => {

      if (result.selection === 0) {
        player.runCommandAsync(`playsound note.hat @s`)
       }

       }

)}

function testmenu(player) {
  
    
    const modal = new ModalFormData();
    modal.title("");
modal.textField("text", "...");

    modal.show(player).then(result => {
    const st = {
    text: result.formValues[0]
};


const stJson = JSON.stringify(st);

player.setDynamicProperty("st", stJson);
 
 
    })
}

#

Working but

#

I want this button to be added to every article I write here, the previous button should not be deleted.

cold grove
fallow rivet
umbral scarab
#
async function giveArmour(player) {
    const equipmentCompPlayer = player.getComponent(EntityComponentTypes.Equippable);
    const boots = equipmentCompPlayer.getEquipment(EquipmentSlot.Feet);
    const leggings = equipmentCompPlayer.getEquipment(EquipmentSlot.Legs);
    const chestplate = equipmentCompPlayer.getEquipment(EquipmentSlot.Chest);
    const helmet = equipmentCompPlayer.getEquipment(EquipmentSlot.Head);
    const dimension = player.dimension;
    const entity = dimension.getEntities({
       closest: 1
    });
    const equipmentCompPlayer2 = entity.getComponent(EntityComponentTypes.Equippable);
    equipmentCompPlayer2.setEquipment(EquipmentSlot.Feet, boots);
    equipmentCompPlayer2.setEquipment(EquipmentSlot.Legs, leggings);
    equipmentCompPlayer2.setEquipment(EquipmentSlot.Chest, chestplate);
    equipmentCompPlayer2.setEquipment(EquipmentSlot.Head, helmet);
}

I've got this error and not sure why

cold grove
# fallow rivet How can I do this?

You dont know what an array is??

const all = [];
// in some part of the code...
// all.push(new article)
// etc


const form =.....
all.forEach((e) => form.button(e.name))```
fallow rivet
#
const data = world.getDynamicProperty("listed_Items");
    const auction = JSON.parse(data);
    auction.push({ player: player.name, item: item, price: price, amount: amount ,itemname: itemn, id: auctionid, texture: texture});
    world.setDynamicProperty("listed_Items", JSON.stringify(auction));
#

Is it like this?

cold grove
#

Yes

next sedge
#

What changes have happened to action forms recently as mine arent working?

remote oyster
next sedge
remote oyster
#

Beta API or no?

next sedge
#

i have no clue if im honest

neat hound
#

Look at your manifest

gaunt salmonBOT
#

Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
glacial widget
#
world.afterEvents.playerInteractWithEntity.subscribe((e) =>{
    const {player, target, itemStack} = e

    if(target.hasTag("n1")){
            pvp.show(player).then(e =>{
                if(e.selection === 0){
                    player.sendMessage(`HCV kitpvp >> you have teleported to pvp`)
                    player.addEffect("slow_falling", 100, {amplifier: 1, showParticles: false})
                    player.teleport({x:20.16, y:129.56, z:42.11})
                }
                if(e.selection === 1){
                    player.sendMessage(`HCV kitpvp >> you have teleported to cpvp`)
                    player.addTag("pvp")
                    player.addEffect("slow_falling", 100, {amplifier: 1, showParticles: false})
                    player.teleport({x:37.98, y:154.69, z:1519.42})
                }
            })
    }
})

how do i stop the npc menu from showing for the ActionFormData to be only showing

solar dagger
#

is there a way to get the player's biome without beta API

amber granite
solar dagger
#

not using the player file

#

but if theres no other way it's fine, ill just wait

amber granite
#

Yeah wait then

brittle wolf
true isle
#

For checking a block neighbor do I just do block.north (+1)?

true isle
solar dagger
neat hound
# brittle wolf Can I recreate totems with this?

No, but you can create totems with programming There may be enough classes with properties and methods along with manipulation for the damage sensor of the player.json for you to be able to mimic it.

runic crypt
#

these are the scripts

#

how do i make them into a single script ?

#

if anyone knows then please tag me :)

amber granite
#

Yeah u can

thorn flicker
amber granite
#

Just move things into the other file

#

That s all

amber granite
runic crypt
#

yea but how ?

amber granite
#

Copy past

runic crypt
#

i tried it didnt work

amber granite
#

Remove the duplicated importa

runic crypt
#

alright

#

imma try that 🫔

amber granite
#

Remove everything duplicated

valid ice
#

If you’re using VSCode, shift+alt+o to sort imports yessir

runic crypt
#

so i tried

#

it didnt work

#

i put the rename one on top so it worked

#

the other one didnt

#

can anyone fix this ?

neat hound
#

Remove Minecraft.

runic crypt
amber granite
#

Why u don't just put the two add-ons

#

On the same world

runic crypt
amber granite
#

Oh i see

#

It s obscured

runic crypt
#

yea the player rename part is, the creator obscured it

amber granite
#

We can't do anything about that

neat hound
runic crypt
#

i have permission to use it tho :)

runic crypt
amber granite
runic crypt
#

a little help guys ? 😭

neat hound
#

the other import did an alias

runic crypt
neat hound
#

Others here will help you. This is against my personal policy. Either you want to know why and learn so you do not have to ask or get others to do it for you, if you can. If I just do it, I become your personal programmer... and that ain't happening... I teach to fish, not fish for you.

neat hound
runic crypt
#

oki

amber granite
#

Or there is the second choice

#

The forbidden one ā˜ ļø

prisma shard
#

hm

#

and whats that

#

forbidden choice

#

lol wtf

sudden nest
# solar dagger is there a way to get the player's biome without beta API

I found a work-around for this but it's for my use-case only. But i think it can also suit to your use-case. Mine was creating an invisible entity that has a timer to despawn and it has this event filter for biomes they're spawned, and just assign a set_property to it, and then you fetch that property in the script api.

#

It's stable, and on my case since i didn't use it in loops, it pretty efficient

deep garden
#

world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
    const item = itemStack;
    if (!item) return;
    
    if (item.typeId === "minecraft:diamond_sword") {
        item?.getComponent('enchantable')?.addEnchantment({type: new EnchantmentType('fire_aspect'), level: 2});
        item.setLore(["Firebrand"]);
        source.getComponent('equippable').setEquipment('Mainhand', itemStack);
    }
});

Does anyone know how to prevent the enchantmentleveloutofbounds error? So this works but I don't know how to get it only to apply the enchantment once. So the error doesn't occur from trying to go past the max level

sharp elbow
#

Here's a small function that caps a level to its maximum bounds. Use it by passing the EnchantmentType as its first argument, then the level you want to set as its second.

function safeLevel(enchantment, level) {
  return level > 0 ? (level <= enchantment.maxLevel ? level : enchantment.maxLevel) : 0;
}
deep garden
#

Lol, not sure why autocorrect kicked in there with your name, sorry about that

solar dagger
sudden nest
#

Ye, sadge. Wait, they're going to remove entity.json stuffs soon?

woven loom
#

anyone know a good GitHub client for Android with all the features, official one is useless

cold grove
#

Web ??

small cloak
#

I just use the official one. šŸ¤·ā€ā™€ļø

#

If I actually need to work on someting, I'll just use my PC.

halcyon phoenix
#

you people know what particles lasts very quick?

#

like half a second or so

woven loom
fallow rivet
#
function menu(player) {

    const form = new ActionFormData()


       form.title(`§eMenü`)
 
        form.body("")





form.button('§eOK\n§r§rTıkla')

          form.show(player).then(result => {

      if (result.selection === 0) {
        player.runCommandAsync(`playsound note.hat @s`)
       }

       }

)}
#

I want to add 1 button for all items in the player's inventory. Is this possible?

woven loom
#

1 btn ?

fallen cape
fallen cape
misty pivot
#

i dont really understand why this isn't working, it's supposed to decrease timers 1 to 6 and when they reach 0 they get removed

const skillTimers = [
    0, 1, 2, 3, 4, 5, 6
]
for (let skillTimer of skillTimers) {
    const getTimer = player.getDynamicProperty(`timer${skillTimer}`);
    if (getTimer !== undefined) {
        if (getTimer > 0) {
            world.setDynamicProperty(`timer${skillTimer}`, getTimer-1)
        }else world.setDynamicProperty(`timer${skillTimer}`, undefined);
    }
}```
#

ah, it's world not player

#

mb mb

fallow rivet
#

Is there a place I can learn?

remote oyster
fallow rivet
remote oyster
# fallow rivet Can you give me a sample code?
import { ActionFormData, ModalFormData, world } from "@minecraft/server";

// Function to create and show the player selection form
function showPlayerSelectionForm(player) {
    const form = new ActionFormData()
        .title("Select a Player")
        .body("Choose a player to view their inventory");

    // Add each player's name as a button
    world.getPlayers().forEach((p) => {
        form.button(p.name);
    });

    form.show(player).then((response) => {
        if (response.selection !== undefined) {
            const selectedPlayerName = world.getPlayers()[response.selection].name;
            const selectedPlayer = world.getPlayers().find(p => p.name === selectedPlayerName);
            if (selectedPlayer) {
                showInventoryForm(player, selectedPlayer);
            }
        }
    });
}

// Function to create and show the inventory form
function showInventoryForm(player, targetPlayer) {
    const form = new ModalFormData()
        .title(`${targetPlayer.name}'s Inventory`)
        .body(getInventoryString(targetPlayer));

    form.show(player).then(() => {
        // Handle any further interaction if necessary
    });
}

// Function to retrieve the player's inventory as a string
function getInventoryString(targetPlayer) {
    let inventoryString = "";
    const inventory = targetPlayer.getComponent("minecraft:inventory").container;
    
    for (let i = 0; i < inventory.size; i++) {
        const item = inventory.getItem(i);
        if (item) {
            inventoryString += `${i + 1}: ${item.id} x${item.amount}\n`;
        }
    }

    return inventoryString || "Inventory is empty";
}

// Example of triggering the form (e.g., when a player uses a custom command)
world.beforeEvents.chatSend.subscribe(event => {
    const player = event.sender;
    if (event.message === "!invsee") {
        showPlayerSelectionForm(player);
        event.cancel = true;  // Prevent the message from appearing in chat
    }
});

Something like this.

remote oyster
#

The code wasn't complete. I only gave an example. The rest is up to you.

fallow rivet
#

Ok

fast lark
#

I need it for my realm

remote oyster
fallow rivet
#

You can do this using

acoustic basin
#

guys, ive got my scriptevent running, but is there a way i can hide this message? i mean, so it didnt appear when the event runs

chrome flint
#

how does custom items are added in in item ID values?

#

is it alphabetical or what

chrome flint
halcyon phoenix
#

why doesn't it do the documentation?

flat barn
distant tulip
#

@fast lark


world.afterEvents.itemUse.subscribe(event => {
  const { source: player, itemStack } = event;
  if (itemStack.nameTag !== "inventory") return;
  const players = ['none', ...world.getPlayers().map(p => p.name)];
  new ModalFormData()
    .title('select player')
    .dropdown('player', players, 0)
    .show(player).then((r) => {
      if (r.canceled) return;
      const [playerName] = r.formValues;
      const inspectedPlayer = world.getPlayers().find(p => p.name === players[playerName]);
      if (!inspectedPlayer) {
        player.sendMessage("§cPlayer not found");
        player.playSound('note.bass');
        return;
      }

      const items = []
      const inv = inspectedPlayer.getComponent("inventory").container
      for(let i = 0; i < inv.size; i++) {
        const item = inv.getItem(i)
        if(!item) continue
        items.push({slot:i, id:item.typeId, amount:item.amount})
      }
      const invScreen = new ActionFormData()
      .title(inspectedPlayer.name + ' Inventory');
      for(const item of items) {
        invScreen.button(`Item: ${item.id} |Amount: ${item.amount} |Slot: ${item.slot}`);
      }
      const item = items[r.formValues[0]]
      invScreen.show(inspectedPlayer).then((r) => {
        if (r.canceled) return;
        const areYouSure = new MessageFormData()
          .title("Are you sure you want to remove this item?")
          .button1("cancel")
          .button2("remove")
          .show(inspectedPlayer).then((r) => {
            if (r.canceled) return;
            if (r.selection === 1) {
              inv.setItem(item.slot, null)
            }
          })
      })
    });
});
#

not tested

fast lark
distant tulip
#

it is working now

plush moss
#

Does anyone know how to display slabs or doors in an NPC as a texture?

chrome flint
#

hey @valid ice can you see dms? i want to ask some things, thank you

sharp elbow
prisma shard
#

How to detect "IF" player is looking at any entity?

i tried to figure it out myself for hours, but i gave up
i tried doing this:

const getEntity = player.getEntitiesFromViewDirection()[0].entity;

if (getEntity) {
  // doesn't work
  console.warn("looking at a entity");
}

i tried doing this, but it doesnt seem to work

#

@distant tulip srry for ping

sharp elbow
#

He needs help that bad šŸ˜…

distant tulip
distant tulip
remote oyster
sharp elbow
next sedge
#

anybody know why this doesnt work for me but works for someone else?

import { world, Player, system, } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui"
export function getScore(target, obj) {
    obj = world.scoreboard.getObjective(obj)?? world.scoreboard.addObjective(obj, obj) 
    return obj.hasParticipant(target) 
              ? obj.getScore(target) 
              : obj.addScore(target, 0)
} 

world.beforeEvents.playerInteractWithEntity.subscribe((data) => {
    let { target, player } = data
    if (target.typeId === "minecraft:npc") { //endr:farmernpc
                    data.cancel = true
        system.run(() => {
            let farmshop = new ActionFormData()
                .title(`§aFarm Shop!`)
                .body(`Welcome to the farm shop, We've got plenty of fresh produce and seeds for you!`)
                .button("§bSeeds\n§8[Click to interact]", "textures/ui/icon_new")
                .button("§bSell Crops\n§8[Click to interact]", "textures/ui/icon_carrot")
                .button("§bAnimal Produce\n§8[Click to interact]", "textures/ui/promo_chicken")
            farmshop.show(player).then(response => {
                if (response.selection === 0) {
                    seedsPage(player)
                }
                if (response.selection === 1) {
                    cropsPage(player)
                }
                if (response.selection === 2) {
                    animalProduce(player)

                }
        })
        })
    }
})
sharp elbow
#

Doesn't work in what way?

next sedge
#

the menu doesnt open.

prisma shard
#

this time it worked

#

lool what

next sedge
soft rune
#

You know how to protect an area so that it doesn't break or block

granite badger
distant tulip
next sedge
distant tulip
#

check if you did

#

and send errors if there is any

next sedge
#

the only errors are with the .lang file

distant tulip
#

let me boot my game and see if it work in my end

next sedge
#

alr ty

distant tulip
next sedge
#

i have no blimmin clue

distant tulip
#

what is your version

next sedge
#

1.21.2

plush moss
#

I think its because of your custom npc

next sedge
#

nah tried it with normal npc

distant tulip
#

put
console.warn("this is the right pack")
in your script root and reload

next sedge
#

alr

#

testing it now

#

it did not appear

distant tulip
next sedge
distant tulip
#

remove the old one if you still have it

next sedge
#

just did that, still nothing from the console

#

why minecraft gotta change its code

fiery solar
next sedge
#

yo can someone dm me a basic manifest, i think its my manifest thats wrong but i dont think my main.js file is running

remote oyster
random flint
#

Cursed Event Ideas:

- cancelable beforeEvent playerLeave
- cancelable beforeEvent worldInitialize

next sedge
#

i found my issue, i left one word in there thats outdated and it broke everything 😭

remote oyster
random flint
#

exactly. xd

remote oyster
neat hound
# chrome flint thank you mr. obvious

Please refrain from sarcastic comments, it is the breeding ground for toxicity, which is the last thing we need in this category. #off-topic is fine for that.

His information was valid and useful for new programmers.

While I understood Gega's comment to be in jest, some people may not have or may be using a translator that does not convey it as that.

chrome flint
#

alr

neat hound
fallow rivet
#

function showInventoryForm(player, targetPlayer) {
    const form = new ActionFormData()
        form.title(`${targetPlayer.name}'s Inventory`)
        form.body("inventory");
        form.button(getInventoryString(targetPlayer))
form.button("ok")
    form.show(player).then(() => {
        // Handle any further interaction if necessary
    });
}
#

How can I make it so that there is 1 button for all items?

chrome flint
#

do loop

#

list all the item ids in an array then do forEach, with form.button() inside

solar dagger
#

Is there a way to obtain the items data value through script? Im trying to see if the player is wearing the ender dragon head item.

system.runInterval(() => {
  world.getPlayers().forEach((player) => {
    const equipComp = player.getComponent('minecraft:equippable');
    if (equipComp) {
      const headGear = equipComp.getEquipment(EquipmentSlot.Head);
      console.error(`${headGear.typeId}`);
    }
  });
}, 20);
wary edge
solar dagger
neat hound
#

Is there any kind of VS-Code shortcuts for inserting JDoc?

neat hound
#

never mind... dang.. it did it for me... I just typed /** and it made this```js
/**
*

  • @param {*} array
  • @returns
    */``` I love you VS-Code
distant tulip
chrome flint
#

ai probably

distant tulip
#

yeah the one nikki sent is default
mine is Codeium ai as i said

#

the different

neat hound
distant tulip
#

just tried it with a blank profile
it is default

neat hound
#

LOL.. I looked at that extension... not sure I am ready to have AI writing snippits for me... I am still learning fluency, so gotta do my own work...

#

But that is one NICE extension

distant tulip
#

i mostly use it for repetitive codes and jsDoc

wary edge
#

Or ust typescript lol

distant tulip
#

no šŸ˜”

neat hound
#

I can't.. I'll go crazy...... I love JS.... and I am learning C#.... typescript will mess me up write now.... and deploying from regolith... too much work... what filter do you use?

wary edge
#

🤷 I literally use TS + regolith

distant tulip
#

i hate compiling

neat hound
#

What filter for the convert?

wary edge
#

There is no filter, i juse do npm run dev

#

Which does tsc && regolith run dev

unique dragon
#

lol

gray tinsel
#

ctrl + shift + b to access that

distant tulip
#

is that a ts thing or am i being dumb

gray tinsel
#

yes it is

distant tulip
#

alr

#

maybe some day

unique dragon
#

xd

gray tinsel
#

trust me it is worth it

neat hound
#

Minato, do you use regolith?

gray tinsel
#

being able to define types easily is a god send

unique dragon
#

what's regolith

neat hound
#

It's org heaven

distant tulip
unique dragon
gray tinsel
#

it's a linux distro?

neat hound
wary edge
#

It's fine

distant tulip
neat hound
#

LOL

unique dragon
#

LOL

#

xd

distant tulip
#

yeah
now i do the same lol

gray tinsel
#

good lmao

distant tulip
#

it is a good change

unique dragon
#

yes

gray tinsel
#

it's for their own sakes

unique dragon
#

really good change

gray tinsel
#

notepad is best though

unique dragon
valid ice
simple zodiac
#

now switch to vim or emacs

chrome flint
#

can someone help me? it says " TypeError: not an object at line 2350"

#

hey @valid ice is there wrong in my item id list?

valid ice
#

yeah uhhh idk it looks fine to me

steady canopy
#

Does someone know about a item database where I can save items with nbt data

chrome flint
#

yeah it keeps saying TypeError: not an object at Map (native) at <anonymous> line 2350

valid ice
#

How're you using it?

steady canopy
#

I don't think that's called cross post

wary edge
#

That is crossposting yes

steady canopy
#

Lol

subtle cove
chrome flint
chrome flint
glacial widget
gray tinsel
#

do I need to install anything alongside the regolith c# extension

pale terrace
#

How can I store data in a block? since there are no dynamic properties for blocks and states need predefined values

amber granite
#

U are on js channel

wary edge
#

Youll need to store data via other dynamic properties. Have a key/val relationship that stores the coords then the id then the data

fiery solar
gray tinsel
wary edge
amber granite
#

@fiery solar

amber granite
amber granite
#

U can add dimension

#

To make it more precise

#

If u want to safe an object:
Stingify it using
JSON.stingify(urObj)

gray tinsel
amber granite
#

Because they use it for c++ , and make ur work easier

#

And vscode isn't equipped enough to handle c languages

#

If u pc is high-end pc ofc

#

U can stick with vscode , it s good too

#

@gray tinsel

stone sage
#

how could i run a command like as the server with BDS? for something like /transfer

simple zodiac
#

have a parent process write into the servers stdin

stone sage
#

Thank you

neat hound
gray tinsel
neat hound
#

I would highly suggest exploring filters and learning to make your own for any useful task.

gray tinsel
#

Right ok

#

Thanks for the invite

serene lava
#

I need to make the mob teleport to either side of the terrain I'm on as long as it doesn't go down the terrain I'm standing on.

for example if I am on the 3rd floor of a building and the mob instead of teleporting
to random locations on floor 3 teleports to floor 2.
How do I solve this?

neat hound
# gray tinsel Thanks for the invite

Sorry about the comments you got from others after.. I was not here to nip that in the bud. He had no idea of the scope of the subject and it's relation to anything. Some people are just like that.

neat hound
#

For a test, tp a mob, commands into a block in the air... and see if it goes to top of block or below the block... I think this may be what is happening., try y+1 to ensure

glacial widget
#
world.beforeEvents.chatSend.subscribe((e) => {
    const { sender, message } = e;
    const inventory = sender.getComponent("inventory").container
    const sword = new ItemStack ("minecraft:wooden_sword", 1)
    const ench = sword.getComponent("enchantable")

    if (message === "loadkit") {
        e.cancel = true;
        system.run(() => {
            inventory.addItem(sword)
            ench.addEnchantment({ type: new EnchantmentType("unbreaking"), level: 3 });
            sender.sendMessage("sword loaded");
        });
    }
});
#

why does addEnchantment not work?

wary edge
glacial widget
wary edge
#

Into the inventory

chrome flint
#

just switch those two lines

glacial widget
glacial widget
amber granite
meager zenith
meager zenith
#

Thank you so much

distant tulip
#

ur wlc

viral plaza
#

I need help making a reliable island generator. Dm me if you can help me JoeWave

woven loom
#

whats island gen

fallow rivet
#
function getInventoryString(targetPlayer) {
let items = "";
    let inventoryString = "";
    const inventory = targetPlayer.getComponent("minecraft:inventory").container;
    
    for (let i = 0; i < inventory.size; i++) {
        const item = inventory.getItem(i);
        if (item) {
        items = item.type.id;
            inventoryString += `${i + 1}: ${item.type.id} x${item.amount}\n`;
        }
    }

    return inventoryString  || "Inventory is empty";
}



function showInventoryFormi(player, targetPlayer) {
    const form = new ActionFormData()
        form.title(`${targetPlayer.name}'s Inventory`)
        form.body(getInventoryString(targetPlayer));
     
        
form.button("ok")
    form.show(player).then(() => {
        // Handle any further interaction if necessary
    });
}
#

How can I see the enchantments of items here?

fast lark
#

Someone have a script for player rank?

fallow rivet
#

You can look here, some people are sharing the mods

nimble radish
honest spear
nimble radish
#

Okay, sorry, can you help me fix it I don’t why but it doesn’t get the right button select and I was going to ask how would you change the percentages of winning if you hit a certain button like. If you select heads you have a 30% chance of it being heads and 70% chance for it to be tails. If you select tails it has a 30% of being tails and 70% chance being heads

glacial widget
#
world.beforeEvents.playerInteractWithBlock.subscribe((e) =>{
  const {player, itemStack, block} = e
  const inventory = player.getComponent("inventory").container
  const sword = new ItemStack ("minecraft:stone_sword", 1)
  const helmet = new ItemStack ("minecraft:chainmail_helmet", 1)
  const chest = new ItemStack ("minecraft:chainmail_chestplate", 1)
  const legs = new ItemStack ("minecraft:chainmail_leggings", 1)
  const boots = new ItemStack ("minecraft:chainmail_boots", 1)
  const ench = sword.getComponent("enchantable")

  if(block.typeId == "minecraft:chest" && block.x == -353 && block.y == 82 && block.z == 17){
    e.cancel = true

    system.run(()=>{
      ench.addEnchantment({ type: new EnchantmentType("vanishing"), level: 1 })
      helmet.getComponent("enchantable").addEnchantment({ type: new EnchantmentType("vanishing"), level: 1 })
      chest.getComponent("enchantable").addEnchantment({ type: new EnchantmentType("vanishing"), level: 1 })
      legs.getComponent("enchantable").addEnchantment({ type: new EnchantmentType("vanishing"), level: 1 })
      boots.getComponent("enchantable").addEnchantment({ type: new EnchantmentType("vanishing"), level: 1 })
      sword.nameTag = "§d§lStarter"
      helmet.nameTag = "§d§lStarter"
      chest.nameTag = "§d§lStarter"
      legs.nameTag = "§d§lStarter"
      boots.nameTag = "§d§lStarter"

      inventory.addItem(sword)
      inventory.addItem(helmet)
      inventory.addItem(chest)
      inventory.addItem(legs)
      inventory.addItem(boots)

is there a better way of doing this

honest spear
#
const items = [
    "minecraft:stone_sword", 
    "minecraft:chainmail_helmet", 
    "minecraft:chainmail_chestplate", 
    "minecraft:chainmail_leggings",
    "minecraft:chainmail_boots"
]
world.beforeEvents.playerInteractWithBlock.subscribe((e) =>{
  const {player, itemStack, block} = e
  const inventory = player.getComponent("inventory").container;
  if(block.typeId == "minecraft:chest" && block.x == -353 && block.y == 82 && block.z == 17){
    e.cancel = true

    system.run(()=>{
      for(const itemId = items) {
        const item = new ItemStack(itemId, 1);
        item.getComponent("enchantable").addEnchantment({ type: new EnchantmentType("vanishing"), level: 1 });
        item.nameTag = "§d§lStarter";
        inventory.addItem(item);
      }
#

@glacial widget

#

This is called loops

acoustic basin
burnt remnant
#

is there a way to get the ingame day?

glacial widget
#

i didnt know u could use loops for it

viral plaza
#

Is there anyway to get a players head, or set a Steve head in a chest ui? Or does anyone have a Steve head resource icon

fallow rivet
#

@viral plaza

viral plaza
tiny fable
#

How do I get the items attack damage?

cold grove
slow walrus
#

just crop it

true isle
fickle dagger
#

what does /scriptevent do and how do I use it?

shy leaf
#

its like functions but for scripts

subtle cove
#

just sample

fickle dagger
#

I see, thank you for the answers Seawhite and Remember M9!

#

I guess this means I can summon an explosion using scriptevents

shy leaf
#

/scriptevent is basically a command event

#

so yes everythings possible (that scripts can do)

quasi meteor
#

I am connected to "script debbuger" successfully so I am be able to use "breakpoints etc." but there is no data in "diagnostic window", does it works for clientside worlds?

#

Here is my launch.json

  "version": "0.3.0",
  "configurations": [
    {
      "type": "minecraft-js",
      "request": "attach",
      "name": "Debug with Minecraft",
      "mode": "listen",
      "targetModuleUuid": "UUID HERE",
      "localRoot": "${workspaceFolder}/scripts/",
      "port": 19144,
    }
  ]
}```
sharp elbow
#

What Minecraft version are you using?

quasi meteor
#

1.21.2

sharp elbow
#

I can't recall if performance debugging is supported on that version. The client stats are certainly not

#

And is that the literal value you set for targetModuleUuid? Or is that redacted just for being sent here

quasi meteor
#

no, i changed it

granite badger
#

diagnostic panel is only for v1.21.20+ , stable cannot use it for now

quasi meteor
#

ty!

wintry bane
#

How do I add custom components to an item and what format version do I need

drifting ravenBOT
#
HCF Removal and Custom Components

The Holiday Creator Features experimental toggle has been removed. Along with it includes JSON block and item events. This functionality has been replaced with custom components.

Please take a look at the following links to learn more about custom components:

wary edge