#Script API General

1 messages · Page 64 of 1

unique acorn
#

switch to stable, that's the only way

olive rapids
#

U can edit this and send me?

#

Pls

distant tulip
#

that just prove it is not yours

unique acorn
olive rapids
#

Ok

olive rapids
unique acorn
#

and if you use any beta stuff in your code, it will break

olive rapids
#

Hmmm ok

#

Thanks

prime zenith
#

Ive learned a possible way to make a grand exchange in minecraft im wondering if i should mske a standalone addon for that for ppl who want there own grand exchange in minecraft

neat hazel
#

How to launch a projectile when using an item?

dim tusk
# neat hazel How to launch a projectile when using an item?
const head = player.getHeadLocation();
const view = player.getViewDirection();

const entity = player.dimension.spawnEntity('minecraft:snowball', head);

const power = 2; // adjust how fast the projectile travel

const projectile = entity.getComponent('projectile');
projectile.owner = player;

projectile.shoot({ x: head.x + view.x * power, y: head.y + 0.1 + view.y * power, z: head.z + view.z * power });```
humble lintel
#

anyone know why ts throws this stupid error?

subtle cove
#

'string' isn't assignable to '(string) => Aform'

humble lintel
#

so i can't use strings?

#

im so confused

subtle cove
#

How're u using it

humble lintel
#

im making a custom form handler

#

class

#

with a constriuctor

#

wait i fixed the body

#

so dont midn that error

#

nvm it works now wtf

subtle cove
#

;-;

humble lintel
#

yes just because of the body it didnt work burh

prime zenith
#

I may beat ai with a binary stick soon can someone tell me how dynamic properties look and how you break them apart trying to learn

deep arrow
# humble lintel

Btw the buttons type shouldn't be optional since action forms require at minimum one button

dim tusk
deep arrow
dim tusk
deep arrow
#

Seems pointless tbh

#

But ig for just quick text displays

dim tusk
dim tusk
deep arrow
deep arrow
dim tusk
#

for you it's useless but for some people yes,

#

way better than MessageFormData lmao

deep arrow
#

Ig

#

I personally haven't had much use but i do understand others might

#

And having more freedom is nice

woven loom
#

what's up

dim tusk
woven loom
#

👋

deep arrow
#

How ya been

young swan
#

I knew something was going to happen XD

loud brook
#

Guys, is there a way I can make a gun shoot constantly without spamming right click?

#
world.afterEvents.itemStartUse.subscribe(data => {
    let player = data.source;
    let entity = player.dimension.spawnEntity('arrow', player.getHeadLocation())
    entity.getComponent('minecraft:projectile').shoot(player.getViewDirection())
  });
loud brook
dim tusk
#

When you do itemStartUse, store in a map the ID of the player, and in runtInterval do a shoot in itemStopUse where you delete the player.id

loud brook
#

i.e. constant shooting

dim tusk
#

I said the step to make what you want, hold right click will constantly shoot until you stop holding it.

loud brook
#

So basically, from what I understood

  1. Use ItemStartUse to start the shooting
  2. when the useDuration ends, itemStopUse will run
  3. Run itemStartUse again somehow
dim tusk
#

when you stop holding it the stopuse is triggered

loud brook
#

or is there a workaround for that

dim tusk
#

there's no workaround for your thing.

loud brook
dim tusk
loud brook
# dim tusk got a better idea?

No, the thing is that I have already managed to do that without scripts
but didn't like the eating noises. so tried attemping it through scripts

dim tusk
#

then no....

dim tusk
loud brook
loud brook
dim tusk
loud brook
#

That makes sense

dim tusk
#

Yes.

prime zenith
#

You know when this projects done ill probobly have better luck marketing it as a minecraft themed rpg private server and target players of rpg games rather then minecraft players lol

#

On another note grand echange is now half way done

dim tusk
#

dayum, it tooked me 3 weeks just to discover how to accurately check if the chest is opened.

#

before people say you can use afterEvents of playerinteractwithblock no you can't it will always return true even if the ui isn't shown or the chest doesn't have the open animation.

simple zodiac
#

isInUi enviromental sensor?

thorn flicker
#

not script api

wheat condor
#

sorry

thorn flicker
#

happens lol

prime zenith
#

My grand echange is so close to being done

random flint
#

Waiting for equipable's getEquipment() to be nonexclusive to the player.

turbid gulch
#

Guys I have one quick question, is it possible to have client side nametags?

lyric kestrel
#

As a first project I suggest making a script that auto-replaces crops when you right-click the crop

#

Not a good explanation tbh xD

random flint
lyric kestrel
random flint
#

Cave divers

humble lintel
unique acorn
jolly citrus
#

elaborate pls idk what that’s supposed to mean

#

do u mean ts transpile to js

unique acorn
past coyote
#

is it possible to detect if a player grabbed an item in their inventory/moved an item?

dim tusk
past coyote
#

would it be better to somehow check both cursor AND for changes if an item moved from one location to another in the inventory?

#

im trying to find a low performance cost way of doing this haha

#

maybe it would be better to just check if the item moved, and what item it was

#

no idea if that would work if you placed one item on top of another to swap them

dim tusk
valid ice
#

Inventory change event when SadChaton

past coyote
#

I guess i'll just have to compare changes manually somehow

valid ice
#

I think the best way would be to check inventory typeIds, slot, and amount for each (and detect when those change)

#

Not very performant, but then again what is?

valid ice
#

lol

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

let previousSlot = new Map();

const itemSounds = {
    "minecraft:stone": "dig.stone",
    "minecraft:dirt": "dig.grass",
    "minecraft:wood": "dig.wood",

};

// Function to play a sound
function playSound(player, sound) {
    console.log(`Attempting to play sound: ${sound} for player: ${player.name}`);
    player.playSound(sound, { pitch: 1.0, volume: 1.0 });
}


system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const currentSlot = player.selectedSlotIndex;
        const playerId = player.id;

        if (previousSlot.has(playerId) && previousSlot.get(playerId) !== currentSlot) {
            console.log(`Player ${player.name} changed slot from ${previousSlot.get(playerId)} to ${currentSlot}`);
            playSound(player, "hotbar_scroll"); // Play a sound when the slot changes
        }

        previousSlot.set(playerId, currentSlot);
    }
}, 1); 

world.beforeEvents.itemUse.subscribe((event) => {
    const player = event.source;
    const item = event.item;

    if (item && itemSounds[item.typeId]) {
        playSound(player, itemSounds[item.typeId]); // Play a sound based on the item type
    }
});

world.afterEvents.itemReleaseUse.subscribe((event) => {
    const player = event.source;
    const item = event.item;

    if (item && itemSounds[item.typeId]) {
        playSound(player, itemSounds[item.typeId]); // Play a sound based on the item type
    }
});```

(ignore how awful this is)
#

i'm basically trying to make sounds for moving items around in the inventory

#

as well as scrolling the hotbar etc...

cinder shadow
#

If you wanted to keep it consistent with vanilla, minecraft doesn't play any sounds if the item has the same typeId

#

But yeah this seems like a big performance draw for a small feature

past coyote
#

really fun to play with

cinder shadow
#

yeah I change my mind that's sick

past coyote
#

its uhh... well its pretty bad.

#

In java edition you can get an item/blocks category, like if its a wet block, if its stoney etc...

unique acorn
#

did someone do a typo or is it supposed to say "Tyring"

cinder shadow
#

You could change the arrays to be more categorical

past coyote
#

I have to add every item from the game though sadly

