#Script API General

1 messages · Page 141 of 1

wary edge
#

It's that simple. They can store Vector3, boolean, number, string.

vast rune
#

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

wary edge
vast rune
#

k

shy leaf
#

oooo

wary edge
#

JSON.stringify(obj) then retrieving it JSON.parse(string)

vast rune
#

alr ty

vast rune
#

is there an event for when the world is closed

earnest meadow
worn basin
#

I am the 100 000 message of script api general🥳

distant tulip
#

congrats

random flint
stray spoke
#

Any algorithm ideas to make gui changes detection?

near siren
#

Any reason why custom commands, even if they are sent to CommandPermissionLevel.Any, wont show up and cant be used on realms?

wary edge
near siren
#
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
        }
    ]
}
wary edge
#

I presume then it works in Single player?

near siren
#

Yes

wary edge
#

It might require cheats enabled?

near siren
#

Hmm maybe

#

Dang it, realized there is a cheatsNeeded property and it defaults to true

stable shadow
#

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"));
            })```
open urchin
stable shadow
open urchin
#

Also got can remove the placed?.setPermutation at the start since getParts also returns the part you're getting the parts from

stable shadow
wary edge
#

Why are you using it via scripts in the first place?

#

The block traits will automatically handle it for you.

stable shadow
#

@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.

wary edge
#

You're using a custom one?

stable shadow
wary edge
#

So you're using a custom implementation.

stable shadow
#

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

chilly vine
#

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

marble sigil
#

Dynamic Properties vs. Tags — which is faster for storing data on Entity?

woven loom
#

go for dp

round bone
#

Tags are like booleans

marble sigil
#

understood, thanks.

fallow rivet
#

Is it possible to create a custom dimension with a single command, or does it have to be done with startup?

fallow rivet
viral osprey
#

Is there any way to override the memory limit watchdog exception without having to dump memory regularly?

woven loom
#

Why do I need cheats enabled to use entity selectors in custom commands?

weary umbra
#

bc its a bug

#

you cant also use /msg command

#

only if have op

#

the same for player selector

woven loom
#

When will it be fixed?

weary umbra
#

Never I think xD because it an older bug

woven loom
#

reported or not?

weary umbra
#

I didnt but I think someone did that

#

not sure

remote oyster
viral osprey
#

Just wanting to know ofc if I can increase the limit of memory

#

Thank you u

remote oyster
#

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

junior hill
#
  player.onScreenDisplay.setTitle(
    `hp:${hp} hunger:${food}`,
    {
      stayDuration: 0,
      fadeInDuration: 0,
      fadeOutDuration: 0
    }
  );
}
#

i wonder if this is right to set titles correctly?

lyric kestrel
junior hill
#

idk why not working atm

#

so im just asking

lyric kestrel
#

Is there an error?

junior hill
#

no

#

o lol i forgot

#

to activate the event with a worldafter

#

but idk if there one with hunger

#

bc i got hp done

lyric kestrel
lyric kestrel
#
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
    }
)```
junior hill
#

minecraft:hunger

#

does this even exist?

lyric kestrel
junior hill
#
    "$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

unique dragon
#

someone know why blocks with custom components, even without the onPlayerInteract event, you can interact with the block?

#

is this a bug?

wary edge
unique dragon
#

ty

crude ferry
#

myEntity.target = newTarget;
Target property of an entity is read only as it's turning out.

#

Any work arounds?

shy leaf
#

😔

crude ferry
#

Unfortunate.

shy leaf
#

do you just

#

store raw data

#

110kb in one block is insane

lyric kestrel
shy leaf
#

OH MY GOD

lyric kestrel
#

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

shy leaf
#

i dont know much about blocks in general, but how is DP stored in a block?

lyric kestrel
#

Well, the cap is 1KB, so uhhh

shy leaf
#

say, when you print it out as text

lyric kestrel
#

It's just the same as items I believe

shy leaf
#

yeah you could... cut down some texts

crude ferry
crude ferry
#

:D

shy leaf
#

