#Script API General

1 messages · Page 94 of 1

ripe dune
#
world.sendMessage(`${o.message.match(/[^a-zA-Z0-9]/g) === null}`)
halcyon phoenix
#

did they change the OnPlayerDestroy() customComponents on blocks?

ripe dune
#

this is a better way lol

chrome gyro
#

Perfect, it's working now, sorry had a lot to convert over to that method before I could test what i did wrong.

halcyon phoenix
#

Thanks Sprunkles

ripe dune
#
/[a-zA-Z0-9]/.test(message)
#

it returns true false so better ig

chrome gyro
#

Oh haha ok, I'll use that then. does it really take up more memory?

halcyon phoenix
ripe dune
chrome gyro
ripe dune
#

yup

ripe dune
halcyon phoenix
#

lemme try

#

it works thanks

sly valve
#

Anyone got better docs than the Microsoft ones?
Need it for Behavior and Resource packs

valid ice
#

Bedrock samples?

final ocean
#

How to make 2 different server_from parts not conflict and cause errors

sly valve
valid ice
sly valve
halcyon phoenix
#

Imagine putting runInterval inside OnTick, could be me.

halcyon phoenix
round bone
#

😭

#

Unless you'll clear it

distant gulch
#

Can i import textures in a behavior?

#

I saw someone do it

halcyon phoenix
#

manipulating the itemstack.amouny doesn't work somehow

#

it still prints the amount

#
playerItem.amount - 2;
sc.print(playerItem.amount)
                    playerEquippable.setEquipment("Mainhand", playerItem);
#

nothing changes somehow

vast grove
#

Problem. You didn't actually set it

halcyon phoenix
#

what did I miss?

vast grove
#

Use -=

halcyon phoenix
#

OH LOL

#

rookie mistake again

#

that's strike 2 of today

#

thanks

vast grove
#

coronalol small shit

#

Big problems. Computers are either easy or insanely hard

halcyon phoenix
#

I solve tons of big problems in this code yet I can't even spot this kind of issues

halcyon phoenix
full idol
#

I'm guessing the debugger can't be used on realms?

vast grove
#

Nope

full idol
#

RIP

#

I have a realm that's lagging massively and I'm not sure if it's the addon

#

1 player out of 10 and it's getting like 5 TPS

vast grove
#

Have ya tried downloading the world?

#

And then running it locally

full idol
#

The addon works fine locally, I assume it is just bad servers. The world file can't be downloaded as it's too big

vast grove
#

Bedrock shit then

night acorn
#

is there a way to run a command as the server instead of a player?

#

like world.runCommand() or smth

woven loom
#

world.getDimension('overworld').runCommand()

night acorn
#

ok

distant tulip
#

if you already have the player reference it is better to do player.dimension.runCommand

fathom hemlock
#

is there a way to modify a chest without replacing it?

worldly heath
#

where can i find documentation for world dynamic properties

#

also is worldinitialise depriciated?

fathom hemlock
#

or replacement

fathom hemlock
#

thx dude

round bone
#

👍

stark kestrel
#

Is it possible to get block broken % or smth?

#

Like how much is it broken

#

AND also when a player stopped mining it

woven loom
#

try item events

twilit sky
# fathom hemlock question is there a event that checks if someone takes a item from the gound (pi...

There's also this new event in 2.1.0-beta: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/playerinventoryitemchangeaftereventsignal?view=minecraft-bedrock-experimental

It should be in the latest update (1.21.90); I believe it's coming to stable in the next update (1.21.100).

Contents of the @minecraft/server.PlayerInventoryItemChangeAfterEventSignal class.

fathom hemlock
#

thx

safe stream
#

2.0.0 is out ??

wary edge
#

Yes.

safe stream
#

hell yeah

valid ice
#

anyone know why doing this:

const entity = world.overworld.spawnEntity('f8:raycast', location);
entity.setProperty('f8:active', true);

does not set the property to the entity? It sets correctly if I dimension.getEntities() and set it in there, but not with the Entity class off the dimension.spawnEntity

valid ice
#
    world.overworld.getEntities({ type: 'f8:raycast' }).forEach(ent => { 
        console.warn(ent.getProperty('f8:active'))
    })
#

just spamming false in console

#

if I set it in the forEach it updates as expected

wary edge
valid ice
#

yes

#

I know

#

That's not the issue

wary edge
#

I've never had this issue, I setproperty and it applies. Verified via client sync.

#

For console.warn I usually waitTicks(1) then verify.

valid ice
#

I'm setting the property in a separate function altogether, it has nothing to do with it applying the property change next tick

#

The forEach console log is only to verify the properties and is being ran in a runInterval

wary edge
#

Ah I see, I assumed the two code were being ran in succession.

valid ice
#
system.runInterval(() => {
    world.overworld.getEntities({ type: 'f8:raycast' }).forEach(ent => {
        console.warn(ent.getProperty('f8:active'))
    })
})

const entity = world.overworld.spawnEntity('f8:raycast', { x: -5994.5, y: 64, z: -5998.5 });
system.runTimeout(() => {
    entity.setProperty('f8:active', true);
}, 1);

Pretty much just this

#

And it's just

#

I tried system.waitTicks as well, it did not change

wary edge
#

Was this an issue in previous versions?

valid ice
#

dunno

#

I didn't have this code on previous versions

knotty plaza
#

Maybe your minecraft:entity_spawned event is setting the property to false?

valid ice
#

Don't even have that event in the entity code

knotty plaza
#

Maybe another interval is setting it?

sharp elbow
#

I would defer in acquiring the entity using EntityLoadAfterEvent.

sterile epoch
#

was the .isOp method removed in 2.1.0-beta? It was working in 2.0.0-beta

sharp elbow
#

@valid ice May this be something you can adapt?

export function onEntityLoad(id, callback) {
  const handler = world.afterEvents.entityLoad.subscribe(function cb(arg) {
    if (!arg.entity.typeId != id) return;
    callback(entity);
    world.afterEvents.entityLoad.unsubscribe(handler);
  });
}
world.overworld.spawnEntity('f8:raycast', { x: -5994.5, y: 64, z: -5998.5 });
onEntityLoad('f8:raycast', (entity) => {
  entity.setProperty('f8:active', true);
});
#

Want to unsubscribe from it after, of course

wary edge
#

EntityLoad has never worked properly for me. I would use EntitySpawn.

valid ice
#

There’s definitely workarounds I can do to get it functioning, I’m just unsure of why it refuses to set in the first place

sharp elbow
#

Perhaps just a flaw. Or a quirk with properties specifically.

distant tulip
sharp elbow
#

Go with the silly workaround for now, then report that as a bug to whomever/wherever it is most appropriate to

knotty plaza
sharp elbow
#

Could be that I'm used to using EntityLoad with structures. I have not tried such a system with Dimension.spawnEntity

distant tulip
#

iirc it works in both cases

wary edge
sterile epoch
sharp elbow
abstract cave
#

for some reason i cant get an entities location when i use player.getEntitiesFromViewDirection

#

can anyone help me with this?

sullen ocean
#

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
NOTE: Some things on that site will not work due to being removed for security reasons, or they don't apply / were not added.

https://regex101.com/
This site helps with testing if a Regular Expression pattern is valid. You can also use it to help with testing that it is working as intended.
NOTE: Remember to select the "ECMAScript (JavaScript)" flavor before you start. (Also note that some stuff might not work with the Scripting API).

chrome gyro
sullen ocean
chrome gyro
sullen ocean
#

just like how 123 is a number literal and "omg" is a string literal...

chrome gyro
sullen ocean
#

?

#

That is a regular expression pattern

#

It isn't exactly a "filter".

chrome gyro
#

Gotcha, but those are opposite right? The regular expression pattern is the opposite of a literal string?

mssg.match([^0-9])