cinder shadow
#
const sounds = [
    {
        ids: [
            "minecraft:jukebox",
            "minecraft:loom"
        ],
        sound: "dig.wood"
    }
]``` it wouldn't make it any faster but at least save some of the copy pasting
past coyote
#

oh wow thats smart

#

duh!

cinder shadow
#

You should also add a default sound that will play if an id can't be found so that it covers any new blocks added in the future

#

at least until you change them

past coyote
#

I do 😉

cinder shadow
#

big brain

past coyote
#

its all the way at the bottom of the million line file I sent 😭

humble lintel
prime zenith
#

How many ppl you think could benefit if i made my grand exchange and bank part of my addon public

valid ice
#

At least 3, likely less than 2 million

#

Probably some number in between

prime zenith
valid ice
#

Interpret it as you will

prime zenith
#

I need opinions release or not to release

Also im eating that m$m guy

valid ice
prime zenith
valid ice
prime zenith
#

Burp

unique acorn
prime zenith
thorn ocean
#

Finally working on a calendar script! One that sets several events to the world on a daily, weekly, seasonal basis!

cinder shadow
neat hazel
dim tusk
#

I wanna check something.

night acorn
#

i had to use that earlier for raycasts

dim tusk
#

ok... Tho I'm not talking to you

#

but anyways.

#

then do js projectile.shoot({ x: view.x * 2, y: view.y * 2, z: view.z * 2 });

jolly citrus
#

is there any way i can detect piston or pressure plate usage & cancel it using the server-net module for example

dim tusk
jolly citrus
#

But

#

It can only listen for packets from the client to the server so

#

Im not sure tbh

#

I don’t think piston events come from the client ..

jolly citrus
dim tusk
#

Iirc that's the name

#

Tho for pressure plate the entity who stepped it is source

neat hazel
night acorn
#

would this be an ok way to kind of have a custom difficulty

export function shouldPerformAction() {
    if (world.getDynamicProperty("dsml:difficultyOffset") == undefined) {
        world.setDynamicProperty("dsml:difficultyOffset", 0);
    }

    if (randInt(0, 100) <= world.getDay() - world.getDynamicProperty("dsml:difficultyOffset")) {
        return true;
    }
    else {
        return false;
    }
}
#

so it gets progressivley harder as each day passes

#

but can be reset by adding the current day to the offset

neat hazel
dim tusk
#

this is already enough.

thorn flicker
dim tusk
thorn flicker
#

entityHurt beforeEvents with a damage property that can be reassigned...

prime zenith
#

Omg im an idiot this whole time i thought values in a dynamic property were read as value1_value2 i didnt kbow it could break it apart for you

dim tusk
#

Strings?

prime zenith
#

I thought value was read ssme as the key nvm im past it

night acorn
#

i just didnt want to send the whole file

neat hazel
dim tusk
prime zenith
#

I need a second person to help testing

prime zenith
#

Can you color an action form button or only the text

dim tusk
prime zenith
#

Well it needs conditions i wont worry about it

I have tested this ge as far as i can buy myself now i need to test it in multiplayer

fallen hearth
#

[Scripting][error]-Unhandled promise rejection: FormRejectError: Player quit before responding

#

help me?

#

When I leave my friend's world, I get this error

prime zenith
#

636 lines of code to get this dam thing to work but until i can get help testing edge cases i wont know 100% how well it works in mulyiplayer

cold grove
fallen hearth
cold grove
fallen hearth
#

[Scripting][error]-Unhandled promise rejection: FormRejectError: Player quit before responding

cold grove
#

Its working properly, just handle the error adding a .cacth() for the show method

subtle cove
#
form.show(player).then(res => {

}, err => console.error(err))
cold grove
dim tusk
subtle cove
#

or if (res.canceled) return

dim tusk
dim tusk
cold grove
#

Dyslexic and autistic naah im done heheheh

prime zenith
#

Anyone able to help me test how well my grand exchange works

fallen hearth
# subtle cove or `if (res.canceled) return`
export async function menuprincipal(player) {
  const form = new ActionFormData()
  form.title("§l§3Bleach")
  form.body("§cYoutube.com/§fPinhoPlays")
  form.button("STATUS", "textures/ui/menu/status.png")
  form.button("SKILLS", "textures/ui/menu/skills.png")

  const result = await form.show(player);
  if (result.canceled) return
  if (!result.canceled) {
    const actions = {
      0: stats,
      1: skills
    }
    const action = actions[result.selection];
    if (action) {
      action(player);
    }
  }
}
dim tusk
#

just do if (res.canceled) return no fancy things

#

make your life easier.

#
// ...

const result = await form.show(player);
if (result.canceled) return;

// ... codes ...```
dim tusk
fallen hearth
#

[Scripting][error]-Unhandled promise rejection: FormRejectError: Player quit before responding

valid ice
#

Valid crashout

dim tusk
dim tusk
valid ice
dim tusk
#

bruh.

dim tusk
#
export async function menuprincipal(player) {
  const menuOptions = [
    { label: 'STATUS', icon: 'textures/ui/menu/status.png', action: stats },
    { label: 'SKILLS', icon: 'textures/ui/menu/skills.png', action: skills }
  ];

  const form = new ActionFormData()
    .title("§l§3Bleach")
    .body("§cYoutube.com/§fPinhoPlays");

  menuOptions.forEach(option => form.button(option.label, option.icon));

  const result = await form.show(player);
  if (result.canceled) return;

  const selectedOption = menuOptions[result.selection];
  if (selectedOption?.action) selectedOption.action(player);
}```
fallen hearth
#

I have several forms

dim tusk
# fallen hearth 🥲

I gave you an easier one to extend. You just need to add those in the menuOptions variable

true isle
#

is it possible for a block to detect the block below its neighbor?

dim tusk
prime zenith
#

999 bugs in my code 999 bugs take 1 down patch it around 25,674 bugs in my code

rapid nimbus
#

@dim tusk Hey man, if I wanted to support dimension titles in Minecraft Bedrock, how would the script be modified?

rapid nimbus
dim tusk
#

Does it display the name on screen?

prime zenith
#

How can i disable vanilla knockback but allow script to cause knockback

rapid nimbus
#

@dim tusk This is the script you sent me the other day but I changed the "player.onScreenDisplay.setActionBar(biome.id)" to "player.onScreenDisplay.setTitle(biome.id)" and I tried in Minecraft 1.21.70.26 then it doesn't show the title (error) when entering the world and going through the biomes, I have logs enabled to save that error,

#

@dim tusk Here is my manifest.json code

#

Here is the error text from the Minecraft 1.21.70.26 logs file:

13:28:56[Scripting][verbose]-Plugin Discovered [Traveler's Titles Bedrock BP] PackId [e3d5c1f9-3f5e-41e4-b6f1-8c9f01b74d82_1.0.0] ModuleId [5a7d3c96-2a1b-4cfd-90f3-8ea7a8e1c123]

13:28:56[Scripting][error]-ReferenceError: Native function [World::getPlayers] does not have required privileges. at <anonymous> (main.js:24)

13:28:56[Scripting][error]-Plugin [Traveler's Titles Bedrock BP - 1.0.0] - [main.js] ran with error: [ReferenceError: Native function [World::getPlayers] does not have required privileges. at <anonymous> (main.js:24)
]

dim tusk
unique acorn
#

oh wait ur on 2.0.0

#

my bad.

dim tusk
#
system.runInterval(() => {
  const player = world.getPlayers()[0];
  if (!player) return;

  // ...
});```
rapid nimbus
#

So what about this script?:

