#Script API General

1 messages · Page 65 of 1

subtle cove
#

const capitalize = (str) => str.split(/:|_/).splice(1).map(s => s[0].toUpperCase() + s.substring(1).toLowerCase()).join(' ');
``````js
entity.nameTag = capitalize(name)
bright dove
#

how to set a name of an item in a container ? @subtle cove

subtle cove
#
const slot = inv.container.getSlot(1)
if (slot.hasItem()) {
  slot.nameTag = name
}
subtle cove
warm condor
#

hey yall, new scripter here

Anybody know how I can make an entity summon another entity through scripting? Once ive done that I have other things I'd like to learn how to do similar to that

subtle cove
bright dove
subtle cove
#

mhmmm, even in stable

warm condor
#

id use the command itself if it wasnt for a limitation that would take some SERIOUS hard coding

subtle cove
#

there's a few things to learn

warm condor
#

definitely

#

i am VERY new to it

subtle cove
#

dimension
getEntities({type:'minecraft:creeper'})
loop through that, then spawn any entity spawnable

warm condor
#

should i cut to what im trying to do as a whole?

subtle cove
#

i'd create a post if i were u

warm condor
#

alright one sec

#

#1350698793816817675 made a post

prisma shard
prisma shard
#

hm so?

warm condor
prisma shard
#

oh

#

ok

prisma shard
warm condor
#

i meant in context

prisma shard
#

alr

warm condor
#

read #1350698793816817675

prisma shard
#

uh-

chilly moth
# subtle cove ```js const capitalize = (str) => str.split(/:|_/).splice(1).map(s => s[0].toUp...

after.entitySpawn.subscribe(({ entity, cause })=>{
    const { x, z } = entity ? entity.location : 0
    const level = Math.round(Math.random() * 5) + Math.floor(Math.sqrt(x ** 2 + z ** 2) / 100 * 5)

const capitalize = (str) => str.split(/:|_/).splice(1).map(s => s[0].toUpperCase() + s.substring(1).toLowerCase()).join(' ');

const entityId = entity.typeId;

const entityNameById = entityId.split(":")[1];
    const name = `${entityNameById}Lv.${ level }`
    if (level && !isType(entity,"minecraft:npc") && !isType(entity,"minecraft:armor_stand")) {
        score(entity, "level").set(level)
        entity.nameTag = capitalize(name)
    }
})

#

it doesn't show anything no errors¿

dim tusk
#

you need to know if the name really change.

chilly moth
#

ok let me check

subtle cove
# chilly moth ``` after.entitySpawn.subscribe(({ entity, cause })=>{ const { x, z } = ent...
const capitalize = (str) => str.split(/:|_/).splice(1).map(s => s[0].toUpperCase() + s.substring(1).toLowerCase()).join(' ');

after.entitySpawn.subscribe(({ entity, cause }) => {
    const { x, z } = entity ? entity.location : 0
    const level = Math.round(Math.random() * 5) + Math.floor(Math.sqrt(x ** 2 + z ** 2) / 100 * 5)

    const entityId = entity.typeId;

    if (level && !"minecraft:npc minecraft:armor_stand".includes(entityId)) {
        score(entity, "level").set(level)
        const name = `${capitalize(entityId)}Lv.${level}`
        entity.nameTag = name
    }
})
subtle cove
#

sorry if i had to remove the isType function there ;-;

prime zenith
#

Anyone willing to help me balance my combat will req live testing so its not as simple as rewriting script snd done

dim tusk
#

Привет...

sly currentBOT
#
finnafinest_

Hello...

prime zenith
#

Lrts all chew coddy out for not using english in an english only channel 😛

prisma shard
#

how do u freeze a entity

#

set the location to the current location of the entity in every tick?

#

but that will be laggy

prisma shard
#

thanks

prisma shard
#

one sec i forgor

prisma shard
dim tusk
prisma shard
#

thx

dim tusk
#

Returns an array of lores per line.

prisma shard
#

wasnt there a hasLore

dim tusk
#

Only hasTag()

#

you must be having the Mandela effect

prisma shard
#

how do i check if a item have a lore 2374pepesob

#

i just totally forogot

#

i reset my brain

prisma shard
dim tusk
#

I mean literally use the include function

prisma shard
#

thankls for remmebering me

dim tusk
prisma shard
#

wait

#

how i get the itemstack

dim tusk
#

use getEquipment() or inventory component

prisma shard
#

oh

#

i dont remember them bcoz i dont have typings at this moment

dim tusk
chilly moth
prime zenith
#

Add me and i will

oak lynx
#

is this less resource demanding than just using dimension.getBlock()

jolly citrus
#

how is it possible for just one of these to show a type error ??

let effect;
    if (castType === CastableEffectType.Click) {
      effect = combatClass.clickEffects[itemTypeId];
    } else if (castType === CastableEffectType.Held) {
      effect = combatClass.heldEffects[itemTypeId];
    }
oak lynx
#

there isnt a good way to store player plots/skyblock islands in an external db right?

#

going over each block takes forever because i cant afford spikes

distant tulip
#

use runJob?

safe stream
#

runJob fixes everything honestly

jolly citrus
#

what is runjob

chilly moth
#

how to run animation on projectileentity when entity hits mobs

ivory bough
#

Hey when I use the Date function in js in a multiplayer world and log it out in chat as each player, will it it return the world's host's date or will each player get their own local date?

chilly moth
#

@chilly dock check

#

‽ı

distant tulip
# jolly citrus what is runjob

a function under the system class that uses generator function to run a set of tasks in different times

Generator functions have something called yeild, when the runjob run the function and reach a yeild it stops the execution and resume it next time the game is free

chilly moth
#

bro came for commission

distant tulip
distant tulip
ivory bough
chilly moth
#

yes

#

projectile animation after hit

distant tulip
ivory bough
chilly moth
fast wind
#

How can I spawn a particle that only the player can see 35 blocks in front of an entity using spawnParticle?

distant tulip
distant tulip
chilly moth
#

ivory bough
distant tulip
fast wind
#

Ok so I have a player and an entity, with player.spawnParticle I want to spawn a particle 35 blocks in front of the entity, like using ^^^35 but in script

distant tulip
distant tulip
fast wind
#

yes that's what I want

distant tulip
#

that what it does...

fast wind
#

I want only the player to see the particle but the location of it should be 35 blocks in front of another entity separate from the player. Sorry English isn't my first language so maybe I didn't explain well

#

Basically how do I get a Vector3 of the block (even if undefined) 35 blocks in front of that entity

distant tulip
#

try this

const { x, y, z } = entity.location;
const { x: rotX, y: rotY } = entity.getRotation();

const rad = (rotY * Math.PI) / 180;
const forwardX = -Math.sin(rad);
const forwardZ = Math.cos(rad);

const targetX = x + forwardX * 35;
const targetY = y + 1; 
const targetZ = z + forwardZ * 35;

player.spawnParticle("id", { x: targetX, y: targetY, z: targetZ });
#

wait, you want it relative to the entity view? sense you said "in front"

fast wind
distant tulip
ivory bough
fast wind
#

Thank you

ivory bough
jolly citrus
#

Somebody explain this madness pls

ivory bough
distant tulip
jolly citrus
#
  displayedStats: Partial<Record<keyof CustomPlayer, () => boolean>>;

    this.displayedStats = {
      combatClassEnergy: (): boolean => {
        return this.activeCombatClass !== "none";
      },
    };

i have displayedStats defined like this on my custom player,