peak jank

crude ferry
#

It works for my very specific use case lol.

shy leaf
#

thats a bless and a curse

lyric kestrel
#

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

crude ferry
#

Oh wait I can just setRotation(). I just need it for head movement anyway.

lyric kestrel
#

I am currently using entity properties, but I want to get rid of that and use a block entity when they come out

lyric kestrel
#

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

shy leaf
#

@lyric kestrel have you considered cutting boolean bloats down and use 16bit integer

#

and not include booleans that are false

lyric kestrel
#

Idk how i'd do that 🥲

#

I'm currently trying out a method to cut it down to only 16 entries atm

shy leaf
#

give me a second

#

actually 16bit integer might not fit

#

i just read more and i see the pattern

lyric kestrel
#

Ok, I think I got it

shy leaf
# lyric kestrel I'm currently trying out a method to cut it down to only 16 entries atm

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

lyric kestrel
shy leaf
#

yeah i dont fully know about the code but

#

from what i see you can cut down a lot by simplifying it

lyric kestrel
#

Yeah, I can very much so

shy leaf
#

aaand this is my random crazy thought

  [
    "zinc_ingot|12", 
    { 
      l: 13,
      n: 13, 
      m: 9
    }
  ],

to

    "zinc_ingot.12.13.13.9",

_ _

stray spoke
#

Why not use Map instead

#

It supports other types than string for keys

#

Oh nvm

round bone
weary umbra
#

Is there away to check if a mob is a boss? Like Ender dragon etc. or like custom mobs

stray spoke
lyric kestrel
#

Yeah, using Map is better

lyric kestrel
#

Wait, duhhh why didn't I do this in the first place 😭

lyric kestrel
#

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 😭

wary edge
#

Cant for maps you also do as const? That might be arrays only I guess.

lyric kestrel
#

Having just the const still allows for editing through methods

wary edge
#

Const arr = [] as const

lyric kestrel
#

I have no idea

wary edge
#

I know that makes the array immutable.

buoyant canopy
#

Why does beforeEvents.entityItemPickup not work on minecarts 😭

#

hopper* minecarts

#

Fix your game Mojang

wary edge
random flint
buoyant canopy
#

players do

stray spoke
#

oh nvm I misunderstood

fallen cape
#

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?

sharp elbow
#

What do you need to update faster than once a tick?

warm mason
random flint
shut citrus
#

anyone got world crashing when runing for loop

shy leaf
trail marten
#

do you guys know which version did @minecraft/server version 2.0.0 were released out of beta?

trail marten
rough anchor
#

what manifest version do i need for beforeChat events?

remote oyster
#
"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"
  }
]
distant tulip
#

just use "beta"

junior hill
#

what are exactly ```js
WeakMap

warm mason
# junior hill what are exactly ```js WeakMap ```
junior hill
#

ok its what i thought thanks

stray spoke
#

Are all entities already loaded also in worldLoad after events to safely manage it

frosty yoke
chilly vine
#

when a player would pop a totem, cancel the damage and then apply damage equal to their current health with the override dmg type

wary edge
chilly vine
#

yea maybe

#

before hurt event has a lot of odd interactions with some things

stray spoke
#

I kinda like this one

shut citrus
weary umbra
shut citrus
#

feature

weary umbra
#

lol

fresh comet
cobalt hollow
#

is it possible in any way at all to clear the item in the players cursor in their inventory?

cobalt hollow
pliant breach
#

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;
stray spoke
#

The error is already said, the entity doesn't have an equippable component

#

It usually works for Players only

shut citrus
#

how to detect an entity attack got cancelled?

crude ferry
#

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;
    }
});```
empty grail
#

when will they make player open container/chest using script api

empty grail
#

pmmp,nukkit,and ofc endstone(bds btw)

turbid canopy
#

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

alpine wigeon
#

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

shut citrus
#