const biome = getBiome(player.location, player.dimension);
    player.onScreenDisplay.setTitle(biome.id);```
dim tusk
#

you put that in the // ...

#

It's not needed that I type it all too, it's a common sense

past coyote
#

Is there a good way to prevent a sound from playing if the item was removed from the players inventory because they dropped it, or placed it (with blocks) or consumed it (with food) or used it (like eggs, ender pearls)

#

I tried implementing it, but it doesn't really work.

untold magnet
#

it is possible to play animations with scripts, but can the animations apply for the FP or only for the TP?

stuck ibex
#

Animations themselves can define wether they show FP/TP.

fast lark
#

What is fp tp

distant tulip
#

First person/ third person camera

distant tulip
prisma shard
#

what's that theme

#

i think you've wrote that 3 times lol

untold magnet
prisma shard
#

force him to make (minecraft inside minecraft)

prisma shard
#

not scripts

untold magnet
#

i think it is possible to detect water while interacting, right?

distant tulip
#

probably

untold magnet
prisma shard
prisma shard
unique acorn
prisma shard
unique acorn
#

we?

fast lark
unique acorn
fast lark
#

Wait

#

How do you create a world inside a world

#

It’s impossible to make mc inside mc

unique acorn
#

make a void world then generate your own terrain

fast lark
#

And the main world?

unique acorn
prisma shard
#

make a github project and lets tell everyone to do contribution to it together we make the best ever addon minecraft inside minecraft

#

-(just kididng)

#

lol

prisma shard
#

such wise words

fast lark
#

I have an idea

unique acorn
unique acorn
#

I can feel my legs, so yeah I'm real..?

prisma shard
fast lark
#

An addon that adds a arcade game that when u start to play with it u will get trasferred to a server that recreate minecraft legend multiplayer

#

All this pay2win, why? Idk i like pay to win

unique acorn
true isle
honest spear
fast lark
#

We need someone that is good with models

unique acorn
#

we?

fast lark
#

And textures

unique acorn
#

what do you mean we

#

there is no we

fast lark
fast lark
#

Im just kidding lol

unique acorn
wintry bane
#

runInterval vs tick.json

#

What's better

rapid nimbus
#

@dim tusk But wait, I have 6 language files (.lang files) in the resource pack and inside those language files I have different names (biomes and dimensions (depending on the language)) so i dont know what script should i add to support the language file i made

bright dove
#

@honest spear setSpawnPoint don't work in the end ?

chilly moth
#

stop fall damage using script?

unique acorn
#

the closest way with scripts is to heal the player the amount of damage they took

bright dove
honest spear
#

i think just try it man

#

but i think it just not possible but you can teleport player on join where you want

chilly moth
jolly citrus
#

on world.beforeEvents.effectAdd, does the duration property reflect the original duration of the given effect or the remaining duration

lyric kestrel
#

Quick question; Is there a way to dynamically add permutations to a block with JS?

lyric kestrel
#

hmm

#

What about textures?

wary edge
lyric kestrel
#

hmm, I guess I'll have to do the long way

tender pier
#

hi, I wanted to ask if anyone knows how to stop a sound from a block, i'm trying to make a radio but i need it to stop the songs

prime zenith
#

You ever use the rest room get done using rest room back to where you were then need to use the rest room again

prime zenith
#

But i want to script a solution to the problem

dim tusk
#
.sendMessage({ rawtext: [{ translate: '', with [] }] }) or
.setTitle({ rawtext: [{ translate: '', with [] }] }) or
.setActionBar({ rawtext: [{ translate: '', with [] }] })```
prime zenith
#

In b4 i script a rest room need into my minecraft world lol

dim tusk
dim tusk
prisma shard
#

ok

dim tusk
safe stream
#

Does PlayerJoinAfterEventSignal not have a player property?

unique acorn
dim tusk
safe stream
#

oh thank you 👍

oak lynx
#
        system.run(async () => {
            const request = new HttpRequest("http://localhost:3000").setMethod(HttpRequestMethod.POST);
            request.setBody("TEST");
            player.sendMessage(request.method.toString());
            try {
            const response = await http.request(request);
            player.sendMessage(response.status.toString());
            player.sendMessage(response.body);
            } catch (error) {
            player.sendMessage("Request failed " + error);
            }
        });
[2025-03-13 22:04:42:340 ERROR] [Scripting] Unhandled promise rejection: InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: HttpRequestMethod
#

am i like stupid or something

#

okay its .setMethod(HttpRequestMethod.Post)
I must have had wrong types installed or something

past coyote
#

is it possible to check if a player is in an enclosed space/inside a building/structure?

true isle
humble lintel
#

monokai night

prime zenith
#

How do i make a custum plant

past coyote
#

is there an efficient way to detect if a player is near a large body of water?

#

every way i've tried is computationally expensive.

past coyote
#

I don't even know where to begin haha

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

const CHECK_RADIUS = 10; 
const CHECK_HEIGHT = 5;

function isNearWater(player) {
    const playerLocation = player.location;
    const volume = new BlockVolume(
        { x: playerLocation.x - CHECK_RADIUS, y: playerLocation.y - CHECK_HEIGHT, z: playerLocation.z - CHECK_RADIUS }, 
        { x: playerLocation.x + CHECK_RADIUS, y: playerLocation.y + CHECK_HEIGHT, z: playerLocation.z + CHECK_RADIUS }  
    );


    const waterBlocks = player.dimension.getBlocks(volume, { includeTypes: ["minecraft:water"] }, false);
    let waterBlockCount = 0;
    for (const _ of waterBlocks.getBlockLocationIterator()) {
        waterBlockCount++;
        if (waterBlockCount > 50) { 
            return true;
        }
    }

    return false; 
}

system.runJob(function() {
    for (const player of world.getPlayers()) {
        if (isNearWater(player)) {
            player.sendMessage("You are near a large body of water!");
        } else {
            player.sendMessage("You are not near a large body of water.");
        }
    }
}, 20); ```
dim tusk
past coyote
#

Huh? Why not? 😭

dim tusk
#

unlike ruInterval it triggers every tick runJob runs next available tick

#

it doesn't throw everything in the same tick, that's why timing isn't required theres

#

Also it's a generator

#

That's why runJob reduce lags

past coyote
#

Interesting, should I try to use runJobs everywhere?

#

I have some pretty nasty code 😭

dim tusk
# past coyote
system.runJob((function* () {
  // ... code ...
  yield;
})());```

Sample.
past coyote
#

What?!

#

That simple?

dim tusk
past coyote
#

Understood

dim tusk
#

like getBlocks()

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

const CHECK_RADIUS = 10;
const CHECK_HEIGHT = 5;

function* checkWaterNearPlayers() {
    while (true) {
        for (const player of world.getPlayers()) {
            const playerLocation = player.location;
            const volume = new BlockVolume(
                { x: playerLocation.x - CHECK_RADIUS, y: playerLocation.y - CHECK_HEIGHT, z: playerLocation.z - CHECK_RADIUS },
                { x: playerLocation.x + CHECK_RADIUS, y: playerLocation.y + CHECK_HEIGHT, z: playerLocation.z + CHECK_RADIUS }
            );

            const waterBlocks = player.dimension.getBlocks(volume, { includeTypes: ["minecraft:water"] }, false);
            let waterBlockCount = 0;

            for (const _ of waterBlocks.getBlockLocationIterator()) {
                waterBlockCount++;
                if (waterBlockCount > 50) {
                    player.sendMessage("You are near a large body of water!");
                    break;
                }
            }

            if (waterBlockCount <= 50) {
                player.sendMessage("You are not near a large body of water.");
            }

            yield;
        }
    }
}

system.runJob(checkWaterNearPlayers());```
#

So like this?

dim tusk
#

Try it.

past coyote
#

HOLY LAG LMAO

#

it just spams "You are near a large body of water!"

#

and crashes out the game

dim tusk
#

runJob can't stop total lag but it can at least reduce it.

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

const CHECK_RADIUS = 10;
const CHECK_HEIGHT = 5;
const WATER_THRESHOLD = 50;
const COOLDOWN_TICKS = 100;

function* checkWaterNearPlayers() {
    const playerCooldowns = new Map();

    while (true) {
        for (const player of world.getPlayers()) {
            const playerId = player.id;
            const currentTick = system.currentTick;

            if (playerCooldowns.has(playerId) && currentTick - playerCooldowns.get(playerId) < COOLDOWN_TICKS) {
                yield;
                continue;
            }

            const playerLocation = player.location;
            const volume = new BlockVolume(
                { x: playerLocation.x - CHECK_RADIUS, y: playerLocation.y - CHECK_HEIGHT, z: playerLocation.z - CHECK_RADIUS },
                { x: playerLocation.x + CHECK_RADIUS, y: playerLocation.y + CHECK_HEIGHT, z: playerLocation.z + CHECK_RADIUS }
            );

            const waterBlocks = player.dimension.getBlocks(volume, { includeTypes: ["minecraft:water"] }, false);
            let waterBlockCount = 0;

            for (const _ of waterBlocks.getBlockLocationIterator()) {
                waterBlockCount++;
                if (waterBlockCount > WATER_THRESHOLD) {
                    player.sendMessage("You are near a large body of water!");
                    playerCooldowns.set(playerId, currentTick);
                    break;
                }
            }

            if (waterBlockCount <= WATER_THRESHOLD) {
                player.sendMessage("You are not near a large body of water.");
                playerCooldowns.set(playerId, currentTick);
            }

            yield;
        }
    }
}

system.runJob(checkWaterNearPlayers());```
#

