#Script API General
1 messages Β· Page 134 of 1
maybe it was
the sad fact is that AI writes so abstract-less code that your abstraction actually makes the code slower
Very poetic
aw please lets not talk about AI coding
-# works only on hight-level languages like , python, js, ts, python, and yea python to be specific
its getting to the point that AI will replace everything
no more art
at least i write code that AI can't understand yet, and my friends either
no more creativity
no more soul
just slop being fed into everyone's gullets, while people get more money from less work.
when the code is so complicated than the project just dies, bc all the contributors forgot how it works in just two weeks π
not AI written btw
Is there a way to detect if the entity's inventory changes other than comparing old vs new everytick
no.
afaik we got some new inventory events lately but they are only for blocks?
Dam
theres only an event for player currently
Yeah but I need it for entity
thats opening and closing
I don't think entities have the inventory component?
they do.
they have, for example cheast_boat got one
I stand corrected
cheast_boat
In fairness, my memory is messed up from surgery lol.
and thats something I cant laugh at
sorry to hear that
damn you got me
bro pulled out the tumor card on my ass
LOL
That's something I can't even tell myself if I were you
huh
Get well soon
E
they cant get well-
tbf you didnt say cured, they can be treated obviously
btw when the AI wants to take your job, good luck buddy
Yeah that's good then
yeah, I think it was called JSON overtake or something, its peak!
the hell
Gotta push that to main
Why are you still using common js
isnt that ESM?
yo
Oh right, I mean the Object prototype method
may I be on your friends list sir
monthly tokens go burrrr
You better try the OverTykes method
Sure
Same lol
I disabled it
Sent
guh?
im off to contemplate if I should sleep or stay up all day until I crash, cya
What is the benefit of using TS over JS for add-ons?
Type checking
Nvm
Uhh is there like pickup cooldown for .spawnItem()? if not it would be a great addition for it
There isn't
If you really need it, structures preserve the item cooldown
You could make your own cooldown using this event for picking up items:
world.beforeEvents.entityItemPickup.subscribe((event) => {});
Okay! Thanks I'll try it later. Thank to you two!!
Oh new Events
Awesome
Also drop event
They have listened to us
But no beforeEvent type of it
they need to get the IA investor's money
How do we detect if animation stopped animating
It's a custom animation, I need to run a function only after the animation is finished
just realised that my monkeypatch https://discord.com/channels/523663022053392405/1485098015416127519 sucks
the dimension gets set too
how am i going to place a block directly above the placed block?
beforeOnPlayerPlace
i need to subclass DebugShape and then make the other subclasses inherit from it
this feels extremely wrong
setType cannot be called in early execution, and using system.run makes it have a delay, which make it look kinda bad
your client reflects the change you make to the world immediately
a server-side script cannot do this
Is there a specific goal or agenda as to why you are attempting to place a block above a block being placed during a before event? I'm asking because during the before event, this block technically hasn't been placed yet.
then ig ill have to use permutations and states to make the placed block invisible the second u place it and make it visible after placing the top block
you can't really do this
a two blocks tall door,
bone_visibility:
What you could do, thinking outside the box here, cancel the event of the block being placed. Then use system.run() to place the other block above, and if the block which you cancelled is still required then add it right after.
yeah, instead of having the bottom block being placed before the top one
the client will still immediately show the result of the interaction (block placed)
The block being canceled wouldn't be placed.
ill try finding a decent workaround,
yeah but the client will still preview it
Possibly. Depending on the latency.
yeah
even when playing singleplayer this is noticeable because the server only runs at 20 ticks per second
i can just use permutationToPlace to hide it the second u try placing it,
20 ticks per second should be sufficient to accomplish the goal with minimum visual hiccups.
The code would be small and light.
Hardware and Internet will be the crutch though.
btw,
if (!block?.above(1)?.isAir) e.cancel = true;
if (dim?.id === 'minecraft:overworld' && bY?.y > 318) e.cancel = true;
if (dim?.id === 'minecraft:nether' && bY?.y > 124) e.cancel = true;
if (dim?.id === 'minecraft:the_end' && bY > 253) e.cancel = true;```is working pretty fine but it cancel the even when the top block is liquid (vanilla doors replaces the liquid)
And the system.run that i am using to place down the top block is not being cancelled with this, so it try placing the block there even when the event is canelled,
But that visual glitch isn't a deal breaker.
ig ill just return or soemthing
i'd rather have visually broken immediate feedback than no feedback
also,
system.run(() => {
const eBlock = block?.above(1).setType('door:block');
eBlock?.setPermutation(eBlock?.permutation.withState('minecraft:cardinal_direction', ePerm?.getState('minecraft:cardinal_direction')));
});;```it doesnt place the block and rotate it for some reason
`permutationToPlace:ePerm`
it should at least place the block with the bottom block direction
it works pretty well, now i just have to place the top block with the bottom block rotation
@untold magnet if you're making a custom door, why not use BlockCustomComponents?
i am using that, im using beforeOnPlayerPlace
all i have to do now is just rotating the top block with the bottom block
Because you shouldn't need system.run with customComponents
playerPlaceBlockBeforeEvent doesnt exist i believe
only playerBreakBlockBeforeEvent exist
correct me if im wrong
then how can i place the top block?
Custom block component
Are you making rotatable blocks based on the player's facing
Cuz I don't think you need scripts if you can do it on client block directly
i know about that, im just working on an addon that has a two blocks tall block, and it is rotateable, i already got the rotation stuff working
now all i need is instantly breaking the block the second one of the two blocks gets broken, currently it has a 1 tick delay which is killing me
Why not use multi block component?
ummm, whats that? send me a docs link if u got any,
didnt even know that thing exists
i think i found it,
So everyone loves docs now
thanks for letting me know about that component
i only use it for new stuff that i have no idea exist, like this multi-block thing
everything else, i make without docs,
I think that's the purpose, docs are there as starter guide
stable or beta?
like what format version? 1.26.1 or something?
It's in preview atm
then ig for my current addon, ill switch from stable game to the beta-preview version to work on the addon
so im on the v26.20.21 version of the beta-preview, and i am using a block format version of 1.26.1, i used the same exact codes from the docs and it doesnt work, why?
it says not registered block state
is there a before event for sending packets?
I have a block that is getting automatically placed near the player, itβs invisible, collisionless, pickless, and unaffected by water, I am wondering if there is a good way to make it pre saturated with non source water when it is placed in non source water..? Currently when itβs placed there is a second where it is placed and the water disappears, then flows into it. Any ideas..?
Can World Dynamic properties cause lag?
by themselves no, even in large amounts. they just occupy storage afaik
In my experience, not really. I have an addon that uses them to encode cooldown data along with location dimension and some other things on a per player basis and even with like a few hundred of them I havenβt had any problems.
Bet
Documentation for @minecraft/server-net
niceee
wait... its only usable on bds isnt it 
is there a reason why they keep it to bds only
all good things are only usable on bds
ye..
Im currently trying to make a system to use worldDynamicaProperties to store block inventories
And im just getting a headache just trying to formulate an object to parse into the thing π
Actually it would be as simple as
VariableName = {
maxWeight = 6400,
items = [
itemStack1,
itemStack2,
itemStack3...
]
}
And the name of the dynamic property is the location of the block
Id probably want to use ddui or JsonUI for this as well tbh
I dont really have a way to test anything rn because of the really annoying bug on windows rn
Is that really annoying bug on Windows also known as "Windows 11"? π
You know there are better ways to store itemStacks?
if you are going to store a blocks inventory using only dynamic Properties, you might lose data
How?
Ty
This is actually very smart, but I don't like the part where it needs to use custom entity
But I like it where it saves the item stacks on cache first so we can access it directly anytime, otherwise if it's empty because of reloads, it gets the structure instead then save to cache again
It clones all the items and save it to the custom entity, saves the entity to structure with the specified key, then despawns it
yep, i think this is one of the best ways of storing itemStacks
cause i havent found anything better yet
just use structureManager
can scripts of different addons use exports of each other?
nope, scripting environment cant interact with each other directly
however there are a few ways to do it, although limited
such as scriptevent
anyone know when 2.6.0 comes out of beta?
most likely in the next mc update
an entity in an unloaded chunk stay valid ?
no
Welp, I'm getting into the scriptAPI development to my first addon as well. Can someone give me advices to improve some stuffs?
learn javascript
Start with TypeScript.
I already know about JS and TS. I mean, how to start about the scripting on here
I tried to make one by scratch, but the bridge app just allows me work with 1.0.0 of @minecraft/server or betas
Intro to ScriptAPI: https://aka.ms/startwithmcscript
Intro to Tests: https://docs.microsoft.com/en-us/minecraft/creator/documents/gametestgettingstarted
Official Docs: https://docs.microsoft.com/en-us/minecraft/creator/scriptapi
Community Docs: https://wiki.bedrock.dev/scripting/game-tests
Script API examples: https://github.com/JaylyDev/ScriptAPI
2021 Q&A: https://wiki.bedrock.dev/scripting/gametest-qna.html
2022 Q&A: https://wiki.bedrock.dev/scripting/scripting-editor-qna.html
so, bridge doesn't works well for this nowadays?
Noy really no.
what's the best way to get the coordinates a certain distance ahead of where a player is looking?
When i work with bridge (only for behavior pack), doesn't appears
really ? because with logs, I noticed that an entity can remain valid even if the chunk is not loaded
but when I change dimension or reload all, the entity becomes invalid
well, I'm not sure it works that simple. But in most case an entity in unloaded chunk means the entity is not valid
Player location + (Player view direction * target distance)
Obviously you need to format it to vector3 but just generally speaking
It was laggy, it's poorly customizable and there are certainly better options. It is beginner friendly but people switch over to more reliable IDE's or code editors like VSC, Cursor or JetStorm (iirc the name)
the update be trollin hard ;-;
Is there an easy way to know what parts of your scripts uses beta APIs?
try to use the debugger bot with a stable version mb
Is there any way to programmatically get the translated text of action bar item names?
you can get the translation key and use it
but you can't know the content of the text
I see, thanks
is there an automated way to get all the generated chunks in the world?
change manifest to not include beta, then watch the content log?
Fixed EntityHurtBeforeEvent.cancel to not allow some sources of knockback (sprint bonus, enchantment, mace smash, projectiles) when set to true
Life is good guys
Nevermind they fully messed up the knockback
average minecraft scripts developer experience:
Just use onPlayerInteract custom component.
you cant cancel this event can you?
What are you trying to achieve.
im trying to setup a 'bulk craft' mechanic for a custom block
And why does that require cancelling interaction. Bulk craft isn't descriptive.
dont matter, ill figure it out.
Im creating a custom bot via gameTest simulated player, but i have a issue where the attackEntity(target) module dosent do anything, it plays a swing animation, but no damage, screen shake, or any related events apply. Why does this happen? and how do i fix it? and no effects are applied
also sidenote its not just in one world, i genuenly did nothing to the code and it all broke, even in different worlds. i even tried with fresh code and it was still broken
ive also found arrows shot by the bot, just pass through me
did you use the beta api?
How do you stop a play animation from running?
I usually just play a small animation on top of that one to stop it from running
I made some gui change detector
But it's not very performance friendly
Since there's no events for detecting inventory changes for other entities nor blocks, I had to use system.runInterval for it
And an option to start or stop to avoid gc
whats the
https://jaylydev.github.io/scriptapi-docs/preview/interfaces/_minecraft_server.BlockCustomComponent.html#onentity
even used for?
That's for when an entity runs an event on it's home block
Oh yeah that's from startup event right?
can i use it along with home block inside the entity to somehow make my entity connect to the block? like a custom chest that u can move with pistons without pushing the entity outside of the block
Not sure if that's how it works
I think the entity just saves the block's position
And runs the event on whatever block is there
πβοΈ
if I put some code to run in a system.runTimeout after say 10 seconds but close the world before it happens, will it keep track of that and run even when I reopen the world or would it act like that never existed
and I assume the same thing applies to realms/servers crashing or closing right
Nothing happen
how would I go about clearing entities if that happens then
could I save the entity id in a dynamic property then do world.getEntity()
You could, but I'd need more context to see if that works for you
Yes you should
for what I'm making I'm spawning entities that have animations for abilities basically
so I would have to clear them or they would awkwardly sit there
You could make it run for every 10 second cycle, by saving the timer every second in a dynamic property like 1 -> 2 -> 3 -> 4 -> 5 β¦. -> 10 until it hits 10 it starts a new cycle and (clear entities) and if the world closes and reopens, the cycle can start again after a player has spawned.?
seems unnecessary, this was my idea
and you would put the id in the dynamic property anywhere you spawn it
as an array
Ooh
guys, if i already placed a chest when my function worked propertly, how do i inject my custom loot on it?
you need to get the block, then get its container component. inside of it you can find methods for all of that
you could try to respawn the entities every time the world opens. Seems more easy to me.
the purpose of all of this is to remove the entities though, not respawn them
i understand that if you leave the world without despawning them, their animation gets stuck the next time you rejoin
its not like a mob entity or something, just for visuals in an ability
What about system.job/run?
oh my god
my content logs are turned off from updating
Did you just call me a god πβοΈ
yet another thing that will randomly get reset whenever a new update comes out π
Skins, Render distance, now content logs??
for some reason my render distance wasnt touched this time I think.
only my sneaking keybind and content logs
I load into a world and all of a sudden my fans kick into high gear
First thing I check is render distance
lol yeah, when it happens im just like "why is my game running like shit... wait a minute"
why does it change it to that high though
makes no sense
who knows, my custom skins haven't really worked in stable for several months now either
defaults me to an Alex skin or one of the other generics for everyone but me
i think I got my skin reset only like once
It wouldn't exist
that looks cool. So you despawn the entity using system.run?
system.runTimeout then I do .remove()
this was just the fallback for if a server crashed or if the world closes before it could be removed so we don't just have random ability axe entities sitting around
Oh like an auto cleanup system
Clearing dropped items and other stuff
That's actually very common on servers
Oh nvm its diff
i think it would be better to clean the entities after the world loads
that way you dont have to run something every tick
No, you can just trigger events that adds component_groups
I said no
No workaround?
I mean yes sorry
You should have component groups for each economy table
Oh and trigger the event ?
Yes
||I read "write"||
Oh , i mean wire like connect to each other
Making communication to change ui dynamically
Yes, people use title and actionbar to update the ui state
What if so many titles in the same time ?
- action bar won't it get like overridden by others , like if an add-on is already using it , won't it make it invisible or glitchy or something
Depends on addon priority
Other addons can break your json ui yes
ok so I have a vector3 direction but need to convert it to a vector2 rotation for the player
does anyone know how to do that?
I deleted it because it was not correct sorry
Oh now i get it
You have direction and you want rotation
yes
oh ok
and what the difference between em
You can use @minecraft/math's Vector3Utils and Vector2Utils for that
not sure if this clarifies at all but im looking for x, y
ok ill look at that rq
You can do npm i @minecraft/math
It gives you tools to handle vectors operations but depends on you how you use it
i dont think the vector3utils has what i'm looking for
function dirToRotation(dir) {
const { x, y, z } = dir;
const yaw = Math.atan2(-x, z) * (180 / Math.PI);
const pitch = Math.asin(y / Math.sqrt(x*x + y*y + z*z)) * (180 / Math.PI);
return { x: pitch, y: yaw };
}
tysm bro
so now i have the values but i'm trying to use setRotation() and it seems to not work
at all
i can't remember if player rotation is 360 or -180, 180
Are you using getViewDirection for vector3
no i'm using the distance from the player to a spruce_log
i'm trying to move the player towards the tree and face them towards it also
well i got it working using runCommand with tp rotation but that's not optimal
const playerPos = player.location;
// Idk if this is the correct api to get the center vector3 location of the block
const blockPos = block.center
const dir = {
x: blockPos.x - playerPos.x,
y: blockPos.y - playerPos.y,
z: blockPos.z - playerPos.z
};
function dirToRotation(dir) {
const { x, y, z } = dir;
const yaw = Math.atan2(-x, z) * (180 / Math.PI);
const horizontal = Math.sqrt(x*x + z*z);
const pitch = Math.atan2(y, horizontal) * (180 / Math.PI);
return { x: pitch, y: yaw };
}
This was about moving the player to block
that's what it's doing
its a system.run not system.runInterval
this runs only when the script is reloaded
Do yall have docs for websocket communication
I tried this but it didn't work now
Minecraft lets you connect to a websocket server when youβre in a game. The server can receive and send any commands. This lets you build a bot that you can β¦ β¦
world.beforeEvents.playerBreakBlock.subscribe((e)=> {
if (running !== true) {
return;
}
e.cancel = true;
})```
Any way to get the location of the broken block?
e.block.location
is there any way to detect if the player is pressing a button other than jump or sneak???
Is it possible to communicate with json with scriptevent or scoreboards , but the scoreboard must be invisible?
Yes, full docs here
Do you mean the json ui
Yes
I saw a post about chat channels, clicking button makes it send a chat, then in the backend it detects the message using chatSend event
Is there a way to detect key presses though?
I think that's the way
Not really
I haven't tried bds, but I think it's just the same
I see.
Obviously, there's no script in json ui
So
I think the send message way only
You can conditionally render in json ui instead
oh i mean like controller keyboard etc buttons
Ohh, I dont think there is, but there's swing event
But only for swinging hands like clicking anything, interacting, etc.
Elaborate please
For example if the title has a prefix like "Β§e", it will show the json ui element
Otherwise it won't display
Oh for the scoreboard you mean ?
What are you trying to make
So i am making this ui which
Is a pop-up , like it appears when something happens
And i am currently having two
That may pop-up in the same time
And trying to find a way to do that
Because when one appeares other disappears
But i want both to appear same time
And i am trying to add a third one too
And i have no idea to what to use to make it work
whats the best way to store information in a block? it can be a custom block
Save it in the world and use the block's position and dimension as the key
Same. I just put my main skin as the middle skin. Because it would keep switching skin slot
Seomeone tested if Math.hypot is less optimized here?
Is there way how we can get block drops for specific item or not? Afaik there was something in changelog long time ago, but now i can't see the apis
Ohh i can see it its under loot tables i see
It depends on the amount of arguments, but you should be fine in my opinion
Stick to it, do not care about performance as it's implemented in core engine anyways
how do I refrence other files?
i did import { myFunction} from './file.js'
but it says it cannot fiind file js
can you show us your whole folder?
@last latch can u help me please
β€οΈβπ©Ή
- Do not ask to get help. Just get into the problem
- Do not mention people that do not have
[@]in their username
I love these questions
You should ask the question first dont you think
"No"
With this !
for what im making it would be too inefficient
Depending on what are you using in JSON-UI
I am using hud_title
And 4 images elements
But when i override the title using /title command some elements disappear
JsonUi related
You should ask there
#1067869374410657962
Ok
Then problem is json-ui general is pretty dead π«ͺ
Cross-posting is aganist rules. Wait on #1067869374410657962
no one is answering questions like that anyway, if you don't have specific question don't expect any reply
HowCan i try it
there is nothing to try yet lol
still working on the pathfinding
Oh
I just don't know how to explain. π
well, how do you expect to get help
I was trying to make 3 system , but when i override title elements just disappear
you still working on the replay mod?
write that there
Ohmm k
do runTimeouts tick values stack? I want to add a runTimeout in a runTimeout
basically, would the second runTimeout occur at the third tick, or the fifth tick?
system.runTimeout(()=>{
//other code
system.runTimeout(()=>{
//stacked timeout code
},3)
},2)
Pretty sure it would occur at the 5th tick
5th.
5th. (totally not late)
alr, thanks fellas π
Yo guys,do i can set double tags like this
if (player.hasTag("mutant,mutant2"))```
or like this
```js
if (player.hasTag("mutant || mutant2")) {```
No.
hasTag(tag1) || hasTag(tag2)
Ah okk thanks!
hasTag is a method of Entity class. Players are also entities, so all the methods of Entity class are also available in Player class. Entity.hasTag("test_tag") returns a Boolean value depending on whether the entity has the exact tag you specified ("test_tag" in this case). If you want to check for the presence of one of tags, you need to use two methods and the || (or) operator. And when you type player.hasTag("mutant || mutant2") you are checking if the player has the tag "mutant || mutant2" and not if he has "mutant" or "mutant2".
The same thing happens with other methods, functions, and operators. For example, you can't do if (test == 1 || 2) {}, you need to do if (test == 1 || test == 2) {}
I decided to explain this because it is the basis of JavaScript itself and not the specifics of this method.
Oh, I see, cuz I was trying to develop a tag system that is not too extended either lengthy when it comes to update my addon. that might help in the future,thanks for the explanation
if you want to make it shorter (just to make it more visibly clear)
const tags = [
"Tag1",
"Tag2",
"Tag3"
]
if (tags.some(tag => entity.hasTag(tag))) {}
basically checks if the entity has at least one tag of the list tags
Yep, and you can also turn that into a Map, so it's look-up is O(1)
(No point in doing so unless you plan to make the look-up table very big)
Yes, that avoids itterating or whatever they call it
Yes
and optional if you or someone prefers for-loops
/**
* @param {Entity} entity
* @param {...string} tags
* @returns {string | undefined} returns the first found tag of input tags or undefined
*/
function hasEntityAnyTag(entity, ...tags) {
for (const tag of tags) {
if (entity.hasTag(tag)) {
return tag; // you can also just: return true
}
}
// and here: return false
}
/**
* @param {Entity} entity
* @param {...string} tags
* @returns {boolean}
*/
function hasEntityAllTag(entity, ...tags) {
for (const tag of tags) {
if (!entity.hasTag(tag)) {
return false;
}
}
return true;
}
but I think for short stuff Array methods are fine enough (some, filter, every and e.t.c)
I'd only prefer or recommend using for/in-loops when you need perfomance or control over your loop and what happens
You can also get all the tags first so you don't have to call the API every time
function hasEntityAllTag(entity, ...tags) {
const list = entity.getTags();
for (const tag of tags) {
if (list.includes(tag)) continue;
return false;
}
return true;
}
Very well, I didnt think of that
and now it shall be overoptimized!!! we need a Cache!!!!!!
Y'all are making it complicated π
we are making it better
for loop is fast tho
there is always a need
we should actually write it in bin for the performance
Maybe if the project was big, but it just seems like a small project
π―
s-size doesnt matter!
but yeah when you have the ability to make it more performant, use it.
no one wants to see:
for (const i in searchTags) {
const entityTags = entity.getTags();
if (entityTags.include(searchTags[i])) return true
}
Does entityHurt beforeEvents ignore the invulnerability timer?
for when applying/changing damage? or when its triggered?
kinda need more details
applying/changing damage
"im kinda detailless"
then no, it still respects iframes
since timer runs when it actually takes damage
I must've messed it up royally, then. It applies continuously decrementing damage each tick until the game(I assume) just rounds it to zero
That's not enough, we need to make our own game and add that native function
But... if it runs on Windows.... we should make our own OS as well
For it use the CPU the best way possible we have to make our own kernel
Own CPU architecture as well. ARM and x64 should not be used
The RAM also has to be custom, DDR5 is way too unefficient
we should also NOT use the binary system
way too unefficient as well
It needs a third number
Let's make one with 0-1-2
It would need to be powered with electricity2
Electricity 2
guys, guys, guys,.We are not thinking outside the box. We need something more original
are you testing on an entity like zombie?
lets use undiscovered laws of pyhsic
our PC, the whole thing, will be working in 6 or 7 different dimensions
why thinking in numbers... I meant β or β
yeah thats good
and we shall let evolution decide our CPU architecture
basically like training a LLM to generate wonders
I have better idea
You guys are going for low level stuff
We need to connect our brains to a machine and run the game there
this channel became the new off-topic lmao
We need to run the game in the off-topic channel
I was testing on the player
oh?
the human machinary centipede
Oh yeah we can't do O(1)
Is it possible to make an entity avoid player dynamically?
In client entities it's possible, like filtering if the entity is a member of a certain family or if it has a tag
Noice
server side
oh
Guys question
whats up
what
Lmao
Hmm is there like an add-on studio like small group of people that works on add-on together?
i would assume so...
That make it for the love of the game...
ah, no
we all work in add-ons out of greed
: T greed of what ?
Why?
Is it possible to set the ItemStack data ID? I want to set the meaning of 14 below on the ItemStack
e.g. /give <player> red_mushroom_block 1 14
Well when you instantiate the ItemStack class, you provide it an ID. You can therefore only initially set it
Just change the argument provided at drop.itemId to change the items ID
The itemId would be red_mushroom_block. I want to set data to 14.
Oh you meant the data
I have come up with a workaround using loot tables & loot spawn though!
Hmm... Only thing I know you can set are dynamic properties, properties, tags? And components
Of course man. How do you expect me not making any money
π βοΈ 
Money in this economy ?
Someone has money?
Where did money go
Invested.
Gachas
now that you ask..
Can you set a fishing hook to be hooked onto a target?
The greed of getting all the errors for ourselves
All the dozens of warnings the trial and errors
π«
-# got this in DM
What is that
Learing JavaScript is better then this
yeah
My first tought...
Someone make a nodes tool
true, this isn't complete anyway, you still need know events properties for example
legit just straight up abstracting something that is already abstract to some level
like javascript is a high level language
we don't need another language ontop of it
Had to implement autocompletions and JSDOC.. and... reinvented IDEs
Lol
i don't see what's the issue with remaking IDEs
the only issue is if they're not realistic about it
yo btw does anyone here use Visual Studio?
i use Visual Studio Code
i'm just wondering what are your thoughts on VS compared to VSC
especially for writing scripts and addons
to each there own use, they are different for a direct comparison
ik they have their own uses
but i'm asking
in general
This is like putting training weels on a bike with training weels
its not that hard to write if()
guys, how can i make that the webs can be separated and spread to other parts of the inventory?
i mean, like this
Depends on when and how you want it to do it
in java edition was easy to put it randomly, but bedrock doesn't works propertly i guess
Are you using Math.random()
nope, i'm just using the simple /loot command after placing the chest
Is it posible to get: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server-gametest/simulatedplayer?view=minecraft-bedrock-experimental
to open a chest thorugh interaction?
Looking nice
I use both, but I mainly stick to VSC because itβs lightweight yet very efficient. For Minecraft Bedrock behavior packs and addons, I donβt really need a full IDE like Visual Studio. VSC gives me everything I need such as syntax highlighting, IntelliSense for JavaScript/TypeScript, and easy integration with JSON and scripting files, which are core for Bedrock addons.
Another big advantage is its cross platform support, I can switch between Windows and Linux seamlessly, which keeps my workflow flexible. Plus, the vast ecosystem of extensions in VSC makes things like code formatting, linting, and even Bedrock specific tools much easier to set up than in full Visual Studio.
For debugging, VSC has good support for scripts and can integrate with Minecraft addon projects via tasks or launch configurations, whereas Visual Studio can be overkill unless youβre doing complex C++ modding. Overall, for Bedrock scripting, VSC hits the sweet spot between functionality and simplicity and that's what I personally favor.
can you trigger a swing somehow
like is there a way to make a player swing an item through script api
Not as far as I know.
how about playing the animation
Hardcoded
The animation is not avaliable to us due to its lack of existence
It means its not accessible in the style of a JSON file, and is written into the actual game's code
what if you make your own swing animation?
Wspppp
Idk
Guys
Guys
Guys
Guys
what have i just created?
its perfect, its peak code, It even has O(nΒ²)
The bigger the number the best it would be : )
The best of all is O(n!)
may I know where exactly am i doing a o(nΒ²) ?
Do y'all know a way to keep the entity that has viewable inventory from dropping those items on death
there is a property in minecraft:inventory component that makes the entity's inventory private, but i don't know if it works of the inventory is viewable
I tried that but that also makes inventory unviewable
then you have to use a script to clear the inventory before the entity dies
Two for loops my man
/**
* Maximum-performance 3x3 chunk scanner.
* Fully unrolled + numeric hashes + no allocations.
*
* @param {{x:number,z:number}} location - World coordinates
* @param {Set<number>} chunks - Set of processed chunks
*/
function scanChunks(location, chunks) {
const baseX = Math.floor(location.x / 16);
const baseZ = Math.floor(location.z / 16);
// Unrolled loop: manually handle each neighbor
const hash00 = ((baseX - 1) << 16) ^ ((baseZ - 1) & 0xffff);
if (!chunks.has(hash00)) chunks.add(hash00);
const hash01 = ((baseX) << 16) ^ ((baseZ - 1) & 0xffff);
if (!chunks.has(hash01)) chunks.add(hash01);
const hash02 = ((baseX + 1) << 16) ^ ((baseZ - 1) & 0xffff);
if (!chunks.has(hash02)) chunks.add(hash02);
const hash10 = ((baseX - 1) << 16) ^ (baseZ & 0xffff);
if (!chunks.has(hash10)) chunks.add(hash10);
const hash11 = ((baseX) << 16) ^ (baseZ & 0xffff);
if (!chunks.has(hash11)) chunks.add(hash11);
const hash12 = ((baseX + 1) << 16) ^ (baseZ & 0xffff);
if (!chunks.has(hash12)) chunks.add(hash12);
const hash20 = ((baseX - 1) << 16) ^ ((baseZ + 1) & 0xffff);
if (!chunks.has(hash20)) chunks.add(hash20);
const hash21 = ((baseX) << 16) ^ ((baseZ + 1) & 0xffff);
if (!chunks.has(hash21)) chunks.add(hash21);
const hash22 = ((baseX + 1) << 16) ^ ((baseZ + 1) & 0xffff);
if (!chunks.has(hash22)) chunks.add(hash22);
}
Do you approve? πππ«ͺπ«£π΅βπ«
Bro what
wrong it has no cache
π
what if i tried calling this function 10^32 times in a single tick
this one was better
Record it π
Bro you cpu dosen't have that much of transistors believe me π
mine not. Cloude's test servers yes
ill ask it to vibe code the funcion to make it 100% better
Have it audit mine too π
π«£
But isnβt VS for C languages?
Ik, and tried
Anyways, is there example snippets for custom form
In the wiki.bedrock.dev
how does << react with negative numbers?
What are the limits to the ticking area manager? I've worked with the ticking area command for a while now but am switching over due to the manager being in stable now, and my major question is just what are the differences?
none?
Oh?
the change log says they aren't limited
Oh wait I thought it was json ui related lol, if not then you might check the intellisense or documention for reference and examples
255 chunks.
those bit operations are way faster than math operations, iirc
So we're counting transistors now 
O(n!!) is way better
YEPYyyy
im curious, is there an n less than 1 such that:
n!!>n! is true?
:-:
Yes
only in a very limited sense, and it depends on how you define the double factorial for non-integers.
interesting
thanks for the answer!
Another day, another painfully replacing mc.EntityComponentTypes.Equippable with runCommand("replaceitem ...")
damn
i feel your pain
Thank the Lord I only need write access. No reading is necessary for this project.
they should add entity equippable component back to entities
reading is possible btw
but it's very limited
compared to just... getting the slot
Tell me the method for future reference.
you'll have to use runCommand + testfor command
with the hasitem selector
and then check successCount === 1 (success)
So you run the command for every item in the game
pretty much
but for my use case i only need to check for two items
use this as reference btw if you ever need read access: https://discord.com/channels/523663022053392405/1306719668429389834
you'll basically have to implement something similar
except for each slot you wanna check instead of the enderchest slot
and yes i am aware of the enderchest component being added to the new versions
anyway gtg cya
Oh I totally forgot that was a thing.
Anyways to detect left click using scripts?
Can someone give me a code that shows TPS in the playerβs action bar?
PlayerSwingStart event
that's not specific to left clicks is it?
It detects whenever the arm swings, including left click
there's also a swingSource property for it now
const entity = dimension.getEntities({
type: 'minecraft:item',
location: block.location,
maxDistance: 5,
closest: 1
})[0]
if (!entity?.isValid) return
const item = entity.getComponent('minecraft:item') as EntityItemComponent
if (!item) return
item.itemStack.amount++
What is the problem?
What does the content log say?
Nothing is showing up
Do you have content log on?
yes
This is a problem where the number of items did not increase.
Ah, I see what you're doing. `item.itemStack.amount++ isn't actually increasing
yes
You're not setting the new itemStack
Give me 5mins to get home.
But in the mean time try doing new itemStack()
yes
Wait, so what exactly are you trying to do?
Are you trying to increment the player's selected hand, or what are you doing?
If you read the code, they're trying to increase an item entity.
Oh. Sorry, got a little confused
itemCompleteUse is deprecated ?
Documentation for @minecraft/server
Ok, I can't help you when I get home. I'm needed to do something else, sorry
Does changing any other property work?
thank you
Changing other attributes has no effect.
Ah right, it's readonly that's why.
Yes, that seems to be the problem.
I would use before item pick up event.
Read the item, cancel the event, remove the entity and then add the new item to the inventory.
Oh, it's okay, thanks I used beforeEvent instead of afterEvent.
I used that feature to increase the number of items dropped when a block is broken to two.
Does the approach of deleting an entity and creating a new one seem okay?
Yewah.
I have resolved the issue. Thanks to everyone who helped me
how to spawn a entity with a tag?
Guys you are pro at js right
So i am making a system, in Minecraft must i put it in all-static class ?
Or instantaneous class
depends on the system
And that depends on the programming style too. You do not need to use a class if you do not want to
The system is global
It needs a class because the code will be large and it needs to be contained
Hmm like a status system
const entity = dimension.spawnEntity('skeleton', location);
entity.addTag('tag');
do u know the difference between static and not static methods?
In reference to a class, I made a comment on this not long ago in the #off-topic channel where someone asked when is it relevant. Will post it here for reference.
#off-topic message
Btw is there an event for worldSavesDataEvent ?
Then think about what to use. There are no rules that tell you whether to use static methods or not. Just think about what will work best
no, but there is system.beforeEvents.shutdown
π«ͺ suggest me something at least
I read it , and i guess it s not a module and it s not logic functions , so i guess the best way to do it is inside a class i guess
Entire modules (JS files you can import) can also be classified as self-contained code. Local variables are similar to properties; non-exported functions are like private methods.
But yeah seems like you get it
Ik but, i insist on using classes because no one will use the code besides me anyways , and i won't use code between files either
I mean : v
- like it s a one time thing
Status being...? I can think of a few disparate concepts all called "status"
Mana as example
Or Thirst
Ah, gotcha. Like attributes, health
I suppose class would be the way to go, since you do want to track state
Ok , but what about the methods inside must they be static ?
Like i don't want it to be instantiated for each player
Because it s like a global thing.
Because i use dynamic Properties and Tags
Is that the best option to stick with ?
Well, why not? While all players have mana, each player should manage their own mana. Having each player instance wrap their own mana class instance means you can write non-static methods to operate on one unit of data at a timeβit showcases your intent more clearly IMO
Maybe you need to create update events
Like: do this if the mana changes
Yeah
it doesnt work but i figured it out
Something i do a lot is create a wapper for an entity and then add my own methods to it
you get a lot of control
Hmmm, i see
like:
CustomPlayer {
constructor(player:Player) {
this.getMana()
....
} }
Its called dependency inversion or something similar
Isn't extending the Player class is better for that ?
Another question, about the events
Yep but every time you get a player from the api it doesn't have ypur custom methods and it'll be necessary to add them anyways
also the Player.constructor is protected
that means you can't extend it
I would follow a pattern kinda like this. Curious to get the room's thoughts
const DEFAULT_MANA = 10;
class Mana {
constructor(player) {
this.saveKey = `project:mana_${player.id}`;
this.value = this.getStoredValue();
}
getStoredValue() {
return world.getDynamicProperty(this.saveKey) ?? DEFAULT_MANA;
}
consume(value) {
// Operate on this.value
}
}
// Initialize property on players
Object.defineProperty(Player.prototype, "mana", {value: undefined});
// Define property on load
world.afterEvents.playerSpawn.subscribe((arg) => {
if (arg.initialSpawn) {
arg.player.mana = new Mana();
}
});
You can override the prototype no? Or extend it, that's how I use Block and Entity methods.
So , i will add a lot of events , must i make their methods inside my class ?
And after that how to connect them to the Events
well you can use getters and setters to manage events
class playerWrapper
set mana () {
//manaEvent modified
}
If you would like to operate on data stored within the class, then methods inside the class would be the most clear way. Not writing methods in the class for that eliminates the advantages of using a class
Is there a way to play the animation that appears when the player attacks?
i read before that its hardcoded
Like
World.event.x.subscibe(e => {
StatusSystem.EventEvnt(e);
})
explain
So, when i write my event inside my class
It won't work until i call them in a real event
Right?
yep
There isn't a better way to do it ? , i mean just create my event inside a class and it is called automatically
If you want to attach it to another event
This is sounding like a question about separation of concerns. You have these outside system (your "events") that interface with a player's mana in some way, and you have the means of storing mana itself. They depend on each other, but they only communicate with each other; IMO they should not be closely interwoven.
Like, let's say you have a magic fireball staff that needs to read mana and consume mana. If you follow a pattern similar to what I showed, you can implement methods for reading/writing mana in the Mana class. But I would not add a "shoot fireball" method to the Mana class; that seemingly falls outside of the sphere that the Mana class cares about
Hmm i see
You certainly could make a "shoot fireball" method on such a Mana class, there's no limitation saying you cannot. At that point it is more of a code organization problem
Which, if that is your preference to do so, by all means go for it. The most important thing is to write code you can come back to after a few months and readily understand what it is doing
(Which reminds me, I have some refactoring to do)
Yeah i gotcha, thx
A gift that's keeps on giving.
anyone knows about making a custom itemGroup?
like ```
Flare guns
- Resource Flare Gun
- Potions Flare Gun
...
not sure what that has to do with scripting but there's documentation here https://wiki.bedrock.dev/items/item-catalog
You can alternately use system.runInterval to check if a property changed
i read that article, but it doesn't specify the place where i need to add that file
?
a
like this as example :
class statusSystem { event1( ev : playerBreakBlock) {} event2(ev: playerBreakBlock) }
world...playerBreakBlock.subscribe(e => { event1(e) ; event2(e) } )
i don't want each time i write new method , to call it manually
@sharp elbow do you know how to do that ?
I suppose you could put a statusSystem instance on each player, similar to the Mana class example I gave. Then you could invoke the methods of statusSystem by accessing them on the player.
// initialize status system instance
world.afterEvents.playerSpawn.subscribe((e) => {
if (e.initialSpawn) {
e.player.statusSystem = new statusSystem();
}
});
// Events
world.afterEvents.playerBreakBlock.subscribe((e) => {
e.player.statusSystem.event1(e);
e.player.statusSystem.event2(e);
});
no i meant u see e.player.statusSystem.event1 , 2 i don't want to write them every time i want something like this statusSystem.events(ev)
and whenever i add new method it auto add it to the code
Ah, gotcha. Then sure, you could add a method to your statusSystem that invokes other methods with the same parameter
class statusSystem {
constructor() {}
events(e) {
this.event1(e);
this.event2(e);
// ...
}
event1(e) { /* ... */ }
event2(e) { /* ... */ }
}
And it should be safe as long as you aren't mutating the event object in some way. Like doing delete e.player or similar
oh
but how to let it knows what event it supposed to work with ?
You could use an instanceof check to guard to specific event responses, I suppose
ok thank that what i wanted
But I think I found an even better, less explicit way to do what you've asked. Instead of manually invoking this.event1 etc., you could populate an array with callbacks to your events, then loop over the array.
class statusSystem {
responses = [
// Example callback
(e) => console.warn(e.player.name)
];
constructor() {}
events(e) {
responses.forEach(cb => cb(e));
}
pushResponse(cb) {
this.responses.push(cb);
}
}
Just need to be careful about knowing where that callback is defined (so you know where to debug later), and to be careful about underestimating the implications of more declarative code like this (less code β performant code, the array could have hundreds of entries)
yep, something you have to take in account is that here you are applying the DRY(dont repeat yourself) rule, this can make things complicated, because it sacrifices granular code for less code
ig im late to the conversation, but you could try using the minecraft:timer component with an event that adds minecraft:instant_despawn
i remember that the last time I tested it, time was still saved even after restarting the world
Vibe coding
Should i do json ui or script as my first menu?
Guys is it possible to make cinematic cur-scenes in Minecraft ?
Yes. Use the Camera APIs.
- is it possible to change fog dynamically in Minecraft?
Yes. Via Fog Command
is it possible to fhange cog
Idk..
me neither
Ne meither?
kho wnows
import { Player } from "@minecraft/server";
/**
* Proxy to ineract with the Fog Command Layer of active fog stack of a player
*/
export default class Fog {
player: Player;
private stacks: { [id: string]: string[] } = {};
constructor(player: Player) {
this.player = player;
}
/**
* Pushes a new fog setting onto the top of the Fog Command layers of the players' active fog stacks.
* @param userProvidedId
* @param fogSettingId
*/
push(userProvidedId: string, fogSettingId: string) {
this.player.runCommand(`fog "${this.player.name}" push ${fogSettingId} ${userProvidedId}`);
(this.stacks[userProvidedId] ??= []).unshift(fogSettingId);
}
/**
* Removes the top-most fog setting that matches the user provided ID (i.e. as provided previously via a {@link FogProxy.push} command)
* @param userProvidedId
* @returns The removed fog setting ID. undefined is returned if the command layer stack or the cache are empty
*/
pop(userProvidedId: string): string | undefined {
this.player.runCommand(`fog "${this.player.name}" pop ${userProvidedId}`);
return (this.stacks[userProvidedId] ??= []).shift();
}
/**
* Removes all matching fog settings, that matches he user provided ID (i.e. as provided previously via ore or more {@link FogProxy.push} commands)
* @param userProvidedId
*/
remove(userProvidedId: string) {
this.player.runCommand(`fog "${this.player.name}" remove ${userProvidedId}`);
delete this.stacks[userProvidedId];
}
}
Can someone give me a code that shows TPS in the playerβs action bar?
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_math.Vector3Utils.html
how can i use this on my projects?
Yes
You have to create a "build" of your code that combines those libraries with your code
If you use TS is already there
do you know how to use ts? xd
thx
I have a issue, im trying to add support to blurry's java combat 1.0.8 to be able to handle simulated players, the issue is if it runs like world.getAllPlayers() any bot shows as undefined, while in my script they show as like "bot" why does this happen? and i did update blurry's manifest to have the gametest dependency.
getPlayers() might only return actual player. try getEntities() using type player, it should work
still dosent work ive tried
i lowky just copied blurry's files into my pack, so now it works fine, and if i post a public version ill just say its not compatable with blurry's and remove those files
Guys how to check if player is in a village, and if it is it get tagged with this "in_village"
A village can either mean the "structure" or the "state" where a group of villagers collectively agreed a bed and a workstation nearby is a village.
You could technically do the environment sensor to test in_village test
yea, if I remember, the player vanilla json environmental sensor is used exactly as that. Detecting if the player is in a village to trigger a Raid
getTopmostBlock() doesn't work on transparent blocks?
Yea you can change the prototype methods/properties, but in lot of cases extending wouldn't work bc your class child instance will never be called by API it self
Have you tried my OverTakes method?
Have you ever tried this one?
If I want to store a Boolean on any entity to check later, which one is faster when used a lot. Scoreboard, tags, or dynamic property?
tags are usually fast enough afaik
scoreboard is overkill if its disposable
and dynamic property is the least headache inducing stuff
i honestly would use dynamic property over anything because of how much control i have compared to any other methods
Thanks!
what if you gave the entity a name, and then tested for that entity with a name and always made a map to store the value?
Not familiar with that one
This method besically pushes it further where you can override already existing methods and still referencing them via super keyword
but here is the limit of how TS could check the types as it doesn't properly defines the behavior of super keyword anway
I think i have update method somewhere as well let me check
Why have the second parameter inherit from a clone (of depth 1?) of the prototype instead of the prototype directly?
bc the clone gives you the old methods and properties of the API, so when u use super, its no longer just the parent class but also its old shape of this current class
its just for that little feature for the super keyword
Ah, it is for safety.
Hmm not sure, wdym
safety of what?
or more like safety from what?
this exaples shows how it works
OverTakesJS(Player.prototype, {
sendMessage(...messages){
if(messages.length === 1)
super.sendMessage(typeof messages[0] === "object"? messages[0]:(messages[0] + ""))
else super.sendMessage(messages.join(" "));
}
});
so you can access sendMessage without calling your self, basically calling the original one
via the super reference
If I overwrote a sister method like getRotation, super.getRotation would use the original method, whereas this.getRotation would use the modified method?
yea
this refers to its caller, if you call something.getRotation, then something is the this in the method
where can i find a list of the special strings that turn into icons for game controls?
not sure if you are in right channel, i think there might be an info on wiki
guys tell me
can you write ts and js for mc bedrock even tho ts does get compiled to js?
How and where di you use them
You need to compile to js
but you still write in ts?
Yeah, it can be useful
@winged drift thinks other wise
I tried to send it in a chat message, it worked
I tried to use it as the text property of a label element in the ui, it didn't
r u talking abt json ui?
The game only run js
You can code in whatever, as long as the final code is js
see that's what im talking abt
you get it coolbep
Did you try it in rawText
wdym?
I was never disagreeing with that lol
btw JSON is valid JS code everyone
JS is a superset of JSON
π
@remote oyster Whats then most weird JS syntax you know? it could be anything
To me? It's people who don't use curly brackets for closures and run it on one line. I find it weird. I've slowly started to do it myself after using JS for some years, but when I first started using JS that logic was foreign to me and it didn't make sense. It was like an incomplete sentence to me.
wait like running it on the same line where its defined?
Haha when i am lazy i do that, mainly for async scope thats not available or something
also for some reason i started using void expression a lot
with combination of return ofc
const add = (a, b) => a + b
Versus
const add = (a, b) => { return a + b }
Or
if (valid) console.log(1+5)
Versus
if (valid) {
console.log(1+5)
}
Ohhh, i am definitely the no brackets guy lol
but if so then this!!!
if (valid)
console.log(1+5)
yea, same i guess
damn
the lines are too long, maybe my taste got processed by formatters lol
The brackets make it more readable. Where it starts and where it finishes. Stuff like that blends in with blocks of code and becomes harder on the eyes in my opinion.
I feel like those that don't use brackets is just a fad.
Haha
but i just found out this syntax, after years of js experience
let anyVar = 0;
let otherVar = 0;
({anyVar, otherVar}) = object;
i always thought i have to use decleration to destruct haha
That was something I learned a little later myself.
Still learning new things too.
but it make sence for perameters destructuring
cant go without brackets, just looks wrong
well i would say that JS is the most complete syntax i ever seen, i mean in every other language there are always some edge cases that doesn't works or weird hacks that doesn't seems natural in that language, but JS just works
Agreed, but I have slowly adapted. Still not a fan. Try to refrain from it as I think it's a very bad habit.
because like, everything below gets nested
JS just has no rules it seems lol.
Throw it in and cook it up lol
i guess
But I've grown to enjoy JS. Just took some time to get use to it.
i found it really interesting of the concept how JS works in general, like the prototypes, its just cool idea on its own
i always used to write new Array() bc i came from C#
now i am starting to writing it again
idk
why
Lol
well considering addons is the only thing im doing, I have to like it lol
Understandable for sure. I came from writing C++, C, Java, Python, Bash, and others. Primarily because AOSP is just a combination of everything really.
id say kotlin is pretty complete too
forest
whos forest?
yeah who is that?
Never did try Kotlin.
i can't relate bc i don't know kotlin enought
good question
the fact you responded with asking who, rather than asking why I said forest, is a dead give away
