#Script API General

1 messages · Page 140 of 1

cerulean cliff
#

btw cool pfp

#

thought it was an anime girl for a second

shy leaf
#

i guess its a slightly inconvenient way to do rawmessage skull_issue_c

shy leaf
#

dude

#

dawg

#

brother

cerulean cliff
#

I WEAR BIG ASS GLASSES

mystic harness
#

Is there a way to summon fireworks? the ones that explode with colors

woven loom
#

How can I detect when an armor stand loads with the world so I can run a function on it?

woven loom
#

doesnt work

#

nvm it does

#

i was testing with reload

mystic harness
#

i tried player.extinguishFire when lightning bolt strikes but seems like i have to delay it a little bit just to extinguish. i tried also to use entityHurt before event but still player kept burning when near the lightning bolt. is there a way to be completely immune by it

stray spoke
#

Add fire resistance effect for a short time

#

then summon lightning bolt

meager zenith
mystic harness
#

ight thanks

crude glacier
#

Huh

ocean escarp
#

Does that "for" method work again?

for (i in var) {
//Output
}
unique apex
#

is there a way to list all dynamic properties/iterate through them?

ocean escarp
crude ferry
ocean escarp
#

I'm trying to apply some default values on world load

shy leaf
#

and then

#

oh efficient was faster

crude ferry
#

That's why they call me "efficient".

shy leaf
#

i also was about to make that joke too

crude ferry
#

lol.

shy leaf
#

you really are efficient

sharp elbow
# ocean escarp As in, I forgot how the syntax goes

There are a few variants of for loops.

You have the C-style for loop, which executes a series of statements:

for (initialization; condition; per-update expression) {
  // ... Loop body
}

for (let i = 0; i < 5; ++i) {
  console.warn(i);
}

You have the for..in loop, which iterates over the enumerable properties in an object:

const foo = {
  a: 1,
  b: 2,
};
for (const key in foo) {
  console.warn(key, foo[key]);
}

You have the for..of loop, which follows the iteration protocol and is generally far more flexible:

const data = new Map([
  ["hi", 1],
  ["there", 2],
]);

// data is a Map; Map implements the iterator protocol
// datum takes on a tuple of [key, value]
for (const datum of data) {
  console.warn(datum[0], datum[1]);
}
ocean escarp
sharp elbow
#

Can you provide an example of how that'd play into a for-loop?

ocean escarp
#

Do you know Lua? Cause I can probably do direct translation