seems to fix the crashing issue haha

random flint
#

for loop with blockLocationIterator often crash the game

#

you need to use the .next() on it manually

past coyote
#

Is it possible to check if a player is inside of a building/structure and not in the open air in a similar way?

random flint
#

Why not try using a flood-fill algorithm?

past coyote
#

For that purpose?

random flint
#

If the flood-fill stops midway, you can assume it's on a closed space.

If it kept filling, you can assume it's on an open space. However, there might be an inaccuracy if the room size is too big using this approach.

past coyote
#

Yeah....

random flint
#

But yeah, flood fill got the best accuracy

deep yew
#

How can I load chunks using script api, such as nobody is near 10k 10k so the blocks aren't loaded, and I want to access those blocks using a structure or something. Can I spawn an entity with nametag or what? Ticking areas seem to not help

random flint
#

/tickingarea command

#

no script api method yet

#

unless ender pearl actually load chunk...

deep yew
#

Well like I just said, ticking area for me seems to not even keep the chunk blocks loaded

wary edge
solar dagger
#

how can i update certain data for an entity if it's only within render distance that of the player?

system.runInterval(() => {
  for (const [mob, sm] of stateMap) {
    const entity = world.getEntity(mob.id);
    if (entity !== mob || !entity) return;
    sm.update(entity);
  }
});
prisma shard
solar dagger
#

Yikes

prisma shard
#

what

shy leaf
#

this is some tricky error

#

trying to send function data via scriptevent using deserialiser since JSON.stringify() kills functions

#

but it didnt work

dim tusk
#

I can probably help you since I have that problem last year and fixed it.

shy leaf
#

the deserialiser or

#

oh wait

dim tusk
shy leaf
#

alr though its a bit too long

dim tusk
#

If you're okay with it.

shut citrus
#

Why does scripts implement function too slow? it takes 6 ticks to run a function

shy leaf
shut citrus
#

js function

shy leaf
#

it

#

shouldnt be slow?

#

though it depends on how clustered your functions are

#

6 ticks sounds way too slow

chilly moth
#

how do I dectect blocks nearby at radius of 1 and change block geometry for that block

cold grove
#

You can just set permutations

turbid delta
thorn flicker
thorn flicker
#

assuming this is a custom block, change its permutation to the one with the geometry with states.

#

not possible if its a vanilla block.

simple zodiac
# shy leaf this is some tricky error

you are trying to create a function from a string, therefor evaluating arbitrary code. For this to be allowed, you need to enable script_eval in the manifest capabillities

grim raft
#

yo

#
export class ActionForm {
    show;
    constructor(title, body, buttons) {
        const ui = new ActionFormData();
        if (title)
            ui.title(title);
        if (body)
            ui.body(body);
        if (buttons)
            for (const button of buttons)
                ui.button(button.name, button.texture);
        this.show = async (player) => {
            const response = await ui.show(player);
            if (!buttons)
                return response;
            if (response.canceled)
                return response;
            let selection = 0;
            if (response.selection)
                selection = response.selection;
            const button = buttons[selection];
            if (button.code)
                button.code(player);
            return response;
        };
    }
}
function mainMenu(source) {
    new ActionForm("Denreishiki", "", [
        { name: "Stats", texture: "textures/items/dummy", code: (player) => statMenu(player) },
        { name: "Rank", texture: "textures/items/shihakusho", code: (player) => player.runCommand("give @s bleach:shihakusho") },
        { name: "eh", texture: "textures/items/apple_golden", code: (player) => player.runCommand("say WIP") },
        { name: "idk", texture: "textures/items/bow_standby", code: (player) => player.runCommand("say WIP") }
    ]).show(source)
}```
I got this from here and it works, I tried to run a function and this error appears
`[Scripting][error]-Unhandled promise rejection: TypeError: value is not iterable`
#

on this line
{ name: "Stats", texture: "textures/items/dummy", code: (player) => statMenu(player) }

stark kestrel
#

god damn, why is setting up ts so hard

#

i tried like, twice, didnt work even once

#

i think im just too dumb

prisma shard
stark kestrel
#

then we're both dumb

prisma shard
#

yep

past coyote
#

Do dynamic properties still have data limits?

Are there any good database systems that interface with dynamic properties?

past coyote
#

I heard it was 32k?

woven loom
#

yes

lyric kestrel
#

There's apparently something wrong with my script dependencies and modules, because when I remove them, my block appears in game and [Texture][warning]-The block named camouflage:camouflage_full_block used in a "blocks.json" file does not exist in the registry stops happening

{
    "format_version": 2,
    "header": {
        "description": "pack.description",
        "name": "Camouflage block BP",
        "uuid": "b5838139-7ba1-4384-a2ae-d73c652eda44",
        "min_engine_version": [
            1,
            21,
            60
        ],
        "version": [
            1,
            0,
            0
        ]
    },
    "modules": [
        {
            "type": "data",
            "uuid": "2863df99-0c6a-492c-959a-469e7bc06fa6",
            "version": [
                1,
                0,
                0
            ]
        },
        {
            "language": "Javascript",
            "type": "script",
            "uuid": "19a4ec5c-72bc-4024-bd22-260753e11873",
            "version": [1,0,0]
        }
    ],
    "dependencies": [
        {
            "module_name": "@minecraft/server",
            "version": "1.17.0"
        }
        ]
}```
#

nvm

#

I'm an idiot

#

like usual

#

I forgot entry 😭

fast lark
#

how can i detect if an armor have more than 50% of durability

unique acorn
past coyote
prime zenith
#

Is there a limit to how many dynsmic properties can be stored

fast lark
#

20%

#

10%

#

40%

#

60%

#

70%

#

80%

#

90%

#

100%

unique acorn
# fast lark and 30%?
const durability = item.getComponent("durability")
if ((durability.maxDurability - durability.damage) > (durability.maxDurability * 0.3)) {
  //run code if true
}

0.3 is 30%, 0.2 is 20%, 0.1 is 10%

unique acorn
#

over here, replace the 0.3

fast lark
#

u dont have to actually make me a list of all %

fast lark
#

its when more of 30% or when 30%

unique acorn
fast lark
safe stream
#

Is it not possible to access block's display name?

subtle cove
#

with this api, not currently possible

safe stream
#

Damn, I really didn't want to manually map their names

fast lark
#

how to get the helmet slot

unique acorn
fast lark
fast lark
#

import { world, system } from '@minecraft/server'

system.runInterval(() => {
for (const player of world.getPlayers()) {
const item = player.getComponent("equippable").getEquipment("Head")
const durability = item.getComponent("durability")
if ((durability.maxDurability - durability.damage) > (maxDurability * 0.3)) {
player.onScreenDisplay.setActionBar("0")
}
}
}, );

unique acorn
#

the part where it goes
}
}
}, )

unique acorn
# fast lark import { world, system } from '@minecraft/server' system.runInterval(() => { ...
import { world, system } from '@minecraft/server'

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const item = player.getComponent("equippable").getEquipment("Head")
    const durability = item.getComponent("durability")
    if ((durability.maxDurability - durability.damage) > (durability.maxDurability * 0.3)) {
      player.onScreenDisplay.setActionBar("0")
    }
  }
});
fast lark
#

ohh im stupid

#

i didnt see the maxDurability

true isle
#

I might try that

prime zenith
#

Is there a limit to how many dynsmic properties can be stored

unique acorn
prime zenith
#

Which does not tell me much

unique acorn
#

nvm.

#

I don't think there is a limit

jade grail
#

nvm i figured it out

fast lark
jade grail
#

i figured it out

jade grail
#

which is alot for js text so basically u wont run out

prime zenith
#

What about world dynamic properties

#

Cause my grabd exchange and farming will use world dynamic properies for each player

jade grail
#

world also has no limit

prime zenith
#

Does the 32k byte effect world