[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

turbid canopy
#

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

fresh comet
#

Creating many custom dimensions and building inside per dimension creates a lot of data

#

Ig, because that's how usually Minecraft bedrock is

turbid canopy
#

Yh I’ve noticed that in videos I’ve seen

#

Really heavy on performance

fresh comet
#

Yeah

turbid canopy
#

I haven’t seen much for myself yet but is it possible to create custom skyboxes for new dimensions or something similar

stray spoke
#

How do yall even generate an infinite structures in dimension

#

In summary

sudden nest
#

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

turbid canopy
#

Anyone know how to get better at scripting

crude ferry
crude ferry
turbid canopy
crude ferry
#

If you are good there, it's mostly making things and asking for help and knowing how to search for the right thing.

turbid canopy
#

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

crude ferry
#

Oh frontend work.

#

I see.

turbid canopy
#

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

crude ferry
#

Have you worked with any other language?

turbid canopy
#

Not really

#

Apart from JSON ofc

#

I have made 2 semi-functional addons using my basic knowledge

crude ferry
turbid canopy
#

Yh

#

I want to know what steps I can take

crude ferry
#
turbid canopy
fresh comet
#

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

crude ferry
#

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.

turbid canopy
turbid canopy
fresh comet
#

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

stray spoke
#

What are you talking bout

lyric kestrel
#

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

stray spoke
#

Kinda the same except I have little experience with html js first

distant tulip
#

learning the syntax is enough, you can learn as you go

lyric kestrel
#

Yeah

stray spoke
#

Yep

untold magnet
untold magnet
#

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

wary edge
#

Youll need to make many items then.

untold magnet
#

yeah ill just use the workaround instead.

cerulean cliff
#

does the debug utilities module support rotations for boxes?

cerulean cliff
#

L another bug

cold grove
#

thats sad

cerulean cliff
#

it'll probably be the same as server-net

woven loom
#

Does Navy know about the bug where the CC with entity selector requires cheats to be enabled?

wary edge
shy leaf
#

has anyone researched EntityHurtBeforeEvent and its quirks? i couldnt test it much on my own

earnest meadow
shy leaf
#

all i know so far is that it doesnt cancel fire aspects, and it has weird behaviors for tamed wolves targeting

shy leaf
#

so no its not stable despite being marked as stable lmao

cyan basin
shy leaf
#

fire tick damage specifically

cyan basin
#

You mean to things like armor or are you saying fire tick damage to player isn't canceled?

knotty plaza
cyan basin
# shy leaf the damage would be already done
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.

wary edge
#

Could you also not read the damaging entity and check the weapon for fire aspect first?

cyan basin
#

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.

wary edge
#

I need to do the bug report of current value returning the health after the damage is applied.

cyan basin
#

Well that's only because currentValue can't be used in early execution and requires a system.run().

cyan basin
#

Oh I guess I meant when trying to set it. Whoops!

wary edge
#

Gotcha, I meant moreso reading it!

shy leaf
#

for my use case, i could do some trickery with entityHitEntity

#

but i dont like doing that tbh, its janky

cyan basin
#

The script I made doesn't stop damage via flint and steel or lava if that's what you're worried about.

shy leaf
#

thats direct fire damage, no?

#

fire tick is when youre set on fire

cyan basin
#

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.

shy leaf
#

does game track for fire aspect's owner? last time i checked there was no damagingEntity from damageSource

cyan basin
shy leaf
#

vid isnt loading

cyan basin
#

Maybe switch channels and back. It loaded fine on my end.

#

Or reload discord.

shy leaf
#

just did that

#

lemme download it

#

oh the download isnt downloading either

#

😭

cyan basin
#

Bruh 😭

shy leaf
#

"24 minutes left"

wary edge
#

LMAO

#

Bro.

cyan basin
shy leaf
#

yeah that ones playing

cyan basin
#

Weird..

shy leaf
#

theres actually two damage source

#

fire and fireTick

#

iirc

cyan basin
#

Yeah, just saw those two looking at the EntityDamageCause..

#

There's also lava too.

shy leaf
#

tbh this is something they definitely overlooked

#

they specifically fixed knockback enchantment from applying

#

but not that

cyan basin
#

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

honest spear
#

in theory you could disable all fire damage in general or something

stray spoke
#

hope they add inventory change event for entities

wary edge
#

😔 Please.

stray spoke
#

and a function that opens an existing chest block

#

Or just a function to interact a block

last latch
#

or an empty function that returns void

#

please mojang

stray spoke
#

Very funny

lyric kestrel
#

Anyone know how intensive loading a full 64x64x64 structure is on the game through Scripting?

lyric kestrel
#

Damn.
Now I'm torn between whether to do my Foundry add-on or mess at custom dimension world gen rn

stray spoke
#

I was planning to make Skyblock addon that works like Skyblock plugin where we generate our personal island and manage it

lyric kestrel
#

Also, I didn't realise features could be placed using scripting

stray spoke
#

But it seems not recommended for performances

lyric kestrel
stray spoke
#

Oh shoot I forgot custom dimensions only created by startup

lyric kestrel
#

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

stray spoke
#

Damn

lyric kestrel
#

Now that I realise you can place features with scripting, I think I'll try placing some caves or smth

lyric kestrel
#

Does anyone know what the new BlockVolume API speed and resource intensity is?
And possibly about placing structures that are 64x64x64🥺

shut citrus
#

I use it to cancel the event but the mob still hits me

#

bugs to bugs

warm mason
stray spoke
stray spoke
#

I've always been curious how to addEffect with infinite duration

#

Or is it only possible with commands?

#

Infinty isn't supported either

crude ferry
#

The max you can do is 20 million ticks.

stray spoke
#

ig that's long enough to act like no expiration

#

Thanks

last latch
last latch
#

yeah

round bone
#

Doesn't exist, lmao

last latch
#

that is what i had in mind

#

i may have dementia tho

#

its like the second time script api gaslights me

lyric kestrel
#

Yeah, sadly infinite isn't considered an int

#

😔

shy leaf
#

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 clueless

crude ferry
#

No?

shy leaf
#

...really?

crude ferry
#

Thought you're saying that such a property already exists.

#

Also, I'm very sure it's -1 and not a boolean for infinity.

crude ferry
#

Yeah.

#
Minecraft Wiki
Mob

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...

lyric kestrel
#

Sadly you can't pass anything less than 1 tick into effects with scripts 😔

cinder shadow
#

we don't have an entityStopSneaking event right?

#

yeah doesn't look like we have one but then there's this 😭

cinder shadow
#

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

alpine wigeon
stray spoke
#

Why do they always ask that

golden holly
#

What is ...

#

?

crude ferry
#

Huh?

#

Oh you mean the spread operator.

crude ferry
#

It is used to spread arrays, map or sets.

#
const arr1 = [3, 4, 5];
const arr2 = [1, 2, ...arr1];```
granite cape
#

well well well

crude ferry
#

Interesting.

shy leaf
#

is Dimension.playSound method not guaranteed to play in the same tick?

sage portal
stray spoke
#

So this is ddui

#

Do yall know what's the grid called

buoyant canopy
#

Does BlockRedstoneProducerComponent work on vanilla blocks? can we read the redstone signal of a comparator?

fallen cape
stray spoke
#

Ohh

#

Thanks

stray spoke
#

Is ddui in beta version only

distant tulip
stray spoke
#

yh figured it out

fresh comet
#

We can make better gambling in ddui

last latch
#

les go gambling

worn basin
#

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

onyx locust
#

does anyone have texture pack for modalform textfield to support multiline or longer texts?

granite badger
last latch
humble lintel
#

Does anyone know anything with how to fix this error in ts when using withState?

last latch
#

as any fixes anything bro

#

Trust me

#

🤫 6153stare

fresh comet
#

💀

worn basin
#

Is there an event for when a player change dimension

fresh comet
worn basin
#

Thanks!

round bone
lyric kestrel
wise nova
#

WIll item's clone function clone the dynamic properties?

warm mason
golden holly
#

why is It Not recommended to run command from script?

snow knoll
golden holly
#

Why

#

Command is command how can one method cause more lag

remote oyster
snow knoll
# golden holly Command is command how can one method cause more lag

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

random flint
# golden holly Command is command how can one method cause more lag

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")

worn basin
#

i made an electricity cable connector

#

using debugshapes

stable shadow
#

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.

distant tulip
#

please add more context
multiBlock and parts are both vanilla native api features

what you have is not using that

wary edge
#

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.

stable shadow
#

I'm going to make one here and record a video showing it.

worldly pier
worn basin
#

Im not the one

worldly pier
#

"All roads lead to rome"

#

⏲️

cobalt hollow
#

doom in DDUI when

cold grove
#

If you can do doom in a pdf you can do it in a form too

shut citrus
#

Why does the game lag when I shoot 80 projectiles using scripts?

shy leaf
#

dont you think 80 projectiles are a bit too much?

shut citrus
#

I tested on mc java and the game still smooth

#

bedrock is poor optimizing

fresh comet
#

Is it possible to use system.runJob in one loop only, instead of 3 nested loops

snow knoll
random flint
shy leaf
#

i dont know what requires 80 projectiles to be shot simultaneously

#

but theres def a room for optimization that may not require that much

worldly pier
# shut citrus bedrock is poor optimizing

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

buoyant canopy
#

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)
}
crude glacier
#

O(n^2) ☠️ damn

#

Wait you can do that in js ?

#

Using an object instead of a regular integer

crude glacier
#

Now bedrock is considered heavy

honest spear
#

all numbers are doubles

honest spear
buoyant canopy
buoyant canopy
honest spear
#

better to bechmark but yea it should be more performant on bedrock

buoyant canopy
# crude glacier Wait you can do that in js ?

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.

honest spear
#

not just js

#

all lnags wherw for loop looks like that

#

c, c++, c#, java

buoyant canopy
#

well the ones that inherited the C for loops

stray spoke
#

Does system runJob only work for nested loops

sharp elbow
#

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

crude glacier
stray spoke
#

Also is there a way to clear the item that the cursor is holding

stray spoke
#

Instead of nested

#

If there's a workaround for it

wary edge
#

What are you trying to use a job generator for?

stray spoke
#

It says Generator(generator, generator, generator) on my logs

worldly heath
#

is there a way to check if a leaf block is naturally grown or not ?

#

i mean decayable or not

wary edge
worldly heath
thorn ocean
#

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.

buoyant canopy
stray spoke
#

mb mistype

distant tulip
stray spoke
#

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())
honest spear
#

yea

slow walrus
#

unless there's something that will take up a whole tick in the for loop

buoyant canopy
#

assuming that the generator object is passed to system.runJob

honest spear
#

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

last latch
#

I still have no idea what jobs are

#

All my projects were so optimized I didn’t ever need to use jobs

drowsy scaffold
# last latch I still have no idea what jobs are

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

woven loom
#

Is there a way to tell if an ItemStack is a block item?

last latch
drowsy scaffold
distant tulip
last latch
#

I mean, if there arent any downsides.

cold grove
distant tulip
last latch
woven loom
cold grove
#

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

worn basin
#

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 😭

last latch
lyric kestrel
#

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 😔

stray spoke
#

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

sharp elbow
stray spoke
#

j*b

sharp elbow
#

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.

last latch
#

so i wasted yalls time

sharp elbow
#

(Just to complete the discussion:)
Jobs have two significant downsides over synchronous code:

  1. 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
  2. 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)

buoyant canopy
#

synchronous code is almost always the way to go, jobs are only good if you have a large task that might hang the engine.

lyric kestrel
stray spoke
crude glacier
#

Having a virtual job

crude glacier
#

Btw is it possible to add glints using script api ?

#

And how to lock lore to an item

stray spoke
#

But you can add glint in custom items via its client item file

stray spoke
#

You have to set the updated itemstack to the slot again to actually update in-game tho

weary umbra
#

Is there a way to set colored bed?

stray spoke
#

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

weary umbra
#

setblock only has bed

#

I used structure for now

stray spoke
#

that also works

wary edge
wary edge
#

Thats #1067876857103536159

weary umbra
wary edge
gaunt salmonBOT
drifting ravenBOT
#
What format version should I use?

"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

weary umbra
stray spoke
#

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

eager venture
#

aymen i love u

turbid canopy
#

My script won’t work for some reason

#

It says on the content log main.js could not load main

eager venture
#

send the js file in here

turbid canopy
#

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

eager venture
#

Oh idk anything abt brdige. sorry

#

i started on vscode

turbid canopy
#

Just gives me suggestions and stuff

stray spoke
#

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

turbid canopy
#

Ty for telling me

viral osprey
turbid canopy
viral osprey
#

in vscode

turbid canopy
#

How does it work

#

Bc I’m planning to migrate to vscode

#

Bridge is kinda sucky

viral osprey
#

It's just an AI model

#

that reads your code as you write

#

and gives you auto-complete suggestions

turbid canopy
#

And I’m able to ask it questions on how to improve my code or how to do something?

distant tulip
#

@turbid canopy Use Blockception extention and npm types for scripting
copilot can be usefull but most of the time not

turbid canopy
#

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

distant tulip
#

there is just a bit of manual work compared to bridge, but you will get used to it

turbid canopy
#

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?

valid ice
#

It's goaded

turbid canopy
#

Also how do I link the addon files into Minecraft so I can use /reload

turbid canopy
#

Last time I talk about non script things in script chat

pale terrace
#

Hello! bad trapdoors rotation when placing an structure with scripting is fixed?

cold shoal
#

Is there an API for the /locate command in scripting to list the locations of some structures?

cold grove
cold shoal
#

Ohh interesting

cold grove
#

I do not recommend it at all

cold shoal
#

Yeah, it may affect performance and I need it on stable but thanks!

stray spoke
#

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

crude ferry
#

Is that your heavy task lol?

#

And yes that does start multiple jobs.

stray spoke
#

The counting task is just a test to see how fast it counts

stray spoke
#

much more efficient if its just directly runInterval but what if there's ≥ 50 players that execute heavy tasks each given tick

#

Could lag

viral osprey
distant tulip
#

what?

#

blockbench is a modeling tool

crude ferry
#

😭

turbid canopy
#

I moved my stuff to vsc

crude glacier
#

Guys is it possible to simulate oxidations effect in script api for other blocks than copper

#

Like rusting , degradation, etc..

#

Without affecting performance much

sharp elbow
#

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

snow knoll
#

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

worldly pier
sharp elbow
snow knoll
sharp elbow
crude glacier
sharp elbow
#

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

snow knoll
sharp elbow
# crude glacier No fr i never used runJob

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.

worldly pier
#

I don't think there's any way of doing that, canceling its vertical component with another vector seems fine enough to me

snow knoll
worldly pier
crude glacier
snow knoll
worldly pier
#

Oh, I didnt know that

snow knoll
#

Learnt it from camman18 like 4 years ago so I'm only so much more informed

sharp elbow
# snow knoll That's a pretty cool way to do it honestly Every time I see Sprunkles answer a q...

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

wary edge
#

You can give slow falling too.

sharp elbow
#

That would help with client visuals, yeah. Makes gravity a little lighter

snow knoll
sharp elbow
#

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

pale terrace
#

I always optimize heavy operations per tick using await and I compared with runJob and the optimization is almost the same

cold grove
#

Does not have nothing to do with optimization practices

#

Generators can yield promises too i guess it has something to do(?

pale terrace
pale terrace
remote oyster
# pale terrace afaik the only difference is that runJob doesnt stop the code execution unlike `...

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.

pale terrace
#

:O

#

Thank you for this info

remote oyster
random flint
# remote oyster 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.

honest spear
honest spear
#

wait, the more i look at it the less i like it

#

the yield example is weird ngl

#

and misleading

honest spear
#

Imagine in what world we would live in if AI was actually good lol

turbid canopy
#

Is it possible to get whether or not a player is riding an entity

open urchin
turbid canopy
#

How do I apply something to the ridden entity

open urchin
#

you can get the ride using

const { entityRidingOn } = player.getComponent("minecraft:riding")
turbid canopy
#

how would I validate this

#

I want changeSpeed to apply to the ridden entity

#

I realised a typo hold on

#

Sorry

open urchin
turbid canopy
#

Typo whoops

#

Changed it

open urchin
#

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);
  }
}
turbid canopy
#

