#Script API General
1 messages ¡ Page 86 of 1
Yo cycro can you help me make a leveling system?
ive made a post in the thread thingy here, if someone could have a look and see if they can help me out that would be amazing :)
depend, it can run more than that or less
really? i was using it and saw things being limited up to 20 executions per second
it run a job whenever the game is free, that can be more then once a tick
My dear chat, you got any Debuff Ideas?
Debuffs for what?
Sorry forgot to tell, It's for a Tower Defense, For the Towers to be exact
Debuffs like Fire (Burns the enemy)
Debuff > Long Term effects
Ability > Only on hit
Necrosis
For which typeof tower?
I think freezing is better
Freezing sounds good
spawn
yes
also when is entity load even triggered?
chunk loaded with the entity inside it
chunkyyy loadyy, anyways insane name dude
How can i do this without using try?
try { return dimension.getBlock(location).typeId == typeId } catch {fallback}
i like being stepped on.
dimension.getBlock(location)?.typeId
return dimension.getBlock(location)?.typeId === typeId;
and check if the locstion.y is above or below the max/min world height
Can i as well?
clamp the location between the dimension minimum and maximum heighRange
I am trying if check the block type in a location that might not be loaded, and if not loaded it will use the last detected value
getting block on unloaded chunk simply just returned undefined.
the problem with that dimension.getBlock returns and error if the location wasn't loaded
Getting block beyond the build range (like void) throws error
that's not my issue here
there are 2 legs.
Ya
Returns
Block | undefined- Block at the specified location, or 'undefined' if asking for a block at an unloaded chunk.
but
lol, weird then xd
it still throws the error
which makes that useless
Then kept the try catch then
it's not working as i intended
stable?
the function returns undefined instead of the fallback value
yes
/**
* @param {import("@minecraft/server").Dimension} dimension
* @param {import("@minecraft/server").Vector3} location
* @returns {String | undefined}
*/
function getBlockType(dimension, location) {
const id = dimension.id.split(':')[1] + '*' + Math.floor(location.x) + ',' + Math.floor(location.y) + ',' + Math.floor(location.z);
let block;
try { block = dimension.getBlock(location) } catch {};
if (block == undefined) return SavedBlockTypesMap.get(id);
SavedBlockTypesMap.set(id, block.typeId)
return block.typeId;
}
const SavedBlockTypesMap = new Map();
Oh, that make senses. On Beta getBlock just simply return undefined for unloaded chunk, thats why It feels weird xd
how could beta be more stable than stable?
I understand that my code went into the void....
Okk........
That's going to be kept for the rest of the script's memory though
Well, he needs to save the ID, there is no other way...
Use dynamic property, so it floods the storage instead of the memory đ
Great idea
Arent DynamicProperties temporary in the RAM as well? (as long as the session is running) ?
So it will flood the memory as well
or am i wrong
Stored on the World's memory, not Script's.
alr
Across world loads yeah
-# (Not across different world)
Alright
True
@random flint it turns out dimension.getBlock doesn't throw an error when the block is unloaded
IG is tied to how far from the nearest simulation distance chunk or smt... idk, I can't read
i think this is outdated
Maybe Ig
Is it beta exclusive?
Quick off topic question.
What do you think of "Rise from Ember"
Arknights đ
-# the anime
-# yes - ROSMONTIS IN ACTIONNNNN
Im so freaking tired
Take a rest đđ
Ill give you a free massage
Virtual massage effectiveness is guaranteed đ
world.getPlayers({ names: ["princesstransgirl"] })[0]
?.triggerEvent("cc:massage")
effectiveness level 99999
What parameters do yous think should be in a function that were to check if player placed blocks are aligned properly?
Like a multiblock structure function
I am unsure on how to proceed with making the function
The return of the function will just be if all blocks are in the correct position, return true
structureName
"aligned properly"?
Sorry, I'm not good with words
Is there an alternative to making runInterval async? I'm tried to yield a for loop and a runInterval and I'm not sure how to workaround it.
const music: Sound[] = [
{
id: 'lbs.music.take_me_out',
volume: 1,
duration: 222,
},
];
world.afterEvents.playerSpawn.subscribe(({ player: plr }) => {
system.runInterval(async () => {
for (const { id, volume, duration } of music) {
plr.playSound(id, {
volume: volume,
});
console.log("Playing...",id)
await system.waitTicks((duration ?? 20) * 20); // 20 ticks per second
}
});
});
k got it working, I just ditched runInterval
async function queueMusic(plr: Player) {
for (const { id, volume, duration } of music) {
plr.playSound(id, {
volume: volume,
});
console.log('Playing...', id);
await system.waitTicks((duration ?? 20) * 20); // 20 ticks per second
}
}
world.afterEvents.playerSpawn.subscribe(async ({ player: plr }) => {
while (true) {
await queueMusic(plr);
}
});
What is the time complexity of Container.prototype.getItem, ItemEnchantableComponent.getEnchantment
test it urself
console.time("time")
Container.prototype.getItem
console.timeEnd("time")
Iâm not on my PC i cantp
That doesnât tell me the time complexity anyway really
I imagine getItem and getEnchantment are constant time. It just might be a large constant time
you need to enable logType "Verbose" in the Creator settings
Likely so
Debug result for [code](#1067535608660107284 message)
Compiler found 2 errors:
[36m<REPL0>.ts[0m:[33m1[0m:[33m9[0m - [31merror[0m[30m TS2339: [0mProperty 'time' does not exist on type 'Console'.
[7m1[0m console.time("time")
[7m [0m [31m ~~~~[0m
``````ansi
[36m<REPL0>.ts[0m:[33m3[0m:[33m9[0m - [31merror[0m[30m TS2339: [0mProperty 'timeEnd' does not exist on type 'Console'.
[7m3[0m console.timeEnd("time")
[7m [0m [31m ~~~~~~~[0m
ESLint results:
<REPL0>.ts
0:0 warning File ignored because no matching configuration was supplied
Iâm wondering what could possibly be the mslt efficient way to check for inventory updates on a player
I need to limit certain enchantments to lower levels than vanilla would allow you to enchant them to
https://jaylydev.github.io/scriptapi-docs/preview/classes/_minecraft_server.WorldAfterEvents-1.html#playerinventoryitemchange
this might be the most efficient, but be warned that checking for enchantments for each item is a tedious process
Oh we have an event for that
(Preview only)
SMH
Did not know you could call the params at the subscribe level
Would that mean you only subscribe to those properties within the event? And any non-specified properties wouldn't work?
Well yes
Youâre destructuring the event signalâs callbackâs properties
it's the equivalent of doing this, but you don't have access to event
subscribe(event => {
let { playerId, playerName } = event;
})
I see
How can I make an entity steal a random item from the player inventory, and store it on it's own inventory?
Does the slot itâs added to for the entity matter?
Get the entityâs container
Get the playerâs container
Then:
const targetSlot = 0; // for example but this can be any slot youâd like
playerContainer.swapItems(Math.floor(Math.random() * playerContainer.size), targetSlot, targetContainer)
wouldnt it be better to select items only from the hotbar? instead of the whole inventory, cause that would pull armor slots too right?
Well they didnât specify that
So why assume
And no it doesnât pull armor slots
Or offhand
im not assuming, im asking
I wasnât trying to say that you were assuming, I meant that if Iâm going to help them then itâs better that I assist them with what they actually requested to get some help with, no?
They didnât say they only want to steal from the playerâs hotbar
and you're right about the container, i just checked the doc
So I wonât help them with only making it steal from the hotbar
Yea any slot works
Get the entityâs container
Get the playerâs container
Then:
const randomSlot = Math.floor(Math.random() * playerContainer.size)
let i = 0;
let playerItem;
while (!playerItem) {
if (i > playerContainer.size) break;
randomSlot = (randomSlot + 1) % playerContainer.size
playerItem = playerContainer.getItem(randomSlot)
i++;
}
if (playerItem) {
targetContainer.addItem(playerItem)
playerContainer.removeItem(randomSlot)
}
I recommend that you improve the logic of the playerItem loop
Iâm on mobile so I just wrote something short to be used as reference
Currently itâs likely to cause multiple unnecessary calls which will result in performance overhead
also i forgot to regen randomSlot in it as well byt yea
Thank you!!
Actually now it should be fine
Basically it initializes randomSlot with a random number within the playerâs inventoryâs slot bounds (in vanilla this is 0-35 -> 36 slots), then checks if they have an item on that slot
If they donât have one on that slot it will check the next slot and go on until it reaches the last slot and then proceeds to the first slot (slot 0) and begins to increment up from there again
But thereâs better ways
I think thereâs a method that lets you find the first item within a container
Maybe make use of that to reduce the number of recursive calls
For basic use this is fine
At a larger scale itâs worth improving though
Out of curiosity, why start at a random slot? This is going to have the same average time complexity at its worst-case as starting from 0 would.
Because they wanted it to steal a random item.
Ah, then I clearly did not read the requirements 
hey @rigid torrent any news on additional block templates? Your templates have helped me cut down production time xD
I'm releasing a web app for it soon
oh nice, cant wait
I'm looking for a method to purge all diamonds, diamond blocks, and diamond ore from inventories, containers, and enderchests.
I was planning on going about it by clearing inventories of the items the first time they join after activation, every container gets cleared the next time it is opened. To deal with shulkers, maybe clear them and add a dynamic property?
is there a link to a doc to get a rundown of how to use ActionFormData? I'm completely new to this
Documentation for @minecraft/server-ui
is making a lib that makes communication between addons easier a good idea?
im making it, but by now is merely for fun
Sure.
so imma just adjust some stuff and put it in a particular github repo
i need people to test and check if there are some bugs or stuff related
its pretty based on client/server communication
i really dont know why in the hell i did choose to make it nestjs like
It is, I also had this Idea but stopped at some point
its pretty simple the way im doing it by the way
i was pretending to call it 'enchanted' but i've decided to call 'zetha' so whatever imma modify the names
and then i put on github
I really hate how discord does blocks i really dont want to see x blocked messages i just want them blocked fully
this is offtopic bro. im not used to be active here but at least respect the purpose of the chat to dont flood
Can a script trigger a component group
You can run an event on the entity that triggers a component group
And that event can detect something the script did to trigger it?
https://github.com/cykna/Zetha here it's. i forgot to add manifest.json into gitignore xd
the way im implementing is pretty easy by the way
when i send something i simply send it via scriptevents adding a header and the content
the header is 5 chars, 2 from the client id, 2 from the server id and 1 for the request index(get track of promises) and after it, its all thr content
i made it using lz/cbor+pako
to simply compress data and exceed the limit of 2043(2048 - 5 of the header) chars per scriptevent
If that person i blocked was answering me im not clicking the blocked messages to see it what you said was very rude
im probably going to implement a method where i can simply dont compress data
it slows the code, but its better to send something huge.
@cinder shadow im unsure how these event triggers work
Even better, You can trigger the event from the script itself
Ohh so in the components event i just add the component group then i trigger that in script
Yep, just use the add remove part of json events
Sweet ty so will a component group over ride the changed components from entity components
nice idea
Im doing a HTTP based system
do you mean really implementing sometjing like the protocol itself
or just the system of client/server stuff?
client/server(i call it host) stuff
an REST-Api
oh, thats the way ive implemented mine
Host registers the routes, and client can send requests
Nice
thst pretty easy if you ain't gonna implement the radix tree by hand
im used to implement algorithms by hand but damn
im using memoirist to do so
ive benchmarked it and it seems to be 2x faster than findmyway(the one that fastify uses btw)
now i think about adding some kind of encrypting
I just do it as a like hobby
the /route/something stuff
what handles it is called "radix tree"
ahh like
players/:id
yeah
or players/:id/log
both are whole npms
but memoirist is about 330 lines
you can check the code on the repoby the way
so memoirist is a so called radix tree
yeah
its a tree that each node is a radix of a string
thsts why
i really dont plan adding GET POST and these methods
and its made to process this input? (example)
input = "players/player123/log?filterDate=282222822"
yeah, as long as you define it
ofc
i did not test with params like ?filterdata=...
but as its used in elysia
theres no reason to it not have this
hmm, this whole topic is pretty interesting
its defined on "routed" on the repo if you want to see it
had to use another lib other than reflect metadata for reflecting
20kb only for about 4 methods xd
Ill do a simple one with "GET" | "POST" | "PUT" | "PATCH" | "DELETE" methods
and a radix tree so i can do routes like players/:id/log or players/
I'm trying to hide HUD elements when a screen appears.
the one thing I can't figure out if we can hide the players hand or held item in first person view?
Is there a way to control that?
holy fuck
what does it do
sorry, i dont know what decorators are
im pretty sure you cant hide hand
class Controller {
@Route("/example")
async f(){...}
}
when i call "/example" it executes this function
though you could do a workaround where you give the player an invisible item
ahhh alright
by the way, if your going to implement it, i think you probably are going to implement streamming
streamming?
if using scriptevents
you send something that the size is >2048 chars
so to send it correctly, you break it into pieces
and send each piece
like a TCP?
so i chunk my too long string and send it in sequences?
yeah
ive solved it by doing well a hashmap
with a circular index
just to do not use much memory
this index is passed on the request
so the server knows that promise to respond
it processes when the data is finalized and sends back to the client with thag index
so the index get that response and use it to resolve the promise
chatSend event only for beta apis?
yes
alright so
damn
the Host notifies the client when all "packages" arrived?
yeah
there are 5 ways of sending a "message" initialization, finalization, packet, batch, single
the single is when data is < 2048 chars so it sends in a single scriptevent
initialization just tells the client/server its going to receive a request/response
the packet is the data streammed
matching the initialization stuff
the finalization tells theres nothing more to receive
so the client/server can process the received data
i did everything by my self, i think you could too
You destroyed my ego
the batch is simple, when requests are small and dont need to be resolved when sended, you can store them
when its close to 2048 chars, it sends them all at once
whats the limit of request per tick in minecraft? 256?
depends
if you block the thread on both sides
or simply dont use runJob
ive got about 3k requests per second
YOU WONT EVER NEED THAT MUCH
Wait you can make a player balloonable
pretty cool
well, it was a basic Hello World response
if you block the thread(or simply use runJob) on the server
hmm whats the topic?
you limit the responses to the client by 20
Client and Host stuff
if on both, by 10
radix trees
was wondering cuz i saw this
well uh
scriptevent command doesnt have a character limit
just telling you
really? ive seen on the docs about 2048
btw
hm, that can be usefull, thanks
where do i normaly put my requestId, in the header?
ive made it in the header
when sending a packet it gotta know from which request it's
to data dont get corrupted
the header is the same at every request
it's all(or almost) documented(please don't mind if you see some &, << and >> operations)
you can check it
though this probably has one tick delay under the hood
but it doesnt have performance loss (or super small if any)
as im planning to send data uncompressed, i think imma check it
i really dont think there are going to have some performance issue
lol
my addon uses a system that makes use of the scriptevent command
or at least not critical
all the knowledge i have its because of i started coding in rust
im not that experienced btw
i code with rust about less than 1 year
i simply cannot understand what's going on here
well my case was just for sending necessary data before the ingame world loads, so i dont know how it would go in real-time practice
(â â˘â âżâ â˘â )
yeah it lacks documents lol
i didn't even know there was some that implemented it before
but what that does is that it encodes data into base64 and send it using scriptevent command
and the other pack receives the scriptevent and decode it
dwmn base64 adds 1 char each 3
it adds 33% overhead
i really do so
but depending on the size, it uses lz to compress
or cbor+pako
which reduce the size of data
instead of grow it
what is "tbf"? i dont speak english natively
its "to be fair"
oh, thanks for clarifying
ja
actually i thought in doing so because i wanted to make an addon that helps others
actually by saving data for them
and maybe some executables
well if your use case doesnt involve stuff like sending function data for new Function(), then IPC might be a bit too much for that
unless you need to encrypt the data to be unreadable for humans
actually it was
how does ipc work by the way?
probably not
yeah
well you can check my use case here:
https://github.com/AnotherSeawhite/sweepnslash/tree/main/behaviors/scripts/IPC
(dont mind the mess, its under a huge code revamp)
i should get rid of the embeds, those are huge
Does onStepOn trigger for block with no collision?
If not, how can I trigger an event when a mob's hitbox is in my block?
No, you need a min of 4 on the y.
i think mine is too overkill for that by the way
im making it about 1 month
the way i implemented is godamn insecure
Why does the health component only change max health on the very first load if i change it but load the same world its not changed
anything i modify can break if its changing the internals
and probably im going to modify compression
How can I detect if the player is on ground? "player.isOnGround"?
yeag thatll work
Are you sure?

I will ad it to the code anyways
Anyone?
(dont mind the .isRiding)

its on the docs
I don't know
its because thats how components work
I was searching for this list thank you
entities dont refresh themselves, the components will stay once its set
@shy leaf so how do i make there max health changeable with component groups if it wont change with the chsnge
@shy leaf I'm trying to continue your dash code
So component groups do over ride its health
From the dungeons camera thing
oh nice
Entity events just triger component groups for component stuff
Wdym?
With .isRiding?
Entities don't save their component group state. You have to retrigger when reloading the world or rejoining a world
I'm too slow to understand some things, especially if it's not in my main language
Oh great, now I want to know

Object.defineProperty(Entity.prototype, "isRiding", {
get: function() {
return this.getComponent("riding")?.isValid ?? false;
}
});
its just for checking if an entity is riding
Riding state is when the player/entity is riding another entity or is in the seat of another entity
Yes but I was asking about isOnGround, not isRiding
yeah i was telling you to ignore it
Bruh
Oh, Thank you
Thats fine the event that runs it will be ran each time it updates but heres a big q if i have a player.json but another pack is to add updates to player.json without over riding it how do i do that
Well then bad luck IG. You can't really change entity health at runtime without data defining components
What?
what
You can use effects
Thats not what i asked
You cannot edit vanilla files without having the risk of it being overriden.
not true
If you wanna change player health without the risk of overriding you can use the effect that changes the player's max health but then it does become a bit annoying to manage the effect but it's less likely to get overriden
I have multiple packs so each pack can manage its own skills but that means player.json may be needing changes in multiple areas
I mean i could make a core pack dependency and use componenent groups thus only 1 player.json
That can work. Only if the users don't use another add-on that overrides the player.json based on addon hierarchy
And no effects wont work as 1 adds 4 however theres an alternative way i can do health if i want and ill leave a note not compatible with other packs that change player.json
In what way? The only way I know that it'll save the state is when you write a property that the molang detects at runtime.
Whatever Components get added via the CGs persists. The entity does not revert back to base component.
no it uses binary encoding. output size is generally smaller than if you were to use something like stringify
But not for entities that are despawned and respawned? Like the player or is that also saved?
if you dont know why are you saying it doesn't
@wary edge so if i add a component group that sets my max health to 21 when activated will it set health to 21
Yes.
Based on my knowledge and my experience with creating entities, this is what I thought.
hm
alreay exists, #1277940040688996512 . Here's the packet standard for the communication if you're interested: https://gist.github.com/OmniacDev/ecd6f61ffd8d0ed6be1b7cf6ecea9145
it does, 2048 bytes
if you have any questions lmk
more specific ones at least, that one is a prety broad question lol
If player.json is in pack a can a script in pack b still trigger event
Yeah. It should be able to
i dont think i have, at least by now. i just think the serialization and deserialization stuff interesting
as the default way im transferring data is json if i remove the compression stuff
I'm having trouble with this why it won't execute
system.runTimeout(() => {
dimension.runCommand(`playsound random.levelup "${player.name}" ~~~ 1 10`);},2);```
where's dimension
and where's player
It was running whne i didn't add the pitch vol
can you answer
You should try using this instead of running a command in the dimension
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/player?view=minecraft-bedrock-experimental#playsound
it would still work, assuming if hes doing it correctly.
Its to late for me save yourself
What?
?
Nothing im bored
okay...
If (kirstin === "bored") { sendRandomMessages()}
TypeError: "sendRandomMessages" is not a function
I had that defined elsewhere tho
TypeSuccess: "sendRandomMessages" is a function
I need to do a million things and lost on what 1 to tackle while slso dealing with some of the most vile people 1 of which is sadly in this server my sanity is slipping
Focus on what you need to do first for something else to work. I usually develop core base frameworks and dependencies first before moving on to other stuff.
player.playSound() is more accurate figured it out
keep in mind that'll only play to that player
So thats for each individuals if via multiplayer just runCommand
no.
there's dimension.playSound
-# world.playSound is deprecated in newer versions
Ohh okay
How do i get the players health snd set it to a variable
get the health component.
Documentation for @minecraft/server
Ok im trying my hardest to follow the example in that docs and i sm failing all i want is to create a var health that is the players health
so store the currentValue property in a variable.
Wdym? It's 1 line...
const health = entity.getComponent(EntityComponentTypes.Health) as EntityHealthComponent;
That throws an error
because thats typescript.
just remove the as part.
Remove as EntityHealthComponent
Ahh
then get the currentValue property.
system.runInterval(() => {
const players = world.getAllPlayers();
for (const player in players) {
const health = player.getComponent(EntityComponentTypes.Health)
console.warn(health)
}
})``` is not a function
that doesnt make sense, it should return object object
and like I said, get the currentValue component for the health value
the const health = ect is where the errors thrown
i thought this was how you got the component
oh whoops typo but you said i still need to get the component
and
it is?
hold on ill test it your going in circles
Lol what
i need its value and max idk how thats done
What you did there in getting the component is correct except for how you're retrieving the player. You have to use for (const player of players) not for (const player in players)
no you said then just get its component
thats not how
but how do you not know how
i possibly do not that i remember
its just dot notation
so health. or player.
import { world, system, EntityHealthComponent, EntityComponentTypes } from "@minecraft/server"
system.runInterval(() => {
const players = world.getAllPlayers();
for (const player of players) {
const health = player.getComponent(EntityComponentTypes.Health);
console.warn(health.currentValue);
}
})
ok thats what i needed
you need this too
Whats the script for a title
get the onScreenDisplay property on the player
Documentation for @minecraft/server
then use the setTitle method
What is the alt code for the color change symbol
§
The slt code but i found it 0167
Yeah that's the correct code
Yo is there a code that I can get the world name
no
offtopic is dead đŚ all chats i have seem dead
You helped me and tell that to wrap it up. I made this:
world.beforeEvents.itemUse.subscribe(event => {
const player = event.source
const item = event.itemStack
if (!item || item.typeId !== "minecraft:compass") return
const riding = player.getComponent("riding")?.entityRidingOn
if (!riding || riding.typeId !== "test:test") return
const tags = riding.getTags()
if (tags.includes("ride_1")) {
player.runCommand("execute if entity @e[type=test:test,tag=ride_1] run event entity @e[type=test:test,tag=ride_1] ride_2");
} else {
player.runCommand("execute if entity @e[type=test:test,tag=ride_2] run event entity @e[type=test:test,tag=ride_2] ride_1");
}
})
But it still says error with privileges
Can you or someone help me?
The runCommand function can't be executed directly during a beforeEvent because it runs at the start of the tick when the event is still in a read-only state. At this point, any method or property that modifies the world is restricted and will throw a "does not have required privileges" error.
To work around this, you need to delay the execution of those methods until the world is in a read/write state, typically at the end of the current tick or the beginning of the next one. One way you can do this is by wrapping the command calls in a function and passing it to system.run(). This effectively schedules it for execution later in the tick, when the required permissions are available.
system.run(() => {
if (tags.includes("ride_1")) {
player.runCommand("execute if entity @e[type=test:test,tag=ride_1] run event entity @e[type=test:test,tag=ride_1] ride_2")
} else {
player.runCommand("execute if entity @e[type=test:test,tag=ride_2] run event entity @e[type=test:test,tag=ride_2] ride_1")
}
})
Like this
??
Thank you so much for clarification!
Is it possible to get the effect a potion gives in minecraft/[email protected]?
Why are you still on 1.16.0?
it's hard to update

Yes, I understand.
It's really hard to change the version.
Not everyone is able to edit a JSON property
where does the getview direction bases it values to the direction the pivot point of the head is facing in its model?
on getRotation()
Entities have a "rotation" property and getViewDirection() basically just turns a Vector2 into a Vector3
many things would break
So what? It's better to spend time updating than to suffer all the time because of the lack of features
not really
btw how did you do that "MIKU" stands next to your name :o
It's a server tag.
I have over 8000 lines đ
I can send you a invite
If you click on the server tag next to the name it will pop up the server. Have to be on PC though. Won't work on mobile.
Pfff, that's not that much
yes please
so? you are using a stable version, changing it to 1.19.0 should work without any errors
maybe I will try it later
I would switch to V2
v2 is still beta tho
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
oh, yeah? well then he can wait
hey how do I know if the function/event im using is beta?
Check the docs.
im using jayly's is there a label somewhere that says it?
yes
Idk.
oh lol thanks a lot it's been at my face the whole time
is there a way to check player is op on stable version
except for tags and isOp since its beta
No. You basically just exclude most of the practical ones with that question.
Scoreboard, dynamicProperty, is an option. But it's redundant and still requires manual handling.
@sly valve can you give me some suggestion? its about the stuff of transfering data between addons
im thinking about changing the way i can transfer data, im sending at the beggining of the type of compression of the content, L for one, C for another(match the initials of the name of the algorithms used), but maybe i can use so to send more data in a single character.
Uhhh idk
in js each char is utf16, so i have 16 bits where i can use them to be bitflags. Instead of sending response/client responses and their respective types with an specific id on the scriptevent, such as
scriptevent zetha:client_packet ...
scriptevent zetha:client_batch ...
scriptevent zetha:server_packet
i could put them in a single char using it as a bitflag 'array'
like
XXXXXXXXXXXXXXX0
means its a request
XXXXXXXXXXXXXXX1
means its a response
XXXXXXXXXXXXXX0X
Means it uses lz for compression
XXXXXXXXXXXXXX1X
means it uses cbor + pako for compression
and so on
:0
so a response which uses lz could be a char whose bits are XXXXXXXXXXXXXX01
aint understanding anything right?
Ill read through it in one sec
I do
But whats the advantage of it
One char for the type of compression used for the content
as i need passing between client and server the method used for compression
i thought it would really suck losing 16bits for only 1 task
Well thats right
and it would make things easier since i wouldnt need 9 types os messaging,
export enum ResponseType {
PacketData = "enchanted:response_data",
BatchResponse = "enchantend:batch_response",
SingleResponse = "enchanted:single_response",
Finalization = "enchanted:response_end"
}
export enum RequestType {
Initialization = "enchanted:request",
PacketData = "enchanted:request_data",
BatchRequest = "enchanted:batch_request",
SingleRequest = "enchanted:single_request",
Finalization = "enchanted:finalize_request"
}
as in here
i could only send 'zetha:message' and on the first char you get all the info you require to know how the data was sent
by now i dont think it's good because i dont have much ideas of what to put in there
Each character is saved with UTF16? So that means they are 16bits long
i've thought about
message type(client, batch, single)
response or request
compression method
if streammed, initialization or finalization
yeah, sadly thats how js works
i'd use String.fromCharCode() to get the number and transform to a char
nothing too complex
And yiu want to use 2bit for the compression type?
1 bit for compression type
as i have only 2 options by now
Ohh alr
.
But isnt it impossible to have a single bit in a string
only the message type would require 2 bits
it gets converted to a char with 16bits
but i can cast it to number using content.charCodeAt(n)
How many bit will the number have?
the bounds of strings, so 16bits as well
imma make flags covering up to 1 << 15
32767 in decimal
send more things, in a single scriptevent id
as i've said, it passes the method the data was compressed
Does the id has a maximum amount of chars??
so im losing 15bits only to check if it used one algorithm or another
scriptevent method has 2048
command has infinite as a bro said
Hmm so id length and the message length in total must be below 2048
I heard 32 somewhere
i just need some ideas of what to transfer on those 16bits
depending of it i can implement
if not im not going to by now
only the first char
Nvm my idea just disappeared
i really got no ideas of what to add
theres no reason to implement only by covering what i've thought
I look at his code and don't understand why there is so much stuff there?...
only interesting thing is about a response that does not expect response
?
hey guys
so i'm moving to v2.0.0, and i'm getting this error
20:05:35[Scripting][error]-ReferenceError: Native function [World::getDimension] does not have required privileges. at <anonymous> (intervals.js:50)
what does this mean? what did they change to world.getDimension()?
what have i missed
Where are you calling it?
Are you calling this at the top level? If so you cant do that. You must call it in worldLoad.
yeah i do
worldLoad is something new?
how do i call it in worldLoad? i'm totally out of loop with the new stuff
it's because in v2 scripts are ran before the world exists, so you can't get its dimensions
okey, good to know, thank you
- for (const player of world.getAllPlayers()) {
- player.sendMessage(`Hello ${player.name}!`);
- }
+ world.afterEvents.worldLoad.subscribe(() => {
+ // This procedure is moved inside the worldLoad callback,
+ // since world.getAllPlayers() can't be called in
+ // early-execution mode.
+ for (const player of world.getAllPlayers()) {
+ player.sendMessage(`Hello ${player.name}!`);
+ }
+ });
woah
that code block looks new
ah yeah? i just did system.runTimeout(() => {}, 100) and it works, but this will be better, thank you
You could just put it in system.run
i've watched the video on minecraft creator channel, it was said that world loads in 5 seconds, so how would system.run work if it runs after only 1 tick?
can confirm that it does somehow
system.run and runTimeout are executed after a tick, not after 0.05 seconds
Which is a tick.
the first tick starts after the world loads so....
20 ticks in a second so...
In ideal conditions, yes.
Is it possible to increase fall damage by x5 i already have a trigger to remobe it in diamond gear whichbi need to stay also
import { EntityDamageCause, world } from "@minecraft/server"
world.afterEvents.entityHurt.subscribe(data => {
if (data.damageSource.cause != EntityDamageCause.fall) return;
const health = data.entity.getComponent('health');
health.setCurrentValue(health.currentValue - (data.damage * 4))
})
Is that type script i used the hurt without needing the entityDamagCause import on js
???????????
Is there a way to detect if the player is holding an entity with a leash?
thx
I never needed the entity damage cause component the event handler has a cause or is this specific for multiplying
EntityDamageCause is just an enumeration of all possible damage types, this is usually done for more OOP style because it makes the code more clear, you can replace this with just the string fall
Ibknow im in school but the event handler slso has a cause built in
cause, which comes from the event, is the cause why the entity received damage, EntityDamageCause is all possible causes why the entity can receive damage. In this case, we do it like this: if cause != EntityDamageCause.fall then the code execution ends by means of return, so the subsequent code will be executed only if cause == 'fall'
Actually i may need to multiply all damage by 5
Cause starting hp was multiplied by 5
Well my code increases fall damage by 5x
Could i just do a world afterhurt event take the damage amount multiply by 5 then apply damage
Yeah.
yeah that works
and in case of damage being high enough to kill the player, you could clamp the health component set value
Why reinvent the wheel when I already wrote this code 500,000 years ago and gave it to you?
Ego maxxing
Well, so... I didn't just write this for no reason, right?
idk
its up to her to decide if use your code or not
maybe its just a self testing thing
Okay, never mind....
@valid ice
Im having trouble with something and my friend told me you helpeed him before with the same problem but for some reason it doesnt work for me
could you help me please?
-# At least ask a question first
-# Now he will ignore you and still ping herobrine
You said thats only fall damage
-# Yes, it's so rational.
-# yep
yap
Well shoot, if only I knew what the problem was
Why canât you send it here
how do you guys do the small gray text?
Bang
But you said you only needed fall damage...
-# like this
-# did it work?
At the time then i said i need to multiply all damage byv5
A space is missing my dear
-# a
Cause i multiplied start hp by 5
-# b
it worked
#off-topic
Sorry đ
Yes, and that's what my code does.
Or wait....
You said it only did fall damage were going in circles
bruh its not that hard to stop filtering from fall damage
Again, what do you need?
idek what it is
its a script i got from someone
just dont ping if you dont even know what do you need
Ah that explains everything, your problem is that something is wrong
ok i figured it what is wrong
i have a chest ui
that makes sense
I needed to multiply all damage by x5 cause start health is multiplied by x5 i was asking if i could simply just multiply by 5 in the hurt event without needing the cause
solution: ctr + x on the line you dont need
Then just remove the line with the condition from my code
and theres this typeId folder for like item textures that show up in it with numbers but all the numbers are wrong
did you add custom items to your addon?
yes
Make sure you have the latest version
that's the issue
got it
so what do i do
how do i know what their numbers are?
so in the forms.js add your items like this in the custom content constatnt
okay thanks ill try that
change the ids to your items
dont copy paste my items couse your items are different from mine
yes i did that
đŻ
the custom items show up but the vanilla ones are still messed up
all items + blocks.....
look better you mightve doing something wrong with ids
There are ppl in the us who think the us is a continent
Please can i leave this planet let me out
@wheat condor what is wrong here why does it mess up the typeIds ```js
/**
- Defines the custom block & item IDs for the form.
- You can reference either a vanilla texture icon, which functions identically to other items...
- ...or reference a texture path, which removes enchant glint and 3d block render capability.
*/
const custom_content = {
'sakura:common_key': {
texture: "textures/items/common_key",
type: 'item'
},
'sakura:rare_key': {
texture: "textures/items/rare_key",
type: 'item'
},
'sakura:server_menu': {
texture: "textures/items/server_menu",
type: 'item'
},
'sakura:epic_key': {
texture: "textures/items/epic_key",
type: 'item'
},
'sakura:legendary_key': {
texture: "textures/items/legendary_key",
type: 'item'
},
'sakura:power_up': {
texture: "textures/items/power_up",
type: 'item'
},
'sakura:sakura_key': {
texture: "textures/items/sakura_key",
type: 'item'
},
'sakura:mythic_key': {
texture: "textures/items/mythic_key",
type: 'item'
},
'sakura:drill': {
texture: "textures/items/drill",
type: 'item'
},
'sakura:hermes_boots': {
texture: "textures/items/hermes_boots",
type: 'item'
},
'sakura:battle_axe': {
texture: "textures/items/battle_axe",
type: 'item'
},
'sakura:life_battery': {
texture: "textures/items/life_battery",
type: 'item'
}
};
//Blocks are excluded from the count, as they do not shift vanilla IDs.
const number_of_custom_items = Object.values(custom_content).filter(v => v.type === 'item').length;
const custom_content_keys = new Set(Object.keys(custom_content));
//Add custom sizes defined in UI
]);```
are they ALL the typeids of your items
yes all
then idk
me neither
stable
is it layest vertsion
are you sure the game is reloading correctly, have you tried to close/reopen the game and the editor
why the editor??
bridge sometimes does not save files and it breaks
are there more than 1 mod in your world?
nope
idk then'
Someone find and delete this code from reality please ```class Society {
static influencers = ["CloutChaser99", "FakeNews4U", "GuruBro"];
static criticalThinkingEnabled = false;
static main() {
for (let i = 0; i < 90; i++) {
let person = new Human();
person.brain.install(Society.createMindlessScrollApp());
person.brain.disable("skepticism");
person.opinion = Internet.TikTok.getRandomMisinformation();
person.shareWithoutReading();
}
console.log("â
Mission Accomplished: Intelligence Level â Critical Low.");
}
static createMindlessScrollApp() {
return new App("ScrollHole", 267, "emotional_manipulation");
}
}
class Human {
constructor() {
this.brain = new Brain();
this.opinion = "";
}
shareWithoutReading() {
console.log("đĽ SHARED: " + this.opinion);
}
}
class Brain {
constructor() {
this.modules = [];
}
install(app) {
this.modules.push(app.name);
console.log(`đ˛ Installed ${app.name}`);
}
disable(functionName) {
console.log(`đ Disabled: ${functionName}`);
}
}
class App {
constructor(name, notificationsPerHour, contentType) {
this.name = name;
this.notificationsPerHour = notificationsPerHour;
this.contentType = contentType;
}
}
// Simulated API
const Internet = {
TikTok: {
getRandomMisinformation: function () {
const junk = [
"The Earth is flat!",
"Vaccines have microchips!",
"You can live off vibes!",
"5G causes telepathy!",
"Bananas cure anxiety!"
];
return junk[Math.floor(Math.random() * junk.length)];
}
}
};
// đĽ Run the simulation
Society.main();```
Holy shiet
what's that đ
The reality code that i assume is why so many stupid ppl exist
you spent time doing that?
Im bored deppressed and hurt ofc i spent time doing err i mean looking for that code
Ill trade issues
i wonder why ur depressed
typing up a storm
Lets see reason 1 may be cause a week ago someone i knew was bullied for being trans and took her life and her death is being celebrated
crazy story
yeah but like you re a bit a cloutchaser too
Excuse ne
yk what cloutchaser means?
First off no and second off im just a girl who posts on here
Im just irritated right now cause of what happened
posting this in script api channel is clout chasing
whats the difference between property and dynamic property on entities?
dynamic properties are variables saved on the entity and properties idk
No its just posting cause i have nowhere else to post it
off topic?
you can just keep it to yourself mate never hurts
properties are from the entity json file
you can't add properties or remove them and the data need to follow the range the property have
dynamic properties dose not have anything to do with the entity json
you can save dynamic properties to the world or entities or unstackable items
the data type is either number vector3 string or boolean, they are unlimited but each dynamic property can only store 32k bit
whats this event about
You cant just keep things to yourself thats how ppl end up dead or worst
Read the rest of what was said
posting that only means that you want approvement and attention
No it means i want to vent
Do dynamic properties on an entity get removed when an entity dies?
Yes
Fir that entity cause its dead
Yep, not the player tho
Unless you set it to be removed on death
i see, thanks
this chat aint a place to to give others negative energy, just be positive and stop posting for approvement
I post to vent stop policing every bit of content and this place has already given negative cause 1 of the ppl supporting this girls death was in this channel
Maybe use #off-topic ?
we re not the place where you just throw your problems and bad news
You mean dead chat topic
wtf are you talking about
It is more active than here
Then ignore me cause idc anymore sick of this shit
SO YOU RE CLOUT CHASING
You want others to see
Just go f yourself then blocking you
Anyway...
Was buttonPush event removed in v2? My editor saying it is deprecated
Documentation for @minecraft/server
The types are wrong?
Wdym?
I typed
world.afterevents.buttonPush.subscribe
And it is showing subscribe crossword over with a deprecation mark
Similar to PlayerSpawn likely, the actual event signal is deprecated in favour for a new one.
wasnt so hard was it
And I was right.
they removed the I in 2.0.0 IButtonPushAfterEventSignal
After what he said i just cant with it
@wary edgeu ever do use numerical item ids?
im having a problem nobodys been able to help with so far
Damn, lol
Was so confused
Thanks both of you
whats the issue
they were removed right?
no?
they are displaying the incorrect texture for some reason
what are you trying to do?
items aux id shift when there is a custom item
how do i do this then?
do what
Shift aux ID I think
i think i have something that ignores the added items
const number_of_custom_items = Object.values(custom_content).filter(v => v.type === 'item').length;
const custom_content_keys = new Set(Object.keys(custom_content));```
idk if this works or what
the code was given to me btw
uh... what, what is that supposed to do
the comment above says
Blocks are excluded from the count, as they do not shift vanilla IDs.
get all items in game and filter by namespace "minecraft:"
my friend said the custom items get ignored?
All new custom items (1.16.100, 1.20.80+ format) have increasingly positive IDs, starting from an ID of 261. These WILL SHIFT VANILLA IDs that are higher than 261. For example, 'minecraft:golden_apple' (ID of 263) will be moved up to an ID of 264 if you have one of these custom items.
that code is out of context, i can't say if it works or not
maybe count all your custom items and increase the aux id accordingly
how many custom items are there?
12
sorry im very new to bedrock api and coding in general
it shouldnt do that but maybe try this first and see what happens.
ItemTypes.getAll().filter(i=>!i.includes("minecraft:")).length
are there any other addons that are adding custom items?
also how are you getting aux id of the items in your custom ui
youre cooked
try looking into the json ui code or where the button is getting added to the form
go into auctionHouse.js
@nova flame
const ID = ( typeIdToDataId.get(targetTexture) ?? typeIdToID.get(targetTexture)) + items
nvm
that is so cursed
like its shifting items upto 100 in between there
can you console.log(ID)
can you post the code here so i can take a look
yeah that whole function
if its short
button(slot, itemName, itemDesc, texture, stackSize = 1, durability = 0, enchanted = false) {
const items = ItemTypes.getAll().filter(i=>!i.id.includes("minecraft:")).length
const targetTexture = custom_content_keys.has(texture) ? custom_content[texture]?.texture : texture;
const ID = ( typeIdToDataId.get(targetTexture) ?? typeIdToID.get(targetTexture)) + items
console.log(ID)
let buttonRawtext = {
rawtext: [
{
text: `stack#${String(Math.min(Math.max(stackSize, 1), 99)).padStart(2, '0')}dur#${String(Math.min(Math.max(durability, 0), 99)).padStart(2, '0')}§r`
}
]
};
if (typeof itemName === 'string') {
buttonRawtext.rawtext.push({ text: itemName ? `${itemName}§r` : '§r' });
}
else if (typeof itemName === 'object' && itemName.rawtext) {
buttonRawtext.rawtext.push(...itemName.rawtext, { text: '§r' });
}
else return;
if (Array.isArray(itemDesc) && itemDesc.length > 0) {
for (const obj of itemDesc) {
if (typeof obj === 'string') {
buttonRawtext.rawtext.push({ text: `\n${obj}` });
}
else if (typeof obj === 'object' && obj.rawtext) {
buttonRawtext.rawtext.push({ text: `\n` }, ...obj.rawtext);
}
}
}
this.#buttonArray.splice(Math.max(0, Math.min(slot, this.slotCount - 1)), 1, [
buttonRawtext,
ID === undefined ? targetTexture : (ID * 65536) + (enchanted ? 32768 : 0)
]);
return this;
}```
open a post, brb
can you post or tell what the typeIdToDataId function does?
are you sure your list typeIdToDataId is correct?
also show the typeIdToID
const baseID = typeIdToDataId.get(targetTexture) ?? typeIdToID.get(targetTexture);
const ID = baseID === undefined ? undefined : (baseID >= 261 ? baseID + items : baseID);
damn i was beat
lol
Is there a way to change item's texture
Nope
I was able to get auto selection of item aux id count, im not home to share the code, but might put something in shared scripts or something to show how I was able to get counts of item ids at world load
For the chestformdata
Get all items (count), remove what starts with minecraft: and then get all block ids, then remove those from the list as well, then get the end count, stick that in the count file dynamically
Issue i see is there is alot of ids haha, so might be a small bit of lagg unless done in some sorta spread out chunks/ticks
this ended up working for him
const customItems = ItemTypes.getAll().filter(i=>!i.id.includes("minecraft:")).length
let ID = typeIdToDataId.get(targetTexture) ?? typeIdToID.get(targetTexture)
if(ID >= 256) ID += customItems
not sure if it is the same one you had
Bet
Actually might be better lmao, ill have to compare when I get a chance
Yours might be better*
alr, lol
let me know when you do so
Is there a way to place down a block in the world through a script?
Dimension.getBlock.setType
How can I account for unloaded chunks
You cant. Whats your use case?
I'm just making a tree regeneration system that regenerates blocks after a certain amount of ticks
world.beforeEvents.playerBreakBlock.subscribe((ev) => {
const { block, player: plr } = ev;
if (plr.getGameMode() === GameMode.creative) return;
const oldBlockLoc = block.location;
const oldBlockType = block.type;
system.runTimeout(() => {
plr.dimension.setBlockType(oldBlockLoc, oldBlockType);
}, 2000);
});
but it works for everything else other than trees
Ah I see. In that case what you want to do is getBlock and check if its undefined or try/catch the Exception.
Anyone any idea why this is crashing FYI it didnt crash before i put the if statement there
also note
world without the behaviour dont crash me but world with it do(any help would be appreciated)
maybe you have an empty import like import "."
this is why u use ts instead of js
Doesn't account for when u leave the world and rejoin or reload
But I used dynamic properties to account for that so we chilling
ty
Is there a spawner addon like the java one i can buy?
you love ts don't you?
just because of that imma start writing code with js and jsdocs
I write in Typescript and I use JSDocs. đ
i do the same, only because theres nothing better than ts for typing
Like donut smp
has anyone gotten block fluid container component for cauldron working? im testing smth with it and for whatever reason the component returns undefined
oh my god i think i know why...
nope nevermind
just check for the state.
no it wasnt that
i just got it working as soon as you said it
apparently trying to get component via string doesnt work but enums work??
what was the string
thats correct
const fluidComp = block?.getComponent("minecraft:fluid_container");
this returns undefined
const fluidComp = block?.getComponent(BlockComponentTypes.FluidContainer);
and this doesnt
đ
like wtf
weird
fluidContainer.
Looks like they didn't follow the snake case naming convention for internal components or components we couldn't use. Or could we use it before?
is there a way to check code performance? i mean, see which functions are slowing down the code and taking longer to complete
preferly inside minecraft, if not possible imma check with quickjs on my pc anyways
i really dont mean using console.time
2 ways.
Use the script api debugger available for vscode ooorrrr
Use a datetime/stopwatch implementation that starts and ends on a function.
how does the script api debugger work?
and where are some docs for it?
đ godamn, i thought i could use that for neovim as well
no way im going to need to open this atomic bomb called vscode
that's life, sadly
vscode is fine tho it's not that much bloated
vscode is great what
how do i save properties with smaller names?
Is there any way to stringify and parse a function from JSON?
Errr not really
I wanna be able to stringify this data and then run the function in it after parsing it
plr.setAttributes({ sellMod: 0.5, duration: 15, onExit: (plr) => plr.sendMessage('§l§cSell values have been restored!') });
Any alternatives or?
A solution to that is to deserialize it to some sort of object that implements a function using the variables from the JSON data
You can't stringify logic unless you eval it or something which isn't exactly recommended
How come eval isn't recommended?
Is it not performant or is there some underlying reason I'm missing
Usually security reasons I think. I don't think mc has an implementation of eval anyways.
Ah okay, thank you
Functions are not numbers or strings, they cannot be created using "calculations". If you use functions, then their number is limited and you wrote them all yourself. Therefore, you can save some function ID in dynamicProperty and later register the function under this ID and execute it
Save a function id?
For example
const functions = {
"test": (player => {
player.sendMessage('123')
})
}
plr.setAttributes({ sellMod: 0.5, duration: 15, onExit: "test" });
And when you want to execute the function, you take it from the functions object by the saved key
Ohhh that is smart, I'll generate a uuid and connect it to a object and run it just like that after I parse it, thank you
Any way I can account for reloading/restarting the world or no?