jade grail
#

doesnt rlly lag it out or anything

prime zenith
#

Thats good

jade grail
#

yh i used world dynamic properties to make a mail system

jade grail
#

rn i gotta work on a dif project

prime zenith
#

Hey is there a built in way to get a radius chat in bedrock or do i need to code that in myself

jade grail
#

Making a custom table 😭

prime zenith
#

Like you can only see chat if a player is whithin x from you

jade grail
prime zenith
#

I know its possible im sure it wont be that hard

jade grail
#

yuh

prime zenith
#

I think this game ran out of creativity on names

fast lark
#

@unique acorn with your help i made this _CatRave

unique acorn
#

wait it displays the armor you're wearing?

fast lark
#

yep

#

wanna see on vc?

unique acorn
#

that is awesome

#

ofc I'll see it

fast lark
jolly citrus
#

how do i detect when a player receives an effect that they already have but at a higher amplifier or duration

prime zenith
#

what is the sound used for farm blocks

unique acorn
#

what do you mean by farm blocks tho

prime zenith
#

If you til a block in minecraft with a hoe

#

That has a dif sound when walked on

unique acorn
#

oh

thorn flicker
#

farmland

prime zenith
#

Im gutting farming to replace it with an instanced farming to better match runescape

#

That sound wasnt lidting as svailable

thorn flicker
#

its just dirt

prime zenith
#

Dirt isnt even valid i tried it defaulted to stone

thorn flicker
#

mb

prime zenith
#

Are you sbout to pull a chatgpt

thorn flicker
#

what?

#

you mean will I be wrong again?

prime zenith
#

Read what i linked earlier

thorn flicker
#

because gravel is the same sound is dirt

dim tusk
# past coyote Do dynamic properties still have data limits? Are there any good database syste...

There's a certain amount

function getFullData(target, name) {
  let data = '';
  for (let i = 0; ; i++) {
    const part = target.getDynamicProperty(`${name}:data${i}`);
    if (part === undefined) break;
    data += part;
  }
  return data ? JSON.parse(data) : undefined;
}

function setFullData(target, name, data) {
  const stringData = JSON.stringify(data);
  const parts = Math.ceil(stringData.length / 32767);
  for (let i = 0; i < parts; i++) target.setDynamicProperty(`${name}:data${i}`, stringData.slice(i * 32767, (i + 1) * 32767));
  for (let i = parts; target.getDynamicProperty(`${name}:data${i}`) !== undefined; i++) target.setDynamicProperty(`${name}:data${i}`, null);
}```
thorn flicker
#

lol

prime zenith
#

Yup that matches ty

thorn flicker
#

np

#

-# also when I said "farmland" I wasnt talking about the name of the sound, I was talking about the block name

prime zenith
#

Still funny what chat gpt did

Its grass no your right its stone no your right its wood no your right its mud

thorn flicker
#

using chat gpt is lame

prime zenith
#

Its useful for fast coding but its sometimes stupid as hell

dim tusk
past coyote
past coyote
thorn flicker
#

look in #1067535712372654091

past coyote
#

It has a better understanding of the current state of the script API

thorn flicker
dim tusk
#

God, stop promoting AI pls.

past coyote
#

Another way to get ChatGPT to understand things better would be to upload all of the types and make your own GPT, but it costs money :\

dim tusk
#

especially in programming generally

thorn flicker
#

promote self intelligence

past coyote
#

I'm going to promote tools that help users create code thats efficient, safe, and maybe even helps them learn something.

dim tusk
past coyote
#

Its a tool. People are going to use a tool.

dim tusk
#

you can't tell me otherwise since I'm this server a lot of beginners start to use AI and become lazy

past coyote
#

It sucks that they clutter the chats with broken code from ChatGPT and expect help

thorn flicker
#

this is something that most likely will replace us in the future...

#

no doubt.

dim tusk
#

use AI all you want just don't drag other people...

past coyote
#

but I use AI all of the time, specifically "Continue" the VSCode Extension, I have a code model that helps write code when I make comments. (which I run locally)

wary edge
#

I've already sent my two cents, but I highly do not recommend recommending new users who have not even read a single documentation AI.

dim tusk
#

"why my code doesn't work?" Gave a code that's 100% ai generated.

past coyote
#

I think it skews how people learn how to code, and it doesn't help develop problem solving skills, and debugging skills.

dim tusk
thorn flicker
#

you did not do anything yourself

dim tusk
thorn flicker
#

People will use this more for a tool to do things for them rather than helping them learn

dim tusk
#

no, I'm not saying using AI is bad, as cenOb said it's a tool why not use it but the thing is people are starting to use it in a different way.

thorn flicker
#

thats how things go.

#

AI was a mistake, and im not looking forward to the progression of it.

past coyote
#

I think AI for programming is pretty great, for some things its allowed me to focus more on creative ideas and concepts rather than slaving away at a keyboard for 10 hours trying to develop something.

#

I still write my own stuff, but sometimes its good to have a tool in my back pocket that can sketch out a concept, or make something simple that I can build off of.

#

Can't just ask it to "Make me a factions server with crates and pvp zones"

thorn flicker
#

like coddy said, its not really a problem if you use it like that

valid ice
thorn flicker
dim tusk
#

as I said they'll just join this server and ask "why this code doesn't work?" "I'll pay you to fix it" "can anyone make a script for me"

thorn flicker
#

art is ruined

inland merlin
inland merlin
#

Api wise

#

Decent at getting latest imports and stuff

dim tusk
#

only AI I use is C.AI

past coyote
#

aw hell naw

#

freaky ai

dim tusk
#

-# I'm bad at communicating so I talk with mark Zuckerberg etc.

thorn flicker
past coyote
inland merlin
#

So i have to start over often

past coyote
#

Really? I never have that issue, I usually have to reprompt often though

inland merlin
#

Mostly just having to make a new chat

past coyote
#

You think grok3 is better logically though?

#

If so I might try it out!

hexed fox
inland merlin
#

Grok3 is impressive

#

Not perfect, but pretty good

past coyote
#

I wish we could feed the typings though... like I feel like that would make things better

#

Trying out Grok3 now, i'll come up with a silly prompt and compare the resulting code

#

Prompt:

I need to implement the following functionality in JavaScript for Minecraft: Bedrock Edition’s JavaScript API (@minecraft/server version: "1.18.0-beta"):
Key requirements:

When a player kills a "minecraft:cow", an explosion particle must play at the cow's location.
A cat should be summoned at the cow's location and named "Kitty."
The block under the cat must be set to stone.

Please consider:

Error handling: Ensure the script checks for valid player and entity references and handles errors gracefully.
Edge cases: Handle scenarios like the cow being killed by an entity other than the player or the cat spawning in an invalid location.
Performance optimization: Ensure that any particle effects or entity spawning does not cause lag or excessive computation.
Best practices for JavaScript in the Minecraft: Bedrock Edition API: Make use of appropriate event handling, entity management, and efficient methods.

Please do not unnecessarily remove any comments or code.
Generate the code with clear comments explaining the logic.

#

...

They all kinda suck LMAO.

inland merlin
#

you have to do more training, and some feeding of good stuff first

#

deepseek is probably the best random

past coyote
#

Firt of all GPT is trying to use require, and then like deepseek just straight up doesn't use some imports that it imports

inland merlin
#

oh

#

you used gpt?

past coyote
#

middle file

inland merlin
#

thats the worst one lol

past coyote
#

yeah 😭

#

I tried to cover most of the methods/events, like particles, checking the death of an entity, setting blocks, renaming entities

prime zenith
#

Chat gpt doesnt add skill it multiplies it ppl dont realize what that neans cause if you dont know what your doing your skill is 0 and anything multiplied by 0 is 0

You can ask it why script isnt working as long as you give it all it needs but if you cant read code its fix wont help you

Do you know how many times a small syntax mistake was found due to chatgpt

How you use chatGPT matters like right now i had it generate something i dont think will work but a tweak should get it to work

inland merlin
#

yes ai can be a helpful tool, but it depends on which one you use right now some are just way ahead

past coyote
#

Thats somewhat true, but sometimes it sends back my working script and a parenthesis is gone 😭

#

or it doesn't declare something and tries to use it

inland merlin
#

yup lol

past coyote
#

DeepSeek has been always on it, like pretty consistantly

inland merlin
#

yup

past coyote
inland merlin
#

deepseek is the best rn,

grok3 is just nicer for less restrictions,

#

but also performs alright.

#

still better to feed it some stuff, they have a thinking button

thorn flicker
inland merlin
#

i get it, ai is annoying because its wrong alot and it does require the person to know how to fix the wrong stuff.

but it really helps those that don't know coding that well get further ahead

thorn flicker
#

not the problem

inland merlin
#

a great tool

inland merlin
prime zenith
inland merlin
#

its lacking behind others

#

the 4o one

#

and over priced

#

for the o3

prime zenith
#

ChatGPT has specualised gpt's i use

inland merlin
#

oh

thorn flicker
inland merlin
#

well, don't really need specialized ones if others are just better out of the gate

thorn flicker
inland merlin
#

lmao

thorn flicker
#

rip fox, you killed him with all this ai talk.

prime zenith
#

Specuslised gpts are trained specificually and are actually high end

past coyote
#

Yeah, I was considering training a gpt with the docs and examples

#

I just don't wanna pay 😭

prime zenith
#

I trained a gpt to only say i am groot

inland merlin
#

lmao

prime zenith
inland merlin
#

alright this is funny, but if you wanna save the most money, deepseek or grok3

#

free

thorn flicker
#

-# or just dont use ai

prime zenith
#

nope grok is horrible and owned by a horrible waste of space

#

also i pay for the most up to date premium chatGPT and we need it for school

prime zenith
inland merlin
#

lol alright to each their own

inland merlin
#

lol

inland merlin
#

lol

thorn flicker
prime zenith
#

the ai has spoken

fast lark
#

Put that ai down

#

And use your brain

prime zenith
#

you dare defy the ai

past coyote
#

What JavaScript engine does the game use?

fast lark
past coyote
#

brother 😭

fast lark
past coyote
#

Chakra JavaScript engine?

#

Thats not what I really wanted to know but awesome

prime zenith
past coyote
#

I did some searching here and its:
Es6 the module target is es2023

prime zenith
#

the ai has spoken of your punishments

#

i have no life

past coyote
#

I wrote some intentionally awful code... like YandreDev level code.

#

I made a prompt that takes the really tragic code and makes it not tragic lmao.

#

- Code Quality and Best Practices: Ensure the code adheres to modern JavaScript standards, particularly up to the features available in ES6, Minecraft API best practices, and other industry best practices. Make sure the final code targets ES2023 module compatibility.

- Potential Bugs or Edge Cases: Identify and address any potential bugs or edge cases specific to the Minecraft gameplay and API usage.

- Performance Optimizations: Optimize the code for better performance within the constraints of the Minecraft Bedrock environment.

- Readability and Maintainability: Improve the readability and maintainability of the code through proper variable naming, comments, and structuring.

- Security Concerns: Identify and mitigate any security vulnerabilities, with a particular focus on common issues in game scripting such as preventing malicious scripts and ensuring API constraints are respected.

Please provide a detailed refactored version of the code along with explanations for the changes made to address each of the aspects mentioned above.```
#