for (const [key, condition] of Object.entries(customPlayer.displayedStats)) {
      const stat = StatMap.get(key);
      if (!stat) continue;

      if (!condition()) continue;

      let statString = customPlayer[key]; // RIGHT HERE
/* continues ... */

but when i try to use it here, it thinks key is a string and not keyof Customplayer so it gives me a type error ??

ivory bough
distant tulip
# ivory bough Wait I don't wanna run a command as soon as the first player joins but in anothe...
import { world } from "@minecraft/server";

let firstPlayer = null;

world.afterEvents.playerSpawn.subscribe((event) => {
    if (event.initialSpawn && !firstPlayer) {
        firstPlayer = event.player;
        world.sendMessage(`First player set to: ${firstPlayer.name}`);
    }
});

world.afterEvents.scriptEventReceive.subscribe((event) => {
    if (event.id === "custom:id") {
        
        if(firstPlayer?.isValid()){
            //go something
        }

    }
});
distant tulip
jolly citrus
#

yes thx figured it out

#

just weird that i even had to use type assertion in this scenario

fast lark
#

Is there a good inventory save i can use?

#

That saves everything

bright dove
#

@distant tulip do you know what the latest beta/stable version of v1 is ?

subtle cove
fast lark
bright dove
subtle cove
distant tulip
oak lynx
#

We are talking about 3.2m blocks

prisma shard
#

anyone has typeIds of all of the ore blocks

#

another question - is Set([]) and a Array the same?

open urchin
prisma shard
prisma shard
open urchin
#

you could probably just check that the typeId ends with "_ore"

prisma shard
#

i have to do some switch case statements w/ them

open urchin
#

these with minecraft: before them

prisma shard
#

alr

#

thanks

#

iron, gold, and copper only drops raw ingots??

#

oh yeah raw diamond dont exist lol

neat hazel
#

How to ignore entities from a specific family using getEntities()?

unique acorn
olive rapids
#

hi

glacial widget
#

is there any way to block invis skins with server-net or a moduel??

neat hazel
#

Is it possible to set an entity on fire?

prisma shard
#

Why not check in the documentation first, before asking it?

neat hazel
#

Sorry

prisma shard
prisma shard
thorn flicker
fallow rivet
#

Where are structures saved?

wary edge
fallow rivet
#

How can I export it to the world as a ".mcsteucture" file?

wary edge
#

Not really a scripting question.

fallow rivet
#

Hmm, You are right

#

But where should I ask this?

fast lark
oak lynx
#

wait so i cant use a generator function like this

#

i am getting closer to giving up on the external db with each passing day

granite badger
oak lynx
#

Yeah I figured that part out

spark slate
#

Is it not possible to open the menu just after we send the command?

world.beforeEvents.chatSend.subscribe((eventData) => {
    const player = eventData.sender;
    const message = eventData.message.toLowerCase();

    if (message === "!faction") {
        eventData.cancel = true; console.log(`Player ${player.name} requested the faction menu.`);
        
        system.runTimeout(() => {
            openFactionMenu(player);
        }, 500);
    }
});```
oak lynx
#

Still too slow

#

Why can't we just get access to regions in bds

oak lynx
#

BTW I reccomend using a map for commands

prisma shard
#

why do you have a runTimeout() set at 500 ticks

#

That will open the form after a wayyyyy long time

prisma shard
#

If you want to open the menu just after you send the command... Just remove the runTimeout()

spark slate
oak lynx
spark slate
prisma shard
#

But a runTimeout() of 500 ticks still doesn't make sense

prisma shard
dim tusk
#

no need for forceShow just do await form.show

prisma shard
oak lynx
#

someone help me figure out how to save a block region to an array without lagging the whole server

oak lynx
#
export async function saveBlockVolume(blockVolume: BlockVolume): Promise<{block: IBlock, count: number}[]> {
    const dimension = world.getDimension("overworld")
    const structureManager = world.structureManager
    const blockArray: IBlock[] = []
    let i = 0
    for(const block of blockVolume.getBlockLocationIterator()){
        i++
        if(i % 6400*2 == 0) await system.waitTicks(1)
        const blockData = dimension.getBlock(block)
        const numericId = getBlockByTypeId(blockData.typeId)
        if(inventoryBlocks.includes(blockData.typeId)){
            const inventory = blockData.getComponent("inventory").container
            const itemArray: IItem[] = [] 
            for(let i = 0; i < inventory.size; i++){
                const item = inventory.getSlot(i)?.getItem()
                if(item){
                    itemArray.push(convertToDbItem(item))
                }
            }
            blockArray.push({
                numericId: numericId,
                states: blockData.permutation.getAllStates(),
                inventory: itemArray
            })
            continue
        }
        blockArray.push({
            numericId: numericId,
            states: blockData.permutation.getAllStates()
        })
    }
    const compressedArray: {block: IBlock, count: number}[] = []
    let currentBlock = blockArray[0]
    let count = 1
    for(const block of blockArray){
        if(count%64000 == 0) await system.waitTicks(1)
        if(JSON.stringify(currentBlock) == JSON.stringify(block)){
            count++
        }else{
            compressedArray.push({block: currentBlock, count: count})
            currentBlock = block
            count = 1
        }
    }
    return compressedArray
}```
prisma shard
#

Oh shit

#

That's a lot of code

#

sorry I can't help lol

oak lynx
#

thats like one of the many functions required to do this

prisma shard
#

That'd ofc lag the whole server

oak lynx
#

i mean i can always just make it do less blocks per tick but that doesnt solve anything

prisma shard
#

wait no lol

oak lynx
#

i mentioned that earlier

dim tusk
fast lark
dim tusk
#

yes it's possible to open but you using 500 ticks is high is what I'm trying to point out

fast lark
#

Bruh

#

Chill *

dim tusk
#

it's not long it's just 25 seconds.

#

-# it's long

dim tusk
# fast lark Bruh

Like I'm not stupid y'know, I literally pointed out wha he said that it's long.

prisma shard
oak lynx
dim tusk
oak lynx
#

i am already splitting it into chunks of 6400 blocks

dim tusk
dim tusk
#

Check even more smaller.

oak lynx
#

lets say i will do 400 thats 9600 ticks

#

thats way too long

dim tusk
#

I mena the purpose of your script generally.

oak lynx
#

i am making a hypixel skyblock like server i need to save the player island to a db

#

(using mongodb)

dim tusk
#

That's the best way since you doing that is very resource intensive that the runJob can't help you that much.

oak lynx
dim tusk
#

Just choose since you can't do anything about either Make it save slow but surely

oak lynx
#

a single island can be up to 40mb

#

thats with compression btw turning typeIds to numeric ids

dim tusk
#

As I said just choose since the way server do it way different than just scripts alone.

oak lynx
#

unless i made islands 64x

#

and made it so that players can have multiple of them

#

that way i can use the structure object to get block data faster

#

hmm i need to benchmark it

distant tulip
oak lynx
#

yeah i tried

#

almost no difference

#

choosing pure bds for hypixel skyblock type of server was a bad idea

distant tulip
#

What are you trying to do exactly

oak lynx
#

i need to save a player island into a format that i can store in a database (using mongodb)

distant tulip
#

Why tho? What is the use case, that seem a bit inconvenient

oak lynx
#

basically storing player stuff outside of the world gives me these benefits:

  • easier updating
  • player data backups
  • regions
  • easy horizontal scaling
random flint
#

save it into a structure :D

oak lynx
#

how do i send a structure via rest api tho?

random flint
#

rest api? not script api?

oak lynx
#

i am using script api

#

i need to send the data to a database and that is done via rest api (server-net)

random flint
#

Maybe try using StructureManager Class. Return Structure Class, then iterate each block permutation within it.

for loop .size:
structure.getBlockPermutation(xyz)

might be faster, idk

oak lynx
#

Already trying this

#

Slightly faster

random flint
#

Might just let it run slow, and put in a progression bar to indicate when it's finished.
-# You can put Loading tips~

oak lynx
#

nah i gotta figure out a faster way to do it

random flint
# oak lynx nah i gotta figure out a faster way to do it

The fastest way is probably just to save the structure locally using World StructureSaveMode
-# "The structure will be saved to the world file and persist between world loads. A saved structure can be removed from the world via @minecraft/server.StructureManager.delete."

Which scraping the idea of external DB

#

You can technically do the block-per-block conversion and saving process in the background for external DB.

Basically treating StructureSaveMode World as a buffer.

oak lynx
#

i am trying some stuff

#

there is no spike

#

but the islands are smaller

random flint
#

was it worth for an extra speed?

oak lynx
#

it takes 5 ticks to save 64x64x64

deep arrow
#

It might be a dumb question but what exactly does system.runJob() do?

oak lynx
dim tusk
oak lynx
#

Nvm I benchmarked it wrong

#

Nah I need sleep

prime zenith
#

I did my estradiol injextion the other day and hit a nerve its not fun

oak lynx
prime zenith
oak lynx
#

Injections suck tho

prime zenith
#

Estragen for everyone

#

Liver damage sucks more so i try to avoid damaging my liver

oak lynx
#

Sucks that there is a patch shortage

distant tulip
#

#off-topic

shy leaf
#

does anyone know the condition for setLore to throw?

distant tulip
shy leaf
#

just that?

#

alr thanks

distant tulip
#

the array and string limit
can't tell if thee is more

cinder shadow
#

any ideas on how to stop a particle from spawning outside of an unloaded chunk? It's being ran when an entity gets hurt

#

isValid doesn't work for whatever reason

past coyote
#

You could spawn only in a radius around the player I suppose

#

There isn’t really a easy way to do it

#

You could try to getBlock under the entity

true isle
#

is their a way to trigger an event like onRandomTick instead of it always being active

past coyote
#

Here’s some pseudo code (I’m on mobile rn)

FUNCTION checkChunkAndSpawnParticle(entity, particleName)
    SET dimension = world.getDimension(entity.dimension)
    SET position = entity.location
    TRY
        SET block = dimension.getBlock(position)
        CALL world.spawnParticle(particleName, position)
    CATCH error
        IF error.name EQUALS "LocationInUnloadedChunkError"
            PRINT "Chunk not loaded"
        ELSE
            THROW error
        END IF
    END TRY
END FUNCTION
``` ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
#

I wish we had a chunk class

cinder shadow
#

thanks that actually works ```js
if(hurtEntity.dimension.getBlock(hurtEntity.location) == undefined) return;

past coyote
#

I’ve been running into that error with getBlock and I figured it might be useful to try and leverage it for canceling stuff outside of the world bounds

#

Your method is way cleaner lmao

cinder shadow
#

I will never try catch anything

dim tusk
past coyote
#

You know what Coddy? You are ugly asf.

cinder shadow
#

try catch is uglier

past coyote
#

I'm joking, im sure you are incredibly handsome.

dim tusk
dense skiff
#

Is there any event that runs whenever the player hits the interaction/placement button? Like even when they click on air or whatever. Essentially just right click detection?

true isle
#

itemUse is one of them if ur using an item for anything

bright dove
#

I activated my behaviour pack but my script doesn't run

shy leaf
#

can anyone help me with something? ive got a script that sends an array with functions inside the items through scriptevent by serializing the items
the main script then deserializes the script event message and pushes the items into main array

#

but for some reason, if the first item in the array has new keyword inside its function, the first item gets ignored entirely before it gets pushed into the main array

#

the rest of the items are fine though

#

i can send codes in dms

prisma shard
#

sussy baka therock

#

Anyways

#

Show your manifest and script

#

"my script doesn't run" this really doesn't help

random flint
dim tusk
dim tusk
#

The way you say things like that in a serious question isn't funny.

prisma shard
#

alr sorry

prisma shard
slow walrus
#

already has Arrays and a bunch of other stuff builtin

shy leaf
#

omg

#

i forgot about this

#

ily

#

wait do you have a guide or example for this

slow walrus
#

no, been procrastinating doing docs lmao

#

I can help you though

shy leaf
#

oh that would be lovely

#

in dms? or here

slow walrus
#

probably in dms

shy leaf
#

alright

olive rapids
#

Does anyone know how I can encrypt my script codes for extra security?

prisma shard
#

There is online JavaScript obfuscator

distant tulip
#

obfuscator*

olive rapids
olive rapids
prisma shard
#

wait uh am I muted??

#

the bot sent me messeges that the links were suspected

olive rapids
#

?

#

When I paste my code, the page closed ._.

#

{
"format_version": "1.20.0",
"minecraft:item": {
"description": {
"identifier": "kit:item",
"category": "items"
},
"components": {
"minecraft:icon": {
"texture": "nautilus_shell"
},
"minecraft:max_stack_size": 1,
"minecraft:display_name": {
"value": "§eSelect Kit §7[Use]"
}
}
}
}

prisma shard
# olive rapids { "format_version": "1.20.0", "minecraft:item": { "description":...

{
"\u0066\u006f\u0072\u006d\u0061\u0074\u005f\u0076\u0065\u0072\u0073\u0069\u006f\u006e": "\u0031\u002e\u0032\u0030\u002e\u0030",
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u0069\u0074\u0065\u006d": {
"\u0064\u0065\u0073\u0063\u0072\u0069\u0070\u0074\u0069\u006f\u006e": {
"\u0069\u0064\u0065\u006e\u0074\u0069\u0066\u0069\u0065\u0072": "\u006b\u0069\u0074\u003a\u0069\u0074\u0065\u006d",
"\u0063\u0061\u0074\u0065\u0067\u006f\u0072\u0079": "\u0069\u0074\u0065\u006d\u0073"
},
"\u0063\u006f\u006d\u0070\u006f\u006e\u0065\u006e\u0074\u0073": {
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u0069\u0063\u006f\u006e": {
"\u0074\u0065\u0078\u0074\u0075\u0072\u0065": "\u006e\u0061\u0075\u0074\u0069\u006c\u0075\u0073\u005f\u0073\u0068\u0065\u006c\u006c"
},
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u006d\u0061\u0078\u005f\u0073\u0074\u0061\u0063\u006b\u005f\u0073\u0069\u007a\u0065": 1,
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u0064\u0069\u0073\u0070\u006c\u0061\u0079\u005f\u006e\u0061\u006d\u0065": {
"\u0076\u0061\u006c\u0075\u0065": "\u00a7\u0065\u0053\u0065\u006c\u0065\u0063\u0074\u0020\u004b\u0069\u0074\u0020\u00a7\u0037\u005b\u0055\u0073\u0065\u005d"
}
}
}
}