Thank you

crude ferry
#

What is line 18?

turbid canopy
#

All line 18 has was that end bracket

open urchin
#

is that main.js?

turbid canopy
#

Yh

open urchin
#

should be data.itemStack

turbid canopy
open urchin
#

not sure why that would be a not a function error though

crude ferry
turbid canopy
turbid canopy
#

Oh right

#

Much easier on the eyes

#

Bridge used to do that automatically

crude ferry
turbid canopy
#

Reloaded and the issue is still there

#

Might be an issue with my manifest but last I checked it was fine

open urchin
#

oh you've removed the initialisation of player

turbid canopy
#

Where do I put that

open urchin
#

you could do data.source instead

turbid canopy
open urchin
#

should be data.itemStack.typeId and player should be data.source

#

itemStack returns an ItemStack so it will never be equal to a string

turbid canopy
#

What if I do “let player = data.source”

open urchin
#

you could do that too

turbid canopy
#

I’ll try it

open urchin
#

should be a const though since the player won't change

stray spoke
#

score component exist?

turbid canopy
#

I’ll reload

#

I PRAY It works

#

That’s annoying

#

It still says that it doesn’t exist

stray spoke
turbid canopy
stray spoke
#

Oh someone already told

turbid canopy
#

Look at this

stray spoke
#

