#Script API General

1 messages · Page 91 of 1

scarlet sable
#

[Scripting][error]-Error: Custom Command reload failed, cannot change parameters for 'easy:cam' during reload. at <anonymous> (main.js:24)

woven loom
#

You cannot register nee commands with reload.

#

Do /reload all

scarlet sable
#

ye it doesn't work

#
system.beforeEvents.startup.subscribe((int) => {
    const CameraCommand = int.customCommandRegistry;
    const options = ['set' , 'add' , 'remove'];
    const command =  {
            name: "easy:cam",
            description: "allows to creat §eCinematic§r shots with no headache",
            permissionLevel: CommandPermissionLevel.Any,
            optionalParameters: [{
                type: CustomCommandParamType.Enum, name: "creator:enum"
            }
            ],
        };
     CameraCommand.registerEnum("creator:enum" , ['set' , 'add' , 'remove'])
    CameraCommand.registerCommand(command,CameraSystem);
});
woven loom
#

What is the errro

scarlet sable
#

there's non

#

it just doesn't appear

#

nor work

gaunt salmonBOT
scarlet sable
#

nvm

#

the namespace

#

I used 2 namespaces

#

yep

#

btw do you have an example?

somber cedar
scarlet sable
#

?

woven loom
scarlet sable
#

cam alone doesn't work

woven loom
#

With 2.1.0+ u will be able to

scarlet sable
#

preview?

woven loom
#

Yes

scarlet sable
#

ahh I see

#

ty

woven loom
#

Hopefully, the next stable release will include it.

acoustic basin
#

hey guys, can i place a feature via script if the features path is something like features/folder0/folder1/feature.json

#

will it work?

acoustic basin
little hull
#

when using system.time interval when the player leaves the game does it pause and when you join it resumes or it will reset again?

hybrid dune
#

Why does it give this error

#

what happened in the update

#
    "dependencies": [
        {
            "module_name": "@minecraft/server",
            "version": "2.0.0-beta"
        },
        {
            "module_name": "@minecraft/server-ui",
            "version": "1.3.0"
        }
    ]
}
wary edge
little hull
#

then how can i prevent it from happening cause what i want is a day counter thing like example every 24000 ticks i show the title of my scoreboard like day 1 i dont want the ticks reseting any way to have an accurate day counter?

woven loom
#

system.runInterval( () => {
if (system.currentTick % 24_000 == 0) {
//code
}

})

#

@little hull

distant tulip
#

didn't know that 24_000 is valid in js

woven loom
#

now u know 🙂

remote oyster
# distant tulip didn't know that 24_000 is valid in js

I didn't know either. Apparently it was introduced in ES2021. Designed to be easier to read the numbers but I'll be frankly honest. I wasn't entirely sure if it represented 24,000 or if it meant something else lol. I speculated it represented 24,000 but I had to Google it to be sure. So I'm not entirely confident it's "easier" to read unless you have knowledge of it.

#

I learned something new.

distant tulip
#

yeah, i guess it could be useful in big numbers
234234322 you can read it easily if it is 234_234_322

woven loom
#

its taken from java i guess

remote oyster
#

Indeed, but I probably would think you were implementing some binary logic if I didn't Google it to verify for context haha.

uncut lynx
#

how can i know from script the time of the animation that it's currently played for?

distant tulip
#

animations are client side, scripts are server side, so unless the animation is played from the script or bp, you can't know it time

uncut lynx
#

gosh after 2 days of head scratching i figured out how to sync the animations

#

(without too much visible artifacts)

prisma shard
#

no shit but i am bored of scripting actually

inland merlin
prisma shard
#

i got burned out of working on same script

#

then just left it out of despair

#

then feeling bored of scripting

uncut lynx
#

also how should 256rpm look like

#

cuz according to my maths, 256 rotations per minute gives 92 160 degrees per minute, so 1 536 degrees per second, so 76.8 degrees per tick. but that is so darn fast it has the "reverse" rotation look

prisma shard
#

so darn fast that why not make it just break

uncut lynx
uncut lynx
prisma shard
#

and why do you care about if i use AI 😭

silent tide
#

since its inefficient in the long run and makes you actively dependant on a third party program to help you get stuff done

#

I mean its not a no go. but don't rely on it

inland merlin
#

But agree on both fronts

silent tide
#

For sure

inland merlin
#

Positives and negatives to it

uncut lynx
inland merlin
#

Those that use ai, usually pull their hair out when ai can't figure out an issue and then the ai starts changing stuff it will try to over do it. You have to know or learn ais limits before it starts being your enemy

#

Im sure someone has a way, but honestly just have a warning limit if someone starts getting alot of diamonds or netherite within a specific amount of time, you can warn admin.

#

Track what they have in their inventory/ blocks mined

#

Could make some things to undo everything that player has mined in a period of time

prisma shard
#

how can i remove the { } after JSON stringifing a object

#

like example it return: { states: hi }

i want it like states: hi

prisma shard
#

thanks

#

i did .slice(1, -1);

#

fixed

prisma shard
#

oh dude

#

strings are so frickin weird

#

help @deep quiver

amber granite
#

So

north frigate
deep quiver
# prisma shard

Just do a loop over Object.entries instead, should be way easier to manage

deep quiver
# north frigate

Theres no reason anyone should obfuscate if they publish their addon anywhere

amber granite
#

So

prisma shard
amber granite
#

So

#

How i make a door that only opens using a key ?

woven loom
#

Bruh

#

Using a var and if else

amber granite
#

How to make a player unable to open it ?

thorn flicker
amber granite
#

Yes

thorn flicker
# amber granite Yes

just use an if statement for your opening mechanics, checking if its the correct item or not.

amber granite
#

How ?

thorn flicker
#
if (item?.typeId === 'your:item') {
// opening code
}
amber granite
#

._. no i mean how to keep it closed

thorn flicker
#

yeah, thats how.

#

if its in the if statement, it wont open without the item.

uncut lynx
#

What do y'all think?

#

Yes ik the animation is laggy when update() func runs

#

i'd need another thread for it not to lag

amber granite
#

ThT locks naice

thorn flicker
#

cant tell if it looks laggy because the video is laggy.

uncut lynx
#

.mkv

thorn flicker
#

lol no

#

im not downloading anything

uncut lynx
#

ok but this is terrible

#

i'mma maybe do sth like 100mib

thorn flicker
#

its still bad

uncut lynx
#

But it's better ig

#

I'mma upload that to youtube fine

#

is that better?

distant tulip
uncut lynx
#

Not yet

#

I'mma do it now

#

okay the block-place lag is REAL

#

let's try async

distant tulip
#

that look as stable as my mental health

uncut lynx
#

lmfao

lyric kestrel
uncut lynx
#

but that is hella laggy

#

still

uncut lynx
lyric kestrel
uncut lynx
#

yeah

#

they work fine when nothing changes in the system

#

mainly due to the bfs that propagates everything in a single tick

scarlet sable
#

how do I detect what enum was chosen?

valid ice
#

wdym

scarlet sable
#

in customcommands

#

how do I detect what enum was triggered

#

like /easycam set

#

how do I detect the "set"

#

nvm I got it

plucky light
little hull
#