prisma shard
#

Use this for obfuscating JSON

slow walrus
#

it's completely useless, anyone with a bit more than 3 brain cells can deobfuscate that

prisma shard
#

I have the same thinking just like you

#

There's no point of obfuscating

#

But he still wanted to

#

Ofsucating is really useless

olive rapids
small cloak
shy leaf
#

why would you obfuscate scripts anyway

#

people who doesnt care about scripts would have bad performance

#

and people who does would deobfuscate it with no issue

#

its like a keylock, but they have bolt cutters

unique acorn
#

how come we aren't blaming marketplace creators too

#

Their code is encrypted, not just obfuscated

wary edge
unique acorn
#

oh Microsoft forces them?

#

fair

wary edge
#

There's an entirely different scenario when you obfuscate something free vs a paid product.

distant tulip
# unique acorn how come we aren't blaming marketplace creators too

obfuscate and encrypting are tow different things, he was talking about how obfuscated code is less performance, and in all honesty, if there was a encrypting method for none mp, most of us for sure will use it.
if i made my pack free that doesn't mean i want people stealing my code. there is a time and place for open sourcing, even licensing your work don't mean anything

woven loom
#

They should introduce some sort of encryption tech for non marketplace creators

slow walrus
#

doesn't work like that

woven loom
#

?

subtle cove
#

I leik free knowledge streams
May be risky, but it's better when more ppl get familiar and adapt with such new stuff

dim tusk
prime zenith
#

I dont always steal code but when i do i make sure there are no witnesses 😛

cold grove
prime zenith
cold grove
#

you can do it or get reported by the author

subtle cove
#

Reduce illiteracy

prisma shard
#

does clearVelocity() clears mobs actions

#

like i want to freeze a entity, clearVelocity() will freeze the mob, but suppose as a skeleton, he will stop moving, but will he shoot arrows?

prime zenith
#