Can you send the error logs

turbid canopy
stray spoke
#

We also need to know what code is in line 19

turbid canopy
stray spoke
#

I see

#

You have typo

turbid canopy
#

Where

stray spoke
#

it should be subscribe

#

Not subcribe

turbid canopy
#

😭

stray spoke
#

lol

turbid canopy
#

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

turbid canopy
#

I don’t think score is a component

#

That might be the biggest issue

stray spoke
#

Yeah its my guess also

turbid canopy
#

I’ll remove it

stray spoke
turbid canopy
stray spoke
#

What's the new code

#

If you want to set a scoreboard score, there's an api for it

turbid canopy
#

Hold on my laptop lost WiFi

#

There

stray spoke
stray spoke
turbid canopy
#

i could have sworn i saw it on entity class

#

for documentation

#

or is that getScores

stray spoke
#
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
stray spoke
turbid canopy
stray spoke
#

I'll type it in for example

turbid canopy
#

I added a console.log to the end of it so it tells me what speed I’m on rn

stray spoke
#
// 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)
turbid canopy
#

And I have to paste this into changeSpeed

#

I want to add score btw

stray spoke
#

alright use addScore instead

turbid canopy
#

Yup

stray spoke
#

much safer to check if objective exist first

turbid canopy
#

I’ll try what you gave me first