sullen ocean
#

[^0-9] is invalid JavaScript.

chrome gyro
#

Oh uh, 🤔 I think I need to learn more lingo to have this conversation haha.

sullen ocean
#

A regular expression pattern must be surrouneded by / characters:

/[^0-9]/  // that is a regular expression literal.
'foo'  // that is a string literal
"bar"  // this is also a string literal

// This creates a variable named `first_name` and
// points it to the area in memory holding the string
// with the value of `Billy`
let first_name = 'Billy';

// Similar but instead points to the area in memory
// holding the object instance for the regular
// expression (with the pattern shown inside it).
let pattern = /^[0-9a-zA-Z]+$/;

// Both of the following two lines are the same.
result = first_name.match(pattern);
result = pattern.exec(first_name);
woven loom
#

whats popin

sullen ocean
#

Not much

sullen ocean
chrome gyro
sullen ocean
#

This only tests if the pattern was found or not. Use if it you are not going to take specific parts out of the string that the regular expression matched against.

REGULAR_EXPRESSION.test(STRING)

These always create a new Array if it succeeded.

STRING.match(REGULAR_EXPRESSION)
REGULAR_EXPRESSION.exec(STRING)
sullen ocean
chrome gyro
sullen ocean
#

Yes, but it may take a moment for the JavaScript engine to actually remove it from memory.

chrome gyro
#

Ok, awesome. so it does cost more, and shouldn’t be used in a repeated every tick or something, but for a one time test probably is ok. Thank you for your detailed responses!!

sullen ocean
#

Using a regular expression object's test method is more ideal if you only want to test if it matches some criteria.

#

But why test every tick?

#

I don't think you should be testing it every tick unless you are trying to debug why something is broken.

jagged gazelle
#

Guys

sullen ocean
jagged gazelle
#

Anyways, is the face location bugged?

sullen ocean
#

Are you expecting it to be somewhere it isn't?

wary edge
jagged gazelle
#

MFA lmao

#

I lost my codes

chrome gyro
#

I just mean hypothetically you wouldn’t ever want to do that since it would be so costy.

sullen ocean
#

2FA? ....

chrome gyro
jagged gazelle
#

Multi factor authentication...

jagged gazelle
sullen ocean
#

The more common term is Two-Factor Authentication or 2FA for short.

sullen ocean
#

Mainly was directed towards those who didn't understand what you meant

chrome gyro
sullen ocean
#

It is, especially if your email is locked behind it as well.

distant tulip
#

is this what are you referring to?

jagged gazelle
# distant tulip

yes but it some location of the block it works but when place in some it's broken asf.

#

You can't tell me my script is broken if my script is literally small asf

#

And I rarely make broken script 😭

sullen ocean
#

Assuming you are using the player's face, have you tried to add the value to the player's coordinates?

jagged gazelle
#
import { world, system } from '@minecraft/server';

world.beforeEvents.playerInteractWithBlock.subscribe((ev, { block, blockFace, faceLocation } = ev) => {
  if (blockFace !== 'Up' || block.typeId !== 'minecraft:furnace') return;

  ev.cancel = true;

  const dir = block.permutation.getState('minecraft:cardinal_direction');
  let { x: fx, z: fz } = faceLocation;

  if (dir === 'east') [fx, fz] = [1 - fz, fx];
  else if (dir === 'south') [fx, fz] = [1 - fx, 1 - fx]
  else if (dir === 'west') [fx, fz] = [fz, 1 - fx];
  // else {}

  const cell = `${String.fromCharCode(65 + Math.floor(fx * 8))}${Math.floor(fz * 8) + 1}`;
  console.error(cell);
});```
distant tulip
#

maybe share your code and the problem you are facing

jagged gazelle
sullen ocean
wary edge
#

Are you using 2.0.0?

jagged gazelle
sullen ocean
#

Why are you not also outputting the coordinates in your "error"s you are making?

jagged gazelle
sullen ocean
#

as in the coordinates you are using after the calculations.

#

(and before)

jagged gazelle
#

Wait I'll be dealing with my 2fa

sullen ocean
distant tulip
jagged gazelle
jagged gazelle
#

Bruh, wait.

untold garnet
#

can we remove the namespace of the custom command now?

distant tulip
untold garnet
#

i see

#

thanks

distant tulip
#

shouldn't this be different? or is it local based but not based on the block origin

#

actually no, @jagged gazelle there is your answer

#

it is not based on the block origin

#

the video you sent is of blocks in different zones +x +z and -x -z

#

and that is why they are different

jagged gazelle
#

Ohhh damn.

#

Okk I didn't fully understand the docs, my reading comprehension is bad

jagged gazelle
distant tulip
#

this is basically what you are doing with the 1 - xy
you can see how it is wrong in the -axes

dusky flicker
#

generally regex its heavy as hell

#

its not good for performance stuff

#

and nobody understands this shit

jagged gazelle
#

I love regex, I spend a whole 2 months understanding them

#

Bonus? I lost my mind. I hate it.

dusky flicker
#

its preferred to simply avoid them

dusky flicker
#

when i see some code right regex i simply skip that part

distant tulip
dusky flicker
jagged gazelle
#

They are so handy.

distant tulip
#

true

#

i would use includes and startsWith and other simple stuff when i can, but stick to using regex for complex matching patterns

jagged gazelle
#

My mood is pretty good rn that's why I'm back here lol

#

-# off topic 😆

distant tulip
#

great to have you back haha
hope things stay that way for you, i mean shit happen but that is life for you

dusky flicker
#

if theyre single char for sure

#

normally i prefer writing tokenizers when talking about more complex pattern

#

but usually the patterns i tend to make arent human readable

#

so regex is not an option

distant tulip
dusky flicker
distant tulip
#

haven't tested out the performance of those so i can't really tell
i will take your word for it lol

dusky flicker
#

i think i still got something on my browser history

distant tulip
#

charAt and charCodeAt
any different?

dusky flicker
#

something like that

#

charCodeAt gets the u16 value of the character

chrome gyro
# dusky flicker its heavy

Katie mentioned that too. It should be ok for my purposes. It will only be for a little bit that coincides with closing a ui. I’ll just use the better method going forward.

distant tulip
#

i assume charCodeAt return a unicode?

dusky flicker
#

if so yeah

#

it gets the underlying number for that character in utf16

distant tulip
#

alright

dusky flicker
#

why the hell is discord so buggy on cellphone?

#

damn

jagged gazelle
#

bloating in searching too

halcyon phoenix
jagged gazelle
#

Lost my main acc because of 2fa shyt

halcyon phoenix
#

also does anybody know the link for the new startup event changelog that will be kind of replacing worldLoad?

halcyon phoenix
jagged gazelle
#

Oof

valid ice
#

@wary edge @sharp elbow Apparently the issue was the delay in the function.. doing spawnEntity and then setProperty in the same tick does set the property, but delaying setProperty does not set it. I tried recreating it in a bugtest pack, but it worked... seems like something weird with my codebase.

valid ice
#

guh

#

😭

shut vessel
#

Hi, my command fails to detect that when the targetcamps is at 1 or 2 it displays its camp

if(msg.startsWith("!scanner")) {
    if (!player.hasTag("oracle")) return player.sendMessage("§cVous n'avez pas accès a cette commande !");
    
    var arg = msg.slice(9).trim().toLowerCase();
    if (!arg) return player.sendMessage("§cUtilisation: !scanner @pseudo");
    
    if (arg.startsWith("@")) {
        arg = arg.slice(1);
    }

    // Vérifier le cooldown
    const cooldownScore = f.getScore("cooldown", `${player}`, true);
    if (cooldownScore > 0) return player.sendMessage("§cVous devez attendre avant de réutiliser ce pouvoir !");

    // Trouver le joueur ciblé
    const targetPlayer = world.getAllPlayers().find(p => p.name.toLowerCase() === arg.toLowerCase());
    if (!targetPlayer) return player.sendMessage(`§cJoueur "${arg}" introuvable ou hors ligne !`);

    // Récupérer le camp du joueur ciblé (pas du scanner)
    const targetCamps = f.getScore("camps", `${targetPlayer}`, true);

    // Ajouter le tag scanner
    player.runCommand(`tag "${player.name}" add scanner`);

    // Déterminer le message selon le camp
    let campMessage = "";
    if (targetCamps == 1 || targetCamps == 3) {
        campMessage = "§qGentil§e";
    } else if (targetCamps == 2) {
        campMessage = "§4Méchant§e";
    } else {
        campMessage = "§7Inconnu§e";
    }

    // Envoyer le résultat
    player.sendMessage(`§eVous venez de scanner ${targetPlayer.name} et il est ${campMessage}. Désormais vous pourriez le scanner à nouveau dans 2 Jours`);
    
    // Appliquer le cooldown et retirer le tag
    player.runCommand(`scoreboard players set @s cooldown 2`);
    player.runCommand(`tag "${player.name}" remove scanner`);
}```
#