crude ferry
sharp elbow
ocean escarp
#
for i,v in ipairs[#var] do
setDynamicProperty("v.property", defaultVal)
end
#

I'm quite a bit rusty

#

So apologies there

unique apex
#

what is that

ocean escarp
#

basic Lua

unique apex
#

ew

ocean escarp
#

I used it as an example as I don't know the js equivalent yet

unique apex
#

what does it do

ocean escarp
#

Loop through all of an array and assigns each a value

#

Trying to do a set default thing

unique apex
#

trying to write this tells me im still a beginner lol

#

you can access any value at array[i] and you can increment i

ocean escarp
#

Specific usecase here is giving very player a default value for several properties

unique apex
#

oh i see so you want to set properties for every player

#

the array being a list of players

ocean escarp
#

Yup

#

world.getAllPlayers()
returns an array iirc

unique apex
#

and you have a second array of objects to set properties and values?

ocean escarp
#

Most of them will be the same
default attack bonus = 0
default parry limit = 2
Etc.

unique apex
#

one sec

#
    allPlayers.forEach(player => {
        player.setdynamicproperty....
    })```
#

this is what i use in a custom party system

ocean escarp
#

That should work yeah

#

Thanks

gaunt salmonBOT
subtle cove
#

it'd be like

unique apex
#

can I access a furnace's inventory using scripts?

#

const container = getBlock(vector3).getComponent("inventory").container;
would this work?

snow knoll
#

On a serious note, it should, but the point above still stands 🙃

unique apex
#

yeah real

sharp elbow
snow knoll
#

Also, Is the velocity that projectiles are shot at with the projectile.shoot() method measured in seconds or ticks?

wary edge
snow knoll
#

I checked one of the sites with the documentation, and it didn't even tell me 😭

#

I was originally going to ask this in #1067869022273667152 but came here since I was going to shoot it with scripts anyways

sharp elbow
#

I suspect it is blocks/tick, like applyImpulse

snow knoll
#

Wait, applyImpulse is blocks per tick?
Been wondering for like, a year plus

sharp elbow
#

I sure hope it is. Otherwise I have made some very incorrect assumptions

snow knoll
#

Loll

near siren
#

Anyone know of a plugin in vscode for bedrock scripting?

fallen cape
near siren
#

Oh wow I completely forgot about that

#

Thank you

honest spear
#

my bad

crude ferry
gaunt salmonBOT
wicked girder
#

Anything cool made with custom dimensions? 👀

stray spoke
#

Isn't it only in preview

fading furnace
knotty plaza
stray spoke
#

I'm still waiting for it to be stable

ocean escarp
#

Can you not force typing with Js
I think what I was trying to do is a typescript thing but It would be nice to do in Js too

#

figured out why my former was broken but pretty sure I can't assign types strictly

twilit sky
wicked girder
ocean escarp
#

Atp I don't see a reason to upgrade my PC until the release of the steam machine which will likely replace it for the most part anyways due to existence of desktop mode

#

How would I grab the product of all player's velocity?

#

because unless XYZ are all 0 that means players are moving

subtle cove
#

oh boi

twilit sky
ocean escarp
#

Of 1

subtle cove
ocean escarp
#

But it's way too tedious

#

Can you pick out the error cause content log is going crazy.

#

Something about not a function at line 18

#

There isn't even a function at line 18

twilit sky
# ocean escarp Something about not a function at line 18

Slightly difficult to do when the line numbers are cut out of the picture. From what I do see, you have PLAYERS assigned to a function, not the function's output.

const PLAYERS = world.getAllPlayers --> const PLAYERS = world.getAllPlayers()

subtle cove
#

in script-api, never put the methods in variables```js
const getPlayers = world.getAllPlayers //bad habit with variables, unless advanced

const players = world.getAllPlayers() //practice this often
```
ocean escarp
#

whoops

#

World.getAllPlayers cannot be used in early execution

#

well that sucks

subtle cove
#

since most methods are bound to their instance, calling such methods would throw bound errors

ocean escarp
#

Should I just change all instances of PLAYERS to the value and forgo defining it?

subtle cove
#

use it inside the function

ocean escarp
#

I don't expect it to work instantly as I have a placeholder for something I don't know how works yet

subtle cove
#

i'd still suggest ```js
system.runInterval(() => {
for (const player of world.getAllPlayers()) {

}

});```

ocean escarp
#

Can you not call functions inside a class?

subtle cove
#

can

twilit sky
subtle cove
#

u can call any function anywhere

ocean escarp
#

It's telling me it's not a function

#

raceHandler.rollRace()
class.function()

subtle cove
#

oh, that

twilit sky
#

Would I be correct to assume that you can't install TypeScript, and the API typings, due to the PC not having Wi-Fi?

ocean escarp
#

I don't like typescript

#

The only part about it that I like is that setter thing

subtle cove
#
class RaceHandler {
    static races = new Map()
    constructor(name, stats) {}
    rollRace(player) {}
}

const race = new RaceHandler("test", {});
race.rollRace(player)

RaceHandler.races
winged drift
#

//@ts-check would be an option

subtle cove
#

the static part is where the class' properties are, while the non-static ones are in its instance

subtle cove
ocean escarp
#

Im still tryna figure out why I can't grab the player's nametag

subtle cove
#

r u sure the players array has players?

ocean escarp
#

Tryna find out what it's returning

twilit sky
#

There's player.name, and player.nameTag. nameTag is the more general one for entities, and name is the actual username.

ocean escarp
#

Ah..

#

Ok that's so much better

subtle cove
ocean escarp
#

Now I just need the product of the player's velocity to test if it's non-zero

twilit sky
# ocean escarp

It's also a string already. You don't need to call toString() on it.

ocean escarp
subtle cove
ocean escarp
#

I don't use that much

subtle cove
ocean escarp
#

Also player.getVelocity() returns an object with 3 vectors right?

#

Is there a shorthand to multiply them all together?

subtle cove
#

other than custom functions or commons lib, no

twilit sky
twilit sky
remote oyster
ocean escarp
#

I've ran into a problem

#

multiplying all the values together does nothing because as long as 1 is 0 that'll become 0

#

11 x 3 x 0 = 0

#

I can't divide because uh.. well you try telling a computer to divide by 0

twilit sky
#

What exactly is it that you're trying to do with the velocity? By product, do you mean magnitude?

ocean escarp
#

I've noticed if I do stuff like player spawn that people won't get to see what race they got assigned because they're still loading in

subtle cove
#

more like magnitude

#
Math.sqrt(v.x ** 2 + v.y ** 2 + v.z ** 2);
ocean escarp
#

If there was a version that didn't rely on velocity I would use it

remote oyster
#

You basically are checking for afk status

twilit sky
ocean escarp
#

I only need to do it once

lyric kestrel
subtle cove
remote oyster
lyric kestrel
#

Ahh

#

Rip

ocean escarp
#

It's just to say
"HEY! it seems this is your first time here, let's roll your race and see what you got!"

lyric kestrel
#

Could do a server.runTimeout(()=>{}, 600)

ocean escarp
#

Im doing an origins-inspired addon

lyric kestrel
ocean escarp
twilit sky
lyric kestrel
ocean escarp
lyric kestrel
#

Like their character could spawn in game, but they might be seeing the loading screen still

subtle cove
#

||spam 1 form show||

lyric kestrel
#

But, you should just be able to do a timeout

ocean escarp
lyric kestrel
ocean escarp
#

1 thing I know can't happen before they get initialised is they gain velocity

twilit sky
#

When I had a server, I ended up going with the alternate route of having an NPC greet players. Plus this was more memorable.

ocean escarp
#

Just gonna run on first move

lyric kestrel
#

Have a form show on their screen that they can just click away when they've read it

ocean escarp
#

Just feels clunky

lyric kestrel
#

It seems like the simplest solution

#

And the best atm

#

It will remove away from your issue of players still loading

ocean escarp
#

So would a vel check

#

I still don't know why my function is saying its not a function

#

should I just not use classes?

twilit sky
#

Which part is it?

ocean escarp
#

I haven't returned anything yet cause I'm still trying to figure that part out but I'm just doing raceHandler.rollRace(player)

twilit sky
#

What line exactly is the error coming up on?

ocean escarp
#

Not a function

remote oyster
twilit sky
#

Oh, it's because that's an instance method. You need to create the raceHandler first.

fading furnace
ocean escarp
#

This is literally my first time using classes

twilit sky
ocean escarp
#

I have to create a map now???

#

Honestly might just go back to basic functions

#

If the aesthetics of the code come at this level of tediousness

twilit sky
#

-# Perhaps not 😨
You just need to create the raceHandler before calling rollRace on it:

Something like

const race = new raceHandler("name", {})
race.rollRace(val)
ocean escarp
#

Oh it's an order issue..

#

I guess I could just drag my class to the top

#

????

twilit sky
subtle cove
#

imagine the class as a template

ocean escarp
#

Same thing as running a Lua function before it's initialised in code

subtle cove
#

create an instance using new

#

then u can use it's non-static properties/methods

ocean escarp
#

Dragging my class to the top means it'll be created first?

subtle cove
#

doesnt matter

ocean escarp
#

So JS isn't order based

#

It doesnt read code from top to bottom

subtle cove
#

class is available/reachable same as functions

ocean escarp
#

I could put my import at the end of the file and it would still work

twilit sky
subtle cove
#

if ur not using any related properties (e.g. name, stats) in the rollrace, put```js
static rollRace(player)

#

then ur code should work as u want em

ocean escarp
#

I think I'll go back to functions.. classes are confusing as hell

#

The tutorial I watched mentioned nothing about this

#

Besides are classes even needed for anything when nested functions exist?

#

Just seems like complexity for the sake of complexity

subtle cove
#

for shared properties, it is very usueful

wary edge
#

OOP is useful in certain scenarios.

twilit sky
#

Good for saving data, and for bigger projects. I use them a lot for when data needs to persist. Have a look at my GitHub profile and go through some of the projects there if you're interested.

subtle cove
#

its a lot to take with such object specifics

ocean escarp
#

I just don't understand why if I create a class I now have to call it in 7 different locations before I can use it, instead of just doing

class.function

subtle cove
#

class.function would need class{static function(){}}

ocean escarp
#

Lua habits yet again I guess

remote oyster
cold grove
ocean escarp
#

I guess classes just do something different than I originally thought

cold grove
#

If it just hosts static methods

ocean escarp
#

I thought they were just like bigger functions

twilit sky
#

Entities and players are considered classes in the API, as well as the events. There can be several instances of each.

ocean escarp
#

hence why I thought you just went down the chain
class.method(args)

cold grove
remote oyster
ocean escarp
#

I guess this works?????

#

It'll be 2040 before I fully get this tho

#

my current usecase doesn't use any of the class' data

#

It doesn't need a name or the stats of anything

twilit sky
#

If your current usecase doesn't need classes, then it might be better to just not use them. Classes are another layer of abstraction that are supposed to make things less confusing.

You'd want to use them when you end up having too many functions, and it doesn't seem like you're at that point yet.

cold grove
#

And do you need a class for??

ocean escarp
#

But are they really ever needed over nested functions?

twilit sky
subtle cove
#

for specific instances, yes

#

sample would be for every group of players

#

they can have same stats, but of different levels

ocean escarp
#

like why can't i?

function a() {
function aDerivative() {}
}
test = a.aDerivative()
subtle cove
#

another confusing stuff

remote oyster
ocean escarp
cold grove
subtle cove
ocean escarp
#

I was told every class NEEDED 1

cold grove
ocean escarp
#

Then why is it called class math {}
????????

subtle cove
#

const

cold grove
ocean escarp
#

Sorry mathUtils

#

mathUtils has no constructor

subtle cove
#

optional for instantiation purposes

ocean escarp
#

I was told it was mandatory

remote oyster
# subtle cove check the `export const math` on this

If you are referring to the export/import logic then it doesn't matter because the export logic is there if to be used in another script but since I implemented it in the same block, simulating the same script, then exporting wasn't needed there.

subtle cove
#

nop

ocean escarp
#

So I can just remove my constructor then?

#

It only exists because I thought it needed 1

#

Tho I guess the usecase of the tutorial version was a lot different to what I'm trying to do here

subtle cove
cold grove
ocean escarp
#

I wanna use classes as a collection of similar functions

#

Eg.
rollRace()
setRace()
removeRace()
getRaceInfo()
blacklistRace() // for the clearly racist

#

Oh god im commenting myself now....

twilit sky
#

You can do that by adding static before the function declaration.

So rollRace() would become static rollRace().

ocean escarp
#

Don't worry I think I actually get it now

#

Classes can store variables right?

#

And I don't need to specify const outside a method because it would be essentially saying const race = const..

#

Ok I have like 2 more errors to fix but they're small syntax confusions

#

I want to be able to both access
RACES_T1 in and outside the method

#

Is that what extends does?

#

No

#

Thats an extension of a different class

remote oyster
#

It takes a class and extends it to another class. For example, Entity and Player. Player is an extended class of Entity.

ocean escarp
#

Oh I forgot static

#

So it would be static var = []

#

I think?

#

Im understanding it more

remote oyster
#

I would avoid var. Use let or const. Var will potentially lead to problems if not used carefully.

ocean escarp
#

But not fully yet

#

so inside a class but outside a method

#

I do

static const RACES_T1 = []
subtle cove
#

remove const

ocean escarp
#

Oh

#

So inside a class I don't require these declarations?

#

What about for something like a luck value that needs to change each time I run a function?

subtle cove
#

static get luck(){ return Math...}

ocean escarp
#

Do I embed into the function as a const?

#

When called: set this value and execute logic based on it

#

I think I'm getting closer

subtle cove
#

that works as well

ocean escarp
#

And once I get 1 right I should be able to make more easier with every try

subtle cove
#

uhhh

ocean escarp
#

races_t1 is not defined

#

so I do race.races_t1?

#

since my racehandler is being defined as a const called race

subtle cove
#

class raceHandler {
    get luck() {
        return Math.floor(Math.random() * 100)
    }

    rollRace(player){
        const luck = this.luck;
        ///stuff
    }
    setRace(player){
        const luck = this.luck;
        //stuuf
    }
}```
ocean escarp
#

It's all working besides 1 thing

#

How do I grab a var from within the class but not the method into the method that is in the class

subtle cove
#

assign it to the instance

#

this.var = sth

#

then access this.var in its co-methods

ocean escarp
#

Huh?

#

Wait hold on

#

Let me try wrap my head around what you said

subtle cove
#

thats how instance works using this

ocean escarp
#

assign it to the instance

#

Wait so I do this.RACES_T1?

subtle cove
#

yup

#

static has a different instance, it's the parent class instance

ocean escarp
#

Cannot read property x of undefined

#

I thought I just defined it

#

Wait did you mean in the method or the class?

subtle cove
#

static is different from the child instance

ocean escarp
#

Wait im so confused lol

subtle cove
# ocean escarp

since its in static there, u can access it by raceHandler.RACES_T1

ocean escarp
#

Oh

#

Ok good news and bad news

#

Good news

#

No errors

#

Bad news

#

No output

subtle cove
#

if u want em available using this in those methods

ocean escarp
#

It did give the tag tho which means it returned successfully

subtle cove
#

sendMessage the luck

ocean escarp
#

Ah I see

#

I love having NaN luck

subtle cove
#

random()

#

;-;

ocean escarp
#

Oh

#

My

#

God

#

Im actually useless lmao

subtle cove
#

dw, that's part of the fun ;-;

ocean escarp
#

Well I solved 1 issue and created another

#

player.removeTag() does exist right?

olive sphinx
#

I thought it was removeTags

subtle cove
#

as long as player is Entity, yes

ocean escarp
#

It must be the fact I'm not looping through the array properly or that I'm messing with the format

#

"ps:races/" ->
"ps:races/human"
"ps:races/fishman"
Etc.

#

It's supposed to randomise it each time

#

Remove any potential existing ones and then roll

#

Ok so removeTag doesn't exist

#

That or my extension isn't showing me it

#

Wait no it's giving me all of them despite the luck thing

subtle cove
#
let race = "";
  if (luck <= 70) {
    race = "human";
  } else if (luck <= 80) {
    race = "fishman";
  } else if (luck <= 90) {
    race = "dunespirit";
  } else {
    race = "ghoul";
  }

  player.addTag(`ps:races/${race}`);
  player.sendMessage(`Congratulations! You rolled ${race.toUpperCase()}.`);
ocean escarp
#

Ohhh.. I just figured out why it's giving them all

#

Wrong operator

#

It's && not ||

subtle cove
#

else stuff, or it has to return after a successful addtag

ocean escarp
#

I fixed it

#

How would I register a custom command btw?

subtle cove
ocean escarp
#

Is that on jayly's?

subtle cove
#

just here

wary edge
lethal lichen
wicked girder
#

will features work in custom dims?

wary edge
wicked girder
#

big sad

ocean escarp
#

I wish I knew how to convert typescript to JavaScript

#

Is chatSend still viable?

wary edge
#

For what?

ocean escarp
#

I might just do
"!ps rollRace"
Instead of dealing with command registery stuff

#

All the tutorials are in typescript

#

And there's enough differences to where I keep messing up

wary edge
#

You would be relying on beta apis which can break and be dropped at any week.

ocean escarp
#

Oh well

wary edge
#

Theres also tons of ts to js online.

#

Its not that hard frankly. TS is just JS with types is all at its core.

ocean escarp
#

And yet I'm still getting errors after omitting those types

wary edge
#

Those being?

ocean escarp
#

A random } that doesn't fit anywhere

wary edge
#

Or why not just learn TS?

ocean escarp
#

It's the telling me I need 1

wary edge
ocean escarp
lethal lichen
wicked girder
#

true

ocean escarp
#

Apparently im missing something

#

No errors tho

#

Smthn about line 65

#

Wanting me to close the bracket

ocean escarp
#

Even tho it's already closed

wary edge
#

JS still uses :

#

It's not type = CustomCommandParamType.string

ocean escarp
#

Odd

#

I thought js didn't use : at all

ocean escarp
#

I just dont like TS

#

I've seen it

#

Just not a fan

wary edge
#

Frankly, if you have to learn TS syntax then manually convert it in your head thats a waste.

ocean escarp
#

Well I fixed half of it

#

And now apparently line 69 also needs a } somewhere

#

All this for some basic auto complete

#

Plus how often are they really gonna change the beforeEvents for chatSend?

wary edge
#

They could just remove it.

#

There's no gurantee really beta becomes stable.

ocean escarp
#

I don't see why they would

#

How hard even is it to process chat input that it would still be in beta?

wary edge
#

At the end of the day it's up to you whether you want to suffer now or suffer later.

ocean escarp
#

This registry is going to triple my file length at the very least...

#

And Im not too confident with splitting my scripts into different folders yet

wary edge
#

So suffer later then?

ocean escarp
#

These commands are only for testing / debugging

#

Maybe I can do without them tbh

unique apex
ocean escarp
#

Not enough content yet

unique apex
#

i see

ocean escarp
#

This project will fail anyways

#

Because I refuse to try Json UI again

unique apex
#

real i got a very basic version of what i want and i called it quits

ocean escarp
#

Im making something similar to origins

#

But cooldown bars and all that is usually UI based

unique apex
#

bleh

ocean escarp
#

I should probably store my race data as objects

#

{ name, tier }

unique apex
#

how else would you do it

ocean escarp
#

I've been doing individual arrays...

#

For each tier

unique apex
#

😭

#

do you like being in pain

ocean escarp
#

I am a masochist so probably

unique apex
#

i found it! i made this in json ui and its buggy and - it doesnt matter because it works and i love it

#

i wont ever touch it again JSON UI is hell

ocean escarp
#

Going 6 years I think now

unique apex
#

6 years for what

ocean escarp
#

I custom resource pack with actual functionality

unique apex
#

youve been thinking about making one for 6 years?

ocean escarp
#

Also prob a Lua oppsie but why cannot store data like this

ocean escarp
#

That ended prematurely

unique apex
ocean escarp
#

I wanted to store

{ Name, tier }

unique apex
#

yeah?

ocean escarp
#

Guess I'll have to store it like this

unique apex
#

yeah object of arrays seems better than an array of objects

ocean escarp
#

Not
My name is human and my tier is 1

wary edge
wary edge
ocean escarp
# wary edge

This just outputs the entire object data rather than isolating the data I want

wary edge
#

Are you planning on more data?

ocean escarp
wary edge
ocean escarp
#

I suppose that works

unique apex
#

wait is this TS and JS

wary edge
#

Maybe.

ocean escarp
#

Wait is there even a difference?

#

Wait

#

I see it

#

Not sure why class test is just an empty object tho

#
"use strict";
class Test {}
#

Does ts just not have class data?

ocean escarp
#

Huh..

#

Whaa im so lost have I been writing a mix of both the entire time then?

wary edge
#

I'm sure it's just how the transpiler is setup in this environment is all.

ocean escarp
#

Ah

#

Do I need to change what val grabs then?

#

Cause now it would grab the object and not the string

#

like can u get the names of the list entries as strings?

sharp elbow
#

Yeah, it would. Though this syntax is not doing what you'd expect for assigning stuff to RACES

ocean escarp
#

I guess I can just make an id part

#

{"id": value, "tier": value}

sharp elbow
#

So you want an array mapping an ID to some metadata? You've got a couple of options; either a 2-length tuple or a Map object.

// Map
static RACES = new Map([
  ["human", {"tier": 1}],
  ["fishman", {"tier": 1}],
  ["dunespirit", {"tier": 1}],
  ["ghoul", {"tier": 1}],
]);

rollRace(player) {
  const luck = Math.floor((Math.random() * 100));
  // The callback for Map.forEach expects the first parameter to be the map value, then the map key
  raceHandler.RACES.forEach((val, key) => {
    world.sendMessage(`${key}: ${val}`);
  }

  // ...
}
#

Map object has other advantages, like you can use the get() method to acquire a mapped entry based on a key

ocean escarp
#

I never understood why people liked maps

#

Isn't it a tiny bit complex?

wary edge
#

Complex in what way?

sharp elbow
#

A bit. Probably overkill in this scenario, since the major advantages of maps only come into play with large data sets, and here you have four entries.

#

But the semantics are still nice

wary edge
#

Every Data Structure has its pros and cons.

ocean escarp
#

If it builds good habits I'll try to get used to it

sharp elbow
#

The other approach is an array of tuples, which is very similar:

// Tuple
static RACES = [
  ["human", {"tier": 1}],
  ["fishman", {"tier": 1}],
  ["dunespirit", {"tier": 1}],
  ["ghoul", {"tier": 1}],
];

rollRace(player) {
  const luck = Math.floor((Math.random() * 100));
  // The callback for Array.forEach expects the first parameter to be the array entry
  // Here we're destructuring the tuple, first index into key, second index into value
  raceHandler.RACES.forEach(([key, val]) => {
    world.sendMessage(`${key}: ${val}`);
  }

  // ...
}
ocean escarp
#

Now my remover isn't working

#

Fixed it

#

I assume I can't add components to entities via scripts?

wary edge
#

Correct.

ocean escarp
#

I'll need a custom breath meter then

lyric kestrel
#

The after/beforeEvents and such, that's detected from packets, right?

lyric kestrel
wary edge
lyric kestrel
ocean escarp
lyric kestrel
#

What is your use-case?

ocean escarp
#

Freedom

#

Dynamic health, damage reduction

#

The whole package

ocean escarp
#

Orange the play?

junior hill
#

does anyone know if it is possible to give individual items properties

wary edge
#

Which only works on non stackable.

ocean escarp
#

I think this is a kill system?

wary edge
#

Why are you setting a property after the entity has been killed?

ocean escarp
#

Iirc they dont reset on death?

wary edge
#

They're removed on death because the entity no longer exists.

ocean escarp
#

I thought players preserve them

wary edge
#

Oh I missed the player check. You should still set it before killing.

#

It's hard to read screenshots.

#

And not even that, a picture of the monitor.

ocean escarp
#

I wish I had a better method rn i truly do

ocean escarp
wary edge
#

That's completely right. entity.getDynamicProperty('blah')

ocean escarp
#

That's weird, my custom health value isn't dropping

#

Do I need a toNumber()?

sharp elbow
#

Here is something to consider: What is the value you receive for the first time when querying a property you have never set before?

ocean escarp
#

It's been set already

#

Im reading it rn as 20

#

It's just not doing math

wary edge
#

Is it 20 or "20". How and when did you first set the property?

ocean escarp
#

Well to get to show I had to toString() but the number is set

#

Here

#

It's called on an interval once and then locked once I get a certain tag

#

Which is also given by the interval

#

How do I check for a type of a value?

#

Im going to print it to find out whats happening

cold grove
cold grove
ocean escarp
#

Is there method for killing the player

#

Entity.kill fails

cold grove
#

Wich error?

ocean escarp
#

None

#

Im just immortal.

wary edge
#

entity.kill()

#

Functions need ()

ocean escarp
#

Whoops

#

Dumbass again

cold grove
ocean escarp
#

But eh

#

I'll fix it tomorrow

distant tulip
#

faild doesn't give much context tbh

#

did it throw erros?

ocean escarp
#

None but my property went from -1 to 16 to 17
Husks deal 3 damage

#

Once it went to 0 or below I should have died but didn't

wary edge
#

Are you perchance in Creative mode?

ocean escarp
#

Nope

#

I think kill is treated as a hurt instance

#

So kill is doing 0 damage

wary edge
#

It does not.

ocean escarp
#

Its showing a value on beforeEvents

#

So it has to be doing something

granite badger
# ocean escarp I think this is a kill system?

I think it might be due to dynamic properties not updating in real time. When you set the dynamic property, calling getDynamicProperty() won't return the same value as getDynamicProperty() - damage

wary edge
#

I never had issue with having to wait 1 tick.

ocean escarp
#

Also w docs

lyric kestrel
#

Are you waiting a tick?

ocean escarp
#

I'll test tomorrow without the damage getting set to 0

#

I have a feeling it MIGHT be that

ocean escarp
warm mason
#

🍿 👀

distant tulip
#

btw, kill do trigger the event

#
import { world, system } from "@minecraft/server";

world.beforeEvents.entityHurt.subscribe(ev => {
    const e = ev.hurtEntity;
    if (e.typeId !== "minecraft:player" || e.getDynamicProperty("ps:pendingDeath")) return;

    let max = e.getDynamicProperty("ps:healthMax") ?? 20;
    let cur = (e.getDynamicProperty("ps:healthCurrent") ?? max) - ev.damage;
    ev.damage = 0;

    cur = Math.max(0, Math.min(cur, max));

    system.run(() => e.onScreenDisplay.setActionBar(`HP ${cur}/${max}`));

    if (cur === 0) {
        e.setDynamicProperty("ps:pendingDeath", true);
        e.setDynamicProperty("ps:healthCurrent", 0);

        system.run(() => {
            e.kill();
            e.setDynamicProperty("ps:pendingDeath", false);
            e.setDynamicProperty("ps:healthMax", 20);
            e.setDynamicProperty("ps:healthCurrent", 20);
        });
        return;
    }

    e.setDynamicProperty("ps:healthCurrent", cur);
});
ocean escarp
#

Just with eventually better UI

#

Curious tho, why are you setting the max health?

#

Also does this actually work well with other health values?

#

I don't see a reason why it wouldn't but I also wanna see my system's flexibility in action

#

@distant tulip

#

I think I just found my replacement for modified move speed in water

#

I can't change the components but I can apply an impulse based on conditions

distant tulip
lyric kestrel
#

I'm trying to figure out what is causing lag within a server I play on, so I'm debugging the add-ons that got added and recently updated

#

Can anbody tell me what GameDirectorEntityServer is?

#

Wait, is it an entity running a command?

#

I just don't know what type of command

#

Looking it up it says something about transitions?

ocean escarp
cerulean cliff
cerulean cliff
ocean escarp
#

Maybe it'll change soon

#

Only time will tell

fallen hearth
#

This happens when a player enters the world, but I want it to only happen once, when the world is generated:

world.afterEvents.worldLoad.subscribe(() => {
})
shy leaf
gaunt salmonBOT
crude glacier
#

Is it possible to generate NPC dialogue? Or event to check whenever a button is clicked or dialogue skipped or anything related to the NPC menu

cold grove
pliant breach
#

hello everyone is there anyway to bypass vanilla I-frame without using the damageSoruce as override or selfDestruct

pliant breach
#

i was making for guns that have fast firing time or weapon skill that dealt damage faster than the 0.5s Iframe of the game

#

but since using the damageSource like those above just ignore mob armor so i want to know if there are anyway other than that

shy leaf
#

my workaround here would be to multiply the damage by 2 if it was dealt during iframes

ocean escarp
#

How can you even test for if iframes are active?

shy leaf
#

although it probably doesnt go well if the final damage changes in any way, such as armor breaking

pliant breach
ocean escarp
#

Ah.. forgot a timer exists

shy leaf
pliant breach
#

i did remember some specific gun addon did somehow bypass that Iframe but i cant remember it name

shy leaf
#

that one most likely uses override or something

#

i forgor

pliant breach
#

also it will be much easier if i can get the armor value of the armor the mob wearing and do the damage calculation in it but there seem noway to get that kind of value for now at least

#

so i think i will stuck with the Iframe thingy for a while haizz

shy leaf
#

beforeEvents entityHurt could be fantastic for this, but theres a bug with iframes at this moment

pliant breach
valid ice
shy leaf
#

i find millisecond inaccurate because of tick delays

#

since 20 tps isnt guaranteed

valid ice
#

10 ticks, then 🗿

shy leaf
stray spoke
#

Then call it using /dialogue without even interacting to the npc

#

As long as the entity is loaded

random flint
valid ice
#

Depends on use case

#

Me, I’d use date now in this scenario because I trust my ticks

ocean escarp
#

What happens when something both functions and errors?

distant tulip
#

You were setting it to false in same tick as you kill the player
The event will trigger while it is false
-# referring to the deleted message

ocean escarp
#

Figure that out now

distant tulip
ocean escarp
#

But I am getting an error log of something being undefined but still applying correct logic

distant tulip
#

Share the error

ocean escarp
#

Line 84

#

Cannot get toString() of undefined

#

Well it clearly can cause my actionbar is updating correctly

distant tulip
#

Well, the property is not defined, but i couldn't tell you why
Can you share the whole event

ocean escarp
#

Which whole event?

distant tulip
#

nvm
Anyway the property is not defined, look into where are you settling it to undefined or not setting it at all

ocean escarp
#

You mean this?

#

I really should make a const for this

#

Or I guess it would be let here

#

This is the first location they are set

distant tulip
#

Where are you initializing the value of the property

ocean escarp
#

Right here in the above image

distant tulip
#

Make sure it actually triggers, the error shouldn't throw if it did

ocean escarp
#

I did

distant tulip
#

write that line that errors in multiple lines so you know where is the error exactly

ocean escarp
#

I did

#

It's the line with the action bar on

distant tulip
#

And?

ocean escarp
#

Wait

#

I might not have understood that correctly

distant tulip
#

One oof the properties is throwing the error

You can't tell if they are both in the same lline

ocean escarp
#

Well I fixed it

#

I guess it just didn't like me using ${v}

random flint
# valid ice Me, I’d use date now in this scenario because I trust my ticks

system.currentTick would sync with Iframes better since they're based on in-game tick (Both influenced by Lags or In-Game pause that reduce or halt the TPS). This way, it avoids desync when tracking iframes.
-# Since you mention "my ticks", I guess you got your own clock to measure ticks?

Date.now() would be better for tracking cooldown in real time regardless of TPS spike though.

ocean escarp
#

@distant tulip so I kinda caved and took a hybrid approach with player Json + scripting

#

I'm trying to figure out why it sometimes doesnt apply the health boost

ocean escarp
#

Also is there some magical restriction im missing on runCommand

#

It never seem to work on the first try

#

Always the 2nd

crude ferry
#

Average JS user.

ocean escarp
#

I cant seem to figure out to make this speed me up

shy leaf
#

wouldnt that...

#

just make you go pwoosh underwater?

ocean escarp
#

That's what trying to do

shy leaf
#

best to limit the speed cuz there isnt one there

ocean escarp
#

But no speed seems to affect it rn

shy leaf
#

players will reach light speed with that

#

oh wait

#

no i looked at the code wrong

ocean escarp
#

I don't know why my multiplier isn't multiplying

shy leaf
#

try printing out the values in actionbar for debugging

#

also, did EntityUnderwaterMovementComponent not work?

ocean escarp
#

So far I'm only using 2 health events to get anywhere between 1 and 512 hearts

ocean escarp
#

Because I plan to make programmable origins eventually

#

needs to be data driven

#

Or whatever the term is

shy leaf
#

i mean you can still do that with the component

#

feels like youre going for hard ways

ocean escarp
#

Well yeah but I would need like 8 events and component groups which will probably already double the file length

shy leaf
#

yeah like

#

nothing wrong with that, unless its physically limited

ocean escarp
#

Im not sifting though 3000 lines of code to fix 1 typo

shy leaf
#

you can divide files

ocean escarp
#

I can't divide player.json

shy leaf
#

one file does this thing, one file does that thing

shy leaf
#

what

#

how many lines does your player.json have

ocean escarp
#

Not much right now because I'm optimising

#

Adding that water move speed thing would double its size

shy leaf
#

. . . ?

#

why would it?

distant tulip
#

dude is overcomplicating everything

ocean escarp
#

It's a script API thing...?

shy leaf
#

...yeah

ocean escarp
#

I thought we couldn't use components??

shy leaf
#

these are what you can edit

#

there might be some entity components that arent attributes that you could edit, but i havent tested

ocean escarp
#

Well that changes a few things now..

distant tulip
granite badger
#

I forgot I added this, thoughts on this?

shy leaf
#

whats that

#

oh

#

that? this Details thing

granite badger
#

I mean the source TS block, just for some people who want a quick overview of the class

shy leaf
#

ah yeah

ocean escarp
#

This is all I need?

shy leaf
#

its neat but i keep overlooking it cuz of how small it is

#

i had to do a double take to find where the source block is at 😭

ocean escarp
#

Odd, I pass number to my function and got a type conversion error?

shy leaf
#

.

#

where are you putting the .toFixed(0) at

ocean escarp
#

I need to actually quit

shy leaf
#

relatable

ocean escarp
#

Tf you mean not a function?

#

Oh

#

I uhh forgot to change the 2nd 1

crude glacier
cold grove
crude glacier
#

Using custom commands

#

You create a command that lets you handle dialogue buttons

#

And then run it using the dialogue buttons

lyric kestrel
lyric kestrel
random flint
shut citrus
#

anyone know why "cannot read property 'Symbol.iterator' of undefined" is in content logs?

open urchin
random flint
stray spoke
#

I didn't know spread operator can be used in itirator

#

Since Map toArray() method doesn't exist on quick js

#

I used for of loop

lyric kestrel
gaunt salmonBOT
fickle dagger
#

what's the best way to make a runTimeout function that repeat multiple times?

#

example:

system.runInterval(() => {}, 5);
system.runInterval(() => {}, 15);
#

I tried using a for loop, but that seems to crash the game

#

hmm

#

I wonder if runInterval is better for this?

pliant breach
#

use runInterval if you want to cancle the loop midway

fickle dagger
#

yeah I'm trying it out

lean badger
#

is there anything like that now?

distant tulip
#

yes

crude glacier
#

Guys what the min-minecraft version i must use in manifest to get detected by bridge

remote oyster
crude glacier
#

Hmmm

cinder shadow
#

Anyone know what could cause a triggerEvent error saying it is undefined on an entity when that entity event clearly exists?

#
const mimic = dimension.spawnEntity('runecraft:ore_mimic', {x: location.x + 0.5, y: location.y, z: location.z + 0.5})
    .setProperty('runecraft:texture', mimicId.entityProperty)
    .triggerEvent('become_hostile')```
#

not sure if it's some runtime issue of the enttiy just spawning or something else, but setProperty works immediately

#

mk, I guess chaining these together doesn't work as I thought

#

I think setProperty() was changing what the entity was

winged drift
#

setProperty returns void

#

so dimension.spawnEntity returns Entity, setProperty is then being called on that entity wich returns undefined and then minecraft tries to call triggerEvent on undefined

lyric kestrel
#

Try setting property afterwards in a system.run so it happens in the next tick

lyric kestrel
#

Ohhh

#

Woops

earnest meadow
#

:D

frozen vine
#

The API has tag fields in the entity; is this tag the family tag or something internal?

earnest meadow
frozen vine
#

I thought it was the tag that's in the mob's json file, in the case of Bedrock Sendono Family.

lyric kestrel
#

Not the nametags

frozen vine
lyric kestrel
#

Yes, it can be

#

It's all tags an entity has

#

Excluding nametags*

frozen vine
lyric kestrel
#

I didn't test it on any entities with families

#

So that part I don't know

#

Sorry

#

Wait, does the player entity have a family?

#

If so, then it doesn't detect families

frozen vine
lyric kestrel
frozen vine
stable shadow
#

Is it possible to detect arrows with an effect using a script?

wary edge
#

Its nothing internal.

wary edge
stable shadow
crude ferry
#

Pretty sure getEffect works on arrows as well.

frozen vine
crude ferry
#

Oh you mean the items.

frozen vine
stable shadow
wary edge
stable shadow
#

item

wary edge
#

Unfortunately, no.

#

To my knowledge anyways. You could do it via runCommand and test every data value with hasitem.

frozen vine
stable shadow
#

That's a shame, I was creating an API that saves everything in the dynamicProperty.

stable shadow
frozen vine
# wary edge No its from /tag

Ah yes, thank you, I was really confused, and apparently ikorbon had used it wrong. Well, thank you for the explanation.

frozen vine
stable shadow
frozen vine
frozen vine
olive sphinx
stable shadow
worldly heath
#

is there any difference between block.x and block.location.x ?

snow knoll
worldly heath
#

ah thanks

snow knoll
#

Np
Its better to use block.x as opposed to block.location, since using .location is slower

lyric kestrel
#

Is there a block.x?

fresh comet
#

Yes lol

#

but It's more clean to use block.location in my opinion

crude glacier
#

Guys i know it is a weird question

naive frost
#

Guys i know this is a question

marble sigil
# stable shadow item

You can use itemName.localizationKey
It gives the potion effect name indirectly, however, it does not include the amplifier.
Then, make a simple if (x) return y; chain.

The localization key is something like tipped_arrow.effect.{x}.

From the en_US.lang:

tipped_arrow.effect.empty=Tipped Arrow
tipped_arrow.effect.mundane=Tipped Arrow
tipped_arrow.effect.thick=Tipped Arrow
tipped_arrow.effect.awkward=Tipped Arrow
tipped_arrow.effect.nightVision=Arrow of Night Vision
tipped_arrow.effect.invisibility=Arrow of Invisibility
tipped_arrow.effect.jump=Arrow of Leaping
tipped_arrow.effect.fireResistance=Arrow of Fire Resistance
tipped_arrow.effect.moveSpeed=Arrow of Swiftness
tipped_arrow.effect.moveSlowdown=Arrow of Slowness
tipped_arrow.effect.water=Arrow of Splashing
tipped_arrow.effect.waterBreathing=Arrow of Water Breathing
tipped_arrow.effect.heal=Arrow of Healing
tipped_arrow.effect.harm=Arrow of Harming
tipped_arrow.effect.poison=Arrow of Poison
tipped_arrow.effect.regeneration=Arrow of Regeneration
tipped_arrow.effect.damageBoost=Arrow of Strength
tipped_arrow.effect.weakness=Arrow of Weakness
tipped_arrow.effect.levitation=Arrow of Levitation
tipped_arrow.effect.luck=Arrow of Luck
tipped_arrow.effect.wither=Arrow of Decay
tipped_arrow.effect.turtleMaster=Arrow of the Turtle Master
tipped_arrow.effect.slowFalling=Arrow of Slow Falling
tipped_arrow.effect.infested=Arrow of Infestation
tipped_arrow.effect.oozing=Arrow of Oozing
tipped_arrow.effect.weaving=Arrow of Weaving
tipped_arrow.effect.windCharged=Arrow of Wind Charging

So, if you want to check if an arrow is Strength:

if(itemStack.localizationKey.includes('damageBoost')) {
  world.sendMessage('Strength effect');
}

Or if it is speed:

if(itemStack.localizationKey.includes('moveSpeed')) {
  world.sendMessage('Speed effect');
}
lean badger
distant tulip
#

🤷‍♂️

#

imo it is best to keep yourself up to date from changelog

patent heath
#

If I wanted to make a skill tree menu would I model it via scripting?

junior hill
#

Can i carry properties between items using “lore”?

#

Like holo scope for a gun

#

Label it in the lore and use that to carry between players using properties in player.json to be activated in rc

#

Unless there is another way to activate it in the rc

last latch
#

I hardcoded the positions in JSON UI

#

but it is possible to make one with dynamic positions with scripting.

#

it all depends if you need new skill trees and you want to code it (or commission someone)

#

(i thought it was json ui channel mb)

stable shadow
#

Is there a way for me to trigger the onEntity event of the customComponent block from the entity in any way I want? For example, if I interact with the entity, it triggers this event and the block receives an interact event.

wary edge
#

onEntity only triggers for entity components that have a block trigger. Such on_reach for move to block.

#

Maybe...the creaking/heart has a componeny that ties data, but not entirely sure. What you can do is tie a dynamic property to the entity.

open urchin
#

The block would have to be set at as the entity's home

#

Then you could use execute_event_on_home_block

dense wraith
#

One message removed from a suspended account.

dense wraith
#

One message removed from a suspended account.

ocean forum
#

Is there a way to forcefully close a gui that is active on a players screen?

somber cedar
woven loom
#

Is there any tool that can tell me what is the minimum API version required to run my code?

frozen vine
#

Is it possible to check if a mob has any families using a script? Or only through commands?

snow knoll
#

How should I go about detecting right-click and holding right-click separately, on the same item?

wary edge
stray spoke
#

I think swing after event can also help

snow knoll
# wary edge Have a use modifier to detect the use duration.

I'm currently using itemStartUse and itemStopUse to detect when right click is being held, to make a function to constantly fire
How does useDuration in itemStartUse actually work?
Does it return a value after you let go of the interact button, or does it work as the button is being held, since startUse only fires when the item is first held

wary edge
stray spoke
#

That's for holding right-click

wary edge
stray spoke
#

while right-click while empty hand is detectable only by swing event in script ig

wary edge
stray spoke
#

Ohh, I thought same right click, just no items

#

coz how could you differentiate it

snow knoll
wary edge
snow knoll
#

I want to be able to right click an item and it does something once, or hold right click and and start a runInterval that ends when I let go of interact

wary edge
snow knoll
#

Bingo
I can't believe I used so many more words

wary edge
#

Custom or Vanilla Item?

snow knoll
#

Custom

wary edge
#

I would have itemUse to trigger A and have itemStartUse have an interval, save the run id and when itemStopUse is called, clear the run.

snow knoll
#

I've already got the itemStartUse with its interval and all
I've just been integrating a secondary function into it
Can I make itemUse not fire with itemStartUse simultaneously?

wary edge
# snow knoll I've already got the itemStartUse with its interval and all I've just been integ...

https://github.com/Mojang/bedrock-samples/blob/main/metadata/engine_modules/engine-after-events-ordering.json

This is the ordereing, I dont think its entirely useful. In my opinion then, I would have a tick check, if the item hasnt stopped use after 2 ticks, trigger B, else trigger A.

GitHub

Samples and assets for building Minecraft: Bedrock Edition add-ons - Mojang/bedrock-samples

dapper smelt
cold grove
marble sigil
#

if we apply a effect, like slowness to an flying arrow, will whoever who gets hit by it get the effect? Or no?

random flint
#

I don't think arrow can be inflicted with potion effects. Tipped arrow also doesn't really "affected" by their potion effect when shot, they only act as the "carrier" of the effect which is tied to their data itself

marble sigil
#

Is it possible to detect when a player makes a nether portal?

distant tulip
#

Item use on obsidian and detect a valid structure or wait for a nether portal block

marble sigil
distant tulip
#

Player interact with block

snow knoll
#

That's a better idea

marble sigil
#

But there's not just one way.
Some players make with flint steel. Others use fire charge.
Then some use speedrunning tricks like lava and wood, I'm talking about those cases.

distant tulip
#

That is true

#

Well

#

Unless you want to tick the whole world looking for a portal block, there is no way

#

Or just check block in player view

cerulean cliff
#

ngl a player.swing() would be cool

thorn flicker
crude ferry
#

What would that do lol?

distant tulip
#

swing the player arm

cerulean cliff
#

Biggest use case I can think of rn is how a player either always swings their arm if a block is interactable, or never if it isnt

shy leaf
#

we need api to cover every use case tbh

#

if theres a thing that detects an action

#

there should be a thing that makes an action

#

like
entityHurt <-> applyDamage

earnest meadow
#

are scripts ran in the same environment across multiple packs?

dapper copper
thorn flicker
shy leaf
#

yeah we dont have that...

#

maybe they forgor? or maybe they are considering it but polishing it first

wary edge
#

Clueless Just edit the healt component.

thorn flicker
#

i mean we can heal, but not in a way to detect it in entityHeal.

wary edge
thorn flicker
wary edge
#

Ok. 👍

wary edge
shy leaf
#

true

#

ive seen totemofundying as heal cause

#

...thats so specific

wary edge
#

@charred dune actually asked for that.

shy leaf
#

oh hmm

#

still quite specific though, how does it work?

wary edge
#

It detects totem of undying.

#

Like...

shy leaf
thorn flicker
#

lol

shy leaf
#

why did i even ask that

#

wait

wary edge
#

Yes totem of undyings are a thing.

shy leaf
#

what if you cancel totem of undying from entityHeal

thorn flicker
shy leaf
#

i think its in preview

thorn flicker
#

ah

shy leaf
#

as beta api

shy leaf
turbid gulch
#

can we use rawtext in console.warn?

charred dune
subtle cove
#

-hp to 1hp

#

entityHeal triggers 1st

fallow rivet
#

Is it possible to create a skyblock island system using custom dimensions?

junior hill
#
player.applyDamage(3, { cause: "magic" });```
#

is there a better way to have the damage ignore armor?

#

i dont like how it says killed by magic when dead

fallow rivet
junior hill
fallow rivet
#

1sec

fallow rivet
#

Is this possible?

junior hill
#

O i see prob wont be practical due to im making a medical mod

#

Ig stick with what i have atm works fine for now as a beta

vast rune
#

yo how do dynamic properties work exactly?
i need to save objects from a custom class in a script that get created whenever a player places a block

#

im guessing i stringify it and store it in the world but idk if thats right

#

since im going to be generating these objects and multiple of them will be in the world, how would i be able to retrieve them? i cant auto generate values or something like that

#

like, how can i figure out the key for each object if i dont know what they are

wary edge