#

No errors

stray spoke
turbid canopy
#

No

#

Another error

#

Cannot read property of getScore of undefined

stray spoke
#

Yeah the objective didn't exist

#

You've to create one first

turbid canopy
#

Ohhh wait

#

I know the issue

#

I haven’t created my create objectives script

#

So it would be a playerJoin afterEvent right?

stray spoke
#

anywhere as long as it exists first before using score operations

turbid canopy
stray spoke
#

it's like

world.scoreboard.addObjective("speed", "speed")
turbid canopy
#

main.js:14 is const score = obj.getScore(entity)

stray spoke
#

try this

turbid canopy
#

It may be because we aren’t using it

#

unless addScore is related to it

stray spoke
#
const identity = entity.scoreboardIdentity
obj.setScore(identity, 1)
turbid canopy
stray spoke
#

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

turbid canopy
#

Replace all entity parts in the function with identity as well?

stray spoke
#

yes

turbid canopy
#

Bc obj isn’t defined at that point

lyric kestrel
#

How come you're not using intellisense?

stray spoke
turbid canopy
#

It doesn’t work

lyric kestrel
#

Huh

turbid canopy
stray spoke
lyric kestrel
#

Intellisense shows you what you can use. A lot of your problems you're having rn can be solved by using intellisense.