could someone help me please

valid ice
#

what is "f", and the getScore() takes the player first, not the objective

#

If "f" is the score objective, you need the player/entity as the first parameter, as the objective is built into the "f"

#

gotcha

#

Swap your objective & player, in that case

#

const targetCamps = f.getScore(targetPlayer, "camps", true);

#

Assuming that you are importing as f

shut vessel
#

okkay

#

thanks

woven loom
#

@random ibex ask in here

random ibex
#

Can someone help me make a script so that a player cannot exit the game during a battle?

woven loom
#

Is that even possible

jagged gazelle
#

I don't think so.

#

Leaving the world is something you can't stop rn.

valid ice
#

you can punish the player upon logging back in

#

or, something more advanced that I did recently, was spawn an unmoving gametest bot in their place and copy over their player data, so if they log out the bot has to be consciously killed

valid ice
#

@minecraft/server-gametest module; lets you run unit tests on certain game mechanics. Not terribly useful, but the simulated players in the module are a carbon copy of actual players in-game and let you play with and set their AI.

sharp elbow
#

That is pretty clever

valid ice
#

It also removes the simulated player after 10 seconds, so if they have not been killed by then they've successfully "logged out" regardless of where they are or what their health was at the time (hitting them resets the timer)

halcyon phoenix
#

that's interesting, ima look into it, thanks for the info.

woven loom
#

what about structure

halcyon phoenix
#

hello again people I need some suggestion on how to do this:

OnTick:
function sspawn entity after 5 seconds
function spawn entity after 2 seconds

however there is a conflict with the timer variable im using, what's one way to make a unique timer for each?

vast grove
#

Use a map and store each timer separately via a manager class or something

halcyon phoenix
#

manager class?

vast grove
#

Yeah. Like a timer manager class

valid ice
#

tick every second, run something every 2nd tick, run something else every 5th tick

#

in-code counter to store current ticker

vast grove
#

You could also just use system.runInterval() with the delay

wary edge
#

Or have two ontick custom components

#

Not even that, system.currentTick % 2

#

Theres multiple ways to handke thism

cinder shadow
#

darn. thought we had localization strings available for custom command description and parameter names

harsh hare
#

guys

#

how to detect player place block

#

i am using place block and interact block event, but i cant figure it out to detect if player is placing block and not interacting block

#

before event btw

jagged gazelle
marsh pebble
#

finnafinest

prisma shard
prisma shard
marsh pebble
prisma shard
#

no

#

unless you tell what your problem is

marsh pebble
#

yes

prisma shard
#

ok.

#

"yes"
-speceficprotienmilkbar

marsh pebble
#

um

#

idk what i need help with

#

wait

#

i got it

marsh pebble
prisma shard
#

what

marsh pebble
#

how to fix

prisma shard
#

how to fix what

#

what is problem with math.random

marsh pebble
#

put in scripts

prisma shard
#

and

marsh pebble
#

put in manifest

prisma shard
#

ok.

marsh pebble
#

it wont work

prisma shard
#

your first bet is:
learn scripting first

marsh pebble
#

i did

prisma shard
#

the fuck you want by putting math.random() inside the whole script and that's it

marsh pebble
#

bc

prisma shard
#

nah it's just kind of joke bye

marsh pebble
#

i asked chatgpt

#

it said put in main.js

#

for rng system

#

pls

prisma shard
#

leave me

#

😭

marsh pebble
#

what

prisma shard
#

wat do you even want to make

valid ice
#

Send your current code, what you are trying to do, and why it doesn't work

prisma shard
#

bro just put math.random() in whole script and calls it a script

marsh pebble
#

what

valid ice
#

Saying a native JS mathod doesn't work is extremely bad debugging and does not tell us anything about what code you are writing

prisma shard
#

dude do you think saying that 'math.random' is your problem can help us identifing the problem??

#

Tell me your error

#

and full code

valid ice
#

So to answer properly: what exactly do you mean by "fix"?
💔

prisma shard
#

hero do you watch jojo

valid ice
#

no

prisma shard
#

it's good watch it

valid ice
#

eh

#

no time

prisma shard
#

okay

#

just anime cartoon fighting stuff
it's worth it watching

vast grove
#

Dude is at it again?

valid ice
prisma shard
#

what

prisma shard
marsh pebble
#

stop

#

i asked for help and you told me to learn it myself