how can i make sure that players are apart from each other when spawning cause im generating a structure between them so there might be a conflict

floral vessel
#

is there a way to check if applyKnockback is valid for an entity? (without running it)

shy leaf
#

i think you could spawn the same entity on somewhere inaccessible and test the knockback?

floral vessel
#

basically I just want to filter out weird shit like items and leashknots without explicitly listing everything I want to ignore

shy leaf
#

hmmm

#

why not use try catch on applyKnockback

fallow minnow
#

get their coordinates and whichever ones you need around them

#

then see if they share the same coordinates

olive rapids
#

Does anyone know how I can update this?

shy leaf
floral vessel
#

why is my block with a custom component interactable?

little hull
#

why does my title disappear so fast even though i use times

#

player.runCommandAsync("title @s times 10 60 10");
player.runCommandAsync(title @s title §cDay ${currentScore + 1});

shy leaf
#

use that instead

halcyon phoenix
#

can somebody link me about debugDrawers? im interested in what they do?

warm mason
uncut lynx
#

wdym?

#

i followed the official addon tutorial

#

run f5 on some random .ts/.js file (project on bridge)

#

and /script debugger connect

#

me placing subsequent new blocks...

#

it just gets worse and worse

#

could anybody help?

#

okay i used Queue in findNetworks:

uncut lynx
#

alr i'mma use linked list taken from internet

dusky flicker
#

i dont know about qjs

#

but with node atleast

#

its faster using simply arrays for so if data length < 64

#

if else, use a implementation of queue

#

and you could simply type your stuff instead of using any

#

the queue and node class are all typed as any

#

holy hell tje code is 1.6k lines im not reading all this

dusky flicker
uncut lynx
#

idk i took Queue from internet

#

idc bout it havin no types

#

i mean it bothers me

#

but i'm lazy

floral vessel
#

api version 1.18.0

uncut lynx
#

i mean linked list improved it and all

#

but it still lags

somber cedar
gaunt salmonBOT
# somber cedar
Debug Result