turbid canopy
#

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);
    }
}

})

somber cedar
stray spoke
#

Yeah that's good I think

turbid canopy
lyric kestrel
turbid canopy
#

Doesn’t come up for scripting tho

lyric kestrel
#

It does

turbid canopy
#

Not for me

lyric kestrel
#

Do you have the modules installed?

stray spoke
#

also make sure the scoreboard objective with id "speed" exist ingame

turbid canopy
lyric kestrel
turbid canopy
#

I installed everything from what the wiki told me to get

#

The code doesn’t work @stray spoke

stray spoke
#

you might also try to log the updated score after the addScore line to check if it works

stray spoke
turbid canopy
#

At const identity = entity.scoreboardIdentity

stray spoke
#

I see

#

It should be

#

function getSpeed(entity)

#

not function getSpeed(identity)

turbid canopy
#

Ok

#

I reloaded

#

Obj is not initialised

#

IT WORKS.

#

Thank you so much @stray spoke

stray spoke
#

really?

turbid canopy
#

Just gotta tie up some loose ends

#

I don’t need help with them tho

violet bloom
#

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)
eager venture
cobalt hollow
violet bloom
#

I did not I didn't

#

@cobalt hollow

#

Because I downloaded a essentials my friend made and used it to make my own

stray spoke
remote oyster
proven zinc
#

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