I have a questipn if i credit the addon maker can i use another players addon to add entities i need for mine to save me time cause idk the first thing about adding a custum entity

unique acorn
prime zenith
#

If i try and noone gets back to me as many of these addon makers dont get back to you then do i just credit them or look for an addon where the addon maker responds

distant tulip
#

the way i see it, i am fine with anyone seeing the code and learning from it, just not straight up copy it to a similar addon and call it a day

prime zenith
#

What if they copy it to use it in there addon and credit you for the features it added

#

I still wish i could cancel vanillas hit censor its so weird when fighting and your attack misses due to my coding logic yet you still show as damaging it

unique acorn
prime zenith
#

I learned cause of my college classes

cinder shadow
#

they have no obligation to respond and confirm whether you can or can't use their work

oak lynx
terse pulsar
#

Jaly its working?

prime zenith
#

Try catch is debug handling and a very useful tool in development 1 of the first things i learned in college a good code aftually ends up with more tests and tries then actual code if you never use it youd slack at making any real software cause once it breaks and it will you will be left lost in potentuslly millions of lines if code unsure where the problem is

cinder shadow
#

skill issue

prime zenith
#

Nope try getting hired in software dev with that attitude

Try debugging millions of lines of code with no try catch

Im in college for this

unique acorn
prime zenith
#

Try catch is so you can find the issue

unique acorn
#

and it also is used to hide the issue

#

🙂

prime zenith
#

It doesnt fix the issue

#

Nope it lets you see what isnt working

#

By throwing the appropriate error

wary edge
cinder shadow
prime zenith
#

See if code fails at some point errors dont always show you what failed try catch will throw the error that you put into it so you know exactly what broke

#

The idea is to ensure any errors your code has you can find out exactly what failed when you end up with over a million lines of code that becomes very importaint your addons may not hit that point but real software

Minecraft estimates at 1.8 million lines of code

cinder shadow
#

I understand coding practices, I have no reason to use try catch for what I'm doing

#

If anything it gets used more often in scripting to prevent content log errors from showing

#

which are already catching errors

prime zenith
#

Its used in debugging massive codes when code gets big those normal errors become less helpful

prime zenith
#

can someone tell me why the healthdisplay var is 3 charecters higher then its supposed to be some reason its 19 chars but its padded to 16 why ```function getHealthDisplay(player) {
let minhealth = scoreboardSet(player, "minhealth");
let maxhealth = scoreboardSet(player, "maxhealth");

let display = `HP: ${minhealth}/${maxhealth}`;

// Ensure it is exactly 16 characters for consistency
if (display.length < 16) {
    display = display.padEnd(16, ' ');
} else if (display.length > 16) {
    display = display.slice(0, 16);
}

return display;

}

function showHealthTitle(player) {
const healthDisplay = getHealthDisplay(player);

// ✅ Correct way to set the title without commands
player.onScreenDisplay.setTitle(`§4${healthDisplay}test`);

}``` im guessing theres 1 thing im missing

#

i mean its not game breaking as the split title works just fine set to 19 i just dont get where the 3 chars are comming from

solar dagger
#

do dynamicProperties save even after the world closes?

solar dagger
cinder shadow
#

I'm not sure if I'm understanding

prime zenith
#

basicually i have the code set to pad the variable display to 16 charecters

#

however for split to work i need to set it to 19 charecters

dim tusk
prime zenith
#

thats 2 tho not 3

cinder shadow
#

the $ also gets counted

prime zenith
#

wait what

#

the game sees $ as a charecter even tho its intended for variables and is ignored in all other context

distant tulip
#

It doesn't count

prime zenith
#

i thoght so

#

id find it really weird if it did

cinder shadow
#

it doesn't?

#

I had this problem a few days ago but I don't remember what I did for it

dim tusk
#

That doesn't make sense to be counted since it's only for variables and it won't ever be a part of storing.

distant tulip
#

;compile js

console.log(`123${4}`.length )
spiral umbraBOT
#
Critical error:

Wandbox replied with: 500 Internal Server Error
This could mean WandBox is experiencing an outage, or a network connection error has occured

solar dagger
#

Heh

cinder shadow
#
const he = 1;
                let string = `§4${he}`
                world.sendMessage(`STRING: ${string} STRING LENGTH: ${string.length}`)```
dim tusk
#

I can't find anything more than 3 unless it's in the scoreboards value

cinder shadow
#

it's definitely counting the $

dim tusk
#

Plus this finest guy

prisma shard
distant tulip
wary edge
cinder shadow
#

woops I read it wrong

dim tusk
#
let str = `c${x}`;
console.log(str.length);```

This one returns 2, which is correct.
distant tulip
#

Depend on the value of x

dim tusk
chilly moth
#

how do I make a form which can change entity name or name tag renaming

cinder shadow
#

kinda need to see what it's outputting to actually find out what's wrong, so showing what's happening is pretty important

dim tusk
#

Need context how you opening the form.

chilly moth
#

on script

#

without res

#

¿

dim tusk
prisma shard
chilly moth
#

@dim tusk item

prime zenith
distant tulip
#

Interact with entity is the bes option here

prime zenith
#

so if you do count 3 what is the third 1

dim tusk
#

Yeah just use playerinteractwithentity

#

tho as I said need more context.

dim tusk
prime zenith
#

i can understand color code counting 2 but the end of the var totals 19

#

because split 1 takes 19 to before it starts but if the var is padded to 16 and color code is 2 thats only 18

cinder shadow
#

can you please show a screenshot of the length 19 output

chilly moth
# dim tusk Then get entity first, yu will use textField? Either way it doesn't matter you s...
    const { player, initialSpawn } = data;
    if (initialSpawn === true) {
        if (player.getDynamicProperty("savedNameTag")) {
            player.nameTag = player.getDynamicProperty("savedNameTag");
        }
    }
})
                    function editPlayerNameForm(player, target) {
                        const editPlayerName = new ModalFormData();
                        editPlayerName.title("")
                        editPlayerName.textField("", "§7Name")
                        editPlayerName.toggle("Nick Enabled", true)
                        editPlayerName.submitButton("Submit")
                        editPlayerName.show(player).then((data) => {
                            if (data.canceled !== true) {
                                const result = data.formValues;
                                page2(target, player)
                                if (result[1] === true) {
                                    target.nameTag = result[0];
                                    target.setDynamicProperty("savedNameTag", result[0])
                                }
                                else
                                target.nameTag = target.name
                            }
                        })}

this is for player

prime zenith
#

here ill show a ss but i may need to explain a few things

distant tulip
#
import { world } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";

world.afterEvents.playerInteractWithEntity.subscribe(event => {
    const entity = event.target;
    if (!entity || !entity.isValid()) return;

    new ModalFormData()
        .title("rename entity")
        .textField("enter new name:", "name", entity.nameTag ?? "")
        .show(event.player)
        .then(response => {
            if (!response.canceled) {
                const newName = response.formValues[0]?.trim();
                if (newName) entity.nameTag = newName;
            }
        });
});
dim tusk
#

I mean itself, not interacting with them.

distant tulip
#

Uh... Yeah that won't work for you to rename your self

dim tusk
#

Meh, just sue this as reference

thorn flicker
#

you can change nametags of players.

distant tulip
#

Yep

prime zenith
#

above the action bar is thge var thsats padded to 16 test starts immediatly after and goes to split 1 to get that positioned correctly i had to get split 1 to start at 19 charecters

#

padding the var makes the var 16 chars long by adding spaces the spaces are invisible

dim tusk
# distant tulip ```js import { world } from "@minecraft/server"; import { ModalFormData } from "...
world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
  if (initialSpawn) {
    const savedNameTag = player.getDynamicProperty('savedNameTag');
    if (savedNameTag) player.nameTag = savedNameTag;
  }
});