chrome gyro
#
system.runInterval(() => {
    const dimensions = ["overworld", "nether", "the_end"];
    dimensions.forEach((dimension) => {
        const entity = world.getDimension(dimension).getEntities({ families: ["cnb_entity"], })
        if (!entity) return;
        entity.forEach(entitys => {
            if (entitys.dimension.getBlock(entitys.location) == undefined) return;

Would it help lag if I somehow got the dimension of any loaded entity then ran the thing? Is this actually executing the whole thing three times?

abstract cave
vast grove
prisma shard
#
const targetedBlock = player.getBlockFromViewDirection()[0]?.block```
valid ice
#

me when extend native properties

vast grove
#

Idk how extensions work in JS. I'm a noob :/

#

Actually imma look it up

marsh pebble
#
const formatTime = (milliseconds) => ({
    days: Math.floor(milliseconds / (1000 * 60 * 60 * 24)),
    hours: Math.floor((milliseconds / (1000 * 60 * 60)) % 24),
    minutes: Math.floor((milliseconds / (1000 * 60)) % 60),
    seconds: Math.floor((milliseconds / 1000) % 60),
});

fix?

valid ice
#

super easy, barely an inconvenience

chrome gyro
valid ice
#

The trick lies in the .d.ts file, because js does not give one iota about what you're changing

#

-# typescript, on the other hand...

vast grove
chrome gyro
#

I'll have to look into doing that, good idea, it would be helpful to know for optimizing. Still a bit new though, so it might be a little bit. Thanks!

vast grove
marsh pebble
#

@vast grove please block me

vast grove
#

No. I'll just use the ignore button

chrome gyro
marsh pebble
#

ok i'll block you

chrome gyro
#

Interesting.

vast grove
#

The difference

marsh pebble
marsh pebble
# chrome gyro Too many 60s
function addItems(player, items) {
    system.run(() => {
        try {
            const inv = player.getComponent("inventory").container;
            for (let [item, count, enchants] of items) {
                const itemStack = new ItemStack(item, count);
                if (enchants && enchants.length > 0) {
                    const enchantComp = itemStack.getComponent(
                        "minecraft:enchantments"
                    ).enchantments;
                    for (const enchant of enchants)
                        enchantComp.addEnchantment(enchant);
                    itemStack.getComponent("minecraft:enchantments").enchantments =
                        enchantComp;
                }
                inv.addItem(itemStack);
            }
        } catch (error) {
            console.log("inventory", error);
        }
    });
}```
chrome gyro
marsh pebble
#

@chrome gyro

valid ice
vast grove
#

I looked it up. Looks fairly simple but a bit more effort than what I am used to :/

valid ice
#

Adds a few things to Entity class, and by extension Player class, as well as adds some stuff to native js modules

chrome gyro
valid ice
#

Me when micro-optimizations but they're for MC modules steve_hmmm

chrome gyro
#

Is there a way to do a memory dump once the load gets to be too much? I'm probably not saying that correctly, hopefully that makes sense.

valid ice
#

huh

vast grove
chrome gyro
#

Aw man, ok. thanks again.

vast grove
#

One way to improve memory management is to reuse stuff like object pooling

#

Or even caching

#

And then reducing API calls is another mc specific optimisation

chrome gyro
#

That's a good idea, I think I've done as much of that as I could though. I've consolidated a lot of variables... not sure I can get that down anymore... I think I added too many variable haha.

chrome gyro
valid ice
#

If you're using a server, I'd recommend a daily restart to clean up unfound script garbage

#

Even if not BDS, it's good practice to perform a daily restart

vast grove
#

So any function you call that is part of the MC types is an api call, some of the properties/members are api calls too for some reason...

chrome gyro
chrome gyro
vast grove
#

Eeehhh yeah most things are an api call. Some aren't cuz they are constants iirc.

valid ice
chrome gyro
valid ice
#

Native JS calls are extremely efficient, being a language that has been worked on for many many years, so micro-optimizations in that area easily pale in comparison to those in script API

chrome gyro
#

I used scoreboards to store a lot of the variables, I think the issue is calling them back to do the thing.

#

Native JS calls, ok I'll have to look into the differences between them then.

valid ice
#

Generally don't worry about native calls

#

Those are pretty dang efficient

vast grove
#

Apparently Entity.position is an api call thonk

#

Idk. Inconsistencies. Should make it so any api call is a function, not a property or member

valid ice
#

One thing I do for scoreboards, where I use them, is:

const objDB = {};
setScore:
  const scoreObj = objDB[objective] ??= world.scoreboard.getObjective(objective);
getScore:
  (objDB[objective] ??= world.scoreboard.getObjective(objective))?.getScore(this) ?? 0;

TLDR just caching the ScoreboardObjective class used to retrieve values

chrome gyro
valid ice
#

Speedy!

vast grove
valid ice
#

better than retrieving score every time

valid ice
# vast grove A what now?

They made isValid for blocks, items, entities, dimension, location, etc. a property rather than method

vast grove
#

Bruuuuhhhh

valid ice
chrome gyro
#

Yeah, plus if I do an update, I only have to change it in one place.

vast grove
#

What the hell is going on...

#

With the api

#

Or the team

#

What standard are they following

valid ice
#

And yet here we are complaining on Discord, the best coded website of all time™

#

I love modern ~~web ~~dev

valid ice
vast grove
#

Makes sense. I was thinking more of coffee with 10x caffeine

chrome gyro
#

-Preworkout-

chrome gyro
chrome gyro
#

Each entity rn has a 5 ms delay when ran at full speed which is every tick. Is that bad? Every time I add an entity it ups by 5 ms. After about 20 it starts to make things like throwing items slow significantly.

vast grove
#

Oh yeah that's not great...

chrome gyro
#

Hmmm I'm tempted to add a cap on ticks. so players can only make the speed down to like 10 ticks.

chrome gyro
#

Hmmm.. nope haha the delay is the same no matter the ticks. I think the load is too big.

vast grove
#

You could try using jobs. But idk if that's a good solution since I've never used them. Look at what part is the biggest slow down and try to find solutions

#

Like is it the getting blocks part?

#

Or getting the entities part?

#

If it's the getting entities part, try looking at caching them

chrome gyro
vast grove
#

I meant like listening to entity spawned, loaded and destroyed events, add them to an array and loop over that

#

Instead of doing a double loop

#

It's event based which will improve perf a fuck ton

#

You're essentially skipping 2 API calls

#

Per tick

chrome gyro
valid ice
#

Really, really good

#

But

vast grove
# chrome gyro Oooh interesting, ok I'll try that tomorrow.

The other code, you'll have to figure out how you're gonna improve. Like reducing the amount of variables you're getting from the API into something smaller or even just storing less things and possibly even moving some to function commands.

chrome gyro
vast grove
#

Is there a reason to use scoreboards? Otherwise you could use dynamic properties

chrome gyro
#

I think they run faster??? Idk, also I haven't learned dynamic properties yet, I keep seeing them when I search, but haven't figured out exactly what they are.

#

Or is it the same as properties in an entity?

vast grove
#

They're essentially like variables you can store on the entity or world. They are individual to each add-on and they're persistent

#

Plus you can store a lot in them

#

Very useful, fairly optimised

valid ice
#

Strings, bools, numbers, even vectors

valid ice
vast grove
#

Entity.setDynamicProperty(identifier: string, value?: boolean | number | string | Vector3): void

#

Very easy to use. Easier than scoreboards

chrome gyro
#

what the whaaaaat? I just found out this was in my code for the function:

    for (let i = 0; i < 1; i++) {

}

I think I was too inexperienced at the time when I added that part to know what it did.

#

Oh wait... maybe it wouldn't have mattered?

valid ice
#

Entity properties are fantastic when communicating between regular BP & RP files, but have limited use when it comes to set-able values (have to define beforehand)

Dynamic properties are solely scripts, and can really set whatever values you want (JSON.stringify() & JSON.parse() OP) with the limitation of being only script based

chrome gyro
#

Oh! Wait a minute... is this a dynamic property?:

grouping.setFloat("variable.cnb_ppl_ptime", time )
vast grove
#

Mmmm no. Unless that's like a wrapper api

#

Or is that a molang variable?

valid ice
#

That’s a molang map, probably a particle, If I had to guess

chrome gyro
#

nvmd sorry, I just looked it up on the main site. I see now.

#

Yeah. good guess.

valid ice
#

Also limited, sadly, as you have to “infer” the type of variable using regular json beforehand

chrome gyro
#

Ok, hmm maybe I need to try out some dynamic properties then and see if applying them helps... Thank you both so much! I have a lot I can try now.

valid ice
#

The big thing is that dynamic properties are solely BP side with zero RP interactions, so

chrome gyro
#

Oooh I was just going to ask that. Ok I gotcha.

vast grove
#

... Weird shit.

chrome gyro
valid ice
chrome gyro
#

Sorry, that probably didn't make any sense I can type it out.

valid ice
#

Caching helps a lot, but be wary of how much caching— it does make a difference.

#

You’re definitely fine for score caching, don’t worry

chrome gyro
#

That's a fair warning... I think whatever addon I make next I will make sure it doesn't have so many variables by design.

valid ice
#

Performance is the main concern when it comes to bedrock scripts

vast grove
#

Wouldn't be so damn important if they used C# instead

valid ice
vast grove
#

I'm still annoyed they weren't able to use it

valid ice
#

When C

#

When qs

#

I want variable variables, dammit

chrome gyro
valid ice
#

I want the operator status of the player to fluctuate depending on the quantum state of the qubit I’m referencing

vast grove
#

At least with C# you're not completely free to do everything but it's still very good since it's optimized at compile time. Roslyn analyzers go brr

#

Oh fuck. Source generation!

chrome gyro
#

Does an "observer_block" count as an "observer"?

chrome gyro
vast grove
#

C# has it's own built-in array pool.

var encodeBuffer = ArrayPool<byte>.Shared.Rent(Constants.MaximumEncodedBytes);
#

So much stuff that JS just doesn't have

valid ice
#

Js is bad but of course humanity adapted it for the general internet

vast grove
#

It's like a set of glass cups, why use a new one when you can just wash and reuse the same one?

valid ice
#

Why do that when you can just order new cups every time you need more

vast grove
#

Oh gosh

valid ice
#

Sure, it costs more, but think of the convenience!

vast grove
#

Garbage man won't like you

valid ice
#

Jason Momoa?

#

He doesn’t know me anyways (yet)

halcyon phoenix
#

I had the chance to learn C# with rimworld but it was too difficult to me

vast grove
#

Welp. My day is wasted. I was gonna work on something then I didn't. Now I just wanna play a game.

marsh pebble
#

HELP

vast grove
#

wait did that site get pulled?

marsh pebble
vast grove
#

Ok. So ask questions properly then I'll stop being a dick to you

marsh pebble
#

        if (player.location.y <= 319 && player.location.y >= -64 && player.dimension.id === "minecraft:overworld") {
            const blockFeet = player.dimension.getBlock(player.location);
            const headLocation = { x: player.location.x, y: player.location.y + 1.0, z: player.location.z };
            const blockHead = player.dimension.getBlock(headLocation);
            if (blockFeet?.isValid() === true && blockHead?.isValid() === true) {
                const lightLevelFeet = await queryLightLevel(player.dimension, player.location);
                objLightFeet.setScore(player, lightLevelFeet);
                const lightLevelHead = await queryLightLevel(player.dimension, blockHead);
                objLightHead.setScore(player, lightLevelHead);
            }
        }
        if (player.location.y <= 127 && player.location.y >= 0 && player.dimension.id === "minecraft:nether") {
            const blockFeet = player.dimension.getBlock(player.location);
            const headLocation = { x: player.location.x, y: player.location.y + 1.0, z: player.location.z };
            const blockHead = player.dimension.getBlock(headLocation);
            if (blockFeet?.isValid() === true && blockHead?.isValid() === true) {
                const lightLevelFeet = await queryLightLevel(player.dimension, player.location);
                objLightFeet.setScore(player, lightLevelFeet);
                const lightLevelHead = await queryLightLevel(player.dimension, blockHead);
                objLightHead.setScore(player, lightLevelHead);
            }
        }
        if (player.location.y <= 255 && player.location.y >= 0 && player.dimension.id === "minecraft:the_end") {
            const blockFeet = player.dimension.getBlock(player.location);
            const headLocation = { x: player.location.x, y: player.location.y + 1.0, z: player.location.z };
            const blockHead = player.dimension.getBlock(headLocation);
            if (blockFeet?.isValid() === true && blockHead?.isValid() === true) {
                const lightLevelFeet = await queryLightLevel(player.dimension, player.location);
                objLightFeet.setScore(player, lightLevelFeet);
                const lightLevelHead = await queryLightLevel(player.dimension, blockHead);
                objLightHead.setScore(player, lightLevelHead);
            }
        }
    }
});```
Getting an error on line 10
vast grove
#

Again. not descriptive enough

vast grove
marsh pebble
marsh pebble
little hull
#

is it possible to modify the players health componenet and add a minimum value to it then modify it again and remove it?

vast grove
little hull
#

through scripts ofcourse not using player.json

marsh pebble
vast grove
#

Ok. So what is the error?

#

Instead of just saying There's an error on line 10 This does not help. It's like saying My power doesn't work

marsh pebble
#

Dont you think i would be able to fix it if i knew

vast grove
#

Buddy. You know there is an error on line 10. Show the error

#

otherwise I am going to just stop

marsh pebble
#

oh

#

it's not on line 10

#

i meant to say 12

vast grove
#

And this shit is why I'll say bye bye!

marsh pebble
#

And you not even telling me either is crazy

vast grove
#

Oh sorry. did you say something?

distant tulip
distant tulip
little hull
#
const healthComp = deadEntity.getComponent(EntityComponentTypes.Health);
      if (healthComp && healthComp.currentValue <= 0) {
        healthComp.effectiveMin;
      }```   what does this do the effectiveMin?
distant tulip
#

the script you send does nothing

#

effectiveMin return the min of the health

#

that property is readonly

marsh pebble
#
world.afterEvents.dataDrivenEntityTrigger.subscribe((ev) => {
    let lightLevel:
    ev.getModifiers().forEach((d) => {
        d.addedComponentGroups.forEach((compGroup) => {
            if (compGroup.startsWith("light_level:")) {
                lightLevel = parseInt(compGroup.replace("light_level:", ""));
            }
        });
    });
    ev.entity.remove():
    promiseMap.get(ev.entity)?.(lightLevel);
}, { entityTypes: ["detect:light_level"] });```
saying there is an error?
little hull
distant tulip
gilded shadow
#

what's the fastest way to visually debug a position (like a line or just a block)

#

particles or entities?

worldly heath
#

console.warn ?

gilded shadow
#

or are there other methods

marsh pebble
gilded shadow
distant tulip
marsh pebble
worldly heath
distant tulip
marsh pebble
#

oh

#

thank you

worldly heath
#

whats the current stable scripting version ?

distant tulip
#

2.0.0

marsh pebble
halcyon phoenix
#

hey im tryna use the search on jayly's docs and searched entity however it doesn't show the entity class

#

broken?

worldly heath
#

i tried to change from 1.1.0 to 2.0.0 and all of my forms shows error , is there any docs on new syntax ?

distant tulip
halcyon phoenix
#

I see thanks

distant tulip
vast grove
distant tulip
marsh pebble
#

how do i get rid of this blocked message thingy

halcyon phoenix
distant tulip
distant tulip
granite badger
marsh pebble
distant tulip
granite badger
halcyon phoenix
#

might be uBlock?

halcyon phoenix
distant tulip
#

i don't have it either

marsh pebble
worldly heath
drifting ravenBOT
#
Learn JavaScript

As the Script API is a framework built on JavaScript code, having an understanding of JavaScript is key.

If you are being shown this, then you most likely are a beginner with JS and could use a little guidance.

Videos on Learning JavaScript
Javascript in 1 hour
Javascript Classes in 1 hour

Web Guide:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

Reference Sites:
https://www.w3schools.com/jsref/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://javascript.info

halcyon phoenix
distant tulip
halcyon phoenix
coral ermine
#

how to check player game version?

marsh pebble
#

here u go

distant tulip
halcyon phoenix
granite badger
#

Can you check if this file is loaded?

marsh pebble
halcyon phoenix
marsh pebble
halcyon phoenix
distant tulip
halcyon phoenix
#

there's scrollbar now

#

what da heck...

marsh pebble
#

might've just have been an issue with the browser your using

halcyon phoenix
#

probably or connection issues

#

I have no idea I never dealt with websites before

granite badger
#

refreshing the page might work, I just used a very hacky way to make the scrollbar (since typedoc doesn't officially support this)

marsh pebble
halcyon phoenix
#

...

#

anyways thanks for the website jayly I'll just refresh it if it happens again

worldly heath
distant tulip
halcyon phoenix
#

entity.id is unique across all entities right?

worldly heath
cerulean cliff
#

wierd how onPlayerBreak in custom components is lacking docs in the types

distant tulip
jagged gazelle
# jagged gazelle
import { world } from '@minecraft/server';

world.beforeEvents.playerInteractWithBlock.subscribe((ev, { block, blockFace, faceLocation } = ev) => {
  if (blockFace !== 'Up' || block.typeId !== 'minecraft:furnace') return;
  
  ev.cancel = true;
  
  const dir = block.permutation.getState('minecraft:cardinal_direction');
  let { x: fx, z: fz } = faceLocation;
  const { x, z } = block.location;
  
  if (x >= 0) fx = 1 - fx;
  if (z < 0) fz = 1 - fz;
  
  if (dir === 'east') [fx, fz] = [1 - fz, fx];
  else if (dir === 'south') [fx, fz] = [1 - fx, 1 - fz];
  else if (dir === 'west') [fx, fz] = [fz, 1 - fx];
  
  const cell = `${String.fromCharCode(65 + Math.floor(fx * 8))}${Math.floor(fz * 8) + 1}`;
  console.error(cell);
});```

-# fixed
cerulean cliff
halcyon phoenix
#

ohhh

jagged gazelle
worldly heath
granite badger
#

Modal*

worldly heath
#

oh im stupid mb

stark kestrel
cerulean cliff
remote oyster
dusky flicker
halcyon phoenix
distant tulip
#

it is this, the error is in the code he sent

sharp elbow
#

I like to think that most properties (if not every property) is a lookup call on the API

vast grove
#

Read further.

sharp elbow
#

I did, and I do not suppose I missed anything.

vast grove
#

The message right after. I said api calls should be functions. not properties/members

#

I understand your point

#

It's just. It's a goddamn variable.

sharp elbow
#

Then all Mojang need do is remove location and rename it to a method of getLocation. Now it behaves like you think :)

#

I like to make a copy of the entity's location so I only do one lookup. Then when I need to read from the location again, I have it cached.
const location = {...entity.location}

vast grove
#

Yeah I know that...

sharp elbow
#

If I need to manipulate the location, I can edit that vector as many times as I please. Then I can set it at the end

sharp elbow
vast grove
#

Syntactically. having it be a property/member doesn't explicitly state it's something that's available to get without having to make some conversion api calls. Kinda like a web server, would you hide a get request behind a property? It just doesn't make sense...

sharp elbow
#

That's why I am not a big fan of setters and getters

#

You don't know from an outside interface if that property lookup is doing something more sophisticated behind the scenes.

#

And I guess, in essence, most properties in scripting are getters? Perhaps not literally

vast grove
sharp elbow
#

I can also see a point where including that might be TMI. Generally performance should not be too big of a concern to the lay user

#

I would like an article from the team describing some optimization strategies—real ones at that

#

Or if it does not already exist, how to profile a pack and determine which calls are consuming the most amount of time

vast grove
#

Yeah. That would definitely help a lot of new scripters understanding why their code is so slow.

sharp elbow
#

A colleague of mine wrote some not-so-optimized code a few weeks back that made me want to cry when I read it

#

General utility functions are great when reusing across the pack, but such self-contained functionality really needs a cache if you are going to make repeated calls with very similar data 😢

vast grove
#

I guess this is why wrappers exist? To help alleviate some of those manual caching calls?

sharp elbow
#

I suppose so. A good wrapper would do that, I would think

vast grove
#

I kinda hate how getHeadLocation(); is a function and shows it does something to get something

sharp elbow
#

Same with getRotation. But at least it's clear that it's a method!

#

Replace isValid with getValidity()

vast grove
#

It was apparently changed from a function to property...

wheat condor
#

the word get its just bad

vast grove
#

get is a meaning of getting something but I understand your point in this case.

sharp elbow
wheat condor
#

get sounds more like for Map dynamicProperties usage

vast grove
#

I wonder if Entity.id is an api call. I doubt it is but if it is. Goddamn I would be surprised.

sharp elbow
#

Only one way to find out!

untold magnet
#

why am i unable to detect the food itemStack saturation?

untold magnet
vast grove
#

yup

untold magnet
#

returns undefined

vast grove
#

which one is undefined?

#

the food component?

untold magnet
#

yes ibelieve

#

maybe the itemstack

untold magnet
vast grove
#

thonk what item are you testing it on?

untold magnet
#

steak

vast grove
#

Ok yeah that's weird...

untold magnet
#

the food component is undefined

#

like

#

console.warn(itemStack?.getComponent('minecraft:food')) returns undefined

untold magnet
vast grove
#

But I thought food items were data driven... according to the bp on the mojang samples...

#

wtf

untold magnet
vast grove
#

idk man...

#

it's supposed to be data driven...

wheat condor
vast grove
#

They're holding a cooked beef.

lyric kestrel
#

Original getCamoState average time: 0.051711560000000205 ms
Optimized getCamoState average time: 0.00015244999999937362 ms
Each ran 10k times
goddamn

#

I shoulda been using hashmaps a long time ago

#

That is actually insane how fast it is compared to what I was doing

#

339x performance improvement

#

omg, now my script runs at under 1ms 😭

#

It used to be 20ms when it had to search through a giant map, but now with the optimisations I made, it runs under 1ms to get to the same block check 😭

sterile epoch
lyric kestrel
prisma shard
lyric kestrel
#

Made by Mojang

#

It's amazing

sterile epoch
#

ooh

lyric kestrel
#

It's actually amazing and has made me look through my code due to how shitty it was running

shy leaf
#

it just straight up doesnt work

sterile epoch
#

not at my pc rn

#

so can't download it

untold magnet
shy leaf
#

not sure

#

considering that vanilla food items are data driven, it probably doesnt work for addon items either

untold magnet
#

I'll try it anyway

shy leaf
lyric kestrel
#

wait, what

#

Even with typeId it's still undefined?

#

TypeError: cannot read property 'typeId' of undefined at <anonymous> (./development_behavior_packs/main.js:8) (main.js:8)

prisma shard
#

system run make no sense there

untold magnet
lyric kestrel
shy leaf
#

odd

untold magnet
lyric kestrel
#

[ReferenceError: Native constructor for [ItemStack] does not have required privileges. at ItemStack (native)

untold magnet
#

i can get the vanilla items saturation from the wiki

lyric kestrel
#

Ye

jagged gazelle
lyric kestrel
#

Bit weird to me that you can't get the saturation from vanilla

untold magnet
#

and get the saturation of the other addons food using the script, so i can use it

jagged gazelle
#

food, compost etc. isn't accessible to a VANILLA item

lyric kestrel
#

Still a bit weird they aren't accessible on Vanilla items

jagged gazelle
#

while for custom ones they are exposed that's why they are accessible.

#

Smokey had explained this before.

untold magnet
#

alright,

#

i can work with that

jagged gazelle
untold magnet
#

(i am making AppleSkin for bedrock, so i need to show the saturation when u hold the food on ur hand)

#

lets do this!

jagged gazelle
#

okie, I'm still brute forcing my main acc

#

I hate 2fa, I forgot I have activated it before

valid ice
untold magnet
jagged gazelle
jagged gazelle
#

it would take me 450 thousand years lmao

valid ice
#

That changes every 30 seconds

prisma shard
untold magnet
#

i just need to show how much hunger / saturation u will regen by eating that specific food

lyric kestrel
#

Oh

#

Good luck

jagged gazelle
untold magnet
#

anyways, gotta add the vanilla foods to the system,

untold magnet
jagged gazelle
#

oh wait I thought grabbing the saturation

#

Mbmb

untold magnet
valid ice
#

Why not change the language files

untold magnet
#

i am rendering that on the screen

#

its not a name thing

valid ice
#

Ah was thinking of something else, nvm

untold magnet
#

i will add that anyway

jagged gazelle
#

it was 32... something

untold magnet
#

no limit i believe

#

idk i haven't touched it since 2024

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

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);
}```
-# Found it. Nvm
valid ice
#

Like the illegal enchants!

untold magnet
# valid ice 32767

well, as for my AppleSkin script, i need to add the food nutrition value to the current hunger value of the player,
i can do that pretty easily using the food component, but that doesn't work for vanilla foods so i have to sort the vanilla nutrition value so i can add it to the player current hunger value to render the ui,
how can i do that?

#

like should i use dynamic properties or something?

#

i know, dynamic properties are the best and the easiest method, but i dont think if my loop can make it works correctly

jagged gazelle
untold magnet
#

hold up nvm

untold magnet
jagged gazelle
untold magnet
fading sand
#

how do i check if an entity is touching an block?

prisma shard
#

uh you mean so touching ground...?

fading sand
#

ye, or a wall

#

lol

#

@prisma shard

wheat condor
# fading sand ye, or a wall

player.isOnGround and for the walls you gotta teste the distance from the player to the wall and find the correct one to detect touch

fading sand
#

ye

#

hmm

#

thx

gaunt salmonBOT
full idol
#

I can't find custom compass point locations in the docs. Is it possible? I could just set world spawn but that feels like a bad solution

wary edge
#

No.

valid ice
#

lodestones or setting world spawn

full idol
#

I'm not sure if I'm looking in the right place but I'm reading through item components

valid ice
full idol
#

Ouch, alrighty, thanks!

ivory bough
#

I know this is probably a dumb question but does the value of for loop stay after player leaves the world?

wary edge
full idol
#

To edit player default health do I need to edit the player.json?

jagged gazelle
#

But for increasing, you can use health boost effect too

full idol
#

Alrighty, thanks

#

Wow I managed to mess that up lol

#

Maybe not...

#

I guess no health for me

jagged gazelle
#

apply it as component groups

full idol
#

Ah right, thanks

full idol
round bone
random flint
#

Is this worthy in the script resource or not? Basically, ender chest scanner... stupidly fast
#1386244732794966117 message

full idol
#

I see, thanks

random flint
grim raft
#

yo Im stuck with the applyKnockback,ik how to make it go to the front and back but idk how to make it go to the right and the left of the player

const viewDirection = entity.getViewDirection();

const horizontalForceL = {
                x: viewDirection.x * 1,
                z: viewDirection.z * 1
            }
            return entity.applyKnockback(horizontalForceL, viewDirection.y * 0)```
snow jungle
#

Can you view whats in a shulker using JS yet?

#

I heard about using droppers/placing it down, but not a fan. Just coming back to this, and seeing if any new developments been made on it.

random flint
#

isnt there storage_item component thingy now?

snow jungle
#

I heard about that

jagged gazelle
random flint
#

Why is there a Second coddy

jagged gazelle
woven loom
#

i think theres workaround

untold magnet
random ibex
#

Can someone help me make a script?

untold magnet
random ibex
untold magnet
#

if u want to open a formUi with redeem code system, u can do that but sadly i dont have the codes on my uploaded projects

random ibex
untold magnet
#

In this video, I demonstrate how to use JSON UI in combination with the scripting api in the Minecraft Bedrock Edition

🔗Links :
Like What I Am Doing? Concider Supporting Me! : https://ko-fi.com/dingsel
Join my Discord! : https://discord.gg/tzrmH56JXC
My Website : http://skyls.de
Music : https://www.youtube.com/watch?v=tEzYsaLm7nw&ab_channel...

▶ Play video
random ibex
jagged gazelle
untold magnet
# jagged gazelle i literally said check my acc about me.

btw, how tf is he opening an inventory ui using commands?
https://youtu.be/wdo2tagU388?si=LSoJC7y_CXNw4r4d

What is up crafters? Today I showed you how to convert GUI for Minecraft Bedrock and GeyserMC. That's literally it, this is really simple and lots of people have been asking me for it, SO HERE YOU GO.

Sorry if this video wasn't as entertaining as usually; I had to record it in my conference room.

Converter: https://abishekbhusal.com/j2b_gui/

...

▶ Play video
#

server client things or something?

jagged gazelle
#

I feel like that's not script only

untold magnet
#

like when he typed /rtp in the chat, he have opened an entity inventory somehow

jagged gazelle
#

third party software too

untold magnet
#

like is it servers exclusive only or something

scarlet sable
#
system.beforeEvents.startup.subscribe((int) => {
    const CameraCommand = int.customCommandRegistry;
    const options = ['add', 'reset' , 'remove' , 'list' , 'visit'];
    const command =  {
            name: "easy:cam",
            description: "allows to creat §eCinematic§7 shots with no headache",
            permissionLevel: CommandPermissionLevel.Any,
            optionalParameters: [{
                name: "easy:enum", type: CustomCommandParamType.Enum
            },
            {
        name: "name",
        type: CustomCommandParamType.String,
        optional: true,
      }
            ],
        };
     CameraCommand.registerEnum("easy:enum" , options)
    CameraCommand.registerCommand(command,CameraSystem);
});

function CameraSystem(origin , mode , name){
    const source = origin.sourceEntity;
    if(source.typeId !== "minecraft:player")
        return source.sendMessage(`§c[ERROR]§f -No player detected`);
    if(mode === undefined)
       return source.sendMessage("help");
    if(mode === 'add'){
        console.log('working')
        try{
            const i = customFunctions.Counter(source);
            console.log(i)
            source.sendMessage(`${brand}${colors.impotant}Position ${i}${colors.neutral}  was added ${colors.success}Successfuly`)
        }
        catch(err){
            if(err instanceof systemErrors){
                source.sendMessage(`${ErrPref}${err.message}`)
            }
        }
    }```
#

The game doesn't detect the "mode"

scarlet sable
#

honestly it looks like a crossplay server

#

nevermind it is java and bedrock crossplay

valid ice
#

So mode in your function is an array

scarlet sable
#

nah it works I'm just dumb

#

i used log

#

thought I was using error

untold magnet
fallow minnow
#

does anyone have a GOOD scoreboard database I don't feel like making one

sullen ocean
#

When it is optimal, use regular string splitting / etc.
When it is used a lot less, regular expressions might be okay (it depends on what your pattern is).

But when it comes to parsing HTML and such, sometimes you should just use the right tool for the job as explained in this answer: https://stackoverflow.com/a/1732454

sullen ocean
#

Just a tip... and for a conversation that is around yesterday my time. Apologizes.

jagged gazelle
distant tulip
#

there is no packet to open a gui?

jagged gazelle
deep quiver
#

the best you can do is simulate a chest ui with json ui and then just open that on the command call

sterile epoch
#

can sum1 help the debugger extension isn't working for me

#

it says failed t connect when I do the cmd in game

tepid fjord
ivory bough
#
world.afterEvents.playerSpawn.subscribe((event) => {
  if (dimensionGenerated === false) {
    dimensionGenerated = true;
    for (let z = 100000; z <= 500000; z += 16) {
        for (let offset = 0; offset <= 400000; offset += 16) {
          if (Math.random() < 0.5) {
 world.runCommand(`structure load mystructure:fieldtree ~${100000 - offset} ~500 ~${z}`);
          } else {
            world.runCommand(`structure load mystructure:fieldbase ~${100000 - offset} ~500 ~${z} `);
            }
          if (Math.random() < 0.5) {
            world.runCommand(`structure load mystructure:fieldtree ~${100000 + offset} ~500 ~${z}`);
          } else {
            world.runCommand(`structure load mystructure:fieldbase ~${100000 + offset} ~500 ~${z} `);
            }
         }
     }
    for (let torture = 100016; torture <= 500000; torture += 9) {
      if (tortureFirstRoom === false) {
      world.runCommand("structure load mystructure:torturenormal ~100000 ~700 ~100000");
      tortureFirstRoom = true;
      }
      const random = Math.floor(Math.random() * 25) + 1;
      if (random <= 23) {
      world.runCommand(`structure load mystructure:torturenormal ~100000 ~700 ~${torture}`);
      } else if (random === 24) {
        world.runCommand(`structure load mystructure:torture_exit ~100000 ~700 ~${torture}`);
      } else {
        world.runCommand(`structure load mystructure:torturechest ~100000 ~700 ~${torture}`);
      }
    }
  }
});

Why does this literally not generate anything?

shy leaf
ivory bough
shy leaf
#

its either entity, player or dimension

ivory bough
shy leaf
#

its ok

ivory bough
#

I was supposed to do overworld

shy leaf
#

common mistakes lol

ivory bough
ivory bough
#

Ye

shy leaf
#

then you should try runJob

#

its specifically made for big stuff like that

#

though i dunno how to use it, ill try searching for a few use examples

ivory bough
shy leaf
#

though i have a question

#

why do you need for loops that big

ivory bough
shy leaf
#

also holy shit a for loop inside a for loop???

#

😭

ivory bough
shy leaf
#

yeah i uh

#

dont know the efficient way to deal with this

#

soz

wheat condor
distant tulip
#

again, 0 tick it misleading, 0 tick is 0 ms and that is not possible

ivory bough
woven loom
#

use job for that

#

i will delay auto

visual zephyr
#

i have no idea why my server-ui script is not working

#

it sends a reference error

wheat condor
visual zephyr
#

and says does not have required privileges

ivory bough
#

I used job inside the for loop

dusky flicker
#

i mean, instead of writing faster code write smarter code

woven loom
#

make loop within job and yield every inter

dusky flicker
#

function *doStuff(){
for(;;) {
yield stuff();
}
}

system.runJob(doStuff());
something like this

visual zephyr
#

how do i use the debug script on debug playground

#

nvm figured it out

distant tulip
ivory bough
# woven loom thats not how it should be used
world.afterEvents.playerSpawn.subscribe((event) => {
  if (hasPlayerJoined === false) {
    hasPlayerJoined = true;
    nullTploc = event.player.location;
  }
  if (dimensionGenerated === false || dimensionGenerated === true) {
    dimensionGenerated = true;
    function torture(offset, z) {
      if (Math.random() < 0.5) {
        overworld.runCommand(`structure load mystructure:fieldtree ~${100000 - offset} ~500 ~${z}`);
      } else {
        overworld.runCommand(`structure load mystructure:fieldbase ~${100000 - offset} ~500 ~${z}`);
      }
      if (Math.random() < 0.5) {
        overworld.runCommand(`structure load mystructure:fieldtree ~${100000 + offset} ~500 ~${z}`);
      } else {
        overworld.runCommand(`structure load mystructure:fieldbase ~${100000 + offset} ~500 ~${z}`);
      }
    }
    function* tortureLoop(){
      for (let z = 100000; z <= 500000; z += 16) {
        for (let offset = 0; offset <= 400000; offset += 16) {
          torture(offset, z);
          yield;
        }
      }
    }
    function field(torture) {
      const random = Math.floor(Math.random() * 25) + 1;
      if (random <= 23) {
        overworld.runCommand(`structure load mystructure:torturenormal ~100000 ~700 ~${torture}`);
      } else if (random === 24) {
        overworld.runCommand(`structure load mystructure:torture_exit ~100000 ~700 ~${torture}`);
      } else {
        overworld.runCommand(`structure load mystructure:torturechest ~100000 ~700 ~${torture}`);
      }
    }
    function* fieldLoop(){
      for (let torture = 100016; torture <= 500000; torture += 9) {
        if (tortureFirstRoom === false) {
          overworld.runCommand("structure load mystructure:torturenormal ~100000 ~700 ~100000");
          tortureFirstRoom = true;
        }
        field(torture);
        yield;
      }
    }
    system.runJob(tortureLoop());
    system.runJob(fieldLoop());
  }
});

Now it doesn't even generate anything for some reason

gaunt salmonBOT
jolly citrus
#

is this prone to duplication glitches?

world.afterEvents.playerInventoryItemChange.subscribe((event) => {
  const { player, itemStack, slot } = event;
  event.itemStack;
  const customPlayer = globalThis.GlobalCustomPlayers.get(player.id);
  if (customPlayer && itemStack) customPlayer.playerInventoryChange(slot, itemStack);
});
/* class CustomPlayer */
playerInventoryChange(slot: number, item: ItemStack) {
    if (!item) return;

    if (item.getDynamicProperty && item.getDynamicProperty("dusted")) {
      return;
    }

    let changed = false;

    const enchantable: ItemEnchantableComponent | undefined = item.getComponent("enchantable");
    if (enchantable) {
      const sharpness = enchantable.getEnchantment("sharpness");
      if (sharpness && sharpness.level > 2) {
        sharpness.level = 2;
        enchantable.removeEnchantment("sharpness");
        enchantable.addEnchantment(sharpness);
        changed = true;
      }
      const protection = enchantable.getEnchantment("protection");
      if (protection && protection.level > 2) {
        protection.level = 2;
        enchantable.removeEnchantment("protection");
        enchantable.addEnchantment(protection);
        changed = true;
      }
    }

    if (changed) {
      if (this.container) this.container.setItem(slot, item);
      this.player.sendMessage("§eYour item's enchantments were set to a maximum of Sharpness II and Protection II.");
    }
  }
#

okay seems that it is

#

no idea how to fix it tho

#

it's hard to dupe the item but the risk is still there, any way i can fix it

severe wave
#

Hello, is there any way of checking when chunks have loaded, and checking the location of said chunks?

severe wave
vast grove
#

Considering players technically are the only ones that can load said chunks. Yeah you could detect it

vast grove
#

Oh. Yeah...

severe wave
vast grove
#

Well iirc. Bedrock loads chunks in a diamond shape... And for each player you could just store their current chunks position, then if it changes, get the new ones using a mathematical equation.

#

Otherwise it's basically a no, there's no proper api for chunks yet

severe wave
grim raft
#

how can I convert this to the new applyKnockback

player.applyKnockback(di.z, -di.x, -3, 0)```
grim raft
# wary edge It's a VectorXZ now.

ik a bit how but idk how to make it go sideways

const horizontalForceF = {
                x: viewDirection.x * 5,
                z: viewDirection.z * 5
            }
            return entity.applyKnockback(horizontalForceF, viewDirection.y * 0.5)```
wary edge
grim raft
#

this error appeares

#

cant put 0

wary edge
#

What did you put?

grim raft
#
const horizontalForceR = {
                x: viewDirection.x * 0,
                z: viewDirection.z * 5
            }```
#

or u didnt mean like that

#

even when I put nothing it says that

wary edge
grim raft
valid ice
#

New format is

applyKnockback({ x: x * hStrength, z: z * hStrength }, vStrength)
instead of applyKnockback(x, z, hStrength, vStrength)

valid ice
#

oh ok

wary edge
#

Im guessing viewDir is NaN

grim raft
wary edge
#

And NaN times a number is NaN

valid ice
#

Not a Number? But it literally is

ivory bough
halcyon phoenix
#

oh wait

#

oh it's just {x, z}

#

welp

night acorn
#

why does the useOn item event not work when interacting with cauldrons?

fallen cape
#

Can I modify item in cursor component to change the itemstack?

wary edge
#

No.

fallen cape
#

sad

chrome gyro
inland merlin
#

Has someone made anything using the new inventory change afterevent ?

#

Seems promising especially for a possibility of testing for recipes like crafting

distant tulip
#

-# and hotbar

inland merlin
#

Could make gui in inventory now right haha

#

Now we have so many options

distant tulip
#

I mean it says player inventory change

inland merlin
#

Yeah player haha

distant tulip
#

You could detect player crafting with it i think

inland merlin
#

Since your inventory changes with craftibg

#

Some custom class i suppose with the event

distant tulip
#

Just exclude item dropped and item storage amd all the events that consume items
Seem a bit janky tho, haha

inland merlin
#

Awh true

#

Forgot about those things

distant tulip
#

An easy one is item pick up event

inland merlin
#

True!

distant tulip
#

Entity remove + that

inland merlin
#

Yeah I like that combo

#

Seems accurate enough

chrome gyro
#

Anyone know how to get the swing animation to play in first person when using an item and playing the animation, my animation only plays in third person for some reason.

distant tulip
#

Yeah, just add location for more accuracy