surprised it didn't do switch statements bao_doggo_hmm

dim tusk
#

#off-topic pls

prime zenith
#

You heard them no more talking about script api here we only talk off topic in this channel now

warped kelp
#

O ya, how can I use potion effects as a timer for scripts?

unique dragon
#

someone know if is it possible to use custom skins for simulated players?

digital trout
#

Is there an event that triggers when a projectile hits a liquid?

It doesn't trigger worldafterevents ProjectileHitBlockEvent

rapid nimbus
#

Bruh, Jayly's bot is offline

unique acorn
#

idk how tho

jolly citrus
#

how do i detect when a player receives an effect that they already have but at a higher amplifier or duration

dim tusk
dim tusk
# jolly citrus how do i detect when a player receives an effect that they already have but at a...
world.afterEvents.effectAdd.subscribe(({ effect: { amplifier, duration, typeId }, entity }) => {
  if (entity.typeId !== 'minecraft:player') return;
  const existingEffect = entity.getEffect(typeId);
  if (existingEffect) {
    if (amplifier > existingEffect.amplifier || duration > existingEffect.duration) {
      console.error(`stronger or longer version of ${typeId}`);
    }
  } else {
    console.error(`new effect: ${typeId}`);
  }
});```
jolly citrus
dim tusk
jolly citrus
#

is there rlly no other way 💔

#

smh my interval loops are already heavy to begin with

#

which one is better on performance if i need to run stuff at different intervals:
a) using only one runinterval throughout my entire project & linking the necessary functions to an index determining the necessary tick cooldowns between each execution (e.g. function updatePlayers() could be ordered to only be run every 10 iterations for a 10-tick delay, even tho the runinterval itself is 1-tick)
b) using multiple runintervals at different speeds tailored for different tasks

dim tusk
fast lark
#

how can i make a numer 1k and not 1000

jolly citrus
fast lark
#

function addCommasToNumber(number) {
let numString = number.
numString = numString.replace(/\B(?=(\d{3})+(?!\d))/
return numString;
}
//makes numbers like 1,000

/**

  • Correct Numerical Values
  • @param {value} value Number Value To Correct
  • @example metricNumbers(10000)
  • @returns Formatted Number Values
    */
    export function metricNumbers(value) {
    const types = ["", "§fk", "§fm", "§fb", "§ft", "§fp", "§fe", "§fz", "§fy"];
    const selectType = (Math.log10(value) / 3) | 0;
    let decimalPlaces = 2;
    if (value < 1000) {
    decimalPlaces = 0;
    } else if (value < 1000000) {
    decimalPlaces = 1;
    }
    let scaled = value / Math.pow(10, selectType * 3);
    scaled = Math.floor(scaled * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
    return scaled + types[selectType];
    }
    //makes numbers like 1k
digital trout
remote oyster
# fast lark function addCommasToNumber(number) { let numString = number. numString =...
function formatMetric(num, decimals = 1) {
    if (typeof num !== "number" || isNaN(num)) return "NaN"; // Handle invalid input
    if (num === 0) return "0"; // Handle zero case

    const absNum = Math.abs(num);
    const units = ["", "K", "M", "B", "T", "P", "E", "Z", "Y", "R", "Q"]; 
    // Z (Zetta), Y (Yotta), R (Ronna), Q (Quetta) for extremely large numbers

    let unitIndex = 0;

    while (absNum >= 1000 && unitIndex < units.length - 1) {
        num /= 1000;
        unitIndex++;
    }

    const formatted = num.toFixed(decimals).replace(/\.0+$/, ""); // Remove unnecessary decimals
    return (num < 0 ? "-" : "") + formatted + units[unitIndex]; // Preserve negative sign
}

// Test cases
console.log(formatMetric(0));             // "0"
console.log(formatMetric(999));           // "999"
console.log(formatMetric(1000));          // "1K"
console.log(formatMetric(1500));          // "1.5K"
console.log(formatMetric(-2500000));      // "-2.5M"
console.log(formatMetric(1e12));          // "1T"
console.log(formatMetric(5.6789e15));     // "5.7P"
console.log(formatMetric(7.89e18));       // "7.9E"
console.log(formatMetric(9.01e21));       // "9Z"
console.log(formatMetric(1.23e24));       // "1.2Y"
console.log(formatMetric(3.45e27));       // "3.5R"
console.log(formatMetric(6.78e30));       // "6.8Q"
console.log(formatMetric(9.99e33));       // "9.99Q" (still handles extreme cases)
console.log(formatMetric("invalid"));     // "NaN"
console.log(formatMetric(null));          // "NaN"
console.log(formatMetric(undefined));     // "NaN"
fast lark
#

world.afterEvents.entityDie.subscribe(({ deadEntity, damageSource: { damagingProjectile, damagingEntity, cause }}) => {
if (deadEntity.typeId === 'minecraft:cow' && damagingEntity.typeId === 'minecraft:player') {
const killer = damagingEntity
const victim = deadEntity

  let killsc = killer.getDynamicProperty(kill) ?? 0;

  killer.setDynamicProperty(kill, killsc + 1);

  let deathsc = victim.getDynamicProperty(death) ?? 0;

  victim.setDynamicProperty(death, deathsc + 1);
}

});

#

idk why but when i kill the cow(is to test) it add me kill and death

untold magnet
#

so dynamic properties can be accessible only from the addon that add them, and other addons cannot get access to them, right? ( making sure )

jolly citrus
#

yes

#

they're bound to the uuid of the pack & the world it's used in

#

if either of those change , the dynamic properties will no longer exist on that 'instance' of the addon

#

is this too heavy to be running every tick

const effectsOfPlayer = customPlayer.effects;
    player.getEffects().forEach((effect: Effect) => {
      const oldEffect = effectsOfPlayer?.get(effect.typeId);
      const newEffect: EffectInfo = {
        effectType: effect.typeId,
        duration: effect.duration,
        options: {
          amplifier: effect.amplifier,
        },
      };
      if (effect.amplifier > (oldEffect?.options.amplifier ?? 0) || effect.duration > (oldEffect?.duration ?? 0)) {
        const canceled = CustomCancellableEvents.emit(
          CustomCancellableEvents.EffectAddedEvent,
          new EffectAddedEvent(customPlayer, oldEffect, newEffect)
        );

        if (canceled) {
          player.removeEffect(newEffect.effectType);
          if (oldEffect) {
            player.addEffect(oldEffect.effectType, oldEffect.duration, oldEffect.options);
          }
        }
      }

      customPlayer.effects.set(newEffect.effectType, newEffect);
    });
#

for every player

untold magnet
# jolly citrus yes

well, in that case i should use scoreboards in order to make my addon work with the second addon i will make

jolly citrus
bright dove
#

is this valid ? ```js

