#Script API General
1 messages · Page 91 of 1
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);
});
What is the errro
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36m<REPL0>.js[0m:[33m14[0m:[33m43[0m - [31merror[0m[30m TS2304: [0mCannot find name 'CameraSystem'.
[7m14[0m CameraCommand.registerCommand(command,CameraSystem);
[7m [0m [31m ~~~~~~~~~~~~[0m
There are no errors from ESLint.
1.21.90
?
Same code
cam alone doesn't work
With 2.1.0+ u will be able to
preview?
Yes
Hopefully, the next stable release will include it.
hey guys, can i place a feature via script if the features path is something like features/folder0/folder1/feature.json
will it work?
Yes.
thank you
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?
All runs reset upon reload.
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"
}
]
}
Cant use stable and beta.
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?
system.runInterval( () => {
if (system.currentTick % 24_000 == 0) {
//code
}
})
@little hull
didn't know that 24_000 is valid in js
now u know 🙂
thank you
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.
yeah, i guess it could be useful in big numbers
234234322 you can read it easily if it is 234_234_322
its taken from java i guess
Indeed, but I probably would think you were implementing some binary logic if I didn't Google it to verify for context haha.
how can i know from script the time of the animation that it's currently played for?
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
gosh after 2 days of head scratching i figured out how to sync the animations
(without too much visible artifacts)
no shit but i am bored of scripting actually
Bored or burned out?
both kinda.
i got burned out of working on same script
then just left it out of despair
then feeling bored of scripting
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
so darn fast that why not make it just break
cuz that's the original mod's limit
did u use AI?
.........Can you stop topics about AI
and why do you care about if i use AI 😭
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
While I agree on dependency, it does speed up my coding 10x, I usually fix api or bugs myself that ai can't find
But agree on both fronts
For sure
Positives and negatives to it
i find my project way more engaging without using ai
This can be true haha, but myself I have limited time with kids and a wife 🤣
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
how can i remove the { } after JSON stringifing a object
like example it return: { states: hi }
i want it like states: hi
Use .slice
So
Just do a loop over Object.entries instead, should be way easier to manage
Theres no reason anyone should obfuscate if they publish their addon anywhere
So
solved
How to make a player unable to open it ?
is it a custom door
Yes
just use an if statement for your opening mechanics, checking if its the correct item or not.
How ?
if (item?.typeId === 'your:item') {
// opening code
}
._. no i mean how to keep it closed
Progress!
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
ThT locks naice
cant tell if it looks laggy because the video is laggy.
would u want original 1.25gib file?
.mkv
ok but this is terrible
i'mma maybe do sth like 100mib
i fit as close to 100mib as i could lol
its still bad
That looks great, did you benchmark it?
that look as stable as my mental health
lmfao
holy
okay i have an improvement...
but that is hella laggy
still
Is that just placing them?
yeah
they work fine when nothing changes in the system
mainly due to the bfs that propagates everything in a single tick
how do I detect what enum was chosen?
wdym
in customcommands
how do I detect what enum was triggered
like /easycam set
how do I detect the "set"
nvm I got it
What are you using to produce this?
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
is there a way to check if applyKnockback is valid for an entity? (without running it)
proooobably not but
i think you could spawn the same entity on somewhere inaccessible and test the knockback?
basically I just want to filter out weird shit like items and leashknots without explicitly listing everything I want to ignore
is this possible?
yes
get their coordinates and whichever ones you need around them
then see if they share the same coordinates
are you using beta api
why is my block with a custom component interactable?
What version?
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});
theres a native method for title
use that instead
can somebody link me about debugDrawers? im interested in what they do?
How did you get the debugger to work?
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:
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
alr i'mma use linked list taken from internet
when using queues of type T
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
where is this at?
idk i took Queue from internet
idc bout it havin no types
i mean it bothers me
but i'm lazy
There are 22 errors from compiler, and 1 errors from ESLint in this [code](#1067535608660107284 message).
Please read the attached file for the result.
my newest
https://pastebin.com/x4xJypep
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
why are you coding this in one file
ahh
how to in hell did linked list solve it?
can you plesse tell where did you modify from queues to linked list?
i modified from array to linked list
in the whole update() chain
just search update():
alright i guess that's better
still tho, 140ms vs normal 50ms time
and it kinda grows lol
300% is better than that 800% am i right?
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 ...
okay but node.js supports it too
can i use either of these?
how do you check this by the way?
you cant
not for minecraft
with the vscode minecraft debugger
sadge
writing with c++ would make anything possible
modifying runtime, creating websockets, http reqs, fs
i wanted only to pass array onto the cpp prog and it'd give the array back modifed etc
good point ig
So i'm stuck with this sht, yay
yeah you stuck with js
you can see what part of the code is causing more lag
and try to resolve it
i was optimizing my BFS
well, i think i can see what is going on
and it looks like the main cause is entity::setProperty
cant you batch these?
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?
this is the lag causer 5000
https://pastebin.com/B9NusrYX
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
don't mind the comments i used github copilot for some of those
same for console.logs
probably wont help that much but as we talking abou qjs
dont use division
if possible, inline constants
use Math functions
and i think it would be good to use runJob
the division avoiding helps for GPU expensive operations e.g. some sorta tracing or for cpus from the 90's
actually is cpu as well, js numbers are float64
its heavy to do division
ohh right
try avoiding them
ik
the cause is setProperty in that func
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
how do i do the runJob with func
isnt there a way for setting vector3?
function* generator(){
yield ...
}
system.runJob(generator());
runJob runs on a generator
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')"
]
}
}
}
}
}
}```
the values are in range from 0 to 360 right?
Don't worry i wrote 12k line C++ class bitset
and i dont know if there are some for molang
yeah
hm, alright then
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
molang doesn't have this
to reverse it would be
X = N >> 18 & bits_of(360)
Y = N >> 9 & bits_of(360)
Z = N & bits_of(360)
now we are fcked
well, yeah test it with generators then
function* generator(component) {
yield component.entity.setProperty(...);
yield ...
...
}
the runJob will execute until find the next 'yield'
so just run system.runJob(generator(component));
try making it only initialize after yielding everything
(idk if 'yielding' is a word)
wdym intialize
initialize the animation
Could i asking something about scripting bug ?
yeah
Anything over 12ms is bad
here's my inconsistency @dusky flicker
I K
u know what?
let u be the guy who optimizes this code @somber cedar
Dawg it works 💀 hell naw, it was very dumb mistake
Send the full addon
actually it is
when you deconstruct, as booleans are primitives, you are copying the value
even if using let{cancel} wouldnt solve anything
Ik
must change the cancel on the event object
Dawg I forget it
fr?
js aint helping as well
pov: u placing subsequent blocks
are you running this every tick?
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
let's see how'd it run without animation
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
doesnt change much.
block place is expensive asf
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
okay
and when you do that, you want to add yield in places with high time complexity, like for loops
e.g.?
loops
function* generatorFunc() {
for (let something of bigList) {
console.log(something)
expensiveFunc(something)
yield
}
}
the for loops are the least of my worries
and if you want to run another generator function inside it, use yield* otherGeneratorFunc()
one, big, singular BFS loop is expensive ASF
BFS?
no, what does BFS mean
ah
in this case i use it to distribute RPM
& while loop?
Depth First Search (DFS) is recursive alternative
... but it's slower
a lot in fact
would be a lot easier if your code was split into multiple files
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
For the blocks moving, are you constantly changing the block state with by replacing the block?
no
Yes
i am using entities
i am
by the way
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
how is what implemented
xd
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
holy hell
So
..... i see you spamming 'So' out of nowhere out of context every day.. bruh lol
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
Not sure if you already got an answer, but its fixed in 2.0
uhhh what's that
why does % not work in sendMessages?
understood, is there a explaination on why this needs to be done?
no
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
Promise
Yed
function runJob( gen ) {
retyrn new Promise( res =>
system.runJob( function *() {
let o = yield * gen()
res( o )
} )
})
}
something like this
-# return*
pretty much nice pseudo
player.runJobStatus = false
//run your things here
runJob(fillBlocks())
await new Promise(async r => {
while (!player.runJobStatus) await system.waitTicks(1)
r()
delete player.runJobStatus
})
//the code here will execute after runJob done
world.sendMessage(`done`)
function runJob(hi) {
system.runJob(function* () {
yield hi()
}())
player.runJobStatus = true
}
i did smth like this
in my worldEdit addon
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
function waitJob(job) {
return new Promise((ok=>{
//You gotta block the thread, runJob doesnt do it
ok();
}));
}
in the custom command is it possible to add enum options for an enum option?
just put a loop and its solved
for(const _ of job) await system.waitTicks(1);
could do it
like more options after set
in that ss
that's called subgroups and no, you can't
You can have more enums after that
But they will be the same no matter if the player uses "set", "delete"
what can I have?
oh
ok but can I allow the player to have an input after the set?
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
yeah
how?
just adding another argument after the enum
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 
nvm I'm right lol
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?
yeah basically
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"
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
why in the world does PlayerSelector for custom commands only give you a list of properties and entity id and not just the player
That seems very 
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
wdym?
It doesn't return the actual entities being selected and only returns their id, typeId, and any properties on that entity
Why do you think so?
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
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.
you have to calculate it on your own
no other solutions
there's no way, I thought of any other way, I couldn't find a solution

no other ways
can pressure plate interaction be cancelled
afaik Nope you can't
It s nice to see something made by your hands work
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
Uhhhh itemUse in beforeEvent
PlyaerInteract
this is only while looking at blocks or entities right? I need this to trigger while looking at air still
Not an event that exists. Only for 2 specific scenarios
Oh you know what I meant.
🙄
Doesn't the before event for itemUse trigger every tick? If not, why not just add it to a map and use a system.runInterval()
itemUse only triggers on the downpress
Sooo use the workaround I said.
BeforeEvent -> add to map
AfterEvent -> Remove from map
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
itemStopUse event exists
Read the descriptions. There's a few stop use events
Actually it looks like that only triggers for chargable items
The other one is for interacting with blocks
That's a #1067876857103536159 discussion. But the limit is there for performance reasons.
Is there any timeline for client scripts?
No.
so it will be limited by mojang
Mojang sets the limit yes. You can choose to go over it, but be warned performance may degrade.
how can i go over it
Wdym?
Again, you can choose to ignore the warning if you don't care about performance.
Can we do custom effects at all?
not officially but you can work around it with some effort
are there any examples I can follow? or working packs I can use to work through?
dunno
you can use system.currentTick to track the time of the potion, and store the effect + amplifier as a dynamic property
here's an example
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
thanks
Is there anywhere to get a map of block typeIds to their placement sound, or is this something I'll have to compile myself?
blocks.json in the bedrock samples
each entry has a "sound" field
Is that something we can pull into a pack dynamically or does it have to be copied
@slow walrus
Guessing copy
it's json so you'll need to parse it with something
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
neither
it's a .json file
you can't import it in minecraft
you'll need to generate a .js file from it
is there a way to detect click and holding a chargeable item
I've been using animation controllers before
https://stirante.com/script/server/2.0.0-beta.1.21.84-stable/classes/WorldBeforeEvents.html#itemuse & https://stirante.com/script/server/2.0.0-beta.1.21.84-stable/classes/WorldAfterEvents.html#itemstopuse
@worldly heath
Documentation for @minecraft/server
Documentation for @minecraft/server
should I use both itemstartuse and itemstopuse
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
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
I guess not for custom chargeable items
I tried to make a bow, and it needs animations & other stuff to make the pull back & slow down
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?
OnStepOn event already exist for block custom compoenents
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
yea but this'll take a pretty bad toll on performance at higher iteration counts (more players)
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
yes?
u can reduce to o(N) using a spatial search
how would i implement a spatial search in this scenario
like checking if it's in any way possible for a player to be on top of one before checking?
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
Whats the bot command that checks for mistakes?
it's not a command
right click your message with your script attached, apps -> debug scripts
assuming you meant the jayly bot's debugger in this server
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
tysm
Well you need to store the data somehow
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
so making a directory is the only solution then welp good luck to me
where can I get all minecraft blocks
well you can't really expect your script to just know what price you want to give certain blocks now, can you
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")
yep thanks for yhe help, it's time to make a dictionary of blocks now
does anybody have any simple mutex for ts/js?
like i dont want to download entire npm package just for mutex
can custom permissions be set for players through scripts
like customizing these options individually
how can i make runJob utilize more tick time for the stuff?
what
idk maybe gamerule?
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
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
hey, so i am wondering whether different addons have different scripting tick space
this isn't gamerule , this is for player perms
i'd love to put animations onto different thread
animation code slows down everythin else 100x
okay screw it i am using 49 miliseconds out of available 50
That script isn’t the cause, something else is adding the playerId. The code you shared on Pastebin returns this instead:
return {
success: true,
summary: { totalPlayers, savedPlayers, ... },
details: { saved: [...], failed: [...], chunks: [...] }
};
It doesn't include playerId at the top level, so the log you're seeing must be coming from another part of the codebase.
How do I make a block give damage like a magma block, but on a specific mob?
onTick idk
oh f my bad i sent the wrong log … but in the actual log i meant to sent, among the normal player names it also includes a log for each player id for some reason
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
Is it possible for me to detect that a mob has something in its mainhand?
you have to use the testfor command
And how can I do it if I want to check that my mob doesn't have any items in its hand?
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
should i let my script take over the tick like to 200ms just to let my system be quicker
or keep 50ms limit???
What's the correct way to make a player invisible?
Player.addEffect('invisibility' some other stuff)
what does this do for ?
Ah thank you!
How are dynamic player properties stored? Are there limits on each property and/or all property storage combined?
theyre stored in world (unique to pack's UUID), and iirc theres no limit on amount of DP, but theres prolly a limit on how much you can store in one
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.
idk i got this from internet lol
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
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"
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
Is there any way to recreate vanilla beds?
What’a the best way to obfuscate code in a way that is basically impossible to undo?
not possible
not possible, also what's your purpose to do this?
adding the real links in my addons so no one can steal the work and claim as their
obfuscate it so hard that it's so tedious to obfuscate it
Yea, save yourself the time and don't bother. Its not difficult to restore the code and make it readable again. Even if you wrote your own custom method it's still reversible because it always follows a pattern.
do some enigma shenanigans
like does the method of filling the addon with a lot of useless files work?
Nope
are there tools to find the correct one?
Don't know, but I personally wouldn't need a tool to syphon out the useless files.
what if i add 200 folders with 300 useless files each one
even if they are all obfuscated?
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.
so basically you can only add time to make it long process but not completely stop
JavaScript follows a set of rules. Validating that the rules are followed quickly rules out the useless junk.
Correct, you can delay access but the inevitable always happens. Its just a matter of how long.
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.
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
structureManager runs on structures id not on folder path
you have to do /place
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,
});
});
});
});
}
);
its like a padlock
stops honest people, doesnt stop lockpickers
or ppl with bolt cutters
i also tried giving the entities a tick_world component but it doesn't help in this case
maybe it'd prevent them from despawning but they're persistent anyway
i just cant spawn them in when they're in unloaded chunks
is it possible to get a mobspawner and its data via scripts?
block.getItemStack(amount?: number, withData?: boolean)
yes
okay i can anyhow fit within 3 floats for 4 values but that aint great optimization
Oh they have boolean now, nice
I havent tracked that in a while
Maybe its always been that way haha
interesting
I havent noticed, but then again I never used the method lol
Fair haha, I sometimes just don't realize the options
iirc, no it is new
Ok nice
can't remember when
No worries
would be cool if we could access the data on the itemstack though
i've been optimizing this for sooo long 😭
How do I get a player's armor slots and unequip it all?
those lagspikes looks spicy
world.getPlayers({ location: loc, maxDistance: 30 });
does any1 know why it's saying location is incompatible with .getPlayers() yet it's on the docs
what does the log say?
getPlayers doesnt allow for that. Use dimension.getEntities
Which docs?
stirante
Oh huh, then I guess it's similar to applyImpulse where it varies. Probably only a few Queries work.
ah I see, interesting
yeah ig it does accept EntityQueryOptions but some are not used for reasons
and for World.getPlayers, location is unusuable probably because of dimensions
that's true, it would be cool if it took a dimension query
very good software and i guess custom kb but idk
i can ask someone
does anyone have a way to automatically get a players timezone?
or a good way other then manually?
rewritten combat using plugins
zeqa doesnt have sprint knockback, and it purely focuses on combo and reach sense
its very simplified
You can’t
dang maybe one day
yeah thats fair
ill just have them select their current time to update it
not the biggest deal
Test this and see what the environment does:
const formatTimestamp = (ms) =>
new Date(ms).toLocaleString("en-GB", {
year: "numeric",
month: "short",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
timeZoneName: "short",
});
console.log(formatTimestamp(Date.now()));
clean setup thank you,
ill just need to adjust it to fit the player/admin zone
looks good
Is there any way I can do something when a player equips an item? Any workarounds?
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.
Do we know if it’ll be stable in 1.21.90?
half related but detecting hotbar change via interval is faster than hotbar change event in preview :sob;
I need that with all of my heart
That doesn't take into account armour as far as I know, nor offhand. Just the 27 inventory slot and hotbar.
Very very sad
is it not documented or does it not exists anymore?
which version
its deprecated in latest stable
how do customComponents works nowadays?
stable
uhhhh i think worldInitialize should be usable in v1 api
maybe tick the deprecated box on the right? if youre using jayly
it shows up now thanks
why is worldInitialize deprecated?
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
so for customComponents worldLoad is now used?
No, startup.
how do you do customComps on stable right now?
for v1, nothing is changed
Check the wiki.
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
for whatever reason, they marked it as deprecated despite the fact that those are still usable on v1
It's deprecated since it will be removed in 2.0
yeah
Deprecated means we do not recommens using this.
ik that, im just saying that it can cause confusions like this
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
Mojang is now band-aiding bugs instead of stitching them
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
hey, as long as it works
I think they should just rebuild some stuff you know for the sake of stability.
well those are low priority in their list so i can understand the band aids
but jeez, sometimes i wish they looked inside deeper
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
yeah
(i cant imagine the pain of bedrock devs when a second combat update gets released)
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?
Uuuuhhhh the first line is useless.
whhhaat?
Effectively you're setting the same item as what the player is holding...
So technically that first line is doing nothing.
oh I forgot ot add e, e is a different entity
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);
});
Oh. Yeah I read that wrong...
Did you test the variables and console warn any exceptions?
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
still doesn't work somehow
Thx
No thank you
do we have custom armor stand on dev resources?
Yes.
thanks
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?
yeah, the commands need to register during world load
@distant tulip
you have to use /reload all instead /reload after modifying custom commands registry
ok
but this ^ @round bone
next params in your function
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
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?
u mean decorators?
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
interface EventMap {
click: PointerEvent;
keydown: KeyboardEvent;
input: InputEvent;
// add more as needed
}
function MapEvent<K extends keyof EventMap>(eventName: K) {
return function <
T extends WebComponent,
U extends (sender: T, event: EventMap[K]) => void
>(
target: Object,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<U>
): void {};
}
How to get accurate reach?
??
I have a reach system but its very inaccurate and doesn't help detect cheaters
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
any way to get the player icon and display it in an actionform?
their head, not really
How can I get their head?
Oddly enough ive seen addons that displayed the users character head icon in the chat
download those addons and see how they do it
hmm, that would most likely be a server then
rather then a world, or realm
idk
||H||||e||||l||||l||||o|||| ||||g||||u||||y||||s||
I may have an idea
You guys know some cool things I can do with Binary operators like ``| or & or >>>`
entity.setProperty("ex:arm", 0.5)
"ex:arm": {
"type": "float",
"range": [0.0, 3.0],
"default": 0.0
}
}```
it doesn't work
wth
Any errors?
How are you verifying it?
setProperty takes 1 tick to apply, so does triggerEvent
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
mcbepm:ui_main
mcbepm:ui
mcbepm:main_ui
mcbepm:uimain
mcbepm:mainui
mcbepm:openui
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?
better namespaces maybe cc: (custom command?)
or hex: (because of your name
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
whats the command purpose?
namespace:gui
well it would be like a main ui for users to navigate from
it would show like daily rewards etc
mcbepm:menu ?
maybe
mcbepm:pmenu ?
mcbepm:playermenu ?
mcbepm:acc
mcbepm:account
thx
maybe always add two variants, like menu and m (only if needed)
hm
but menu is aleady short, so no need to
new way to use world dynamic properties https://discord.com/channels/523663022053392405/1382072758938112120
Have you tested if the shutdown event works even if the world crashes out of nowhere?
nope
You should test it and tell me
If it doesn't it isn't a good idea to save the dps on shutdown event
closing the app making it crash is not meant to be played
like its a bug not an actual thing
yeah if it's not being saved when it crashes then it's better to save the dps on runtime
maybe doing a runinterval every minute to save it would be the the best
hellooo guys, is there a way to make a climbable vine block, like the ones in vanilla?
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
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
a lot of stuff
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
So i could do 1101 for true, true, false, false.
And how'd I check like the last or the first Bit value
using << and >> and &
Sorry but can you show me an examle
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
Hmmm
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
Binary operations are insane
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)
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
for that you need some kind of pattern
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
btw >> does
a >> b === a * b² ? Or was it dividing
shifts a by b bits to right
1010 >> 1 = 101
so
1100 >> 2 = 0011?
yeah
And
1100 << 2 = 0000?
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 >>
both will, both are less than 1byte
supposing that the limit is 4bits, 1100 << 1 will be 1000
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?
it shifts 12 by 1 to the left
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
Mb , i didnt see that i said "by 2"
const IS_ACTIVE = 0b0001
const IS_INACTIVE = 0b0010
const IS_STANDBY = 0b0100
let state = IS_ACTIVE
if (state & IS_ACTIVE) { ... }
?
Konnchiwa kiro san
Why did u use binary._. ?
Because its powerful
hello
.
Doest Player.getGameMode() exists already?
I just know this method lol
I'm still pretty new to scripting btw
Yet?
Yet?
not everyone feels that way
it will result in 1
yeah, its valid
Yes it is
what
can i redirect a player from a world onto a bds server?
that feel trippy
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
i figured itout already
but ty
and yes u can transfer from worlds to servers
should I use the same dynamic property for everything?
Uuuuuuhhhh I don't think it matters but probably no. Cuz if you load a massive DP then that's gonna cause some issues.
So I should have them seperately or not?
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
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...
you could check for the block type under the player's position with getBlock()
and from there you do your if/switch logic
It was a bit tricky to make, but I’ve already managed to get it done :)
woo!!
Any ideas on how to test if a number is even versus odd?
const even = number % 2 === 0
What the what??? is % a Maths test I never heard of? Thank you!
Modulo. Divides and gets the remainder iirc
Awesome, that's good to know. thanks again.
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
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);
what's the major difference of onRandomTick and onTick?
Random is random ontick ticks every x intervak defined in the JSON.
how random is random? wht is it based on?
Its based on random tick mechanic.
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.
Thanks
@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
Thanksss
Thanks