function editPlayerNameForm(player, target) {
  const editPlayerName = new ModalFormData();
      .title(' Edit Player Name');
      .textField(' Enter Name', '§7Name');
      .toggle('Nick Enabled', true);

  editPlayerName.show(player).then(({ formValues, canceled }) => {
    if (!canceled) {
      const [newName, nickEnabled] = formValues;
      if (nickEnabled) {
        target.nameTag = newName;
        target.setDynamicProperty('savedNameTag', newName);
      } else target.nameTag = target.name;
    }
  });
}```
#

Ohh shit wrong reply

#

Mbmb

#

@chilly moth

cinder shadow
#

I have no idea what you just typed

chilly moth
distant tulip
#

pffft

dim tusk
cinder shadow
#

not you

dim tusk
#

Ohh mbmb

cinder shadow
#

assuming max is 100 already

prime zenith
#

the values of min and max are put into the padded var before its padded there for its irrelevant

#

see if min was 1000 max was 1000 it would add less spaces to keep it at 16

dim tusk
# chilly moth I am looking to rename entity
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
  if (source?.typeId !== 'minecraft:player') return;

  if (itemStack?.typeId === 'minecraft:stick') system.run(() => editPlayerNameForm(source, source) );
});```
prime zenith
#

and i tested by adding more chars to var split 1 stays so its padding correctly

#

i mean this in no way breaks anything id just like to know what outside the var is counted as a space

cinder shadow
#

couldn't really tell you, I didn't really change anything and mine is returning the correct length

fallow rivet
#

Hello

cinder shadow
#

only adding 2

fallow rivet
prisma shard
fallow rivet
prisma shard
#

🐨

cunning canyon
#

Hello guys!

#

Can I save a JS variable to memory? 🧐

#

I want to store an array of items that I don't want to lose if the player quits the game.

dim tusk
#

Check the #1067535712372654091 for saving ItemStack

prime zenith
#

How chatGPT just numbered the things in its post concerns me

It numbered them 1 2 3 3 4 5 4 6

cunning canyon
past coyote
#
async function loadIslandStructure(origin) {
    const structureName = "island";
    const overworld = world.getDimension("overworld");

    if (!overworld) {
        console.error("Failed to retrieve the overworld dimension.");
        return;
    }

    try {
        // Debug: Log available structures
        const structureIds = world.structureManager.getWorldStructureIds();
        console.log(`Available structure IDs: ${JSON.stringify(structureIds)}`);

        if (!structureIds.includes(structureName)) {
            console.error(`Structure ${structureName} not found in world.`);
            return;
        }

        console.log(`Attempting to load structure: ${structureName} at X: ${origin.x}, Z: ${origin.z}`);

        await world.structureManager.place(structureName, overworld, origin, {
            rotation: "0_degrees",
            mirror: "none",
            animationMode: "block_by_block",
            integrity: 1.0,
            seed: 0,
        });

        console.log(`Island structure loaded at X: ${origin.x}, Z: ${origin.z}`);
    } catch (error) {
        console.error(`Failed to load island structure at X: ${origin.x}, Z: ${origin.z}:`, error);
        throw error;
    }
}```

How do I load a structure from the behaviours "structures" folder?
dim tusk
past coyote
#

I guess I'm loading from the world

#

how do I load a structure from the BP though?

dim tusk
past coyote
#

oh brother. alright then!

#

thanks for the help

hexed fox
dim tusk
hexed fox
#

I want to run this emotes.

dim tusk
wary edge
hexed fox
hexed fox
dim tusk
#

If you mean that animations.

hexed fox
#

I can send the player to this form from Mojang when the player click to my form button?

valid ice
#

Maybe it can’t

hexed fox
# wary edge You cant.

I can send the player to this form from Mojang when the player click to my form button?

wary edge
#

I have no idea what that means.

hexed fox
#

Not run the emotes, run this form from Mojang

wary edge
#

What does that mean?

valid ice
#

You cannot do that

hexed fox
# wary edge What does that mean?

Is it possible to make it so that when the player presses the button, he gets this form with permissions from Mojang? That is, the call form is created by Mojang with support.

valid ice
hexed fox
#

If no, are there any alternatives for this?

valid ice
#

Recreate the emote menu using json ui hollow

hexed fox
wary edge
hexed fox
#

oh

#

I asked because I saw a squid game map before in 2021-2022 and you could change the skin there.

dim tusk
dim tusk
valid ice
#

e.g. a squid game suit over top of the player skin

#

That is completely unrelated to scripts, though, and all within #1067869590400544869

oak lynx
#

What is the lore reason behind this being useless returning only block locations

dim tusk
#

Then do getBlocks()

#

It uses BlockVolume

oak lynx
#

I just don't understand why there aren't any functions to get an area of blocks

dim tusk
#

wdym?

#

saying it's useless and not knowing the full use is the useless one.

#

I'm not saying you btw but the function itself lmfao

oak lynx
distant tulip
#

kinda agree tbh
you would assume getBlocks get you an array of blocks 🤷‍♂️

distant tulip
dim tusk
#

Ya.

#

The filter exists too

distant tulip
#

it is only useful because of the allowUnloadedChunks and BlockFilter

oak lynx
#

After days of thinking about this

#

I will just save the player island in layers

#

Then when they build/destroy stuff I will just save just the layer

#

Can't wait for mojang to release a function that will make all of this brainstorming useless once I actually make it work

dim tusk
#

I used velocity before getMovementVector() exists

oak lynx
#

Damn

#

if mojang wants people to use bds they need to add more features for server developers

#

We need more server-net and server-admin features

unique acorn
#

they should make it so you can read what's inside a packet

#

that'll be very useful

oak lynx
#

The most useful feature would be a useful version of get blocks

dim tusk
oak lynx
#

I am not missing much stuff tbh

#

Like people complain about lack of beforeHitEvent but I just modified all mob jsons 🗣️🗣️

dim tusk
oak lynx
#

We can do biomedetection unless I am dumb

dim tusk
#

It's based on bounding box.

#

So even if you're in the biome if the bounding box didn't reach it, it won't work.

#

Taking an account using one function alone takes a lot of ticks so doing a lot for EACH player is already bad.

#

That's why people do use another entity and manually put biomes

oak lynx
#

I don't have to deal with stuff like this thankfully

dim tusk
#

And tp that mob to player for detection and BLA BLA BLA

oak lynx
dim tusk
#

Me in json UI be like:

oak lynx
#

I mean the api situation is much better than in like 2022

#

I remember pre dynamic property days

#

Scary stuff

solar dagger
#

who has a block templates?

wary edge
shy leaf
#

still waiting for beforeEvents entityHurt

shy leaf
#

can server tick be slowed down or sped up? im thinking of switching from Date.now() to server tick for precise tick check but im wondering if server lag can put server tick behind

dim tusk
#
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const { getComponent, inputInfo: { getMovementVector } } = player;

    const movementVector = getMovementVector.call(player.inputInfo);
    const health = getComponent.call(player, 'health');

    console.error(JSON.stringify(movementVector), health.currentValue);
  }
});```

This is getting out of hand.
dim tusk
# shy leaf bro wtf

I don't use it but I just discovered the use of .call() and .bind() yesterday and I said... Hmm why not?

dim tusk
# shy leaf bro wtf

Same goes to thisjs world.beforeEvents.chatSend.subscribe((ev, { message, sender } = ev) => { if (message === 'curse') ev.cancel = true; });

shy leaf
#

this is cursed

dim tusk
#

I also used that chatsend way or other thing when canceling events.

#

but if not I just destructure it properly ({ message, sender })

pale terrace
#

its possible to get a list of all custom entities from my addon?

thorn flicker
#

and filter it out by your namespace

#

EntityTypes.getAll().filter(e => e.id.includes('namespace:'))

pale terrace
prime zenith
#

someone please tell me why im getting these errors the addons blank that i tested except for the console warn is this a feature mojang themselves broke or something idk its annoying i want it gone

#

ima get sa fresh 1

#

[Recipes][error]-recipes/reducer_quartz_pillar.json | minecraft:quartz_pillar | Material Reduction recipe duplicates a previously registered recipe with input minecraft:quartz_pillar. Skipping recipe.