lyric kestrel
warm mason
#

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

lyric kestrel
warm mason
lyric kestrel
#

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

warm mason
#

so, it should be like that:

function blockAboveIsAir(block) {
    return block.dimension.heightRange.max == block.y || block.above()?.isAir;
}
lyric kestrel
#

Oh, there's an isAir property now???

warm mason
#

it has been around for a very long time

lyric kestrel
#

How long has that been a thing? 😭

lyric kestrel
lyric kestrel
proven zinc
#

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

lyric kestrel
#

Oh

proven zinc
#

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

warm mason
# proven zinc Ah I wasn't clear, I wanted to scan for the **next** air block. As in if the blo...
/**
 * @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;
}
stray spoke
#

🔥

#

Can't remember when I was first asking dumb questions here

#

Now I'm pretty much flexible in script api and reading docs

buoyant canopy
#
block.dimension.getBlockFromRay(
  block.location,
  {x: 0, y: 1, z: 0}, 
  {includeTypes: ["minecraft:air"]}
)?.block
proven zinc
#

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

subtle cove
buoyant canopy
#

oops

crude ferry
#

😂

shy leaf
#

would canceling and applying damage in the same beforeEvents entityHurt cause an infinite loop? clueless

shy leaf
#

i saw that

fallen cape
#

correct url

shy leaf
#

im afraid of my laptop dying from this skull_issue_c but

#

yeah ill try

shell sigil
#

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

shut citrus
#

Is it possible to load these 1 million blocks using script?

buoyant canopy
shut citrus
#

normal mc structure

buoyant canopy
#

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

buoyant canopy
#

scripts can't do that

#

there is that export button if you are on windows 10

golden holly
#

ty @snow knoll @remote oyster @random flint

sage portal
# shy leaf ok it does

Y'could try bypassing it by checking for a dynamic property, since those can be set in beforeEvents.

shy leaf
#

hmmmmmmmm yeah i could try that

warped kelp
#

Hello can I use EntityHurtBeforeEvent now? Is it stable?

snow knoll
warped kelp
#

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

snow knoll
#

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_modifiers in an item)
blissful hazel
#

Anyone know a script that block death?Like totem of undying?

wary edge
blissful hazel
#

Ohhh thx bro

ocean escarp
#

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

dapper copper
#

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