{
const dimension = world.getDimension();
if (!dimension.stopSound) {
const dimensionProto = Object.getPrototypeOf(dimension);
/**
* Stops a sound at the specified location.
*
* @param {string} soundName - The name of the sound to stop.
* @param {{x: number, y: number, z: number}} location - The location at which to stop the sound.
* @returns {Result} The result of the call.
*/
dimensionProto.stopSound = function (soundName, location) {
return this.runCommand(
execute positioned ${location.x} ${location.y} ${location.z} run stopsound @a ${soundName}
);
};
}
}```

jolly citrus
#

it's not

bright dove
jolly citrus
#

though

#

no

#

world.getDimension() required an argument

#

if you want to get say, an entity's dimension, use the .dimension property

#

you can do for example player.dimension

#

world.getDimension() is just used to get an object of class Dimension because Dimension is, by default, a private class which you cannot construct an instance of yourself using parameters

jolly citrus
#

to get a Dimension in return

fast lark
jolly citrus
jolly citrus
#

you also need to add a custom player system

#

doesnt need to be set up the way i did

#

you can just use maps within the script to store kv pairs of player id and then the necessary data

#

this is just the logic itself, you need to make a lot of changes to make it work for u

#
    const effectsOfPlayer = customPlayer.effects;
    const currentEffectTypeIds = new Set();

    player.getEffects().forEach((effect: Effect) => {
      const effectTypeId = effect.typeId;
      currentEffectTypeIds.add(effectTypeId);

      const oldEffect = effectsOfPlayer?.get(effectTypeId);
      const newEffect: EffectInfo = {
        effectType: effectTypeId,
        duration: effect.duration,
        options: {
          amplifier: effect.amplifier,
        },
      };

      if (effect.amplifier > (oldEffect?.options.amplifier ?? 0)) {
        const canceled = CustomCancellableEvents.emit(
          CustomCancellableEvents.EffectAddedEvent,
          new EffectAddedEvent(customPlayer, oldEffect, newEffect)
        );

        if (canceled) {
          player.removeEffect(newEffect.effectType);
          if (oldEffect) {
            player.addEffect(oldEffect.effectType, oldEffect.duration, oldEffect.options);
          }
        }
      }

      customPlayer.effects.set(newEffect.effectType, newEffect);
    });

    /* remove nonexistent effects from map */
    customPlayer.effects.forEach((effect, effectTypeId) => {
      if (!currentEffectTypeIds.has(effectTypeId)) {
        customPlayer.effects.delete(effectTypeId);
      }
    });

run this for every player every tick

#
CustomCancellableEvents.EffectAddedEvent.subscribe((event) => {
  console.warn("added effect");
  const { customPlayer, newEffectInfo, oldEffectInfo } = event;

  const { player } = customPlayer;

  /* Added due to frequent lookups (>1) */
  const { effectType: newEffectType, duration: newEffectDuration } = newEffectInfo;

  const startTick = system.currentTick;

  if (oldEffectInfo) {
    system.runTimeout(() => {
      console.warn("removed current effect before re-adding old, prevent conflict");
      player.removeEffect(newEffectType);

      /* Checks if effect is infinite (duration = -1) */
      if (oldEffectInfo.duration < 0) {
        console.warn("old effect is infinite, using command");
        player.runCommandAsync(
          `effect @s ${oldEffectInfo.effectType} infinite ${oldEffectInfo.options?.amplifier ?? 0} ${!(
            oldEffectInfo.options?.showParticles ?? true
          )}`
        );
        console.warn("added infinite effect");
      } else {
        const newDuration = oldEffectInfo.duration - (system.currentTick - startTick);
        player.addEffect(oldEffectInfo.effectType, newDuration, oldEffectInfo.options);
        console.warn("added non-infinite effect");
      }
    }, newEffectDuration);
  }
});
#

can u use beta versions of @minecraft/server on bds

jolly citrus
#

why do some people even use stable then

#

i've never understood

#

only problem i can see is that

#

some features are sometimes bugged

unique acorn
#

probably to ensure their addons are compatible with newer versions

jolly citrus
#

and u have to maintain ur code more

jolly citrus
#

right i forgot people make public add-ons

warped kelp
#

What can you do with just stable stuff?

wary edge
#

A lot.

prime zenith
#

Question if i want to save the current tick to a dynsmic property and a tick amount eg 10,000 so i can check if 10k ticks passed since the property was saved

wary edge
#

I've done so for a project.

distant tulip
prime zenith
#

So i forgot the how do i do that part

sage sparrow
#

hi experts, how do I set the rotation of the camera follow_orbit? I can set the viewOffSet but not the rotation, am I m doing it right?
entity.camera.setCamera("awp:follow_orbit_r06", { viewOffset: { x: 0, y: -0.2 }, rotation: { x: 0, y: 90 } });

prime zenith
wary edge
#

system.currentTick.

cold grove
#

🙊

prime zenith
#

Ahh ok should i also do remainingTick if i want to let ppl see how long is left

wary edge
#

Yeah.

jolly citrus
#

can somebody explain how thge script profiler works

#

im so confused

#

some of the times it gives make sense but stuff like this ??!+

#

it does not take 28 seconds to get the amplifier of an effect

past coyote
#

yeah its pretty odd

distant tulip
# jolly citrus can somebody explain how thge script profiler works

it tracks how many times a function is called.
it sums up the total time spent inside that function across all calls.
if a function calls other functions, their execution time may also be included.

28 seconds for effect.getAmplifier() is not saying a single call takes that long. instead it is saying that across all the times getAmplifier() was called, it added up to 28 seconds of execution time

jolly citrus
#

i wanna know how long it takes for a single call on average

distant tulip
#

run it once?

jolly citrus
#

i thought i could use it to determine what parts of my scripts are causing lag within my pack in different scenarios

#

whilst loading chunks, with lots of players in the world etc.

distant tulip
#

no idea how the debugger work beside that info

prime zenith
#

I actually like how the planting turned out

neat hazel
#

How to ignore items with this?
I don't want to apply damage to items that are on the ground

const entities = dimension.getEntities({
    location: pos,
    maxDistance: 8,
    minDistance: 0.5
  });

  for (const entity of entities) {
    entity.runCommandAsync("damage @s 8");
  }```
neat hazel
jolly citrus
#