[Recipes][error]-recipes/reducer_smooth_quartz.json | minecraft:smooth_quartz | Material Reduction recipe duplicates a previously registered recipe with input minecraft:smooth_quartz. Skipping recipe.

[Scripting][warning]-im alive bitch```
dim tusk
#

Addons pls

slow walrus
#

not something you did

prime zenith
#

I want it gone tho why mojang its annoying

dim tusk
#

-# json ui

solar dagger
#

Best way to obtain the Waters surface level no matter the entity position?

solar dagger
#

Where water meets air

#

For a body of water

prime zenith
#

Water meets air all over cause fir every 2 hydrogen theres 1 oxygen 😛

solar dagger
dim tusk
solar dagger
#

It can be the ocean of the world but I'm using an entity to get that y level

dim tusk
solar dagger
#

Yikes

#

Uh I'll look more into it and see if there's an alternative

jolly citrus
#

Is it possible to detect the type of input device a player is using

dim tusk
#
const { inputInfo } = player;
const device = inputInfo.lastInputModeUsed;```
prisma shard
past coyote
#
        if (world.beforeEvents.entityHitEntity) {
            world.beforeEvents.entityHitEntity.subscribe((event) => {
                const { damagingEntity, hitEntity } = event;
                if (damagingEntity.typeId === "minecraft:player" && hitEntity.typeId === "minecraft:player") {
                    const island = getIslandAt(hitEntity.location.x, hitEntity.location.z);
                    if (island && !hasPermission(damagingEntity.name, island, "attackPlayers")) {
                        event.cancel = true;
                        damagingEntity.sendMessage("You do not have permission to attack players here.");
                    }
                }
            });``` 

This doesn't work?
#

it says world.beforeEvents.entityHitEntity is undefined

jolly citrus
past coyote
#

Yep

jolly citrus
#

Or stable

jolly citrus
#

Idk

past coyote
#
        {
            "module_name": "@minecraft/server",
            "version": "1.18.0-beta"
        },```
jolly citrus
past coyote
#

I did some research in the discord, seems like you cant cancel entity damage

jolly citrus
#

Ctrl + /

#

Ctrl + S

jolly citrus
#

Ou can’t

#

OH

#

right

#

Bro

#

its because

#

you’re indexing it on beforeEvents

past coyote
#

Yeah people were saying you have to use resistance or something

jolly citrus
#

It only exists on afterEvents

jolly citrus
#

world.afterEvents.entityHitEntity

past coyote
#

well if I do it after, its kinda null though right? because after means the damage is gonna go through

jolly citrus
#

in player.json

#

n create a custom hit system

#

its better anyway

past coyote
#

I cant though, because this is for all entities

#

Someone said you could do something similar with a super high resistance effect

#

but how do I apply that to the entity on the same tick or before an attack?

jolly citrus
past coyote
#

😭

jolly citrus
#

afterevents run after the packet has already been received

#

they run after the tick it was sent on, not on the tick

#

@past coyote

past coyote
#

ah

jolly citrus
#

you could use a damage controller that prevents the player itself

#

from damaging

#

like player has tag

past coyote
#

thats too messy

jolly citrus
#

then add/remove the tag whenever

jolly citrus
#

it’s the most straightforward way ever what ..

past coyote
#

its just annoying, like I can do this with server plugins but the api can't do it?

jolly citrus
#

server without software means no server side functionality all in all

#

they can customize whatever they want

#

but script api is built on top of vanilla mc

#

vanilla mc behaves differently

#

they chose to handle hit events differently from vanilla

#

you need to get used to the fact that half the things u wanna do in script api will require workarounds @past coyote

#

if u dont want that just switch to server software instead

past coyote
#

yeah its just a little annoying

jolly citrus
#

script api works at a much higher level

#

than server sofrware does

#

server software can do almost anything they’d like to the server

past coyote
#

I understand.

Alright, so how do we make this work with the player.json?

jolly citrus
#

ask in entities

past coyote
#

Will do

jolly citrus
#

#1067869022273667152

past coyote
#

thanks for the help man

jolly citrus
#

yw

shy leaf
#

this will disable dealing damages entirely

#

theres also another way though, its in bedrock addons wiki iirc

sage sparrow
halcyon phoenix
#

what is the easiest way to set a block with air without using commands?

halcyon phoenix
#

Thanks

#

what's the difference between Type and TypId?

subtle cove
#

type is an object instance
while typeId is a string

#

its just how the api is oriented,
type is prob has the shorter code integration
string is commonly used for mapping

#

hypothetically speaking

halcyon phoenix
#

I see thanksss

next fjord
#

hello :::)

slim forum
#

@next fjord

