#Script API General
1 messages · Page 141 of 1
yes but my object will not be any of those types
im storing railroad tracks for my train addon
they have 4 points(vec3) for a cubic bezier curve plus 2 OTHER connected track objects
Then stringify the JSON.
k
oooo
JSON.stringify(obj) then retrieving it JSON.parse(string)
alr ty
is there an event for when the world is closed
I am the 100 000 message of script api general🥳
congrats
Yeah, congrats for being the 124th user of claiming the 100000 message milestone.
-# It'll revert back to 99999 in a few hours
Any algorithm ideas to make gui changes detection?
What?
Any reason why custom commands, even if they are sent to CommandPermissionLevel.Any, wont show up and cant be used on realms?
Is your Custom Commands rely on player selector?
They do not
const changeNicknameCmd: CustomCommand = {
name: 'retrqol:nickname',
description: 'Change your nickname',
permissionLevel: CommandPermissionLevel.Any,
optionalParameters: [
{
name: 'name',
type: CustomCommandParamType.String
},
{
name: 'retrqol:nicknameType',
type: CustomCommandParamType.Enum
}
]
}
I presume then it works in Single player?
Yes
It might require cheats enabled?
How do I rotate the multiblock using a script? Every time I try to rotate it, it simply breaks the block, even after setting permutation on all blocks.
block.dimension.setBlockType(loc, d.typeId);
const placed = block.dimension.getBlock(loc);
placed?.setPermutation(block.permutation.withState("minecraft:cardinal_direction", "north"));
placed?.getParts()?.forEach(r => {
// r.setPermutation(BlockPermutation.resolve(d.typeId, baseStates));
r?.setPermutation(block.permutation.withState("minecraft:cardinal_direction", "north"));
})```
You need to be doing r. permutation.withState
I used
Also got can remove the placed?.setPermutation at the start since getParts also returns the part you're getting the parts from
Sorry for taking so long to reply, I've already tried that too.
Why are you using it via scripts in the first place?
The block traits will automatically handle it for you.
@wary edge I'm developing code that places multiple multiblocks at once, which is why I'm trying to rotate it. I don't want to use structure blocks for this.
Oh, you're not using a normal multi block.
You're using a custom one?
Yes, I am using the regular one, but it has several parts.
So you're using a custom implementation.
I put everything together to form a block, so I'm trying to develop something that automatically adds that.
without having to place block by block
does any1 know a workaround for the fact that increasing damage dealt using beforeEntityHurt will cause totems to just not work
since it seems if you do any more damage than normal, totems just break
nvm i figured it out yay me
Dynamic Properties vs. Tags — which is faster for storing data on Entity?
go for dp
Always go for DP, unless you will also use tags
Tags are like booleans
understood, thanks.
Is it possible to create a custom dimension with a single command, or does it have to be done with startup?
Via startup

Is there any way to override the memory limit watchdog exception without having to dump memory regularly?
Why do I need cheats enabled to use entity selectors in custom commands?
bc its a bug
you cant also use /msg command
only if have op
the same for player selector
When will it be fixed?
Never I think xD because it an older bug
reported or not?
If it's related to scripts then this should disable it. You can find it in server.properties for BDS. If you are referring to a Realm then there is nothing you can do about it other than reduce your memory use and/or verify you don't have one or more memory leaks from bad code.
script-watchdog-memory-limit=0
It’s just that I’m storing alot of data in memory. But I’m thinking of just dumping it, after use because it’s not exactly important data
Just wanting to know ofc if I can increase the limit of memory
Thank you u
Then that property I mentioned will disable it on BDS. Can't help with Realms other than what I suggested.
A long time ago you use to be able to disable watchdog but they disabled that on Realms because it was allowing people to not debug poorly written code and putting stress on the servers so they basically said, "No more nonsense. Fix your code or it will get shut down". Lol
player.onScreenDisplay.setTitle(
`hp:${hp} hunger:${food}`,
{
stayDuration: 0,
fadeInDuration: 0,
fadeOutDuration: 0
}
);
}
i wonder if this is right to set titles correctly?
You should try it
Is there an error?
no
o lol i forgot
to activate the event with a worldafter
but idk if there one with hunger
bc i got hp done
Try player.getComponent("player.hunger").currentValue
Although, it might be better to setActionBar rather than setTitle
const food = player.getComponent("player.hunger").currentValue;
const hp = player.getComponent("health").currentValue
player.onScreenDisplay.setActionBar(
`hp:${hp} hunger:${food}`
)```
If you want to still do the setTitle method,
const food = player.getComponent("player.hunger").currentValue;
const hp = player.getComponent("health").currentValue
player.onScreenDisplay.setTitle(
`hp:${hp} hunger:${food}`,
{
stayDuration: 10, // If this is 0, it won't appear
fadeInDuration: 0,
fadeOutDuration: 0
}
)```
No
"$update_string": "hunger:",
"type": "image",
"texture": "textures/ui/empty_hunger",
"size": [180, 32],
"offset": [0, 105],
"controls": [
{
"progress": {
"type": "image",
"size": ["100%", "35%"],
"layer": 1,
"$one": 1,
"$max_hunger": 20.0,
"clip_direction": "left",
"clip_pixelperfect": false,
"texture": "textures/ui/fill_hunger",
"bindings": [
{
"binding_type": "view",
"source_control_name": "data_control",
"source_property_name": "((#preserved_text - $update_string) * $one)",
"target_property_name": "#hunger"
},
{
"binding_type": "view",
"source_property_name": "(($max_hunger - #hunger) / $max_hunger)",
"target_property_name": "#clip_ratio"
}
],
"controls": [
{
"data_control": {
"type": "panel",
"size": [0, 0],
"bindings": [
{
"binding_name": "#hud_title_text_string"
},
{
"binding_name": "#hud_title_text_string",
"binding_name_override": "#preserved_text",
"binding_condition": "visibility_changed"
},
{
"binding_type": "view",
"source_property_name": "(not (#hud_title_text_string = #preserved_text) and not ((#hud_title_text_string - $update_string) = #hud_title_text_string))",
"target_property_name": "#visible"
}
]
}
}
]
}
}
]
},```
ik this is scripts
but this is right?
for the ui?
i just used my health bar code
bc that worked
someone know why blocks with custom components, even without the onPlayerInteract event, you can interact with the block?
is this a bug?
That should have been fixed. What format version?
myEntity.target = newTarget;
Target property of an entity is read only as it's turning out.
Any work arounds?
Unfortunate.
So, this is the database currently.
The true|false sections are checking whether a layer already has something in it.
OH MY GOD
Yeah 🥲
It can definitely be rewritten a LOT
I just don't know how to do it 😭
I checked also, and since it's a map, the 308 or so entries doesn't do anything for scripting timing mostly
i dont know much about blocks in general, but how is DP stored in a block?
Well, the cap is 1KB, so uhhh
say, when you print it out as text
It's just the same as items I believe
yeah you could... cut down some texts
Turns out teleporting the entity with a facing [entity] argument sets that entity as the target.
:D
peak jank
It works for my very specific use case lol.
thats a bless and a curse
I was thinking of a system like this;
new Map<([
{"layer1", {/*Set a liquid type, eg gold, iron, etc. Default would be "undefined"/"empty".*/}},
{"layer2", etc, etc
])```
Only problem is, I don't know how I would go about that
So if layer1 is undefined/"empty" then it would set it, and if it had something in it, it would go to the next one
The only problem is I don't know how to set that undefined or empty as initial
Oh wait I can just setRotation(). I just need it for head movement anyway.
I am currently using entity properties, but I want to get rid of that and use a block entity when they come out
So, I'm wanting to reduce it to way below 1kb with just 16 entries
Actually, hmm
I don't know how I'd do that as I'm using an entity currently to dynamically change which layers appear or not
@lyric kestrel have you considered cutting boolean bloats down and use 16bit integer
and not include booleans that are false
Idk how i'd do that 🥲
I'm currently trying out a method to cut it down to only 16 entries atm
give me a second
actually 16bit integer might not fit
i just read more and i see the pattern
Ok, I think I got it
instead of this monolithic thing
["foundry:zinc_ingot|true|true|true|true|true|true|true|true|true|true|true|true|false|false|false|false",
{
layer1: true, layer2: true, layer3: true, layer4: true, layer5: true, layer6: true, layer7: true, layer8: true,
layer9: true, layer10: true, layer11: true, layer12: true, layer13: true, layer14: false, layer15: false, layer16: false,
materialProperty: "foundry:layer13_material", materialPropertyNumber: 9
},
],
you can do this
type foundryEntry = {
l: number;
m: number;
n: number;
};
[
"zinc_ingot|12",
{
l: 13,
n: 13,
m: 9
}
],
and parse the stuff from script side
this may only work if the pattern is consistent
Nope. Apparently it kept going to the next one and doesn't reset to the 1st layer 😔
Hmm
yeah i dont fully know about the code but
from what i see you can cut down a lot by simplifying it
Yeah, I can very much so
aaand this is my random crazy thought
[
"zinc_ingot|12",
{
l: 13,
n: 13,
m: 9
}
],
to
"zinc_ingot.12.13.13.9",
_ _
It's better to stringify it
Is there away to check if a mob is a boss? Like Ender dragon etc. or like custom mobs
expensive to use JSON.stringify often
Yeah, using Map is better
Ok, I think the way you did I could 100% do
Wait, duhhh why didn't I do this in the first place 😭
Ok, I've managed to get this working
const playerInputItemsIntoFoundry: ReadonlyMap<string, { materialNumber: number }> = new Map([
["minecraft:iron_ingot", { materialNumber: 2 }],
["minecraft:gold_ingot", { materialNumber: 3 }],
["minecraft:copper_ingot", { materialNumber: 4 }],
["minecraft:diamond", { materialNumber: 5 }],
["minecraft:netherite_ingot", { materialNumber: 6 }],
["minecraft:obsidian", { materialNumber: 7 }],
["foundry:aluminium_ingot", { materialNumber: 8 }],
["foundry:zinc_ingot", { materialNumber: 9 }],
["foundry:osmium_ingot", { materialNumber: 10 }],
["foundry:titanium_ingot", { materialNumber: 11 }],
["foundry:lead_ingot", { materialNumber: 12 }],
["foundry:silver_ingot", { materialNumber: 13 }],
["foundry:brass_ingot", { materialNumber: 14 }],
["foundry:steel_ingot", { materialNumber: 15 }],
["foundry:dragon_steel_ingot", { materialNumber: 16 }],
["minecraft:redstone", { materialNumber: 17 }],
["foundry:palladium_ingot", { materialNumber: 18 }],
["foundry:adamantium_ingot", { materialNumber: 19 }],
]);```
And I've found out there's ReadonlyMaps
Which is amazing, as I'm bound to probably mess up and accidentally add to it in a different file somewhere 😭
Cant for maps you also do as const? That might be arrays only I guess.
Not what I meant.
Const arr = [] as const
I have no idea
I know that makes the array immutable.
Why does beforeEvents.entityItemPickup not work on minecarts 😭
hopper* minecarts
Fix your game Mojang
File a bug report? Does it work with other mobs such as allays and whatever siphons.
I usually use before entityRemove for that. But even before events has weird priority issue against picking up item...
i don't even wanna try
players do
It can be done with just plain objects if the keys are just strings. But the Map has a has method to search directly so I think that's faster
oh nvm I misunderstood
Is there any way we can update something more than once in a tick? Overall, is there something that can be updated more than once in a tick in the whole game?
What do you need to update faster than once a tick?
not really, why do u need this?
Server side stuff is restricted to 1 tick synchronous operation. Only RP (Like MoLang animation) can do something under a tick since they're updated per-frame. (Though, molang queries only update per tick, but basic operation aren't)
anyone got world crashing when runing for loop
if youre using JS native loop, it wont end well (mainly crash) if theres nothing that stops it
do you guys know which version did @minecraft/server version 2.0.0 were released out of beta?
around 1.21.100 it seems
thank you
what manifest version do i need for beforeChat events?
Beta API
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "2.8.0-beta"
},
{
"module_name": "@minecraft/server-ui",
"version": "2.1.0-beta"
},
{
"module_name": "@minecraft/server-net",
"version": "1.0.0-beta"
}
]
just use "beta"
what are exactly ```js
WeakMap
A WeakMap is a collection of key/value pairs whose keys must be objects or non-registered symbols, with values of any arbitrary JavaScript type, and which does not create strong references to its keys. That is, an object's presence as a key in a WeakMap does not prevent the object from being garbage collected. Once an object used as a key has be...
ok its what i thought thanks
Are all entities already loaded also in worldLoad after events to safely manage it
what was it
when a player would pop a totem, cancel the damage and then apply damage equal to their current health with the override dmg type
It also could be because entity heal takes place first? So the totem heals however many to get to the 1 hp but then hurt activates so you overrode it? 
I kinda like this one
Is that real?
Bug
feature
lol
z index of floating item renderer just lower than the search bar panel
is it possible in any way at all to clear the item in the players cursor in their inventory?
Use the .clear() function of thr component
Documentation for @minecraft/server
i just got it ty:)
i'm trying to get mob mainHand slot using script but it keep saying that it cant get the component does anyone know how to fix it
function tryEquipWeapon(entity) {
const equip =
entity.getComponent("minecraft:equippable")
if (!equip) {
console.warn("Missing equippable");
return false;
}
const mainhand =
equip.getEquipment(EquipmentSlot.Mainhand);
// Already holding weapon
if (mainhand)
return false;
const inventory =
entity.getComponent("minecraft:inventory")
.container;
The error is already said, the entity doesn't have an equippable component
It usually works for Players only
how to detect an entity attack got cancelled?
Got cancelled in what way?
How does an attack get cancelled unless you're doing it yourself using EntityHurtBeforeEvent.
world.beforeEvents.entityHurt.subscribe((event) => {
// prolly some code that cancels the event.
if (event.cancel) {
console.log("Damage was cancelled BEFORE it applied");
return;
}
});```
when will they make player open container/chest using script api
event.cancel = true
like pls,every other api has it
pmmp,nukkit,and ofc endstone(bds btw)
Does anyone know how to improve at script API
I want to start learning advanced programming so I can start making custom dimensions in the near future
well i know how to make dimensions but not how to generate things in them
this is deffo the best update for the game EVER.
custom dimensions are gonna open even more infinite possibilities if we don't have to teleport 100K blocks away in the end
I mean the damage applied on the target unsucessul
[Scripting][warning]-SUCCESSFULLY INSTALLED
[UI][warning]-UI Control: centerer | UI Control: main | UI Control: bg | UI Control: hori | UI Control: information_panel | UI Control: label_stack | UI Control: block_states | UI Control: border | On Control Path: /hud_screen/variables_button_mappings_and_controls/safezone_screen_matrix/inner_matrix/safezone_screen_panel/root_screen_panel/root_panel/waila/centerer/main/bg/hori/information_panel/label_stack/block_states/border/list | JSON UI parse failure - expected a string.
Getting a strange bug while I scripting only
Yup
I’m planning on working on a massive souls like space addon
I have made all the souls aspects already
Just gotta make all the space stuff
But instead of following how to’s and tutorials I wanna learn scripting as a whole so I can do my own work on my own pace
There's performance limitations tho
Creating many custom dimensions and building inside per dimension creates a lot of data
Ig, because that's how usually Minecraft bedrock is
Yeah
I haven’t seen much for myself yet but is it possible to create custom skyboxes for new dimensions or something similar
not sure if this is a bug, but last time i check this minecraft:tamemount component to get the player or owner still doesn't work, it still doesn't work now
Anyone know how to get better at scripting
Not really sure what that is, never worked with JSON UI.
How are you with JS/TS?
I know the basics
If you are good there, it's mostly making things and asking for help and knowing how to search for the right thing.
Gimmicky things you see in how to guides
The most advanced thing I made is probably a Form
It was to select classes
It didn’t work very efficiently
The only thing I have made using initiative is a damage sensor system to check how much damage you have taken and run a function accordingly
Have you worked with any other language?
Not really
Apart from JSON ofc
I have made 2 semi-functional addons using my basic knowledge
JSON is a data format lol.
Anyways about the JS part. You might wanna get a little more comfortable and proficient with it.
Thank you very much
The most important actually, is you learn to understand/read docs
Then you can do the rest all by yourself
With some little help ofc
Coding in cleaner way and performance friendly is a bonus
Yeah. And you also learn more doing stuff than reading stuff.
Always do some project that is a little harder than what you can do or have done so far.
That’s my biggest issue
I try to push myself but I default to chunky function files that can be 300 lines long of straight variables
It's not too hard, first ofc you learn JavaScript and typescript, then you'll start to understand the script api docs to use it by yourself
Fair enough
What are you talking bout
Nahhhh
I just went right into scripting
Didn't know JS beforehand 😂
Just trial and errored hahah
I did know some Python beforehand though, so kinda made it a bit easier imo for the basics
Kinda the same except I have little experience with html js first
learning the syntax is enough, you can learn as you go
Yeah
Yep
yao, how can i save the block state when it breaks?
my block will have like two states that will change the texture (material instances stuff), so whenever it breaks or gets picked up, the state will be the same like same textures
That explains it.
brokenBlockPermutation
can the dropped item texture change based on it?
im just trying to avoid adding another 50 blocks for the new textures,
IF thats just not possible, i can make it works, i have a small workaround
No.
Youll need to make many items then.
yeah ill just use the workaround instead.
does the debug utilities module support rotations for boxes?
nope, the property doesnt work :(
L another bug
dont think we'll ever see a stable version
it'll probably be the same as server-net
Does Navy know about the bug where the CC with entity selector requires cheats to be enabled?
There should be a bug report yes.
has anyone researched EntityHurtBeforeEvent and its quirks? i couldnt test it much on my own
is there any reported quirks? im pretty sure they only make these kind of events stable once it is actually stable
all i know so far is that it doesnt cancel fire aspects, and it has weird behaviors for tamed wolves targeting
inconsistency with invulnerability frames is the one thats reported the most atm
so no its not stable despite being marked as stable 
I mean there’s always a workaround for fire aspect like extinguishing the fire on the player on entityHurtAfterEvent or something
the damage would be already done
fire tick damage specifically
You mean to things like armor or are you saying fire tick damage to player isn't canceled?
Just cancel it from another entityHurtBeforeEvent
import { Player, system, world } from '@minecraft/server';
world.beforeEvents.entityHurt.subscribe((event) => {
const target = event.hurtEntity;
const source = event.damageSource.damagingEntity;
const reason = event.damageSource.cause;
if (!(target instanceof Player) || (!(source instanceof Player) && reason !== 'fireTick')) return;
event.cancel = true;
system.run(() => target.isValid && target.extinguishFire(false));
});```
Just been messing around with it and this cancels just fine though it does still flash the fire on the player.
No damage is dealt though.
Could you also not read the damaging entity and check the weapon for fire aspect first?
As long as you specify the damage cause it stops the damage of it.
You just then need to use the extinguishFire() function to stop them from burning.
Even then that doesn't continue to cause damage since we canceled it originally.
I need to do the bug report of current value returning the health after the damage is applied.
Well that's only because currentValue can't be used in early execution and requires a system.run().
That makes no sense.
Oh I guess I meant when trying to set it. Whoops!
Gotcha, I meant moreso reading it!
yeah thats kinda an issue... it would also disable things like fire tick from other sources
for my use case, i could do some trickery with entityHitEntity
but i dont like doing that tbh, its janky
The script I made doesn't stop damage via flint and steel or lava if that's what you're worried about.
But the script I made is also checking if the damage is coming from a Player.
The game seems to know when the fireTick was triggered by the source. Not sure how but it does.
does game track for fire aspect's owner? last time i checked there was no damagingEntity from damageSource
vid isnt loading
Bruh 😭
Does this work?
yeah that ones playing
Weird..
ok so uh to answer that
theres actually two damage source
fire and fireTick
iirc
tbh this is something they definitely overlooked
they specifically fixed knockback enchantment from applying
but not that
Well this one works so that the player can't deal any kind of fire damage now which is pretty neat. ```js
import { Player, system, world } from '@minecraft/server';
world.beforeEvents.entityHurt.subscribe((event) => {
const reason = event.damageSource.cause;
const source = event.damageSource.damagingEntity;
const target = event.hurtEntity;
if (!(target instanceof Player)) return;
const fireCauses = ['fireTick', 'fire', 'lava'];
if (!(source instanceof Player) && !fireCauses.includes(reason)) return;
event.cancel = true;
system.run(() => {
if (target.isValid) {
target.extinguishFire(false);
} else return;
});
});```
Pretty cool that they track the owner that placed the fire or lava.
Nevermind, I think this somehow cancels damage either way.
Yeah nevermind, my code was just poor and was canceling the damage either way. #nojavascriptskills #cantcode
Well this is well known issue you are dealing with, we just have to wait for beforeEntityHit pretty much to cancel out all the effect caused by other player
in theory you could disable all fire damage in general or something
hope they add inventory change event for entities
😔 Please.
and a function that opens an existing chest block
Or just a function to interact a block
Very funny
Anyone know how intensive loading a full 64x64x64 structure is on the game through Scripting?
Damn.
Now I'm torn between whether to do my Foundry add-on or mess at custom dimension world gen rn
I was planning to make Skyblock addon that works like Skyblock plugin where we generate our personal island and manage it
Also, I didn't realise features could be placed using scripting
But it seems not recommended for performances
Thought it was just structures
Both.
Multi task. NOW
Oh shoot I forgot custom dimensions only created by startup
I've made a small terrain gen thing for a custom dimension using AI to see if I wanted to actually learn world gen, and it's not bad.
I'll try to send a video of the generation in a bit
Yeah
Damn
Now that I realise you can place features with scripting, I think I'll try placing some caves or smth
Does anyone know what the new BlockVolume API speed and resource intensity is?
And possibly about placing structures that are 64x64x64🥺
ye it is an unstable feature
I use it to cancel the event but the mob still hits me
bugs to bugs
everything works fine for me
I've always been curious how to addEffect with infinite duration
Or is it only possible with commands?
Infinty isn't supported either
The max you can do is 20 million ticks.
tbf i realized some time ago that script api doesnt support infinite yet I have clear memories where i appliedi infinite effects without commands 😭
infinite option
yeah
that is what i had in mind
i may have dementia tho
its like the second time script api gaslights me
isnt infinity for mob effect duration basically a boolean (under the hood)?
whether an effect has a timer or not
how hard would it be to add an extra property inside that interface anyway 
No?
...really?
Oh you said under the hood.
Thought you're saying that such a property already exists.
Also, I'm very sure it's -1 and not a boolean for infinity.
Yeah.
A mob (short for mobile, mobile entity, or mobile object) is an AI-driven game entity. All mobs can be attacked or hurt (from falling, attacked by a player or another mob, falling into the void, hit by an arrow, etc. with the exception of natural creakings), and have some form of voluntary movement. Different types of mobs often have unique AI a...
Sadly you can't pass anything less than 1 tick into effects with scripts 😔
we don't have an entityStopSneaking event right?
yeah doesn't look like we have one but then there's this 😭
well, wolfs can sneak iirc
cats mb
etc
oh wait..
yeah, we only have a startSneaking event
I mean this was added last week, so maybe we're getting a stop sneaking one soon
@wary edge not sure if you saw this last week when you were rambling in your old age about a stopSneak event
practice and read the wiki, look up JS functions online, ask someone experienced ¯_(ツ)_/¯
i'd be willing to help you with anything i know about so feel free to dm
Why do they always ask that
Thank you very much
It is used to spread arrays, map or sets.
const arr1 = [3, 4, 5];
const arr2 = [1, 2, ...arr1];```
well well well
Interesting.
is Dimension.playSound method not guaranteed to play in the same tick?
Havent figured out how to specifically replicate it so that I can mark it as a bug (if someone else hasn't figured it out already) but when lowering a large amount of damage that would realistically kill the player, the game only lowers the damage instead of all of the other hit mechanics (hit sound effect, applying the knockback, invulnerability time).
So this is ddui
Preview 1.26.10.22で追加された DDUI (DataDriven UI) を使ってbadappleを作ってみました!
Do yall know what's the grid called
Does BlockRedstoneProducerComponent work on vanilla blocks? can we read the redstone signal of a comparator?
That grid is just a label with squares
Is ddui in beta version only
No
yh figured it out
We can make better gambling in ddui
les go gambling
Do you guys know why the debugShapes from @minecraft/debug-utilities is showing in every dimensions even if it’s set to over world only
does anyone have texture pack for modalform textfield to support multiline or longer texts?
Check out the source https://www.curseforge.com/minecraft-bedrock/addons/gametest-interpreter
{
"[email protected]_text_edit_box": {
"$text_box_name": "notes_field",
"$text_edit_text_control": "notes",
"$text_edit_box_label_anchor_point": "top_left",
"max_length": 412,
"size": [
"100%",
"130px"
]
}
}
Does anyone know anything with how to fix this error in ts when using withState?
💀
Is there an event for when a player change dimension
Thanks!
That's the easiest solution actually
block.setPermutation(permutation.withState("pipez:type" as keyof BlockStateSuperSet, "input"));
WIll item's clone function clone the dynamic properties?
it clones everything
why is It Not recommended to run command from script?
Causes more lag than using built in methods
The short version: commands are expensive because they go through a completely different pipeline than native API calls.
The long version:
It is not "one method"
It is the fact that commands in scripts cause more lag since API calls in general aren't as efficient as they could ideally be
Because if this when using a command the game has to parse through the entire command and translate it into an understandable medium, whereas a native function will just tell the game to do what it you want in the most direct format possible, therefore making your game do less and be more efficient
It's essentially the equivalent to talking to someone in their first language vs talking to them in a language they don't understand and using Google Translate to put it in their primary language
It's mostly just a fact that I've taken as granted now. For example, if you run setblock runCommand thousands of times, the API's equivalent Dimension.setBlock will finish it earlier...
In the first place, the overhead of the communication is the issue.
In-Game, commands may work like this:
Command Parser -> Game Engine(2 layers)
In Script, commands may work like this:
runCommand (API call) -> Command Parser -> Game Engine(3 layers)
while ScriptAPI call:
Dimension.setBlock (API call) -> Game Engine(2 layers)
-# (In a nutshell: The more layers, the more overhead. While fewer layers are more performant, thus "faster")
Peak explanation
Is there a way to apply a rotation to the multiBlock using a script?
Every time I try to apply a rotation to the multiblock, it breaks on its own. Oh, and I'm even applying it to other parts of it.
please add more context
multiBlock and parts are both vanilla native api features
what you have is not using that
Go open a post in #1067535382285135923 with your script and your block JSONs.
Because what you are doing is not multi-blocks. It's a custom system. No one can help you if you use the wrong terminology.
I'm going to make one here and record a video showing it.
Bad apple when?
doom in DDUI when
Why does the game lag when I shoot 80 projectiles using scripts?
dont you think 80 projectiles are a bit too much?
Is it possible to use system.runJob in one loop only, instead of 3 nested loops
Base game, no optimisation mods at all?
Maybe don't shoot 80 of them in the same tick? Splice them into a group, 10 every tick. So it takes 8 ticks to shoot all 80 projectiles.
The actual projectile simulation shouldn't lag.
i dont know what requires 80 projectiles to be shot simultaneously
but theres def a room for optimization that may not require that much
I though it was the other way around. Bedrock was optimized to run into computers with a fraction of the processing power required to run java. The lag may be because your PC isn't giving enough ram to the game
which loop is better?
for (let x = -1, y = 0; x < 2; x++) for (let z = -1; z < 2; z++) {
const target = block.offset({ x, y, z })
}
for (const o = {x: -1, y: 0}; o.x < 2; o.x++) for (o.z = -1; o.z < 2; o.z++) {
const target = block.offset(o)
}
O(n^2) ☠️ damn
Wait you can do that in js ?
Using an object instead of a regular integer
That was in the past
Now bedrock is considered heavy
wdym? JS doesnt use int
all numbers are doubles
second might be more performent on JITless engines
it looks scary until you realize that n is 3
like bedrock?
better to bechmark but yea it should be more performant on bedrock
for loops are very versatile in JavaScript, the first term runs before the loop starts, the second term runs before each iteration and exists if it evals to false, and the third term runs after each iteration.
well the ones that inherited the C for loops
Does system runJob only work for nested loops
Jobs work best when operating on many small operations, not so much on a few big operations. The strength of jobs is being able to use yield to defer execution until a later tick.
That said, I have not tried using jobs on singularly expensive operations, like placing structures
i meant integers like - 1 , -2 , -3 , 0 , 3 , 2 , 1 in loops ' nobody uses pi in loops
Also is there a way to clear the item that the cursor is holding
Documentation for @minecraft/server
Something like
function* singleLoop(){
for(let i = 0; i < 20; i++){
//Something...
yield;
}
}
Instead of nested
If there's a workaround for it
What are you trying to use a job generator for?
It says Generator(generator, generator, generator) on my logs
Woww thankss
is there a way to check if a leaf block is naturally grown or not ?
i mean decayable or not
Check the persistent bit state.
Thanks it works!
Can you stringify functions? I noticed when stringifying data, it seems to struggle to properly save them, which is an issue, as I need to save them.
you won't use a const as a loop variable, but yeah, that will run the task in 20 ticks
mb mistype
not while using i++ at least
it does work in for of, and for in
I was wrong sorry
The error I was receiving:
[Scripting][error]-[Experiment] TypeError: Native type conversion failed. Function argument [0] expected type: Generator<void, void, void> at <anonymous> (src/ddui.js:23)
Was just because I didn't execute the generator first, I thought the syntax meant like this
for(...){
for(...){
for(...){
}
}
}
I typed it as
system.runJob(()=> theJob())
Instead of executing it
system.runJob(theJob())
yea
no it'll run it in one tick
unless there's something that will take up a whole tick in the for loop
assuming that the generator object is passed to system.runJob
yea but not 20ticks
yield is something the engine consumes as much as possible every tick if there is a time left in the tick
so for busy ticks it could be like 3 yields only
on other hand for empty words with no entities and no ticking areas and stuff like that, this could run about 800x per tick
I still have no idea what jobs are
All my projects were so optimized I didn’t ever need to use jobs
they're basically just a form of running something in sync that would've been super unperformant and splitting it across multiple ticks as needed for performance, super useful thing for actions such as filling large areas
Is there a way to tell if an ItemStack is a block item?
what stops me from running every single thing inside a job?
I mean, in theory? nothing
BlockTypes.getAll() and compare it to the items one
tho keep in mind not all blocks have same id as the item
seed for example
Then, why isnt all code ran inside a job from default?
I mean, if there arent any downsides.
that is what i am doing rn
runJob is made for things that dont have to finish in one tick
if i am not wrong, that is the only way
But it seems logical that almost every code/feature shouldnt lag the server.
hm, thanks tho 🙂
it should not lag the server
there are things that should be instant for the game experience
also if your server is that bad it will look laggy anyway because it took more ticks to finish a task
Is there a simple way to save big json structures (no limit)?
Because I made an Addon and that’s the only thing holding me down 😭
yeah that is why i said almost every code.
Is @minecraft/server 2.8.0-internal upcoming scripting Events that are still being made, or just internal ones that won't ever come out?
I don't know if the internal means like internal testing or what
Because some of these events look sick
{
"name": "DataStorePayloadAfterEvent"
},
{
"name": "ModeChangeAfterEvent"
},
{
"name": "CursorPropertiesChangeAfterEvent"
},
{
"name": "ClipboardChangeAfterEvent"
},
{
"name": "SelectionEventAfterEvent"
},
{
"name": "BlockPaletteSelectedItemChangeAfterEvent"
},
{
"name": "CurrentThemeChangeAfterEvent"
},
{
"name": "CurrentThemeColorChangeAfterEvent"
},
{
"name": "SimulationStateAfterEvent"
}```
Oh wait, that's @minecraft/server-editor-bindings 0.1.0-beta
Damn 😔
There are some issues where the loop can't run anymore at a certain amount in an instant
that's why I have to use runJob to run it safely by queueing it by ticks
It's what I've experienced when I tried to spawnParticle at ≥ 200 positions
Jobs have their advantages and disadvantages, so as long as you work competently with them then nothing stops you, I suppose.
j*b
Not everything runs inside a job because jobs are built with a different purpose in mind. The scripting API assumes everything to be synchronous, and it will perform all of its operations instantly if it can—from the perspective of the server, nothing is out of order; stuff that happens in one tick stays in one tick.
Where you run into problems is when your operations take a lot of time to run. When we introduce the client into this model, we introduce at least two new different perspectives where this operation time matters: The player's experience & expectations, and the information the client sends to the server.
so i wasted yalls time
(Just to complete the discussion:)
Jobs have two significant downsides over synchronous code:
- The amount of time given to a particular job is unknowable, and it will depend on the device and the current server load, so the quantity of operations done in a job cannot be relied upon; and
- There is no guarantee that they will complete in a finite amount of time.
(I assume 2. to be true unless the job system guarantees that every job gets at least one operation a tick before it yields again)
synchronous code is almost always the way to go, jobs are only good if you have a large task that might hang the engine.
No. I've learned that I should add Jobs to my custom dimension terrain generation script!
Having a virtual job
Btw is it possible to add glints using script api ?
And how to lock lore to an item
I think the only way is real enchantment, not just glint visually on any item
But you can add glint in custom items via its client item file
If you meant adding lore, there's a setLore method
You have to set the updated itemstack to the slot again to actually update in-game tho
Is there a way to set colored bed?
can't find a way either, since there's no item ids like red_bed,cyan_bed,lime_bed etc.
you can use runCommand instead
nope you cant
setblock only has bed
I used structure for now
that also works
Cant you setblock with data values?
Thats #1067876857103536159
No because the bed doesnt have color permutation or data value
I wager thats for the item only then?
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]
"format_version" tells the Minecraft API which version of the add-on system to use for a specific file. It's sadly not as simple as matching the game version however, since some systems are not updated very frequently. You may have to use an old format version with them!
You can read more about format versions here: https://wiki.bedrock.dev/guide/format-version.html
No items does have the color in it lile red_bed, lime_bed etc
The current ddui form api is kinda confusing
A simple gambling form takes many observers and functions to update states
damn I deleted my code
aymen i love u
So do I
My script won’t work for some reason
It says on the content log main.js could not load main
send the js file in here
That’s the thing
It’s empty
I’m trying to type on it but there are no suggestions on bridge
I’m trying to fire an event on World.afterEvents
It works the same as vscode
Just gives me suggestions and stuff
Usually this error happens when it can't find the script or the script file is empty
Make sure your script root file is correct in your manifest.json
if the file is empty, then that's the reason it logs that
Yh I fixed it. That was the reason
Ty for telling me
just use copilot if u want suggestions
Copilot?
in vscode
It's just an AI model
that reads your code as you write
and gives you auto-complete suggestions
And I’m able to ask it questions on how to improve my code or how to do something?
worst suggestion ever
@turbid canopy Use Blockception extention and npm types for scripting
copilot can be usefull but most of the time not
Ok thx
I installed vsc and all of the plugins needed
The ones bedrock wiki told me to get
Now I’m watching an intro video
Then I’ll migrate all of my stuff from bridge to VSC
there is just a bit of manual work compared to bridge, but you will get used to it
Yh
This is probably the best way to learn how to code
I don’t want to be spoonfed
These guys are glazing intellisense is it any good?
It's goaded
I just ported my entire addon into VSC and it’s telling me I have a lot of errors although none of these issues were present in game
Also how do I link the addon files into Minecraft so I can use /reload
Quick update: I sorted through each issue and all of them make sense and I have fixed them, apart from one according to vsc the component “Minecraft:input_air_controlled” doesn’t exist when it very much does so what do I do
Last time I talk about non script things in script chat
Hello! bad trapdoors rotation when placing an structure with scripting is fixed?
Is there an API for the /locate command in scripting to list the locations of some structures?
Not for now
You can try check for every chunk: Dimension#getGeneratedStructures()
And TickingAreaManager
Ohh interesting
I do not recommend it at all
Yeah, it may affect performance and I need it on stable but thanks!
I just want to ask if there's a better way to make a performance friendly loop.
It's about looping through players every given ticks to do heavy tasks
My current setup is like this:
import { world, system } from "@minecraft/server";
const PLAYERS = new Map();
const LEVEL_DATA = [];
// save player
world.afterEvents.playerSpawn.subscribe((data) => {
const { player, initialSpawn } = data;
if (!initialSpawn) return;
PLAYERS.set(player.id, player);
});
// delete player
world.beforeEvents.playerLeave.subscribe((data) => {
const { player } = data;
PLAYERS.delete(player.id);
});
// start loop
world.afterEvents.worldLoad.subscribe(() => {
for (const player of world.getAllPlayers()) {
PLAYERS.set(player.id, player);
}
system.runInterval(() => {
system.runJob(defineLevelFunctions());
}, 5);
});
let count = 0;
function* defineLevelFunctions() {
for (const player of PLAYERS.values()) {
player.onScreenDisplay.setActionBar(count + "");
count++;
yield;
}
}
After I tested it, it seems slow when counting
And I think it creates multiple threads every 5 ticks because of runJob
The counting task is just a test to see how fast it counts
alright
much more efficient if its just directly runInterval but what if there's ≥ 50 players that execute heavy tasks each given tick
Could lag
It's better than whatever blockbench he's using lmfao
😭
It was bridge lol
I moved my stuff to vsc
Guys is it possible to simulate oxidations effect in script api for other blocks than copper
Like rusting , degradation, etc..
Without affecting performance much
Probably, yeah. Based on the Java Edition explanation: The oxidization step is a bit expensive as it scans 128 blocks, but this happens very uncommonly (once on a random tick, and with a 64/1125 chance), and you could probably move the scanning into a job. @crude glacier
Does anyone know what value of applyImpulse is good enough to keep an entity static in midair
I know that the applyKnockback equivalent value is 0.040763 but I'm since I'm using applyImpulse in this case I see no reason to use both
What is a job ☠️
A better question could be... what's the value of gravity in Minecraft?
Not trying to be rude—but are you pulling my leg? lol
How i see it
Are you right: Yes
Could I edit my way of wording: perhaps, (but i also like making long questions intentionally) lol
I just didn't really think about it like that XD
In theory you could apply the reverse of the entity's velocity:
function vec3_scale(vec, scalar) {
vec.x *= scalar;
vec.y *= scalar;
vec.z *= scalar;
return vec;
}
// ...
entity.applyImpulse(vec3_scale(entity.getVelocity(), -1));
No fr i never used runJob
Thats smart
But I imagine you'll see the entity stutter a bit as the clients receive conflicting information. Might be better to solve this at the source and disable gravity if you can
That's a pretty cool way to do it honestly
Every time I see Sprunkles answer a question, I find it just fascinating to read
But would that work in a situation where velocity is also applied at the same time
It's a feature in the scripting API that leverages generator functions to spread an operation across several ticks. Jobs take a function; each job is given a slice of time by the internal job manager each tick, and the job tries to execute as many operations as it can within that time. Naturally, on slower hardware this means it can take longer to complete.
I don't think there's any way of doing that, canceling its vertical component with another vector seems fine enough to me
Maybe the value is the same as real life where its acceleration due to gravity is just 9.81 m/s² in ticks instead of seconds
It would make more sense if it was in blocks instead of meters
Hmm, so what are you trying to say. instead of doing a job instantaneously, you just split it over chunks on different ticksusing generator functions and runJob ?
A block is a meter 💀
Oh, I didnt know that
Learnt it from camman18 like 4 years ago so I'm only so much more informed
Mm, I suppose if you know what that velocity should be, you could add it and the negated existing velocity:
function vec3_add(vec1, vec2) {
vec1.x += vec2.x;
vec1.y += vec2.y;
vec1.z += vec2.z;
return vec1;
}
// ...
const myVel = {x: 1, y: 0, z: 0};
entity.applyImpulse(vec3_add(
vec3_scale(entity.getVelocity(), -1),
myVel
);
But you could also negate only the y-component of the velocity if you're just trying to fight gravity
You can give slow falling too.
That would help with client visuals, yeah. Makes gravity a little lighter
That's a great point
Definitely will be doing that
Aye. Something like a for-loop could benefit from a job. Here's a basic example:
function* hundredOperations() {
for (let i = 0; i < 100; ++i) {
// Tells the job manager that it is safe to pause
yield;
doSomeExpensiveOperation(i);
}
}
const myJob = hundredOperations();
// Pass job into the job manager
system.runJob(myJob);
In theory, the job manager should execute at least one iteration per tick. So this could take anywhere from 0 ticks to 100 ticks to run
But I honestly don't know the specifics of how the job manager works
what is the difference between using await?
I always optimize heavy operations per tick using await and I compared with runJob and the optimization is almost the same
await is used for asynchronus behaviour, stops the execution until the promise is resolved or rejected
Does not have nothing to do with optimization practices
The async function declaration creates a binding of a new async function to a given name. The await keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains.
Generators can yield promises too i guess it has something to do(?
Well, it does, it's much more efficient when you distribute operations by ticks, but from what you're saying, runJob is better for these cases if you dont need to stop de code while the operation is playing.
afaik the only difference is that runJob doesnt stop the code execution unlike await
Both runJob and await do pause execution, just for different reasons. With await, execution stops until a Promise resolves:
for (const player of world.getPlayers()) {
/**
* doTask would be an asynchronous
* function, making it appropriate to use await
*/
await doTask(player);
}
Here, each iteration waits for its async task to finish before continuing. Once the code in doTask completes, it resolves its Promise, and the loop proceeds to the next player.
In contrast, system.runJob() pauses a generator at each yield, not because something finished, but to give control back to the game loop and resume on a later tick:
function* job() {
for (const player of world.getPlayers()) {
doTask(player);
yield;
}
}
system.runJob(job());
So the real difference is that await waits for async results, while runJob simply time-slices execution across ticks.
A picture to help visually
I like putting the concept of await as "manual" tick-slicing, and runJob's yield as "automatic" tick-slicing.
-# "manual" because the dev decided where it should pause. And "automatic" because the game is the one that decides when to pause.
I like putting the concept of await as "manual" tick-slicing, and runJob's yield as "automatic" tick-slicing.
I don't think its good puitting the concept of await as "manual" ticking-slicing
After all it doesn't much relates to ticks or tick slicing, if you refer to promise creation from system.waitTicks or other timing methods, then its more about promises than concept of await
looks good even of its AI designed, i guess most of the text is written by you anyway but i can't unsee this misaligment
wait, the more i look at it the less i like it
the yield example is weird ngl
and misleading
Imagine in what world we would live in if AI was actually good lol
Is it possible to get whether or not a player is riding an entity
player.hasComponent("minecraft:riding")
Thx
How do I apply something to the ridden entity
you can get the ride using
const { entityRidingOn } = player.getComponent("minecraft:riding")
how would I validate this
I want changeSpeed to apply to the ridden entity
I realised a typo hold on
Sorry
I'd do it like this
if (data.itemStack.typeId === "pr:md_vehicle_speed_changer") {
const ride = player.getComponent("minecraft:riding")?.entityRidingOn;
if (ride) {
changeSpeed(ride);
}
}
What is line 18?
is that main.js?
Yh
should be data.itemStack
Ok
not sure why that would be a not a function error though
~~Please do Ctrl + A and click format document 😭 ~~
I had a few a while ago and my whole addon broke
What does that do
Oh right
Much easier on the eyes
Bridge used to do that automatically
Yeah.
I did it
Reloaded and the issue is still there
Might be an issue with my manifest but last I checked it was fine
oh you've removed the initialisation of player
Where do I put that
you could do data.source instead
should be data.itemStack.typeId and player should be data.source
itemStack returns an ItemStack so it will never be equal to a string
What if I do “let player = data.source”
you could do that too
I’ll try it
should be a const though since the player won't change
score component exist?
Ok
I’ll reload
I PRAY It works
That’s annoying
It still says that it doesn’t exist
it should be data.itemStack.typeId
I did that
Oh someone already told
Can you send the error logs
We also need to know what code is in line 19
Where
😭
I’ll try it now
No error came up
New error
According to this my changeSpeed function is undefined
How do I define the entity
Same code just without the subscribe having a typo
I don’t think score is a component
That might be the biggest issue
Yeah its my guess also
I’ll remove it
I can't find score in entity components
Well now it says it’s not a function since I removed that
yes please
getScore doesn't exist
Alright
oh
i could have sworn i saw it on entity class
for documentation
or is that getScores
function getSpeed(entity){
const objective = world.scoreboard.getObjective("speed")
const score = objective.getScore(entity)
return score;
} // May fail if objective I'd doesn't exist
It's from scoreboardobjevtive class if you mean getting the scoreboard score
I want to get the score and change it using the change speed item
You can by using setScore() once you get the scoreboard objective class
I'll type it in for example
I added a console.log to the end of it so it tells me what speed I’m on rn
// you need to get the objective first
const obj = world.scoreboard.getObjective("speed")
// to get the score
const score = obj.getScore(entity)
// to set new score
obj.setScore(entity, 1)
// Or to add
obj.addScore(entity, 1)
alright use addScore instead
Yup
much safer to check if objective exist first
The score changed tho?
Ohhh wait
I know the issue
I haven’t created my create objectives script
So it would be a playerJoin afterEvent right?
anywhere as long as it exists first before using score operations
Now it has failed to resolve identity
it's like
world.scoreboard.addObjective("speed", "speed")
try this
const identity = entity.scoreboardIdentity
obj.setScore(identity, 1)
Replace line 14 with that?
append it on the very top of the function and replace the "entity" from functions like setScore/addScore/getScore into "identity"
I also want to see the updated code after this
Replace all entity parts in the function with identity as well?
yes
Wait if I place this above when I made obj wouldn’t it fail
Bc obj isn’t defined at that point
How come you're not using intellisense?
I meant inside changeSpeed
I don’t trust it
It doesn’t work
Huh
Can I send you what I’ve done
Yes
Intellisense shows you what you can use. A lot of your problems you're having rn can be solved by using intellisense.
Do you mean the autocomplete? Or the AI
The AI is bad
The autocomplete is pretty good
import { world, system, EntityComponentTypes, DimensionLocation } from "@minecraft/server"
import { ActionFormData, MessageFormData, ModalFormData, FormCancelationReason } from "@minecraft/server-ui"
function createScores(player) {
player.runCommand ("function stats_start")
}
function getSpeed(identity) {
const identity = entity.scoreboardIdentity
// you need to get the objective first
const obj = world.scoreboard.getObjective("speed")
// to get the score
const score = obj.getScore(identity)
// Or to add
obj.addScore(identity, 1)
}
world.afterEvents.playerJoin.subscribe((data) => {
createScores(data.player)
})
world.afterEvents.itemUse.subscribe((data) => {
const player = data.source
if (data.itemStack.typeId === "pr:md_vehicle_speed_changer") {
const ride = player.getComponent("minecraft:riding")?.entityRidingOn;
if (ride) {
getSpeed(ride);
}
}
})
This AI is good https://jaylydev.github.io/scriptapi-docs/meta/llms.html
Yeah that's good I think
Try running this
Ok
this
It does
Not for me
Do you have the modules installed?
also make sure the scoreboard objective with id "speed" exist ingame
It does
Might not
npm i @minecraft/[email protected]
I installed everything from what the wiki told me to get
The code doesn’t work @stray spoke
you might also try to log the updated score after the addScore line to check if it works
what error
Invalid redefinition
At const identity = entity.scoreboardIdentity
Ok
I reloaded
Obj is not initialised
IT WORKS.
Thank you so much @stray spoke
really?
Yup
Just gotta tie up some loose ends
I don’t need help with them tho
I making my own Astra Essentials addon and my menu not opening
world.beforeEvents.itemUse.subscribe((event) => {
const player = event.source
const playerList = world.getPlayers()
const playerNameList = playerList.map(p => p.name)
const item = event.itemStack
if (item.typeId === "mydemons:staff_menu") {
system.run(showAdminMenu)
function showAdminMenu() {
const form = new ActionFormData()
form.title("Staff Menu")
const buttonList = [
{ text: "ranks V1", id: "ranks", icon: "textures/ui/color_picker" },
{ text: "World Customization", id: "customization", icon: "textures/ui/icon_setting" },
{ text: "Plugins", id: "plugins", icon: "textures/ui/infobulb" }
]
form.addButtonList(buttonList)
form.show(player).then((response) => {
if (response.canceled) return;
const selectedButtonId = response.getSelectedButtonId(buttonList)
addButtonList() and getSelectedButtonId() are not real vanilla ActionFormData methods.
tell me you used ai without telling me you used ai
I did not I didn't
@cobalt hollow
Because I downloaded a essentials my friend made and used it to make my own
Documentation for @minecraft/server-ui
Documentation for @minecraft/server-ui
he might not understand how to use the info from docs in code
If he doesn't then he can make it known and it can go from there. But it's best for them to have the resources so they can at least make an effort to learn. Otherwise there is no growth.
Wise words. 🔥
What would be the best way to get the next air block above from a solid block? I have tried using getBlockAbovebut the raycast is stopped by the solid block and getTopmostBlock can skip valid locations
if (block.above().typeId === undefined)
{
}```
Block.typeId can't be undefined
u should check if the block itself is defined or not
but block can be undefined only if it's in unloaded chunk or something like that
Ahh
Hmm ok didn't know that
if u just use block.above() it won't be undefined
I thought it would've been undefined because there's no block there. Gimme a min to get back to my PC and I can do a proper check for him
so, it should be like that:
function blockAboveIsAir(block) {
return block.dimension.heightRange.max == block.y || block.above()?.isAir;
}
Oh, there's an isAir property now???
it has been around for a very long time
How long has that been a thing? 😭
Oh 😭
@proven zinc use this one
Ah I wasn't clear, I wanted to scan for the next air block. As in if the block above is not air, keep going until it finds an air block
Oh
Solution I currently have is to use a block volume. Make a BlockVolume 1 block wide and the height to check from the location to consider. Then do a dimension.getBlocks for all air blocks.
Then use the getMin to get the lowest block
Looks like it works as intended, though not sure if its optimal
/**
* @param {Block} block
* @param {Number} [maxDistance]
* @param {(arg0: Block) => Boolean} [allowFunc]
* @returns {Block | undefined}
*/
function getGroundBlock(block, maxDistance = 7, allowFunc = (block => {
if (block.isAir || block.isLiquid || block.y == block.dimension.heightRange.max) return false;
const above = block.above();
if (above.isAir) return true;
})) {
if (block == undefined) return;
for (let d = 0; d < maxDistance; d++) {
let location = { x: block.x, y: block.y+d, z: block.z };
if (location.y > block.dimension.heightRange.max || location.y < block.dimension.heightRange.min) continue;
const ground = block.dimension.getBlock(location);
if (ground && allowFunc(ground)) return ground;
}
return undefined;
}
or mb like that..
fax
🔥
Can't remember when I was first asking dumb questions here
Now I'm pretty much flexible in script api and reading docs
You cast a ray from your block upwards and look for an air block
block.dimension.getBlockFromRay(
block.location,
{x: 0, y: 1, z: 0},
{includeTypes: ["minecraft:air"]}
)?.block
I had tried that but the raycast stops whenever it hits a solid block regardless. The include Types just determines whether the result returned is undefined or the block
minecart
💔

oops
😂
would canceling and applying damage in the same beforeEvents entityHurt cause an infinite loop? 
i saw that
Is there way to get banner patterns
The colors and patterns how do i get them
And also is there way to get what type of potion inside of the Cauldron
ok it does
dear god
Is it possible to load these 1 million blocks using script?
load them into what?
normal mc structure
If you have the mcstructure files and you want to load it in a world, yes
if you have it in a world and want to save it in mcstructure files, you have to use structure blocks
how does I save it
manually
scripts can't do that
there is that export button if you are on windows 10
Oh alr
ty @snow knoll @remote oyster @random flint
Y'could try bypassing it by checking for a dynamic property, since those can be set in beforeEvents.
hmmmmmmmm yeah i could try that
Hello can I use EntityHurtBeforeEvent now? Is it stable?
Yes
Has been stable for a bit
Yay
Is it better to use compared to the old after event for entity being hurt,
Cuz mine uses that for the parry system, etc, and it kinda sucks
Can you show me what it currently looks like?
I think it should work well for you
The only 2 reasons for why someone would need a beforeEvent of anything are:
- To cancel it
- To not need things like components in an item or entity (e.g.
use_modifiersin an item)
Anyone know a script that block death?Like totem of undying?
EntityHurtBefore Event. Cancel the damage.
Ohhh thx bro
Can someone explain to me how I would implement a breadth-first search algorithm into my codebase
I think my problem is wrapping my head around recursive functions
does anyone know if you can place a block with permutation thats a mob spawner? like the spawner block with an entity inside?
if not possible, i will just use structures



but