how do i check if a value is of type Vector3

random flint
prisma shard
jolly citrus
#

no

#

Vector3 is a private class you can't import it or construct from it

#

it can only be used as a type

#

or interface

#

idk what its called

random flint
#

Vector3 More like an interface

prisma shard
distant gulch
#

then check its keys, like if it only haves x, y and z its a vector

jolly citrus
#

#1067535608660107284 message

#

but thank you Thumbs

dim tusk
#
function isVector3(obj) {
  return (
    obj !== null &&
    typeof obj === 'object' &&
    Number.isFinite(obj.x) &&
    Number.isFinite(obj.y) &&
    Number.isFinite(obj.z) &&
    Object.keys(obj).length === 3
  );
}```
#

Lmfao, it's in my saved files

random flint
#

Revised, Infinity and NaN is a "number";

function isNumber(value) {
return typeof value === "number" && isFinite(value);
}

function isVec3(vector) {
return (
typeof vector === "object" &&
vector !== null &&
isNumber(vector.x) &&
isNumber(vector.y) &&
isNumber(vector.z)
);
}

dim tusk
#

I might test it in the debug playground wait.

#

You can also check it too.

solar dagger
jolly citrus
#

you can get entities within a specific distance of a location

solar dagger
#

Is that really the best option?

jolly citrus
#

never done it

#

just first thing that came to mind

#

how else do you think you could do it

solar dagger
#

Well...

#

No other thing tbh

jolly citrus
#

yeah

jolly citrus
#

actually nvm

#

im not sure

dim tusk
jolly citrus
#

because i dont think theres a way

#

to retrieve the render distance of a player

dim tusk
#

The problem is you can't get current render distance only max render distance

solar dagger
#

Not that I know of tbh

#

I noticed that there's an error for unloaded chunks, could I use that to my advantage here?

random flint
jolly citrus
#

that's the simulation distance

#

it might work in singleplayer though

#

but at least not in multiplayer worlds

solar dagger
#

Oh wait I'm actually saving this entities spawn location as well maybe I can retrieve that?

#

See if it's in a loaded chunk?

dim tusk
#

It will work single player only, since other players can see the entities in that chunk while others can't.

prime zenith
#

Question i know on a world ticks dont happen when its offline but on a server will they still update as long as its live even if noones on

jolly citrus
#

depends on the host

dim tusk
jolly citrus
#

it doesn't require player traffic for ingame events to occur

solar dagger
#

What's the max distance for get entities?

prime zenith
#

Ok cool

dim tusk
#

realms and multiplayer or single player, it only becomes online if there's at least one single player.

jolly citrus
#

you can get all entities too so why would there be a limit for the distance

random flint
#

The limit is the dimension where it gets executed on iirc

solar dagger
#

🤔

#

Yeah I'm not exactly sure how to go about this.

jolly citrus
#

why do some effects not trigger effectAdd

#

haste, absorption for example

#

they are also not returned in getEffects()

#

wait nvm

#

are there any events that can be listened for before the behavior pack reloads

random flint
#

especially the shutdown

prime zenith
#

@somber cedar hey whats it like with so much of you always being imported and exported all the time

somber cedar
#

I don't get that many pings

dim tusk
#

import { ItemStack, BlockVolume } from '@somber cedar'

fast lark
#

is there a add effecft function?

dim tusk
#

addEffect() already tho.

fast lark
dim tusk
fast lark
#

oh no lol

dim tusk
fast lark
#

thx

#

can u help some more?

#

#1350481488558297158 here

#

🙂

dim tusk
fast lark
prime zenith
#

What is script api for titles and actionbar titles

jade grail
#

Anyone know how to make a server and add / commands with plugins?

oak lynx
#

there is no way to get a player xuid with just script api right

unique acorn
oak lynx
#

yeah i figured that out already

#

no native method kinda sucks but whatever

neat hazel
#

Is it possible to cancel entity attacks on the player?

oak lynx
wintry bane
#

Is there a way to get the min and max of a block's state?

neat hazel
neat hazel
wintry bane
#

block.permutation.getState("state") but get the max and min value of the block state?

oak lynx
wintry bane
oak lynx
dim tusk
#
const state = BlockStates.get('<id>');
console.error(JSON.stringify(state.validValues));
#

it returns validValues

wintry bane
#

How do I get it from the block I'm interacting with?

distant tulip
#

const states = Block.getStates()

And loop through them and use what coddy sent

wintry bane
#

okay, thanks

dim tusk
fast lark
jolly citrus
#

before they already got their answer in this channel

jolly citrus
oak lynx
# fast lark How how how how
export async function getXUID(player: Player) {
    try {
        const response = await http.get(`https://playerdb.co/api/player/xbox/${player.name}`);
        const data = JSON.parse(response.body);
        if (data.success) {
            return data.data.player.id;
        } else {
            return "ERROR";
        }
    } catch (error) {
        return "ERROR";
    }
}
#

example usage

        system.run(()=>{
            getXUID(player).then(xuid=>{
                player.sendMessage(`XUID: ${xuid}`)
            })
        })
jolly citrus
#

is player.getComponent("inventory")?.container a reference to the player's current inventory, or a copy of the inventory at time of execution? if the player receives an item after this value has been stored inside of a variable, will this new item also be retrievable?

distant tulip
#

to the current inventory

jolly citrus
#

will that work

#

to get a reference

#

and not a copy

distant tulip
#

it is not a copy, the inventory is just a reference to the "inventory"
get items and set items are the ones dealing with the container directly

prime zenith
dim tusk
prime zenith
#

Remember reusability is key

#

I just do playerData = getPlayerComponents(player)

Then i can do playerData.basicually any player component and boom alot cleaner

dim tusk
#

I made my own too, tho I saved every part of the entity (those who's accessible), I also made a deserializer for ItemStack and Blocks

#

and yes the ItemStack has every component

prime zenith
#

Ya i got add and remove items scoreboardSet for scoreboards dynamic property getter and setter

#

Every obtainable item is getting put in itemComp since 90% have special components i also made ge work only with items in itemComp

jolly citrus
#

it works just fine

prime zenith
#

Which btw works now ive not tested edge cases of how well it handles a ton of data but ya

dim tusk
#

But meh, you do what you do.

jolly citrus
#

theres so much to it that even with everything as optimized as possible itll be hell to run with more than 10 players

dim tusk
#

Mehh

shut vessel
# dim tusk Mehh

Can you tell me what's not working quickly? js case `!freeze`: var arg = msg.message.slice(6).toLowerCase() if (arg.startsWith("@")) { arg = arg.slice(1) } eventData.cancel = true; eventData.sender.runCommandAsync(`inputpermission set ${arg} movement disabled`); break;

jolly citrus
#

print stuff into the console

#

and see what values come up as unexpected

shut vessel
#

i want to freeze a player

jolly citrus
#

context , as in what this snippet of code is part of ...

#

it's likely the problem lies somewhere else than this part of code specifically

dim tusk
#

Like do console.error(arg)

shut vessel
#

i have no error

jolly citrus
#

it's not supposed to have an error, ur supposed to LOG the errors urself

#

like log the variable values

#

of different stuff

#

and see if they're what you expect them to be

shut vessel
#

The argument is to know if there is an @ after the "!freeze" then the player will be frozen via an inputpermission but it does not show me the errors, surely the code works but it does not do the right thing

valid ice
#

Well if it doesn't do the right thing then it doesn't work 😛

#

You have content log enabled, yeah?

jolly citrus
#

os ot normal for the tps to exceed 20

#

im getting like

#

20.08-20.49

subtle cove
#

@shut vessel

dim tusk
jolly citrus
dim tusk
jolly citrus
#

ok thx

shut vessel
shut vessel
subtle cove
#

"${arg}"

#

Or just use the inputPermissions property

oak lynx
#

wait there is a getBlocks function

#

nah its a different thing

past coyote
#

has anyone made a forms framework?

#

This looks good

#

ah nice profile picture.... smh.

chilly moth
#
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;
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 = name
    }
})

#

how do I capitalize 1st letter

#

in entity name?

azure lichen
#

how to check player in water?