world.beforeEvents.worldInitialize.subscribe(event => {
  event.blockComponentRegistry.registerCustomComponent('hycomponent:tree_gradient_leaves', {
    onRandomTick: ev => {
      // Top = 2
      // Top MIddle = 1
      // Middle (Default) = 0
      // Bottom = 3
      const block = ev.block;
      if (block.permutation.getState("hycraft:gradient") > 0) return;
      const blockX = block.location.x;
      const blockY = block.location.y;
      const blockZ = block.location.z;
      const playerInRange = world.getAllPlayers().some(player => {
        const playerX = player.location.x;
        const playerY = player.location.y;
        const playerZ = player.location.z;
        const distance = Math.floor(Math.sqrt(
          Math.pow(blockX - playerX, 2) +
          Math.pow(blockY - playerY, 2) +
          Math.pow(blockZ - playerZ, 2)
        ));
        return distance <= 32;
      });
      let extraOperations = world.scoreboard.getObjective("extraoprtn").getScore(worldController);
      const extraOperationsChance = Math.floor(Math.random() * ((64 - extraOperations) + 1));
      if (extraOperations > 0 && extraOperationsChance == 0) {
        if (playerInRange) {
          let applyTopGradient;
          let applyTopMiddleGradient;
          let applybottomGradient;
          applyTopGradient = false;
          applyTopMiddleGradient = false;
          applybottomGradient = false;
          system.runTimeout(() => {// Top Gradient
            let x = block.location.x;
            let y = block.location.y + 1;
            let z = block.location.z;
            const blockLocation = {
              x,
              y,
              z
            };
            const topBlock = world.getDimension(block.dimension.id).getBlock(blockLocation);
            if (topBlock.typeId === 'minecraft:air') applyTopGradient = true;
            if (topBlock.typeId != 'minecraft:air' && topBlock.typeId === block.typeId && topBlock.permutation.getState("hycraft:gradient") == 2) applyTopMiddleGradient = true;
          }, 1);
          system.runTimeout(() => { // Bottom Gradient
            let x = block.location.x;
            let y = block.location.y - 1;
            let z = block.location.z;
            const blockLocation = {
              x,
              y,
              z
            };
            const bottomBlock = world.getDimension(block.dimension.id).getBlock(blockLocation);
            if (applyTopGradient === false && applyTopMiddleGradient === false && bottomBlock.typeId != block.typeId) applybottomGradient = true;
            if (applyTopGradient === true) applybottomGradient = false;
            if (applyTopMiddleGradient === true) applybottomGradient = false;
          }, 2);
          system.runTimeout(() => {
            if (applyTopGradient === true) block.setPermutation(block.permutation.withState("hycraft:gradient", 2));
            if (applyTopMiddleGradient === true) block.setPermutation(block.permutation.withState("hycraft:gradient", 1));
            if (applybottomGradient === true) block.setPermutation(block.permutation.withState("hycraft:gradient", 3));
          }, 3);
        }
      }
    }
  });
#

This made my tree gradient automaticaly, but I use only on tree buildings

#

During tree building process

#

Its an old code, so, sorry for bad organization

next fjord
#

So your trees are not structures but tree_features?

slim forum
#

Structure

slim forum
next fjord
#

ok

slim forum
#

To get the gradient

slim forum
next fjord
#

Thank you very much for explaining it to me, I'll try and see how it goes.

slim forum
#

Perfect

prisma shard
#

check if the slot is not undefined add slot there

#

you have to iterate though all slots in the inv

distant tulip
#

just use addItem

dim tusk
#

addItem().

woven loom
#

nice stuff

dim tusk
#

Quick one, don't put the inventory component setting item in the system.run(), only put the addItem in the system run.

distant tulip
#

also, if the inv is full, add item return the left amount of items that didn't get added

dim tusk
#
function giveItem(player, itemId, amount, name = undefined) {
  const { container } = player.getComponent('inventory');

  if (container.emptySlotsCount === 0) return;

  const itemStack = new ItemStack(itemId, amount);
  itemStack.nameTag = '§r' + name;

  system.run(() => container.addItem(itemStack) );
}```
distant tulip
#

why the system run

dim tusk
#

This one right here I just copied it.

past coyote
#
import { world, DynamicPropertiesDefinition } from "@minecraft/server";  

world.beforeEvents.worldInitialize.subscribe((event) => {
    const def = new DynamicPropertiesDefinition();
    def.defineString("playerData", 1024);
    event.propertyRegistry.registerEntityTypeDynamicProperties(def, "minecraft:player");
});```
#

Is this not how you do this?

#

I found some examples here and it seemed like this was right

wary edge
past coyote
prime zenith
#

Is tgere a script api way to load a structure

wary edge
prime zenith
#

Whats the syntax may i ask or a leatn article on it

prime zenith
#

Is it possible by any means to make a grid based button form or no

valid ice
#

Only with Jason ui

fast lark
#

yo

#

someoe who knows ts

#

interface Home {
name: string;
location: Vector3;
dimension: string;
}

interface Button {
text: string;
icon?: string;
callback?: Function;
}

#

how can i write this in js

dim tusk
wary edge
fast lark
#

then how can i "translate" this to js

#

idk how to say that

#

but yh

wary edge
#

Again, JS doesn't have interfaces.

#

It literally transpiles into nothing.

fast lark
#

k

#

thx

dim tusk
fast lark
wary edge
dim tusk
fast lark
#

but i only know js

dim tusk
distant tulip
fast lark
fast lark
#

definition of compile

#

ill just google it

distant tulip
#

Same 🤷‍♂️

fast lark
#

version of math module

#

It's not a module. You'll need to separetly install it then bundle it with your code.

#

how

#

im confused

somber cedar
dim tusk
thorn flicker
#

either way, it'll work.

pale terrace
thorn flicker
prime zenith
#

posted a complex question

prime zenith
#

can i get help

strange sundial
#

guys what problem {: ?
[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at initialize (main.js:13)
at <anonymous> (main.js:187)
Even when I use the compass the forms doesn't work.

terse pulsar
valid ice
#

Also don’t use 1.3.0 for server- use 1.17.0. It’s the latest stable version

terse pulsar
#

Anyone know how can i show a scoreboard on screen constantly ?

#

Like HP: 40 MP: 20

valid ice
#

system.runInterval

terse pulsar
strange sundial
valid ice
terse pulsar
#

But i need a player to use the title

valid ice
dim tusk
terse pulsar
valid ice
warped kelp
#

Is there a way to test for if a specific weapon/item kills an entity?

dim tusk
prime zenith
#

Can anyone help i posted the question

prime zenith
#

What is scripts method to tp player

cold grove
#

All is documented

drifting ravenBOT
prime zenith
#
    const totalCities = world.getDynamicProperty("totalCities") || 0;

    if (totalCities === 0) {
        player.sendMessage("⚠️ No cities found.");
        return;
    }

    // ✅ Pick a random city ID
    const randomCityId = Math.floor(Math.random() * totalCities) + 1;
    let cityData = world.getDynamicProperty(`city_${randomCityId}`);

    if (!cityData) {
        player.sendMessage(`⚠️ City ID ${randomCityId} not found.`);
        return;
    }

    if (typeof cityData === "string") {
        cityData = JSON.parse(cityData);
    }

    // ✅ Get city's original location
    const originalX = cityData.location.x;
    const originalY = cityData.location.y;
    const originalZ = cityData.location.z;

    // ✅ Add (13, 3, 51) to coordinates
    const newX = originalX + 13;
    const newY = originalY + 3;
    const newZ = originalZ + 51;

    // ✅ Teleport player
    player.teleport(newX, newY, newZ);

    player.sendMessage(`✅ Teleported to City ID ${randomCityId} at (${newX}, ${newY}, ${newZ})`);
}``` throws an error
#

so im assuming im writing it wrong

#

unless how its getting city data is wrong

#
    const totalCities = world.getDynamicProperty("totalCities") || 0;

    if (totalCities === 0) {
        player.sendMessage("⚠️ No cities found.");
        return;
    }

    // ✅ Pick a random city ID
    const randomCityId = Math.floor(Math.random() * totalCities) + 1;
    let cityData = world.getDynamicProperty(`city_${randomCityId}`);

    if (!cityData) {
        player.sendMessage(`⚠️ City ID ${randomCityId} not found.`);
        return;
    }

    if (typeof cityData === "string") {
        cityData = JSON.parse(cityData);
    }

    // ✅ Extract x, y, z from cityData.location
    const { x: originalX, y: originalY, z: originalZ } = cityData.location;

    // ✅ Add (13, 3, 51) to coordinates
    const newX = originalX + 13;
    const newY = originalY + 3;
    const newZ = originalZ + 51;

    // ✅ Get the Overworld dimension
    const overworld = world.getDimension("overworld");

    // ✅ Teleport the player using extracted values
    player.teleport(newX, newY, newZ, overworld);

    player.sendMessage(`✅ Teleported to City ID ${randomCityId} at (${newX}, ${newY}, ${newZ})`);
}``` i cant get this to work at all
#

Well i know the coords are correct but the teleport isnt working

dim tusk
#

Player.teleport({ x: 0, y: 0, z: 0 }, { dimension: overworld })

prime zenith
#

I cant do x:0 it has to use that variable

#

but ill try that with var

#
    const totalCities = world.getDynamicProperty("totalCities") || 0;

    if (totalCities === 0) {
        player.sendMessage("⚠️ No cities found.");
        return;
    }

    // ✅ Pick a random city ID
    const randomCityId = Math.floor(Math.random() * totalCities) + 1;
    let cityData = world.getDynamicProperty(`city_${randomCityId}`);

    if (!cityData) {
        player.sendMessage(`⚠️ City ID ${randomCityId} not found.`);
        return;
    }

    if (typeof cityData === "string") {
        cityData = JSON.parse(cityData);
    }

    // ✅ Extract x, y, z from cityData.location
    const { x: originalX, y: originalY, z: originalZ } = cityData.location;

    // ✅ Add (13, 3, 51) to coordinates
    const newX = originalX + 13;
    const newY = originalY + 3;
    const newZ = originalZ + 51;

    // ✅ Get the Overworld dimension
    const overworld = world.getDimension("overworld");
    console.warn(newX, newY, newZ)
    // ✅ Teleport the player using extracted values
    player.teleport({ x: newX, y: newY, z: newZ }, { dimension: overworld });

    player.sendMessage(`✅ Teleported to City ID ${randomCityId} at (${newX}, ${newY}, ${newZ})`);
}
``` still fails
prime zenith
#

Do i req to give manifest capibiliries to teloport it says entity lacks permission

#

Wtf sm i missing

humble lintel
#
system.run(()=>{/**code**/});
prime zenith
#

Its saying lacking permission how will that fix it

humble lintel
#

it gives u higher perms

#

ur probably running ur code on read mode

#

which si the default

#

if u still get permission issues after using that then idk what's wrong

prime zenith
#

ill try but how do i not run code on read only wouldnt other stuff fail if it was read only

humble lintel
#

no only some are i beleive

dim tusk
#

you use beforeEvents?

humble lintel
#

if iget p[ermission error i just use system.run

dim tusk
#

system.run(() => {});

humble lintel
#

if it works for me it works i dont change

dim tusk
#

so yeah lemme explain it to you, since you're dealing beforeEvents means before it happens, you can't modify the world, so the purpose of system.run is to run the thing in the next tick, to escape the read-only mode, tho it's not just system.run only you can use anything as long as it happens next tick not the same tick...

thorn flicker
prime zenith
#

Ill never understand why but it worked

thorn flicker
pseudo timber
pseudo timber
prime zenith
#

Thanks well the good news is this means i can pull the location from the city_id woohoo

dim tusk
pseudo timber
#

god dam it

dim tusk
pseudo timber
#

stupid mc

#

i go cry now

thorn flicker
pseudo timber
thorn flicker
#

calling the mojangsters stupid?

pseudo timber
#

everything

dim tusk
prime zenith
#

Is there a way to take coords from 2 corners and make it so no blocks can be placed or broken within a certain radius of it using script

prime zenith
#

What do you do once you already have the coords then these docs arent as easy to read snd transparrent as you think they are

random flint
prime zenith
#

So what would the full syntax be to make an area whithin the coords fully protected

random flint
# prime zenith So what would the full syntax be to make an area whithin the coords fully protec...
function inBoundary(pos1, pos2, target) {
  const minX = Math.min(pos1.x, pos2.x);
  const maxX = Math.max(pos1.x, pos2.x);
  const minY = Math.min(pos1.y, pos2.y);
  const maxY = Math.max(pos1.y, pos2.y);
  const minZ = Math.min(pos1.z, pos2.z);
  const maxZ = Math.max(pos1.z, pos2.z);

  return (
    target.x >= minX &&
    target.x <= maxX &&
    target.y >= minY &&
    target.y <= maxY &&
    target.z >= minZ &&
    target.z <= maxZ
  );
}

AI simplified ^

Mine:

function inBoundary(pos1,pos2,target) {
  const [xPos1,xPos2] = pos1.x < pos2.x ? [pos1.x,pos2.x] : [pos2.x,pos1.x];
  const [yPos1,yPos2] = pos1.y < pos2.y ? [pos1.y,pos2.y] : [pos2.y,pos1.y];
  const [zPos1,zPos2] = pos1.z < pos2.z ? [pos1.z,pos2.z] : [pos2.z,pos1.z];
  
  if (xPos1 <= target.x && target.x <= xPos2)
  if (yPos1 <= target.y && target.y <= yPos2)
  if (zPos1 <= target.z && target.z <= zPos2) return true
  else return false
}
prime zenith
#

How does that keep ppl from breaking or placing blocks

random flint
#

It's a function that detects if the location is within your protected area.

It returns Boolean.

Cancel the playerBreak event if its true

prime zenith
#

Ir do i run that threw a before pkayer place block event

#

Can break block event get the blocks location

random flint
#
world.beforeEvents.playerBreakBlock.subscribe((evd)=>{
    const { block } = evd;
    //retreive protected regions as pos1 & pos2
    if (inBoundary(pos1,pos2,block.location) { evd.cancel = true; return; }

    //rest of the code outside protected region
})

.

prime zenith
#

Ok ty

random flint
#

It's box shaped btw

prime zenith
#

Wait so not rextangle shaped?

random flint
#

you want the sphere one?

prime zenith
#

No

random flint
prime zenith
#

I mix up box and square

random flint
prime zenith
#

While i wait for stuff on my rpg im making an rts that is 99.9% just dynamic property manipulation lol

#

Ill need to do some more ligics as ill need to set a for loop to create hundreds of these

#

Its actually not the whole area just the structure

#

Or well alot of structures

random flint
#

That sounds troublesome, good luck

prime zenith
#

Probobly not that hard btw does after worldinitualize mean only 1 time per world gen

#

Im off to bed tho nighty night let the bed bugs eat you alive

random flint
dim tusk
#
world.beforeEvents.playerBreakBlock.subscribe((ev, { block, } = ev) => {
  const volume = new BlockVolume({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 });
  if (volume.isInside(block.location)) ev.cancel = true;
});```
random flint
#

-# I must be a genius to have accidentally forgotten such feature

dim tusk
dim tusk
dim tusk
prime zenith
#

Coddy yours is harder for me to figure out how to plug into mine tho

dim tusk
#

Also compared to gega it's better, faster and built-in version

#

overall smaller.

prime zenith
#

I have a dynamic property i need to apply theres used a function yours is just in the event

dim tusk
#

make a function 🤷🤷

random flint
#

You can compile those dynamicProperties at script loads into BlockVolume

dim tusk
#

It's not that complicated tbh

#

They work EXACTLY the same

prime zenith
#

I need to loop threw every city_id to get its location add to x y and z

dim tusk
random flint
#

Does BlockVolume throw errors when dealing unloaded chunk?
-# Doesn't matter, you can't break block in unloaded chunk anyway

prime zenith
#

As i said point 1 is obtained in every city_id

#

Thats irrelevant when position 1 is the location in the city_id property btw id is numerice city_1 city_2

dim tusk
random flint
prime zenith
#

You need to know where the structure is

dim tusk
#
function isLocationInsideVolume(location, point1, point2) {
  const volume = new BlockVolume(point1, point2);
  return volume.isInside(location);
}

world.beforeEvents.playerBreakBlock.subscribe((ev, { block, } = ev) => {
  const point1 = { x: 0, y: 0, z: 0 };
  const point2 = { x: 10, y: 10, z: 10 };

  if (isLocationInsideVolume(block.location, point1, point2)) ev.cancel = true;
});
random flint
#

epic

prime zenith
#

I still need to set every structure to have a volume to check

random flint
#

Okay then add placeholder entities to your structure to act as marking points for those volume. Or anything that works

prime zenith
#

Why when looping threw the ids for there location and setting the box that way makes more sence and is easier

random flint
#

Have a good night sleep

prime zenith
#

I can get all the protected areas set at world load

random flint
#

Guys, how do I force a fishing bobber to hook to an entity? Especially when it already touches the floor/walls or water.

random flint
#

Plan B: teleporting abomination it is.

prime zenith
#

Not the abomination

#

Why am i still awake

random flint
#

Not sure. Maybe the device you're using causes the "There's a monster nearby."

dim tusk
#

-# sorry from tagg 🥺

prime zenith
#

Oh wait theres zombies outside my window oh well

prime zenith
#

So many ppl on earth forget to set spawn point before they die and never make it back to earth and by nany i mean all of them is spawn broken in reality

prisma shard
#

Can u detect if player hits air

shy leaf
#

does anyone have a function that checks if the entity is in rain?

shy leaf
#

i need a way to check if an entity is in rain

prisma shard
#

why check entity is in rain

shy leaf
#

impaling enchantment

prisma shard
#

if its rainin' the whole dimension is rainin'

prisma shard
#

@shy leaf

prisma shard
#

BRO

prisma shard
#

why you check a specefic entity for if he IS IN rain

shy leaf
#

ok can you tell me how trident's impaling and riptide works

prisma shard
#

so if you hit a drowned with impaling trident, he get more damage than normal trident

shy leaf
#

which is in java edition

#

now what about bedrock

prisma shard
shy leaf
#

you can say that i guess?

prisma shard
# shy leaf you can say that i guess?
  • check for if the trident has impaling lore
  • do entityHurt event
  • check for if a entity got hurt and the source is player
  • check if the mob is aquatic (e.g. drowned)
  • deal extra damage to the hit mob
shy leaf
#

impaling enchantment deals extra damage to mobs in water or in rain

#

in bedrock

prisma shard
# shy leaf ok can you tell me how trident's impaling and riptide works

And riptide enchantment throws the player when you shoot the trident.
so make the riptide enchantment,

  • you detect if its raining (u can use my function i sent)
  • check if the trident is in the mainhand, and if it has riptide lore
  • use player.applyKnockback() to throw the player and use player.getViewDirection()
shy leaf
#

dude

#

the

#

the enchantment doesnt work if youre not in rain

prisma shard
shy leaf
#

IN RAIN

#

if youre indoors or

#

if you have a solid block above your head