There are 22 errors from compiler, and 1 errors from ESLint in this [code](#1067535608660107284 message).
Please read the attached file for the result.

uncut lynx
somber cedar
#

why are you coding this in one file

uncut lynx
#

why not?

#

does it change anything

somber cedar
#

yes

#

people won't bother looking at your code

uncut lynx
#

ahh

gaunt salmonBOT
# uncut lynx my newest https://pastebin.com/x4xJypep
Debug Result

JavaScript/TypeScript code blocks not detected in [message](#1067535608660107284 message).
You can either send the script in code block highlighted in JS format:

​`​`​`js
world.sendMessage("Hello World");
​`​`​`

Or Send an attachment end in .js to debug the file.

dusky flicker
dusky flicker
uncut lynx
#

i modified from array to linked list

#

in the whole update() chain

#

just search update():

uncut lynx
#

alright i guess that's better

#

still tho, 140ms vs normal 50ms time

#

and it kinda grows lol

uncut lynx
#

show me that guy who said "wHy ArE yOu OpTiMiZiNg JaVaScRiPt LoL?"

#

i have to ask

#

how can i write sum shit in C++ and import it into my addon with js

#

So according to this https://youtu.be/sRCgu1ng6Bo the JS is about 8x slower than C++, that ain't that bad ig

USENIX ATC '22 - Investigating Managed Language Runtime Performance: Why JavaScript and Python are 8x and 29x slower than C++, yet Java and Go can be Faster?

David Lion, University of Toronto and YScope Inc.; Adrian Chiu and Michael Stumm, University of Toronto; Ding Yuan, University of Toronto and YScope Inc.

The most widely used programming ...

▶ Play video
#

okay but node.js supports it too

#

can i use either of these?

dusky flicker
dusky flicker
#

not for minecraft

uncut lynx
uncut lynx
dusky flicker
#

writing with c++ would make anything possible

#

modifying runtime, creating websockets, http reqs, fs

uncut lynx
uncut lynx
#

So i'm stuck with this sht, yay

dusky flicker
#

yeah you stuck with js

#

you can see what part of the code is causing more lag

#

and try to resolve it

uncut lynx
#

i was optimizing my BFS

dusky flicker
#

well, i think i can see what is going on

uncut lynx
#

and it looks like the main cause is entity::setProperty

dusky flicker
#
private async updateConnections(): Promise<void> {
        //console.log(`§d[RotationSystem] Updating connections for ${ this.components.size } components`);
 
        // maybe use for later ?
        let totalConnections = 0;
        let connectedCount = 0;
 
        // Update all connection states
        for (const component of this.components.values()) {
            const componentKey = this.getBlockKey(component.block);
            //console.log(`§d[RotationSystem] Updating connections for component at ${ componentKey } `);
 
            for (const connection of component.connections) {
                //console.log(JSON.stringify(connection));
                if (!connection) {
                    continue;
                }
                //console.log(JSON.stringify(connection));
                totalConnections++;
                const connectedComponent = this.getConnectedComponent(component, connection);
                connection.connected = connectedComponent !== null;
 
                if (connection.connected) connectedCount++;
            }
        }
 
        //console.log(`§d[RotationSystem] Connection update complete.${ connectedCount } /${totalConnections} connections active`);
    }```
what in hell is this function doing?
uncut lynx
#

updating connections, obviously

#

updating .connected states

dusky flicker
#

oh only for that? really?

#

alright then

uncut lynx
#

don't mind the comments i used github copilot for some of those

#

same for console.logs

dusky flicker
#

and i think it would be good to use runJob

uncut lynx
dusky flicker
#

its heavy to do division

uncut lynx
#

ohh right

dusky flicker
#

try avoiding them

uncut lynx
#

i do it once Math.abs(component.RPM) / 1200

#

and it ain't even the cause

dusky flicker
#

ik

uncut lynx
#

the cause is setProperty in that func

dusky flicker
#

the problem is the setProperties

#
            component.entity.setProperty("createbedrock:begin_rotation_x", beginRotation.x);
            component.entity.setProperty("createbedrock:begin_rotation_y", beginRotation.y);
            component.entity.setProperty("createbedrock:begin_rotation_z", beginRotation.z);
            component.entity.setProperty("createbedrock:target_rotation_x", targetRotation.x);
            component.entity.setProperty("createbedrock:target_rotation_y", targetRotation.y);
            component.entity.setProperty("createbedrock:target_rotation_z", targetRotation.z);

put this on a function

#

and try using runJob

#

test if thats gonna help

#

and by the way

uncut lynx
#

how do i do the runJob with func

dusky flicker
#

isnt there a way for setting vector3?

dusky flicker
#

runJob runs on a generator

uncut lynx
# dusky flicker isnt there a way for setting vector3?

i need to reference these values from animation like here

{
    "format_version": "1.10.0",
    "animations": {
        "animation.entity.rpm_rotation": {
            "loop": true,
            "animation_length": 0.05,
            "bones": {
                "bone": {
                    "rotation": {
                        "0.0": [
                            "query.property('createbedrock:static_rotation_x') + query.property('createbedrock:begin_rotation_x')",
                            "query.property('createbedrock:static_rotation_y') + query.property('createbedrock:begin_rotation_y')",
                            "query.property('createbedrock:static_rotation_z') + query.property('createbedrock:begin_rotation_z')"
                        ],
                        "1.0": [
                            "query.property('createbedrock:static_rotation_x') + query.property('createbedrock:target_rotation_x')",
                            "query.property('createbedrock:static_rotation_y') + query.property('createbedrock:target_rotation_y')",
                            "query.property('createbedrock:static_rotation_z') + query.property('createbedrock:target_rotation_z')"
                        ]
                    }
                }
            }
        }
    }
}```
dusky flicker
uncut lynx
#

begin are

#

target are from 0 to 1536

dusky flicker
#

you could use bitwise operations

#

but that for sure would bug your mind

uncut lynx
#

Don't worry i wrote 12k line C++ class bitset

dusky flicker
#

and i dont know if there are some for molang

dusky flicker
#

for rotation you could store a single numer

#

as its 0..360, 9 bits per field, so a 27bit number would solve it

#

X << 18 | Y << 9 | Z

uncut lynx
#

molang doesn't have this

dusky flicker
#

to reverse it would be
X = N >> 18 & bits_of(360)
Y = N >> 9 & bits_of(360)
Z = N & bits_of(360)

dusky flicker
#

well, yeah test it with generators then

uncut lynx
#

how do i do generator from this?

#

i've never used js generators

dusky flicker
#

function* generator(component) {
yield component.entity.setProperty(...);
yield ...
...
}

#

the runJob will execute until find the next 'yield'

#

so just run system.runJob(generator(component));

uncut lynx
#

now testing generators

#

the animation is soooo inconsistent now

dusky flicker
#

(idk if 'yielding' is a word)

uncut lynx
#

wdym intialize

dusky flicker
#

initialize the animation

uncut lynx
#

the animation runs in a loop.

#

constantly

worthy comet
#

Could i asking something about scripting bug ?

worthy comet
uncut lynx
#

u did const { cancel } not let { cancel }

#

const is readonly

#

wtf u mean

somber cedar
uncut lynx
uncut lynx
#

u know what?

#

let u be the guy who optimizes this code @somber cedar

worthy comet
#

Dawg it works 💀 hell naw, it was very dumb mistake

somber cedar
dusky flicker
#

actually it is

#

when you deconstruct, as booleans are primitives, you are copying the value

#

even if using let{cancel} wouldnt solve anything

dusky flicker
#

must change the cancel on the event object

worthy comet
#

Dawg I forget it

uncut lynx
dusky flicker
uncut lynx
#

pov: u placing subsequent blocks

slow walrus
#

that is awful

#

you should try something like setting an initial started variable, and an rpm variable, and then calculate the rotation in the animation based on those

uncut lynx
#

let's see how'd it run without animation

slow walrus
#

changing that won't improve anything right now

#

your issue is every time you place a block, you set needsUpdate to true, which does whatever on your network thing

#

I think you're misunderstanding what async is doing

#

if you want to spread something across multiple ticks, you need to use a runJob with generator functions

uncut lynx
#

doesnt change much.
block place is expensive asf

slow walrus
#

either way, your code just needs a lot of optimisation. I defo don't think your entire network needs an update every single time you place a block

slow walrus
#

and when you do that, you want to add yield in places with high time complexity, like for loops

uncut lynx
#

e.g.?

slow walrus
#

loops

#
function* generatorFunc() {
  for (let something of bigList) {
    console.log(something)
    expensiveFunc(something)
    yield
  }
}
uncut lynx
#

the for loops are the least of my worries

slow walrus
#

and if you want to run another generator function inside it, use yield* otherGeneratorFunc()

uncut lynx
#

one, big, singular BFS loop is expensive ASF

slow walrus
uncut lynx
#

yeah

#

u didn't see it?

slow walrus
#

no, what does BFS mean

uncut lynx
#

Breadth First Search

#

Algorithm for graphs

slow walrus
#

ah

uncut lynx
#

in this case i use it to distribute RPM

slow walrus
#

turn your BFS into a generator function

#

I assume it's recursive?

uncut lynx
#

nope

#

it uses queue

slow walrus
#

& while loop?

uncut lynx
#

Depth First Search (DFS) is recursive alternative

uncut lynx
#

a lot in fact

slow walrus
#

would be a lot easier if your code was split into multiple files

uncut lynx
#

Alr i'mma split the component defs

#

so "misc" "components" and "main"

slow walrus
# slow walrus & while loop?

yeah you're using a while loop, so turn your findNetworks function into a generator, then chuck a yield in the while loop

#

and then use a runJob

uncut lynx
#

i cannot import .ts file???

#

it has to be .js

#

?

slow walrus
#

don't put .ts on the end

#

import './file' not import './file.ts'

uncut lynx
#

ah

#

do i put export in front of everything?

lyric kestrel
lyric kestrel
uncut lynx
#

i am using entities

lyric kestrel
#

Oh

#

Are you not using animations?

uncut lynx
#

i am

dusky flicker
#

how is it implemented?

#

i know disjoint set algorithm that is a good option for tracking groups

#

not how to implement it, but i know its good for tracking it

uncut lynx
#

how is what implemented

dusky flicker
#

O(n²)?

uncut lynx
#

it propagates using BFS

#

wait hmm

#

lemme see the time complexity

#

(i.e. ask ai)

dusky flicker
#

xd

uncut lynx
#

looks like O(V² + E×V) in the worst case
V -> number of components
E -> total num of connections

#

that's terrible i see

#

Average case is likely much better than worst case - most mechanical networks don't have complex conflict chains

#

The quadratic behavior primarily comes from the conflict resolution system where illegal gear configurations can cause cascading recalculations through the network.

#

since i allow 2V revisitings of each component before it breaks, lets try to set that to V

#

(the case for this is when the cogwheels loop around with large/small -> small/large

#

that breaks the system then

amber granite
#

So

prisma shard
# amber granite So

..... i see you spamming 'So' out of nowhere out of context every day.. bruh lol

amber granite
#

._.

#

No

uncut lynx
#

yeah i'd say it's fine that half the system gets destroyed when one component conflicts

#

better than no break

#

alright as they say

#

optimization is the last step

#

anyway i optimized it enough

#

it is usable

#

not super usable

#

alr alr i'mma just do the generators

#

but thats it

wary edge
north frigate
snow jungle
#

why does % not work in sendMessages?

dawn zealot
#

%%

snow jungle
steady canopy
#

no

uncut lynx
#

can i wait for my runJobs to finish or sum like that

#

i need to not trigger certain func on tick unless other has finished

distant tulip
woven loom
#

function runJob( gen ) {
retyrn new Promise( res =>
system.runJob( function *() {
let o = yield * gen()
res( o )
} )

})
}

something like this

distant tulip
#

-# return*

honest spear
#

pretty much nice pseudo

prisma shard
#

i did smth like this

#

in my worldEdit addon

uncut lynx
#

alright, thanks

#

that looks just as bad visually

#

but at least it doesnt lag the server as much

#

also i switched the animations to be synced via system.currentTick

#

instead of tryna keep them independent

#

still not great tho

uncut lynx
#

alright how do i properly wait for a job

#

i dont understand what ur saying

dusky flicker
scarlet sable
#

in the custom command is it possible to add enum options for an enum option?

dusky flicker
#

just put a loop and its solved

#

for(const _ of job) await system.waitTicks(1);

#

could do it

scarlet sable
#

in that ss

steady canopy
#

You can have more enums after that

#

But they will be the same no matter if the player uses "set", "delete"

scarlet sable
#

what can I have?

#

oh

#

ok but can I allow the player to have an input after the set?

jolly citrus
#

Does anybody know why I can expand this part of my code ?? is there some syntax issue i'm missing, there's no type/syntax errors or anything like that shown

steady canopy
#

yeah

scarlet sable
#

how?

steady canopy
scarlet sable
#

so origin is the entity source and mode is the enum

#

will that make input the input value?

#

wait no I think I've said smtg dumb bao_comm_hatchi_what

#

nvm I'm right lol

jolly citrus
#

does world.getDimension(dimensionId: string) expect dimensionId to always include a namespace? will it default to minecraft if i pass a parameter like overworld to it?

steady canopy
#

i'd recommend if you wanna have subgroups

#

Like different arguments for each enum

#

Use the namespace as the name of the command

#

example "camera:set" "camera:delete" "camera:whatever"

jolly citrus
#

Can anybody think of a scenario where the teleportation logic would not work as a viable anti for blockglitching?

/* PlayerBreakBlockBeforeEvent */
world.beforeEvents.playerBreakBlock.subscribe((event) => {
  const { itemStack, player, dimension, block } = event;

  const customPlayer = globalThis.GlobalCustomPlayers.get(player.id);
  if (!customPlayer) return;

  const permission = OverworldClaimManager.hasPermissionAtPosition(customPlayer, player.location, "break");
  if (permission) {
  } else {
    event.cancel = true;
    const oldTick = system.currentTick - 1;
    system.run(() => {
      const position = globalThis.PlayerPositionsCache.get(oldTick)?.get(player.id);
      if (position) player.teleport(position);
    });
  }
});

hopefully the variable names already hint enough at what they are, but globalThis.PlayerPositionsCache stores player locations from the last 20 ticks

#

i know you could technically disconnect yourself frfom the server temporarily to ensure no packets from the server reach you , but that doesn't really matter as you'd be teleported back anyway once you reconnect pretty sure

cinder shadow
#

why in the world does PlayerSelector for custom commands only give you a list of properties and entity id and not just the player

lyric kestrel
#

That seems very pepe_huh_wtf

cinder shadow
#

and there's no getPlayer call either

#

so I have to do getPlayers and then filter it based on id to get the selected player?

#
player.sendMessage(`${JSON.stringify(playerInfo)}`)
    player.sendMessage(`${playerInfo.id}`)``` ????/
#

oh wait

#

okay I fixed that one, it's an array, but still

#

I'm assuming there's some limitation where they don't want to send that much info if the selector were to include a lot of entities

cinder shadow
# honest spear wdym?

It doesn't return the actual entities being selected and only returns their id, typeId, and any properties on that entity

honest spear
#

try calling .teleport or some general method on it

#

do you use JSON.stringify to display objects?

#

keep in mind that JSON.stringify selects only instance properties not getters/setters

cinder shadow
#

ahh wait a minute 😭

#

I made a mistake

rose light
#

is there a way to get the damage of an entity without taking the damage?

#

I am making a shield addon, but I am having trouble defending the player's back because I am using damageSensor from the Behavior pack, and it blocks everything. So the alternative I thought of would be to apply artificial damage.

round bone
#

no other solutions

rose light
rose light
round bone
#

no other ways

jolly citrus
#

can pressure plate interaction be cancelled

amber granite
#

Hallao

#

Does someone knows how to deal with fabrix ?

halcyon phoenix
amber granite
#

It s nice to see something made by your hands work

dense skiff
#

is there an event or other detection that triggers every tick a player uses an item?

#

There's itemUseAfterEvent ofc but that only triggers on the first press, not if the button is held

vast grove
#

Uhhhh itemUse in beforeEvent

amber granite
#

What u mean by button held ?

#

U mean mouse ? Left click ?

wary edge
#

PlyaerInteract

dense skiff
vast grove
wary edge
#

🙄

vast grove
dense skiff
#

itemUse only triggers on the downpress

vast grove
#

Sooo use the workaround I said.
BeforeEvent -> add to map
AfterEvent -> Remove from map

dense skiff
#

Both the before and after event only trigger on the downpress

#

if there's no new event beyond the downpress a map & runInterval() will have nothing to do

vast grove
#

itemStopUse event exists

dense skiff
#

Ah I haven't seen that one before

#

That'll probably work, thanks

vast grove
#

Read the descriptions. There's a few stop use events

dense skiff
#

Actually it looks like that only triggers for chargable items

#

The other one is for interacting with blocks

wary edge
#

That's a #1067876857103536159 discussion. But the limit is there for performance reasons.

plucky light
#

Is there any timeline for client scripts?

shut citrus
wary edge
wary edge
#

Again, you can choose to ignore the warning if you don't care about performance.

plucky light
#

Can we do custom effects at all?

sterile epoch
plucky light
#

are there any examples I can follow? or working packs I can use to work through?

sterile epoch
#

dunno

#

you can use system.currentTick to track the time of the potion, and store the effect + amplifier as a dynamic property

sterile epoch
#
world.afterEvents.itemCompleteUse.subscribe(({ source: player, itemStack: item }) => {
  if (item.typeId == "example:potion") {
    const effectData = {
      effect: "idk",
      amplifier: 0,
      duration: system.currentTick + 20 * 60 * 3 // 3 mins
    };
    player.setDynamicProperty("potion", JSON.stringify(effectData));
  }
});

system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    const data = player.getDynamicProperty("potion");
    if (!data) return;
    const potData = JSON.parse(data);
    const now = system.currentTick;
    const amplifier = potData.amplifier;
    if (now > potData.duration) player.setDynamicProperty("potion", null);
    if (amplifier == 0) {
      // ...
    } else if (amplifier == 1) {
      // ...
    }
  }
}, 5);
#

you'd obviously have to do a bit more if you wanted amplifiers and different potion durations but this is just an example

plucky light
#

thanks

dense skiff
#

Is there anywhere to get a map of block typeIds to their placement sound, or is this something I'll have to compile myself?

slow walrus
#

each entry has a "sound" field

dense skiff
#

Is that something we can pull into a pack dynamically or does it have to be copied

#

@slow walrus

#

Guessing copy

slow walrus
#

it's json so you'll need to parse it with something

dense skiff
#

Ofc. I'm asking if it has an import we can just use or if I have place a copy of the file in my BP

slow walrus
#

neither

#

it's a .json file

#

you can't import it in minecraft

#

you'll need to generate a .js file from it

dense skiff
#

Yeah I just ran into that lol

#

Alright, thanks

worldly heath
#

is there a way to detect click and holding a chargeable item

#

I've been using animation controllers before

worldly heath
#
const holders = new Set();

world.afterEvents.itemStartUse.subscribe(e => {
  if (e.itemStack?.typeId === "zzk:pow") holders.add(e.source);
});

world.afterEvents.itemStopUse.subscribe(e => {
  if (e.itemStack?.typeId === "zzk:pow") holders.delete(e.source);
});

system.runInterval(() => {
  for (const player of holders) {
    testfunc(player)
  }
}, 1);

something like this does work ,is it an efficient way of doing it

dense skiff
#

Yes, that or something similar looks good to me if you have a chargable item

#

Btw do chargable items always have that pull back strechy animation? & do they always slow the player down

prisma shard
#

I tried to make a bow, and it needs animations & other stuff to make the pull back & slow down

jolly citrus
#

is it possible to create a custom event that can be listened for in scripts which fires when you step on/off of a custom block?

prisma shard
#

Either way you can make a custom event too.
You need to use map to trigger it only for one time, and use runInterval to detect every tick if standing on block, if it is standing on that block, trigger the event
You can make custom callback in a function like that
Pseudo code:

const a  = new Map()

function onStepOnCallback(blockTypeId, callback) {
system.runInterval() =>
  const b = {
  x: player.location.x,
 y: player.location.y - 1,
z: player.location
}
if (dimension.getBlock(b).typeId === blockTypeId) {
 a.set(true)
}
If (a is true) {
 callback()
}
}
#

Pseudo code cuz I'm typing on mobile

jolly citrus
#

i'm trying to make a custom block that's like a vanilla pressure plate visually except by default it doesn't do anything

#

but i need something to listen for when the player steps on it

#

i dont need the actual redstone functionality of it tho cos im using this so that i would actually replace the fake pressure plate with a real one temporarily if a player has sufficient permissions

#

does the dimension property on PlayerBreakBlockBeforeEvent include the dimension namespace by default?

#

if i'm in the end for example will the value of it be minecraft:the_end

woven loom
jolly citrus
#

like checking if it's in any way possible for a player to be on top of one before checking?

woven loom
#

Map the players in an interval so that you do not have to test for each player in that tick. Not a dramatic improvement, but still

scarlet sable
#

Whats the bot command that checks for mistakes?

jolly citrus
#

assuming you meant the jayly bot's debugger in this server

halcyon phoenix
#

I'm trying to add costs for each item and blocks in the game, what other methond can I implement instead of making a dictionary of all item and adding a cost

jolly citrus
#

How else are you expecting to store it

#

You can store it as tuples, in a map, literally anything but you still need to define them one way or another

halcyon phoenix
#

where can I get all minecraft blocks

jolly citrus
#

depending on how you want to set it up you could for example define a default block price, or maybe define a price for blocks whose typeId match a certain condition eg. typeId => typeId.includes("log")

halcyon phoenix
#

yep thanks for yhe help, it's time to make a dictionary of blocks now

uncut lynx
#

does anybody have any simple mutex for ts/js?

#

like i dont want to download entire npm package just for mutex

jolly citrus
#

can custom permissions be set for players through scripts

jolly citrus
uncut lynx
#

how can i make runJob utilize more tick time for the stuff?

prisma shard
jolly citrus
#

code: https://pastebin.com/75y7yJSW

Someone explain how it is even possible for this to be saving the player names using the player IDs as the keys?? like how does it manage to save it both ways im so confused, im 99% sure im not saving inverse pairs of the two in globalThis.GlobalPlayerNames

log: https://pastebin.com/jS9hPb7e

uncut lynx
#

hey, so i am wondering whether different addons have different scripting tick space

jolly citrus
uncut lynx
#

i'd love to put animations onto different thread

uncut lynx
#

animation code slows down everythin else 100x

uncut lynx
#

okay screw it i am using 49 miliseconds out of available 50

remote oyster
pallid stag
#

How do I make a block give damage like a magma block, but on a specific mob?

jolly citrus
#

like let’s say my player id would be -10

”iehl”: {
bytes: 95
},
”-10”: {
bytes: 95
}

it’d show both of these in the log somehow

#

OK it fixed itself now somehow

#

idk what happened

#

but it doesn't seem to occur in any new logs

frozen vine
#

Is it possible for me to detect that a mob has something in its mainhand?

open urchin
frozen vine
rose light
#

How do I run animation via script in the attachables?

 player.playAnimation("fire", {
           players: [player.name],
         });

Is it correct?

#

I'm trying to perform a shooting animation, when the entity shoots the weapon, perform this animation

uncut lynx
#

should i let my script take over the tick like to 200ms just to let my system be quicker

#

or keep 50ms limit???

full idol
#

What's the correct way to make a player invisible?

valid ice
#

Player.addEffect('invisibility' some other stuff)

woven loom
full idol
plucky light
#

How are dynamic player properties stored? Are there limits on each property and/or all property storage combined?

shy leaf
small cloak
#

There's a max string length and numbers are stored as floats.

#

The float thing matters if you're storing large numbers that need to be interpreted as an integer.

prisma shard
bold stratus
#
import { MinecraftEntityTypes, MinecraftEffectTypes } from "@minecraft/vanilla-data";

world.afterEvents.entitySpawn.subscribe((event) => {
  const entity = event.entity;

  if (entity.typeId === MinecraftEntityTypes.zombie) {
    entity.addEffect(MinecraftEffectTypes.speed, {
      duration: 2147483647,
      amplifier: 0,
      showParticles: false
    });

    console.warn("Gave zombie infinite Speed I.");
  }
});``` 

is this true? how to set up manifest for vanilla-data? minecraft 1.21.82
sterile epoch
#

you don't import vanilla data it's not a module it's intended to be copied into your scripts for use

#

but it's more effort you might as well just do "minecraft:zombie" and "minecraft:speed"

bold stratus
#
        entity.addEffect("minecraft:speed", {
            duration: 2147483647,
            amplifier: 0,
            showParticles: false
        });``` for some reason I got error in this line
#

[Scripting][error]-TypeError: Object did not have a native handle. Function argument [1] expected type: number at <anonymous> (main.js:412)

#

oh never mind it fixed

tender pier
#

Is there any way to recreate vanilla beds?

wheat condor
#

What’a the best way to obfuscate code in a way that is basically impossible to undo?

woven loom
#

not possible

round bone
wheat condor
halcyon phoenix
remote oyster
halcyon phoenix
wheat condor
#

like does the method of filling the addon with a lot of useless files work?

wheat condor
#

are there tools to find the correct one?

remote oyster
#

Don't know, but I personally wouldn't need a tool to syphon out the useless files.

wheat condor
#

what if i add 200 folders with 300 useless files each one

remote oyster
#

Still too easy

#

Even on mobile.

wheat condor
#

even if they are all obfuscated?

remote oyster
#

I could run code to detect obfuscation patterns, then deobfuscate those files flagged. The rest would be dumped. After that it's a matter of trashing the useless ones by determining which files are not being exported and imported efficiently.

#

I can go further if need be. I'm sure others here can too.

wheat condor
#

so basically you can only add time to make it long process but not completely stop

remote oyster
#

JavaScript follows a set of rules. Validating that the rules are followed quickly rules out the useless junk.

remote oyster
#

Fwiw @wheat condor, not everyone has the understanding to deobfuscate. So for those individuals you would be protected against. So it's not an entirely large waste of time. Just no guarantee that some scum will not take your code and claim it lol.

acoustic basin
#

hey guys! how can i place a structure with structureManager if it's path is structures/folder0/folder1/structure.mcstructure? i've tried folder0:folder1/structure, but it doesn't work

wheat condor
#

you have to do /place

jolly citrus
#

is there any way i could spawn the pillar entities even tho the location they should be in is in unloaded chunks? i also have to delete them afterwards though

const pillarsConfig = [
  {
    pillarTypeId: "ultra:pillar_aqua",
    chatColor: "§b",
    displayName: "Aqua",
  },
  {
    pillarTypeId: "ultra:pillar_green",
    chatColor: "§a",
    displayName: "Green",
  },
  {
    pillarTypeId: "ultra:pillar_light_purple",
    chatColor: "§d",
    displayName: "Light Purple",
  },
  {
    pillarTypeId: "ultra:pillar_red",
    chatColor: "§c",
    displayName: "Red",
  },
  {
    pillarTypeId: "ultra:pillar_yellow",
    chatColor: "§e",
    displayName: "Yellow",
  },
];

Commands.instance.registerCommand(
  "map",
  "Show the corners of nearby claims",
  undefined,
  [],
  1,
  "teams",
  ({ args, sender }: { sender: CustomPlayer; args: { [key: string]: any } }) => {
    const { player } = sender;
    const { y: yLevel } = player.location;
    const allClaims = ClaimManager.getAllClaims(player.dimension.id);
    const nearest = ClaimUtils.getNearestNClaims(player.location, allClaims, 5);

    nearest.forEach((nearbyClaim, index) => {
      const config = pillarsConfig[index % pillarsConfig.length];
      player.sendMessage(
        `${config.chatColor}${config.displayName} Claim §eowned by §c${nearbyClaim.claim.displayName}`
      );
      system.run(() => {
        Object.values(nearbyClaim.corners).forEach((value) => {
          player.dimension.spawnEntity(config.pillarTypeId as VanillaEntityIdentifier, {
            x: value.x,
            y: yLevel,
            z: value.z,
          });
        });
      });
    });
  }
);
shy leaf
#

stops honest people, doesnt stop lockpickers

#

or ppl with bolt cutters

jolly citrus
#

maybe it'd prevent them from despawning but they're persistent anyway

#

i just cant spawn them in when they're in unloaded chunks

rapid granite
#

is it possible to get a mobspawner and its data via scripts?

distant tulip
rapid granite
#

thanks!

#

does it work even if I get the blocks via getBlocks first?

distant tulip
#

yes

uncut lynx
#

okay i can anyhow fit within 3 floats for 4 values but that aint great optimization

inland merlin
#

I havent tracked that in a while

#

Maybe its always been that way haha

thorn flicker
thorn flicker
inland merlin
distant tulip
inland merlin
#

Ok nice

distant tulip
#

can't remember when

inland merlin
#

No worries

thorn flicker
#

would be cool if we could access the data on the itemstack though

uncut lynx
full idol
#

How do I get a player's armor slots and unequip it all?

distant gulch
#

What makes zeqa pvp so smooth

#

Custom knockback?

halcyon phoenix
sterile epoch
#
world.getPlayers({ location: loc, maxDistance: 30 });

does any1 know why it's saying location is incompatible with .getPlayers() yet it's on the docs

wary edge
sterile epoch
#

damn

#

why's it on the docs then lmao

wary edge
#

Which docs?

sterile epoch
#

stirante

wary edge
#

Oh huh, then I guess it's similar to applyImpulse where it varies. Probably only a few Queries work.

sterile epoch
shy leaf
#

yeah ig it does accept EntityQueryOptions but some are not used for reasons

#

and for World.getPlayers, location is unusuable probably because of dimensions

sterile epoch
fallow minnow
#

i can ask someone

inland merlin
#

does anyone have a way to automatically get a players timezone?

#

or a good way other then manually?

shy leaf
#

zeqa doesnt have sprint knockback, and it purely focuses on combo and reach sense

#

its very simplified

inland merlin
valid ice
#

Doubtful tbh

#

Security stuff

inland merlin
#

yeah thats fair

#

ill just have them select their current time to update it

#

not the biggest deal

remote oyster
inland merlin
#

looks good

rigid torrent
#

Is there any way I can do something when a player equips an item? Any workarounds?

#

Without ticking (?)

vast grove
# rigid torrent Without ticking (?)

There's not really any official api for it. There is this https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/playerinventoryitemchangeaftereventsignal?view=minecraft-bedrock-experimental but idk if it detects attachments and it's still beta.

The only way I can think of is to store each player's current equipment state in a map and tick it. Otherwise you're most likely out of options.

Contents of the @minecraft/server.PlayerInventoryItemChangeAfterEventSignal class.

rigid torrent
shy leaf
#

half related but detecting hotbar change via interval is faster than hotbar change event in preview :sob;

rigid torrent
#

I need that with all of my heart

wary edge
rigid torrent
#

Very very sad

halcyon phoenix
#

is it not documented or does it not exists anymore?

shy leaf
#

its deprecated in latest stable

halcyon phoenix
halcyon phoenix
shy leaf
#

uhhhh i think worldInitialize should be usable in v1 api

#

maybe tick the deprecated box on the right? if youre using jayly

halcyon phoenix
#

why is worldInitialize deprecated?

shy leaf
#

its changed in v2

#

for afterEvents, its world.afterEvents.worldLoad

#

and for beforeEvents, its system.beforeEvents.startup

#

and the way how both works are a tiny bit different iirc

halcyon phoenix
#

so for customComponents worldLoad is now used?

halcyon phoenix
shy leaf
#

for v1, nothing is changed

wary edge
halcyon phoenix
#

I see worldInitilize still works. I always check index.d.ts before using an event and I was wondering why worldinitialize wasn't there

#

welp beta it is

shy leaf
#

for whatever reason, they marked it as deprecated despite the fact that those are still usable on v1

wary edge
shy leaf
#

yeah

wary edge
#

Deprecated means we do not recommens using this.

shy leaf
#

ik that, im just saying that it can cause confusions like this

halcyon phoenix
#

it's fine I should've read deeper

#

and I am already using beta so it's fine

shy leaf
#

oh

#

on an unrelated note, instant health with modifier level of 255 (256) fires entityHurt event, and a huge negative... int? float? value as damage

#

this makes me wonder if this is a result of band-aiding a bug where giving an instant health effect with huuuuge modifier can kill entities by causing overflow

halcyon phoenix
#

Mojang is now band-aiding bugs instead of stitching them

shy leaf
#

well theyre devs too, band-aiding will work until someone finds it out

#

like how they band-aided a bug of hud animation speed

#

the entire hotbar has comically fast animations, especially hearts and hunger bars

#

they fixed super fast heart animations by slowing the speed of heart animation instead of fixing the comically fast animation speed

halcyon phoenix
#

hey, as long as it works

shy leaf
#

some parts are still broken 😭

#

like heart blinking animations

halcyon phoenix
#

I think they should just rebuild some stuff you know for the sake of stability.

shy leaf
#

well those are low priority in their list so i can understand the band aids

#

but jeez, sometimes i wish they looked inside deeper

halcyon phoenix
#

yeah and they are a big studio with microsoft backing it

#

I don't really know that much about professional game dev and scripting but in my experience when you have a script that has bugs it's best to stitch it properly rather than band-aid it as it can stack and it will end up as a bigger problem in the long run

shy leaf
#

yeah

#

(i cant imagine the pain of bedrock devs when a second combat update gets released)

halcyon phoenix
#

Lol

#

this doesn't work:

const playerItem = player.getComponent("equippable")?.getEquipment("Mainhand");

e.getComponent("equippable")?.setEquipment("mainhand", playerItem);

but this works:

e.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 minecraft:dirt);

what's the difference?

vast grove
#

Uuuuhhhh the first line is useless.

halcyon phoenix
#

whhhaat?

vast grove
#

Effectively you're setting the same item as what the player is holding...

#

So technically that first line is doing nothing.

halcyon phoenix
#
const shrine_slot = dimension.getEntities({
                type: "tm:shrine_slot",
                maxDistance: 1,
                location: blockCenter
            });

            shrine_slot.forEach((e) =>{
                console.warn("Swapped");
                e.getComponent("equippable")?.setEquipment("Mainhand", playerItem);
            });
vast grove
#

Oh. Yeah I read that wrong...

#

Did you test the variables and console warn any exceptions?

halcyon phoenix
#

nope no errors

#

when I interact no errors too

halcyon phoenix
#
 onPlayerInteract: (event) => {
            const { player, block, dimension, face, faceLocation } = event;
            const playerItem = player.getComponent("equippable")?.getEquipment("Mainhand");
            let blockCenter = block.center();

            blockCenter.y += 1;
            const shrine_slot = dimension.getEntities({
                type: "tm:shrine_slot",
                maxDistance: 1,
                location: blockCenter
            });
            shrine_slot.forEach((e) =>{
                if (e.typeId == "tm:shrine_slot") {
                    console.warn(playerItem.typeId);
                    e.getComponent("equippable")?.setEquipment("Mainhand", playerItem);
                };
            });
        },
#

it prints the playerItem id so the playerItem is good

#

oh lol

#

how do I make this exist in my entity?

#

welp this exists

halcyon phoenix
#

still doesn't work somehow

distant gulch
halcyon phoenix
#

do we have custom armor stand on dev resources?

halcyon phoenix
#

thanks

prisma shard
#

what this error "cannot change parameter during reload"

#

ok wtf so i gotta reload the whole world each time i tinker with the parameters???/

#

im making custom slash commands

#

ok so now how do i get the parameter's value inside the callback, where we execute things after the command ran?

distant tulip
round bone
prisma shard
#

ok

round bone
#

next params in your function

prisma shard
#

next params??

#

what

somber cedar
# prisma shard next params??
system.beforeEvents.startup.subscribe((init: StartupEvent) => {
    const helloCommand: CustomCommand = {
        optionalParameters: [
            { type: CustomCommandParamType.Integer, name: "celebrationSize" },
            { type: CustomCommandParamType.Integer, name: "celebrationSize2" },
            { type: CustomCommandParamType.Integer, name: "celebrationSize3" },
        ],
    };
});

function helloCustomCommand(
    origin: CustomCommandOrigin,
    celebrationSize?: number,
    celebrationSize2?: number,
    celebrationSize3?: number,
): CustomCommandResult
dusky flicker
#

how in hell in ts i do something like


class SomeHandler extends HandlerFor<WebComponent> {
  @MapEvent("click")
  f/*f automaticaly is typed as*/ sender: WebComponent, event: PointerEvent): void {}
}

class WebComponent extends BasisComponent {}

so when i create another method mapping event "keydown", it types the function as (sender: WebComponent, event:KeyboardEvent)=> void

#

where are the typescript lovers to help me now?

woven loom
#

u mean decorators?

dusky flicker
#

i mean typing with them

#

if i use @MapEvent("someventname") the second parameter must the be event that corresponds to that name passed on the decorator

remote oyster
dusky flicker
#

gpt gave me the same answer

#

i've already tested it

sweet seal
#

How to get accurate reach?

woven loom
#

??

sweet seal
#

I have a reach system but its very inaccurate and doesn't help detect cheaters

remote oyster
# sweet seal How to get accurate reach?

Checking reach is difficult because you use an afterEvent to monitor the behavior. So you have to take into account latency between the clients and the server, plus the fact that you are checking their positions after it has happened. So you have to do some predictions. You can use my script as a reference for ideas.

https://github.com/Visual1mpact/Paradox_AntiCheat/blob/rewrite/penrose/modules/reach.ts

GitHub

A utility to fight against malicious hackers on Bedrock Edition. - Visual1mpact/Paradox_AntiCheat

mighty igloo
#

any way to get the player icon and display it in an actionform?

inland merlin
mighty igloo
#

How can I get their head?

inland merlin
#

can't

#

as far as im aware

mighty igloo
#

Oddly enough ive seen addons that displayed the users character head icon in the chat

jolly citrus
mighty igloo
#

maybe

#

I do not remember which addon I saw that did that.

inland merlin
#

rather then a world, or realm

mighty igloo
#

idk

sly valve
#

||H||||e||||l||||l||||o|||| ||||g||||u||||y||||s||

mighty igloo
#

I may have an idea

sly valve
#

You guys know some cool things I can do with Binary operators like ``| or & or >>>`

wintry bane
#

entity.setProperty("ex:arm", 0.5)

  "ex:arm": {
    "type": "float",
    "range": [0.0, 3.0],
    "default": 0.0
  }
}```

it doesn't work
#

wth

wintry bane
#

I still get "0"

wary edge
wintry bane
#

I'll delay it

#

ok

mighty igloo
#

I got a question. I need a suggestion. What is a good command for a main ui. Im utilizing minecrafts custom commands because they have the autofill stuff in chat making it easier for users to find it. Plus I dont plan on releasing my addon until slash commands are released without namespaces. Anyway should I use /main, /server, idk

#

for now it would show up as /mcbepm:{command name}

#

since mcbepm is my namespace

sly valve
mighty igloo
#

hmm but for user friendly purposes its probably not best to put ui in the name. It would show publicly for all users. Thanks for the suggestions. Do you have any more?

sly valve
mighty igloo
#

well when the commands release the namespace wont be a problem. its just temporary

#

but as for the name of the command I have no idea

sly valve
remote oyster
#

namespace:gui

mighty igloo
#

well it would be like a main ui for users to navigate from

#

it would show like daily rewards etc

mighty igloo
#

maybe

sly valve
#

mcbepm:pmenu ?
mcbepm:playermenu ?

mighty igloo
#

thats simple enough

#

alright ill probably just use menu

sly valve
#

mcbepm:acc
mcbepm:account

mighty igloo
#

thx

sly valve
#

maybe always add two variants, like menu and m (only if needed)

mighty igloo
#

hm

sly valve
#

but menu is aleady short, so no need to

wheat condor
steady canopy
steady canopy
#

If it doesn't it isn't a good idea to save the dps on shutdown event

wheat condor
#

nope it doesnt

#

doesnt save

wheat condor
#

like its a bug not an actual thing

steady canopy
wheat condor
#

maybe doing a runinterval every minute to save it would be the the best

violet harbor
#

hellooo guys, is there a way to make a climbable vine block, like the ones in vanilla?

distant gulch
#

Its the first time im using chat gpt

#

And he made me a battle pass

#

First try

#

Im scared

#

Last time i tried(6 months ago) he was giving me scripts with 10 errors per line

silver agate
#

For some reason my code for removing player mainhand item if they is not on creative is not working
Code:
if (!creative) player.runCommandAsync(`clear ${player.nameTag} ${itemId} 1`);

Creative Const:
const creative = player.matches({ gameMode: GameMode.creative });

Also, i will send the full code, if someone wants to have a closer viee

dusky flicker
#

i dont know what to mention, but generaly theyre used to simply make things faster

#

like, if you got an array of booleans, you could simply store it all in a number

#

like [true, false, true] could be understood as 101 which is 5 in binary

#

so instead of 24 bytes(1 boolean = 1byte) you understand it as 4bytes(default in js if number < 2^31)

#

everything bit operations do is just do the same but faster

#

and generally, very faster

sly valve
#

Luv u

#

Thats actually smart

sly valve
sly valve
dusky flicker
#

M << N returns Q where Q is M but N bits to the left, same with >>, but that is for the right.
In understandable words,
101 << 2 == 10100

sly valve
#

Hmmm

dusky flicker
#

so if you got
110, to check if the second one is 1, just do

110 & (1 << 1) == 010

#

1 << 1 == 10
110 & 10 = 010

#

to know if the nth bit of a number is 1 just do N & (1 << N) == 1 << N, or simply check if not 0

sly valve
#

Binary operations are insane

dusky flicker
#

i do like this N & (1 << N) == 1 << N because of code i've seen in C

#

to set is using |, because 1 | 0 = 1, 1 | 1 = 1, 0 | 0 = 0

#

so to set the nth bit of a number to be 1, just do
Q | (1 << N)

sly valve
#

Can you show me an example how to find out from a nth. position in the bin, if its true or false, somehow i cant get this in my brain

#

Bin stuff is too much

dusky flicker
#

for example

#

lets suppose i need just to store values between 0 and 15

#

obviously i dont need 1 byte for so. lets say i need 2

#

0 ~ 15 is 4 bits

#

so i could save these 2 in the same number

#

where 0bXXXXYYYY X are the bits of the first number, Y of the second number

#

so to get the first, i can do
const ACTUAL_VALUE = ...

const highest_number = ACTUAL_VALUE >> 4;
const lowest_number = ACTUAL_VALUE & 0b1111;

#

the 'highest' do
0bXXXXYYYY >> 4 -> 0b0000XXXX

the 'lowest' do
0bXXXXYYYY & 0b00001111 -> 0b0000YYYY

#

if i need a list of 8 flags, for example

#

normally what people do i store it on a enum or something like that

sly valve
#

btw >> does
a >> b === a * b² ? Or was it dividing

dusky flicker
#

1010 >> 1 = 101

sly valve
dusky flicker
#

yeah

sly valve
#

And
1100 << 2 = 0000?

dusky flicker
#

no, only if the 2 first bits are 1

#

if its 11000000, yeah

#

because it gets out of bounds

#

and that supposing a single byte

#

like, supposing a u8(unsigned byte)
11000000 << 1 will overflow, so theres no way to move it, so 0 is placed

#

if it was u16
000000001100000000 << 1 still has space, so as it aint overflow, no 0 is going to be placed

#

and the bits will be just moved

#

the same logic for >>

sly valve
#

So 1100 << 1 wont eork

#

But 0100 << 1 will?

dusky flicker
#

supposing that the limit is 4bits, 1100 << 1 will be 1000

sly valve
#

As far as i know, >> or << is shifting the bins by n, like 12 << 1 shifts the binary pattern of 12 by 2 to the left, right?

dusky flicker
#

12 in binary is 1100, shifting this by 1 is 11000

#

which is 24

#

but yeah, the logic is right

#

sorry if something got confused, bitwise operations are confuse and i dont speak english natively so its hard for me to explain

sly valve
amber granite
#

Hello overyone

#

I said hello :-:

sly valve
#
const IS_ACTIVE = 0b0001
const IS_INACTIVE = 0b0010
const IS_STANDBY = 0b0100

let state = IS_ACTIVE

if (state & IS_ACTIVE) { ... }

?

#

Konnchiwa kiro san

amber granite
#

Why did u use binary._. ?

sly valve
#

Because its powerful

thorn flicker
sly valve
amber granite
#

Yet !

#

Yet ,__,

#

What do u mean by yet ?

silver agate
#

I'm still pretty new to scripting btw

sly valve
amber granite
#

Yet?

amber granite
#

Guys

#

Why are Minecraft java mods are not enjoyable anymore

thorn flicker
dusky flicker
#

yeah, its valid

amber granite
thorn flicker
dawn zealot
#

can i redirect a player from a world onto a bds server?

vast grove
# dawn zealot can i redirect a player from a world onto a bds server?

If you're able to access the server-admin module then you should be able to. Afaik this is enabled by default on BDS and Realms so it should apply to regular worlds since well they're essentially just a BDS running in the background.
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server-admin/minecraft-server-admin?view=minecraft-bedrock-experimental#transferplayer

Contents of the @minecraft/server-admin module

dawn zealot
#

but ty

#

and yes u can transfer from worlds to servers

mighty igloo
#

should I use the same dynamic property for everything?

vast grove
#

Uuuuuuhhhh I don't think it matters but probably no. Cuz if you load a massive DP then that's gonna cause some issues.

mighty igloo
#

So I should have them seperately or not?

valid ice
#

Separate would be better… just save with the key being player ID or something, still gettable when the player is offline, so you’re fine

violet harbor
#

Does anyone know how to make a block apply an effect to the player when the player touches the block? Like slowness for example...?

#

I would greatly appreciate it if someone could help me...

safe stream
#

and from there you do your if/switch logic

violet harbor
safe stream
#

woo!!

chrome gyro
#

Any ideas on how to test if a number is even versus odd?

vast grove
#

const even = number % 2 === 0

chrome gyro
vast grove
#

Modulo. Divides and gets the remainder iirc

chrome gyro
#

Awesome, that's good to know. thanks again.

nova flame
#

anyone know how i would make a actionFormData UI with randomised buttons

#

like i wanna have random button displays and functions chosen from some sort of array i have set up but idk how i would do it

vast grove
#
const actionForm = new ActionFormData();
const months = ["January", "February", "March", "April", "May", "June", "July"];

const random = Math.floor(Math.random() * months.length);
const value = months[random];
actionForm.button(value);
halcyon phoenix
#

what's the major difference of onRandomTick and onTick?

wary edge
halcyon phoenix
wary edge
#
Minecraft Wiki

Nearly all video games (including Minecraft) are driven by one big program loop. Just as every gear in a clock is synchronized with the pendulum, every task involved in advancing a game simulation is synchronized with the game loop. Appropriately, one cycle of the game loop is called a tick.

halcyon phoenix
#

Thanks

shy leaf
#

@slate loom hi, this is the place for scripting api talk

#

if you have super specific questions, you can use #1067535382285135923 to make a post

slate loom
#

Thanksss

halcyon phoenix
#

Thanks

scarlet sable