#Script API General

1 messages · Page 21 of 1

simple zodiac
#

are you not writing libary code?

#

its a good practice

wary edge
#

Sure...but in Nikkis case...it is unlikely shes writing a lib for other users

sharp elbow
#

Still good to sanity check yourself too

buoyant canopy
simple zodiac
#

yeh ik

neat hound
#

it is for a library file

#

fake class

shy leaf
#

does anyone have a code that changes x angle (in Entity.getRotation().x) to x and z in vector3

sharp elbow
#

I have this bit still in my program meant to ... remind me to fix it, if it ever does break

shy leaf
#

mine just broke for some reason

sharp elbow
#

The y-rotation I could understand

neat hound
#

isn't what x/y means diff

shy leaf
#

waaait

buoyant canopy
shy leaf
#

i mean like

neat hound
#

one for where looking up/down , other for body angle

sharp elbow
#

You're wanting an atan2 function of some kind(?)

shy leaf
#

changing it into radian or something (i dont do math)

#

and my school wifi died again

shy leaf
#

cant believe i forgot about that even though my first ever project used it 💀

sharp elbow
#

Actually, atan2 would be the reverse process—turning a position into an angle. You want to turn an angle into a position

shy leaf
#

did my school wifi die again

#

oh it didnt

sharp elbow
#

That would be plugging the rotation into Math.cos and Math.sin for z and -x, respectively, the angle being multiplied by π/180 (approx 0.0174532925)

shy leaf
#

neato, ty

#

(also did you memorize that number)

sharp elbow
#

Nah, pulled up my calculator on Windows and crunched it

shy leaf
#

ah

sharp elbow
#

Although I do recall pi up to maybe the 8th 18th digit

neat hound
#

Sprunkles.. I kinda FF thru the JS throw error part of class... what is the best way for the API... just console.error? or actual throw?

sharp elbow
#

I actually don't know what console.error does. Other than log something

neat hound
#

LOG FILE

#

I mean, that is where the erros pop up

wary edge
#

Its the same as .warn or .log

neat hound
#

mc js, has no .log

#

sad

wary edge
neat hound
#

my logs have to say warn

sharp elbow
#

The throw keyword terminates script execution from the point it is at. The end user would need to wrap the function in a try ... catch expression to prevent it from causing problems

neat hound
#

nothing shows up when I use... I tried them all... or does the log say warn.. I forgot..

wary edge
neat hound
#

oh

sharp elbow
#

throw is good if someone is trying to do an illegal operation. Various scripting API calls already can throw errors, and scrupulous developers will use try .. catch to account for that failing

neat hound
#

yay

sharp elbow
#

Even better if you make your own Error subclass as part of a broader API design. I don't know enough about using that though

distant tulip
#

i use try catch only if there is a lot of things that can go wrong

neat hound
#

I just use my primitive js class ConsoleAlert { prefix = `§d${pack.packName}§r`; log (msg = '', debug = true) { if (debug) console.warn(`${this.prefix}: ${msg}`); } success (msg = '', debug = true) { if (debug) console.warn(`${this.prefix}: §aSuccess: ${msg}`); } warn (msg = '', debug = true) { if (debug) console.warn(`${this.prefix}: §6Warning: ${msg}`); } error (msg = '', debug = true) { if (debug) console.error(`${this.prefix}: §cError: ${msg}`); } }; //============================================================================== class ChatMsg { prefix = `§b${pack.packName}§r`; log (msg = '', debug = true) { if (debug) world.sendMessage(`${this.prefix}: ${msg}`); } success (msg = '', debug = true) { if (debug) world.sendMessage(`${this.prefix}: §aSuccess: ${msg}`); } warn (msg = '', debug = true) { if (debug) world.sendMessage(`${this.prefix}: §6Warning: ${msg}`); } error (msg = '', debug = true) { if (debug) world.sendMessage(`${this.prefix}: §cError: ${msg}`); } }; //============================================================================== export const alertLog = new ConsoleAlert() export const chatLog = new ChatMsg()

#

I use for errors and debuging

#

I'm started to develop my own style for my addons to keep me consistent and easy to set up a new one. I do a settings.js to turn on/off stuff for testing and the code above is in there (which I should centralize)js export const pack = { packName: 'Tree Spider', isLoadAlertsOn: false, hasChatCmd: -1 }; //============================================================================== export const dev = { debugAll: false, debugCallBackEvents: false, debugChatCmds: true, debugEntityAlert: true, debugGamePlay: true, debugPackLoad: false, debugSubscriptions: false };

#

I am currently working on a tree spider... getting the json and scripting all lined up to make a little spider that goes all over and makes webs in trees and on plants... was a fun challenge...

#

move_to_block... was... fun...not

buoyant canopy
#

i find the try keyword useful for just silencing errors

#

for example i use it to test if a chunk is loaded, if it's not then it will throw an error that i just silence with js try {} catch (error) {null}

neat hound
#

Smokey... is system.run same as system.runTimeout with a 0 tick delay?

#

interchangeable?

distant tulip
#

one tick

neat hound
#

isn't system run, end of current tick

sharp elbow
neat hound
#

so you are saying timeout defaults to one if less than one?

sharp elbow
#

The system.runTimeout function behaves much like system.run except that it offers a new parameter that lets you indicate how many ticks into the future it should run. If that future tick is 0, it means the current tick or as soon as possible. If the parameter is 1, it behaves much like the standard system.run. A value of 2 means to skip the next tick and execute on the one after.

#

Be careful with a time of 0 in system.runTimeout. It can run immediately—treat it with the same level of care as you would functions and recursion

shy leaf
# shy leaf neato, ty
export function viewDirection(player) {
    const viewCenter = {
        x: player.location.x-((Math.sin(player.getRotation().y*(Math.PI/180))*1.2)),
        y: ((player.location.y+player.getHeadLocation().y)/2),
        z: player.location.z+((Math.cos(player.getRotation().y*(Math.PI/180)))*1.2)
    }
    return viewCenter;
}```
ill never get used to math
#

ever

#

at least it works

sharp elbow
#

pro tip: store the y property from player.getRotation() and incorporate that in your calculations to make it faster

neat hound
#

what if -1... all hell breaks loose?

neat hound
#

I should at least error check that

shy leaf
#

im organizing it later

sharp elbow
#

So you can force someone to enter a universe where there's a warzone in their own neighborhood, or one where a black hole is headed toward earth in 90 days

#

No ... more likely that it either treats it as 0 or throws an error

neat hound
#

So...I can build a timemachine add-on....

#

Sprunkles tells a joke... it is a new day....

sharp elbow
#

I'm not that bad of a drag! Am I? bao_foxxo_crying

neat hound
#

no... You are just gushing fountain of knowledge and I have never seen that side of you

#

and a no nonsense but very fair person...

#

was a great admin

#

fan club member

remote oyster
# neat hound what if -1... all hell breaks loose?

Fun fact, if you define the default value for a drop down in a new instance of ModalFormData in server-ui with -1 it will not select an element from the array by default when you select the submit button. Thus, allowing you to not enforce a selection and rather offer an alternative such as an input from a text field.

dropdown(label, options, defaultValueIndex?): ModalFormData

Example:

modalForm.dropdown('Dropdown w/ default', ['option 1', 'option 2', 'option 3'], -1);

That parameter is optional so even if left undefined or directly passing undefined it will default to the first element in the array unless you explicitly pass it a negative value.

neat hound
#

Good to know.. whenever I venture that way... I will hit you up for your knowledge

#

but I will try -1 on runTimeout to see what happens for real tho... just so I know and can say I know.. LOL... unless Sprunkles was right and I go back in time... then,... gateKeeping that knowledge...

distant tulip
remote oyster
distant tulip
#

you just " figured it out" lol
how do you even do that

neat hound
#

usually by mistake

remote oyster
#

Nah, this one was intentional lol. Literally thought about it, plugged it in, ran a test build in a BDS environment, then confirmed it and was satisfied 😂

neat hound
#

Should negative one everything... see what happens... I'd like to buy that for -1 dollars....

remote oyster
#

Stumbled across it some days back. Can't remember exactly when. It was recent. Needed it because of how I dynamically build the GUI when called.

distant tulip
#

you should add it as a note in some of the docs

neat hound
#

as they say, necessity is the mother of invention...

remote oyster
#

August 31st is when I discovered it. Just checked my commit on GitHub lol.

neat hound
#

but what really happened is that his intention to find a solution was strong and his higher self put the answer in his field of potentiality for him to pluck out...

#

happens to me all the time

remote oyster
#

Still working on my GUI. Making a script that dynamically builds it based on the design of your other scripts built with command-line in mind has been a task.

remote oyster
neat hound
#

You can contribute to the wiki... see Llama/Smokey

gaunt salmonBOT
#

Description
Demostration of showing another Minecraft UI form after a player confirms or cancels the dialog.

Credits
These scripts were written by FrankyRayMS

random flint
#

getBlock() returns undefined if the block is an unloaded chunk.
While the Block class that isn't valid anymore can be tested with isValid()

fair quarry
#

Does someone know some workarounds to make something like "world.beforeEvents.entityDie"?

#

Cuz only the afterEvents exists

valid ice
#

Cancel all damage via damage sensor, apply damage & needed effects via entityhurt/entityhit events

random flint
fair quarry
#

K, thx I'll try

buoyant canopy
random flint
#

Use what you want, it's your code after all. I'm just telling you that silencing errors with try and catch is bad practice

fiery solar
random flint
#

-# well you asked for it, so...

neat hound
fiery solar
# neat hound Uncalled for. You can keep comments like this to yourself, especially since you...

Sorry, I worded that poorly. I didn't mean to offend. It was a genuine invitation to encourage people to post for math-related help in the channel. I have a math degree and was a college math tutor for years so I wanted to let people know that there are people that would be willing to help with the complex math part even if it's not strictly script API related. (Also didn't realize how long it had been)

true isle
#

if that makes sense

random flint
neat hound
# true isle so question then, is there a way to check a 6x6 for blocks and place a block on ...

You can use the getBlocks() based upon a location, Took me a minute to figure out how to use it for my Tree Spider... but here is a small sample.```js
/**
* @param {Dimension} dimension
* @param {import("@minecraft/server").Vector3} location
* @param {number} [radius=1]
* @returns {import("@minecraft/server").Vector3[]}
*/
static blocksAround_locations (dimension, location, radius = 1, filter = {}) {
const atBlock = dimension.getBlock(location);
if (!atBlock) return [];
if (radius === 0) radius = 1;

    const bottomOffset = atBlock?.offset({ x: radius * -1, y: radius * -1, z: radius * -1 });
    const topOffset = atBlock?.offset({ x: radius, y: radius, z: radius });
    if (!bottomOffset || !topOffset) return [];

    const blockVolumeDef = new BlockVolume(bottomOffset.location, topOffset.location);
    const blockVolumes = dimension.getBlocks(blockVolumeDef, filter, true);
    return [ ...blockVolumes.getBlockLocationIterator() ];
}```the filter object can take a few properties```

excludePermutations
excludeTags
excludeTypes
includePermutations
includeTags
includeTypes```Once you have the location array back, you can get blocks. If this is of interest, I can post the other 2 functions I made.
I currently use it to find the air or web blocks around a location.
This example is a cube, but can be converted for 2D with the blockVolumeDef...
So for example, if for like bonemeal, do 2D, filter on grass block, get array back, randomize and take a few of the locations for conversion

random flint
#

Isn't bonemeal use radius?

#

...in spherical shape

#

Smokey—I mean, Llama has bonemeal script: #1067870355814895687 message

still sorrel
#

Hey, if anyone can help me that'd be great!

How can you script something like this (if it's even possible):

  1. Place a block down and it detects the exact same block to the left or right of it
  2. If the same block is to the left of the block, with the same rotation and has a certain texture on, change the texture of the current block to different one
  3. If the same block is the right of the block, with the same rotation and has a certain texture on, change the texture of the current block to different one
  4. If both same blocks are on the left and right of the block, with the same rotation and has a certain texture, change the texture of the current block to a different one
slow walrus
#

yes it's possible

#

with block permutations

still sorrel
#

Thanks thumbs_up_AE

neat hound
#

but right and left will be relative to where the player is standing/facing....

still sorrel
#

Not the block?

neat hound
#

not sure y ou can test for texture. You may need to keep a property in there to stand for texture.

still sorrel
#

Alright, but the right and left needs to be relative to the blocks position, is that possible?

neat hound
#

it matters because if I am facing west... north is my right

still sorrel
neat hound
#

what do you mean by block position... but if it is data captured within a state/trait/property... you can test for it in permutaions

still sorrel
#

The glow lichen in the middle will test for the block to the left and if so it will change it's texture. Same for the right.

#

Is that possible?

neat hound
#

are you trying to get it to not look the same?

#

if it is a block, there is a auto way for that

still sorrel
still sorrel
neat hound
#

well connected blocks, is not the same thing as variation/randomness

#

Iif I recall correctly.. it is done via blocks.json

still sorrel
#

Yes, I'm trying to do connected blocks, sorry.

neat hound
#

you can look at code for connected blocks like that above.. it will have kinda what y ou need

still sorrel
#

Sort of like fences but instead of geometry changing, it's the texture.

neat hound
#

search the discord.. Kaioga and Smokey have githubs with code and check #1067535712372654091

still sorrel
#

Thanks! thumbs_up_AE

shut citrus
#

how to displays an advancement-like "toast" message to all targeted players?

shut citrus
#

how to test how far above the ground the player is?

scarlet sable
#

Good morning

chrome flint
#

how many dynamic properties can an entity have?

#

and how do i delete an existing one

distant tulip
slow walrus
#

there's no limit on the amount of dynamic properties

#

there's a limit on the sizes

distant tulip
#

keys too

slow walrus
#

yeah sizes is key & values

distant tulip
#

you will run out of keys eventually

chrome flint
#

alr

#

how do i remove a certain dynamic property

distant tulip
#

set it to undefined

proud cliff
proud cliff
slow walrus
#

what is 32767^65536

still sorrel
distant tulip
#

still limited

slow walrus
#

essentially infinite

proud cliff
distant tulip
still sorrel
slow walrus
#

there's a higher chance the monkeys will type hamlet than you running out of keys

#

lmao

distant tulip
#

yeah but it is still limited 🤷‍♂️

slow walrus
distant tulip
umbral scarab
#

Am I able to add a cooldown to any item? Or is it just once with already existing cooldowns (ender pearl etc)? This is without creating a custom entity btw

shy leaf
#

though you cant add your own cooldown on vanilla items

umbral scarab
untold magnet
#

sup, i want to make a limit of how many entities can be spawned, .playerPlaceBlock will spawn an entity after the player places a specific block, i had to make a limit of those entities, like placing 50 of that block will spawn 50 entities, but it will not spawn entities after it reaches the limit

#

what method should i use for that?

#

tags? properties?

shy leaf
buoyant canopy
buoyant canopy
amber granite
#

@untold magnet

#

U can make a global variable

#

And then put the event or the event that spawns in it with if statement

#

Then save it every 10 blocks and 5 blocks in dynamic proprety

untold magnet
#

@amber granite j didn't get it

amber granite
#

Like this

let mobsNum = world.getDynamicProprety("mobsNum") ?? 1 ;
const limit = 50;
if ( mobsNum != limit ) {
//Put ur event here then save the number in dynamic proprety and retrieve it later
}
amber granite
#

Give me ur event

#

What event do u use ?

untold magnet
#

uh, wait

#

that script will not spawn the entities, right?

amber granite
#

After 50 ?

#

Yes

untold magnet
#

alright so i dont need an event

#

i have to make it limited

amber granite
#

What ?

#

No

#

@untold magnet

#

U need increase the variable inside the event whenever the mob spawns

untold magnet
#

hmm

untold magnet
#

the system should stop spawning entities after spawning 50 of them, and the number of those entities should decrease when one entity is died

#

this should work? js world.afterEvents.playerPlaceBlock.subscribe(({ block }) => { if (block.typeId === 'my:block') { block.dimension.spawnEntity('my:blockEntity', block.center()) for (const entity of block.dimension.getEntitiesAtBlockLocation(block.center())) { let amount = entity.setDynamicProperty('limit') ?? 1; const limit = 3 if (amount != limit) world.sendMessage('Hi') } } })

#

no its not

keen folio
#

anyone help me with #1283463196728102953

alpine ibex
#

Does anybody know how to kill a mob with min HP? I like to kill them when they are 1HP they don't die for a amount of time like 2 seconds then after those they are killable also they can't be killed after /kill while in the state

wanton ocean
#

Could do damage sensor for fatal damage

alpine ibex
wanton ocean
#

It has damage sensor stuff in it

scarlet sable
#

hello

neat hound
#

but that is for loaded chuncks

#

so tech can have more than 50 in world if move far away

neat hound
alpine ibex
neat hound
#

no one but a player can survive /kill

alpine ibex
#

Just by adding a min: on

minecraft:health
value: 20
min: 1
They can survive /kill
neat hound
#

is that a bug

#

what is the point of having a command to kill when it cannot kill

alpine ibex
neat hound
#

I would not count on something like that as permanent

alpine ibex
neat hound
#

if I do a /kill @e[whatever selectors]... it is because I am testing and they better f'n die

alpine ibex
#

Wanted to recreate it

neat hound
#

do a custom command

#

can your players use slash commands

alpine ibex
#

No

sharp elbow
#

/kill inflicts a mind bogglingly large amount of damage. In Java Edition I believe it is MAX_FLOAT, probably something similar in Bedrock. No amount of damage can defy a minimum health value, though

#

The health will ever only go as low as the minimum value set; so if that value is greater than 0, the entity cannot die by any conventional means

alpine ibex
sharp elbow
#

Well, those are not killing the entity. Despawning simply removes it

#

I imagine the .remove method in scripting can remove it just fine too

alpine ibex
#

But I need to it die after a few secs by being able to deal damage to it tho

sharp elbow
#

With the minimum health set, that effectively becomes the lowest health. You would need to implement your own death animation and removal when the entity reaches that minimum health

neat hound
#

put the real kill event in runTimeout.. with a 40-60 tick delay

sharp elbow
#

Aw this article is useless here.

#

I thought it would have had a section for what I described

alpine ibex
#

I needed transform thing for my other mob

alpine ibex
#

I would credit anyone that could help me with it

#

With my addon

neat hound
#

try the environment sensor.... see if a filter for health, then run an event to do what you want

frozen vine
#

Is it possible to receive an effect and have it not appear in the effects hud? Are they hidden?

unique dragon
#

i think it's only possible using like 5 ticks

#

idk

frozen vine
unique dragon
#

so yes, it's using a smol number

#

but idk if is still working

#

for me before it was working

#

like 3 releases ago lmao

frozen vine
unique dragon
#

1 second is too much

untold magnet
#

i mean

untold magnet
# untold magnet i mean

after the player placed 50 blocks each block will have an entity, the script will test for how many entities are in the world, if there are 50 entities it will be detected and run a function after placing the same block ( the 51 entity will be removed )
||hoping i explained it right||

untold magnet
#

for (const entity of block.dimension.getEntities()) { ,,, }and?

wary edge
untold magnet
wary edge
#

No

#

Please read the docs

amber granite
#

@untold magnet

untold magnet
amber granite
#

U did it the wrong way

#

U didn't even increment the variables

untold magnet
#

ik

amber granite
#

Or changed the name

#

Of the property

#

That must be setted

frozen vine
amber granite
#

Like this

let mobsNum = world.getDynamicProprety("mobsNum") ?? 1 ;
const limit = 50;
if ( mobsNum != limit ) {
//Put ur event here then save the number in dynamic proprety and retrieve it later
world.afterEvents.playerPlaceBlock.subscribe(({ block }) => {
  if (block.typeId === 'my:block') {
    block.dimension.spawnEntity('my:blockEntity', block.center())
  
      mobsNum++;
world.setDynamicProprety("mobsNum" , mobsNum);
 
})
}
untold magnet
#

if the script detects 50 mobs it will run a function

frozen vine
amber granite
#

And every 20 ticks = 1 sec

amber granite
#

Because after exceeding the limit of 50 the event won't ever trigger= more performance

#

@untold magnet

untold magnet
#

the number of those entities should be degreasing when the entity is dead, i mean after i reach the limit i cannot spawn more entities, but when i killed some entities i will be able to spawn them u know what i mean

amber granite
#

Ah , so don't want to shut down ur event for ever ?

#

That remove the if statement

#

And add new event

#

Instead of the iterations

untold magnet
#

my brain not braining

amber granite
#
  • put if statement inside the playerPlaceBlock event
neat hound
#

Should write a reusable function to count a certain entity period and add to a library of functions, organized your way, and then call it when you need it. It should either return a number or the array...... tech should have 2, one that returns the array and the one that returns the number calls the array one and you just return the count......

amber granite
#

X2 my brian isn't braining

neat hound
#

reusable code...

amber granite
#

Yeha but it doesn't need functions

#

U know

#

One variable and two events

neat hound
#

if you say so.... whatever

amber granite
#

Yeah

neat hound
#

Which route to take will depend on several things.... if 50 is a world limit or a loaded limit. What if 2 players are doing this.... is it 50 period.... so @untold magnet .. if 50 period, no matter when, loaded or not loaded, do dynamic properties at world level... if loaded or just around a player... then can do dynamic on the player or do a local count.

#

a flow chart helps

#

when its too big

amber granite
#

U mean whether to handle the total of 50 mob for the whole world
Or 50 mob spawning ability for each player

neat hound
#

spell out the rules

amber granite
#

@untold magnet

neat hound
#

or what if 2 players in same area

#

all scenarios must be accounted for

#

3 players doing this far apart, then one logs off with 20 down

untold magnet
#

is it really important to have a limit?bao_comm_dead

neat hound
untold magnet
#

to provide lag from that dumb friend, yes but if ur friend kept placing the same block 200+ times, just kick him out the server

neat hound
amber granite
#

You are bedrock player

neat hound
amber granite
#

And others are bedrock's players too,
That means they are likely to be playing or android or ios ( mobiles )

neat hound
untold magnet
amber granite
#

☠️

neat hound
#

make sure you are on right version.. but any should be fine for this one

neat hound
untold magnet
amber granite
#

So , 50 blocks in total is the limit across all the players and in the whole world?

#

Or every player can spawn 50 mobs

untold magnet
amber granite
#

U want to limit bro

untold magnet
amber granite
#

So

#

More questions

#

The entity gonna die when u destroy the block oy right ?

untold magnet
#

the entire world has a limit of 50 entities

amber granite
#

Hmm no other factors will kill it right ?

neat hound
#

so chickens.... and cows added to your block and players.... all just 50?

amber granite
#
  • Did u write an playerBreakBlock event or other events like blockExplode to hande that ?
untold magnet
neat hound
#

just run a thing.... killing random over 50

amber granite
#

Why ?

neat hound
#

in that case of lag, loaded is what is important

untold magnet
#

i can make a system that will automatically kill the entity after it is out of the block

amber granite
#

So if u break the block ur system will detect that

#

And kill the entity

#

Is that system is made with script api ?

neat hound
#

what is this for, that helps to figure out the best way to do something... do you want the entity for anything, or is it there so you know some info?

#

What are you trying to stop?

untold magnet
# amber granite Is that system is made with script api ?

look bro, theres so many ways u can destroy the block with, i dont have to make each way has it own system, i should just make a system that will test if the entity is inside the block, and if it wasn't inside the block it will be automatically killed

amber granite
untold magnet
amber granite
#
  • that s smart , i really made events for all those cases ☠️
#

I mean that s the smartest thing i ever seen today

untold magnet
#

the block will use onTick anyway, so i can teleport the entity if u pushed it with a piston

amber granite
neat hound
distant tulip
#

i was doing that in my banner markers addon
got a lot of situations where the entity get out of the banner
so i made it check by it self

amber granite
#

U could save me a lot of time

distant tulip
untold magnet
amber granite
distant tulip
#

i did
i think?

neat hound
#

then have the entity use an enivro sensor and if it is not in_block then despawn

amber granite
#

No u didn't ☠️

distant tulip
#

give me a sec

frozen vine
amber granite
untold magnet
amber granite
#

Like this

let mobsNum = world.getDynamicProprety("mobsNum") ?? 1 ;
const limit = 50;
//Put ur event here then save the number in dynamic proprety and retrieve it later
world.afterEvents.playerPlaceBlock.subscribe(({ block }) => {
if ( mobsNum == limit ) retrun;
  if (block.typeId === 'my:block') {
    block.dimension.spawnEntity('my:blockEntity', block.center())
  
      mobsNum++;
world.setDynamicProprety("mobsNum" , mobsNum);
 
})

// Ur system for killing the entity add for it this after the killing code 
mobsNum--;
world.setDynamicProprety("mobsNum" mobsNum);

neat hound
#

Just have the entity despawn if it is in minecraft:air.... you can do that in the entity's json... no extra work needed

distant tulip
untold magnet
#

i did it like this

neat hound
#

doesn't the new block spawn a new entity

amber granite
untold magnet
#

const block = entity.dimension.getBlock(entity.location)
if (block.typeId !== 'minecraft:dirt') delete.function.com

neat hound
#

it is like TNT, it is a block with an entity

untold magnet
distant tulip
untold magnet
neat hound
#

Is this any block, vanilla..... are you using player plack block to put an entity inside the block?

#

there is a missing piece of info here

untold magnet
neat hound
#

okay, I'm lost.... this is all over the place.... have fun guys

untold magnet
#

i also got a problem that is kinda weird, the script cannot detect hitting the entity

#

i think

#

i write it wrong

#
world.afterEvents.entityHitEntity.subscribe(({ damagingEntity }) => {
  if (damagingEntity.typeId === 'exe:grinder') damagingEntity.triggerEvent('exe:small')
})```i think so
#

i did it with any entity that hit my entity so it will work fine on the morph addon

#

i mean

#

in that morph addon, the player will be turned into different mobs and i think that will make it not be detected perfectly with scripts

gaunt salmonBOT
#
No Errors

No errors in [code](#1067535608660107284 message)

untold magnet
scarlet sable
#

I made more research and i found ut that the camera api is a bit too advanced

#

so ig it's time to switch projects

untold magnet
#

@neat hound hmmm, sorry for the ping but;
i thought about a really nice way to make a limit of entities blocks,
each player will have a limit of 50 block entities, if one of the players reach the limit, the script will no longer spawn an entity while placing the block, however if he breaks the block entities that he already built, he will be able to place the blocks back and spawn entities.

#

just like an entity counter, if one of the player has a 50 entities counted, and those entities are still in the world they will be detected, after he reaches the limit the spawning entities system will stop so he can place blocks but without spawning entities with it.

neat hound
# untold magnet <@463116989662101514> hmmm, sorry for the ping but; i thought about a really nic...

Each person can place 50 blocks with entities? Different ways to go.

  • But first I would make sure I can tag the entity with player name or even a stringyfied copy of the person's scoreboard player obj, the entity can have dynamic properties too.
  • For the players I would probably use a scoreboard to add and subtract as the player does his thing. Use the scoreboard to decide whether or not to place the entity.
  • now let's say you log off and someone else destroys one of your blocks... since the entity hold owner information you, in theory, should be able to subtract from his scoreboard entry.

Something like that.. that is off the top of my head.

untold magnet
#

my hands telling me to do it, but my brain is disagreebao_foxxo_what

distant tulip
#

use dynamic properties in the world

  • each block have a dp:
    include player id and entity id
  • each player have a dp in world
    include how many blocks he have and there positions if needed
    when a block is broken check the dp with it corrds
    and get that player id and dp so you can decrees the amount
neat hound
untold magnet
#

apparently it used scoreboard alot, i dont really know about scoreboard system yet so I'll think about it later

#

i will be using scoreboards in the addon, generating energy required scoreboards, saving the energy inside blocks required scoreboards, traveling energy from the generator into the saver block requires scoreboards

#

i just had so much work to do, but making working furnace is quite hard to do,

#

i think

#

i had to use scoreboard on smelting things too

#

like, when the item is placed inside the entity inventory in a specific slot, it will start giving the entity a score, if that item is taken out the entity score will reset
if that score reaches like 20 it will be detected and stop the script from adding score to the entity and clear the item from that slot and place a different item in a different slot all at the same time

#

if i think about it yes, it is possible to make custom furnace that will work perfectly fine

#

i gotta learn about scoreboard system + dynamic property tomorrow

warm drum
#

I have some problem with the playAnimation(), I can't make the entity to play any animation at all

#

Even vanilla mob

#
world.afterEvents.buttonPush.subscribe(e => {
    let block = e.block;
    let dim = e.source.dimension;
    let creeper = dim.spawnEntity("creeper", block.center());
    creeper.playAnimation("animation.creeper.swelling");
})
#

For example this

#

Is it broken?

empty quail
#

How can one get the riders on an entity? Resolved

shy leaf
unreal cove
oblique heath
#

^

shy leaf
#

whats server-editor module

flat dew
shy leaf
obsidian coyote
#

It’s for the Bedrock Editor

shy leaf
untold magnet
#

hmmm,

#

after i place the block and the entity spawn, the entity will get a property number like 0, when i place another block the entity will get a property number of 1, allway to 49

#

using that method i can fix a problem that will make the entity disappear while pushing the block with a piston

#

and make a limit of how many blocks each player can place

#

the only problem is, idk how to make the system set property each time the player place a block

#

gosh my hurt brains

#

opened a post #1283731287475097644bao_doggo_smug

winter plaza
#
export function itachi_tick_block(block) {
  const
    entities = block.dimension.getEntities({maxDistance:10,location:block.location,type:"minecraft:player"}),
    location = block.location;
  if (entities.length > 0) {
    block.dimension.runCommandAsync("execute as @p run say sa");
    location.runCommandAsync("fill ~~~ ~~~ air");
  }
}
#

giving an error, it says the function does not exist after I put the block.location

distant tulip
winter plaza
#

what

#

location is the const of the block location

distant tulip
#

do

const {x,y,z} = block.location
block.dimension.runCommandAsync(`fill ${x} ${y} ${z} ${x} ${y} ${z} air`);

or use fill native method

alpine ibex
#

How to apply Knockback to player/entity that makes them move forward or upward?

#

Anything is appreciated

#

As well as where the player is looking

chilly fractal
#

Guys

#

Anyone know how to rotate a block? (Any vanilla block and custom blocks if we can rotate custom blocks), I just want to know how to rotate a block if it can be rotated nothing else.

#

#1082528730242625546 message

#

But it's from a year

#

I'll test it out anyway

abstract cave
#
world.afterEvents.itemUse.subscribe((data => {
    const item = data.itemStack;
    const player = data.source;

    // Check if the item is a wand AND mana is 50 or more
    if (item.hasTag('wands:is_wand') && mana >= 50) {
        mana -= 50;  // Deduct 50 mana
        player.runCommand("/say I took ye mana");
        item.setLore(['Fireball']);
    } else if (item.hasTag('wands:is_wand') && mana < 50) {
        player.runCommand("/say Not enough mana!");


    }
}));

The code block runs smoothly, but the item lore doesnt get added, is there something im missing

chilly fractal
runic crypt
#
world.beforeEvents.playerPlaceBlock.subscribe((event) => {
    const player = event.source;
    if (event.permutationBeingPlaced.type.id === "minecraft:bedrock") {
        event.cancel = true;
        system.run(() => {
            player.runCommandAsync('say §cYou may not place bedrock§r');
        });
    }
});

why doesn't it send the message ?

#

i it says <anonymous> in errors

abstract cave
shy leaf
abstract cave
#

so you mean ```js
item.setEquipment

shy leaf
#
  1. get equippable component from player
  2. get slot, and in this case, it would be "Mainhand"
equippableComponent.setEquipment(slot, item)```
cold grove
shy leaf
#

aw come on discord

#

really?

#

there we go

cold grove
#

Yey

runic crypt
# cold grove event.player*
world.beforeEvents.playerPlaceBlock.subscribe((event.player) => {
    const player = event.source;
    if (event.permutationBeingPlaced.type.id === "minecraft:bedrock") {
        event.cancel = true;
        system.run(() => {
            player.sendMessage("You cannot place Bedrock");
        });
    }
});

this ?
also can i add multiple blocks in this if possible ?

cold grove
#

No

runic crypt
runic crypt
abstract cave
runic crypt
shy leaf
cold grove
#

No

#

Replace source by player

runic crypt
#
world.beforeEvents.playerPlaceBlock.subscribe((event) => {
    const player = event.player;
    if (event.permutationBeingPlaced.type.id === "minecraft:bedrock") {
        event.cancel = true;
        system.run(() => {
            player.sendMessage("You cannot place Bedrock");
        });
    }
});
#

this ?

#

i hope so

shy leaf
#

yeah that

runic crypt
#

alright

#

thanks 🙂

chilly fractal
untold magnet
#

umm, #1283731287475097644 ?

untold magnet
chilly fractal
glacial widget
#

"hey" was to test if the event was working

solar dagger
#
        const rayResult = dragon.dimension.getEntitiesFromRay(
          location: dragon.location,
        )```
Im not understanding, the 'location' parameter is giving me this error:
```txt
Argument of type 'Location' is not assignable to parameter of type 'Vector3'.
  Type 'Location' is missing the following properties from type 'Vector3': x, y, zts(2345)```
glacial widget
glacial widget
oak lynx
#
world.beforeEvents.playerInteractWithBlock.subscribe(data => {
    const player = data.player
    const location = data.block.location
    if(isInMapRegion(location) && player.getGameMode()==server.GameMode.survival){
        data.cancel = true
    } else {
        //todo
    }
}

shouldnt this stop the player from being able to waterlog stuff?

#

because the player can waterlog most stuff and the water doesnt spill and doesnt work with sponges

untold magnet
#
const entitiesArray = ["0", "1", "2", "3", "4"]
const options: EntityQueryOptions = { ??? }```
#

u,h

shy leaf
untold magnet
#

idk what should i use, im completely lost

untold magnet
shy leaf
#

also are you using typescript

untold magnet
shy leaf
#

then that aint no javascript thing

glacial widget
#

could someone help me with this?

world.afterEvents.entitySpawn.subscribe((e) =>{
  console.warn("hey")
  if(e.entity.typeId !== "minecraft:item") return

  if(e.entity?.nameTag == "§d§lStarter") return e.entity.kill()
})
shy leaf
# untold magnet javascript
const entities = player.dimension.getEntities({
    type: "namespace:typeId"
});
console.warn(`${entities.length}`);
#

heres an example

glacial widget
shy leaf
#

you need to first get item component on entity, and then check for nameTag (on itemStack) on it

#

just checking for nameTag will try to track the entity's nameTag and not the item

distant tulip
#

you can also get what item is that exactly

glacial widget
#

i thought that way would work best

distant tulip
glacial widget
untold magnet
distant tulip
glacial widget
#

oh but am tryna get the nameTag

solar dagger
glacial widget
#

not id

glacial widget
#

i was unsure if it was a object or array

solar dagger
#

yeah ill clarify next time, but thanks

glacial widget
solar dagger
solar dagger
#

@glacial widget do you know how I can obtain the FOV of an entity?

Update: nvm i figured it out

winter plaza
#

help

#
[Scripting][error]-Unhandled promise rejection: TypeError: Native type conversion failed.
import * as mc from '@minecraft/server';

mc.system.afterEvents.scriptEventReceive.subscribe(event => {
  const wg = event.id.split("power:")[1];
  const eventEntity = event.sourceEntity;
  switch (wg) {
    case "ball":
      shootPower(eventEntity, "wesl3y:projetil", null, ball, eventEntity.name);
    break
  }
});

export function shootPower(player, powerId, offset, eventId, name) {
  const location = player.getHeadLocation();
  common(location);
  function common(location) {
    const power = player.dimension.spawnEntity(powerId,location);
    if(name != null){
      power.nameTag == name;
    }
    if(eventId != null){
      power.triggerEvent(eventId);
    }
    const projectileComp = power.getComponent("projectile");
    projectileComp.owner = player;
    projectileComp.shoot(player.getViewDirection());
  }
}
lyric kestrel
#

Is it possible to do a check for pickaxes with a certain tag while mining a block to see if it can mine it and drop loot, using scripts?

#

One that could work across multiple add-ons

wintry bane
#

Can ActionFormData buttons be created automatically or are they manual?

inland merlin
inland merlin
wintry bane
lyric kestrel
inland merlin
# wintry bane Can you give me an example?
import { ActionFormData } from "@minecraft/server-ui";
import { world } from "@minecraft/server";

// Sample array of tools
const tools = ["Pickaxe", "Axe", "Shovel", "Sword", "Hoe"];

// Function to show a tool selection form
function showToolSelectionForm(player) {
    // Create a new ActionForm
    const form = new ActionFormData()
        .title("Tool Selection")
        .body("Choose a tool from the list below:");

    // Dynamically add buttons for each tool in the array
    tools.forEach(tool => {
        form.button(tool); // Add a button with the tool name
    });

    // Show the form to the player and handle the result
    form.show(player).then((response) => {
        if (response.canceled) {
            player.sendMessage("You canceled the selection.");
            return;
        }

        // Get the selected tool from the array based on the selection index
        const selectedTool = tools[response.selection];

        // Display the selected tool to the player
        player.sendMessage(`You selected: ${selectedTool}`);
    }).catch((error) => {
        player.sendMessage("An error occurred while showing the form.");
        console.error(error);
    });
}

// Event listener for player spawn (as an example)
world.afterEvents.playerSpawn.subscribe(event => {
    const player = event.player;
    showToolSelectionForm(player); // Show the tool selection form to the player when they spawn
});```
wintry bane
#

I see, thank you

lyric kestrel
#
{
    "pools": [
        {
            "conditions": [
                {
                    "condition": "match_tag",
                    "tag": {}
                }
            ],
            "entries": [
                {
                    "type": "item",
                    "weight": 37,
                    "name": "raw_iron"
                },
                {
                    "type": "item",
                    "weight": 20,
                    "name": "raw_iron",
                    "amount": 2
                }
            ]
        }
    ]
}```
#

@inland merlin something like that but with scripting

#

Like isntead of matching an item, it matches a tag

#

I could do beforeBlockBreak event?

inland merlin
#

You would have to create your own loot class. But you could make your own setup I suppose.

lyric kestrel
#

own loot class?

inland merlin
#

well, code you can tap into for repeated use.

#

We can't use json loot tables into js (as far as I'm aware)

lyric kestrel
#

sorry, for acting ignorant, I haven't done add-ons in a few months xD

inland merlin
#

But you could structure it that way if you want.

#

You would have to create your own loot_table manager from scratch

#

In js, so basically you just use the before or after event

#

For breaking blocks

#

And could make it do whatever you want

lyric kestrel
#

hmm, I think I might do that

inland merlin
#

I made my own loot_table system for one of my addons for entities

#

I made an in game config for server owners (not perfect but worked)

#

For loot they wanted entities to drop

#

I had to add enchantment calculations (which I need to visit again)

inland merlin
#

With events

lyric kestrel
#

thank you

untold magnet
#

hmm

#

making a function that will add a dynamic property for an entity using const array = [ "M1", "M2" ] and add one of them to the entity,
if M1 property is used ( theres an entity in the world that has the M1 property id ) it will not use it and use the second property ( M2 )

lyric kestrel
#

Ok, Bit confused how to implement what I'm trying to do xD

#

Sorry to bother @inland merlin, need a bit of help if you don't mind

lyric kestrel
#

done

serene radish
#

is there any way to automatically set max players?

shy leaf
#

not sure about BDS though

serene radish
#

alr

lyric kestrel
#
import {system, world, ItemStack} from "@minecraft/server";
world.beforeEvents.playerBreakBlock.subscribe((e) => {
    const block = e.block;
    const player = e.player;
    const item = e.itemStack;
    const location = {
        x: block.location.x+0.5,
        y: block.location.y,
        z: block.location.z+0.5
    }
    const bauxite1 = new ItemStack("raw_iron", 1);
    const bauxite2 = new ItemStack("raw_iron", 2);
    const bauxite3 = new ItemStack("industry:raw_titanium", 1);
    //Loot table weight variable
    let weight = Math.random();

    const pickaxe_level3 = item?.hasTag("pickaxe_level3") || item?.hasTag("pickaxe_level4") || item?.hasTag("pickaxe_level5") || item?.hasTag("pickaxe_level6") || item?.typeId.includes("iron_pickaxe") || item?.typeId.includes("diamond_pickaxe") || item?.typeId.includes("netherite_pickaxe");
    const pickaxe_level4 = item?.hasTag("pickaxe_level4") || item?.hasTag("pickaxe_level5") || item?.hasTag("pickaxe_level6") || item?.typeId.includes("diamond_pickaxe") || item?.typeId.includes("netherite_pickaxe");
    const pickaxe_level5 = item?.hasTag("pickaxe_level5") || item?.hasTag("pickaxe_level6") || item?.typeId.includes("netherite_pickaxe");

    if(block.typeId.includes("bauxite_ore") && (pickaxe_level3)){
        if (weight < 0.38)
        {
            system.run(() => {
                block.dimension.spawnItem(bauxite1, location)
            })
        }
        if (weight > 0.37 && weight < 0.58)
        {
            system.run(() => {
                block.dimension.spawnItem(bauxite2, location)
            })
        }
        if (weight > 0.57 && weight < 0.63){
            system.run(() => {
                block.dimension.spawnItem(bauxite3, location)
            })
        }
    }
})```
#

I'm finally going to bed after finally getting it to work :¬)

shy leaf
#

(j, rest well)

lyric kestrel
#

I would put the bauxiteN's into their own file in a function for easier viewing, but for some reason I'm getting an error what I refer to this

export OreLootTable(block, ItemStack){
  const bauxite_1 = new ItemStack("raw_iron", 1)
 return{
   bauxite_1
 }
}
shy leaf
#

ill just do it hold on

lyric kestrel
lyric kestrel
#

There, it's in now

#

I'll look into how I can get it to work in the later morning

lyric kestrel
#

I haven't used JS in 5 months

shy leaf
# lyric kestrel ```js import {system, world, ItemStack} from "@minecraft/server"; world.beforeEv...
import {system, world, ItemStack} from "@minecraft/server";

world.beforeEvents.playerBreakBlock.subscribe((e) => {
    const { block, player } = e;
    const item = e.itemStack;
    const weight = Math.random();
    
    function rawIron(amount) {
        const item = new ItemStack("raw_iron", amount);
        return item
    }
    const rawTitanium = new ItemStack("industry:raw_titanium", 1);

    const pickaxe_level3 = item?.hasTag("pickaxe_level3") || ["iron_pickaxe", "diamond_pickaxe", "netherite_pickaxe"].some(type => item?.typeId.includes(type));
    const pickaxe_level4 = item?.hasTag("pickaxe_level4") || ["diamond_pickaxe", "netherite_pickaxe"].some(type => item?.typeId.includes(type));
    const pickaxe_level5 = item?.hasTag("pickaxe_level5") || item?.typeId.includes("netherite_pickaxe");

    if (block.typeId.includes("bauxite_ore") && pickaxe_level3) {
        let itemToDrop = null;
        if (weight < 0.38) {
            itemToDrop = rawIron(1);
        } else if (weight < 0.58) {
            itemToDrop = rawIron(2);
        } else if (weight < 0.63) {
            itemToDrop = rawTitanium;
        }
        if (itemToDrop) {
            system.run(() => {
                block.dimension.spawnItem(itemToDrop, block.center());
            });
        }
    }
});```

note that `.some` for array is equivalent to `||`
#

its kinda missing pickaxe level checks though

wary edge
#

This is where i wish we had better loot table support

shy leaf
#

ikr

unkempt siren
#

i know this sounds like a weird question but is there a way to get the mouse position of a player when on ui via script api? doesn't have to be a supported function or anything but is there a way to calculate it somehow?

oblique heath
#

is the maxDistance option in EntityQueryOption for x and z directions or for xyz?

shy leaf
#

in preview? iirc

#

but its also very limited

distant tulip
#

if there is something it is probably in the editor api

celest fable
honest spear
celest fable
#

its just main.js on the scripts folder

sudden nest
# lyric kestrel I would put the bauxiteN's into their own file in a function for easier viewing,...

you can use this instead, i use it all the time for weighted random stuffs, it's easy to use:

/**
 * Class representing an entry with an object and its accumulated weight.
 * @template T - The type of the object being stored.
 */
class Entry {
    /**
     * Creates an entry.
     * @param {T} object - The object associated with the weight.
     * @param {number} accumulatedWeight - The accumulated weight value of this entry.
     */
    constructor(object, accumulatedWeight) {
        this.object = object;
        this.accumulatedWeight = accumulatedWeight;
    }
}

/**
 * A class for performing weighted random selection.
 * This class allows adding objects with associated weights, 
 * and then randomly selects one of the objects with probability proportional to its weight.
 * 
 * @template T - The type of the object being stored in each entry.
 */
class WeightedRandom {
    constructor() {
        this.entries = [];
        this.accumulatedWeight = 0;
    }

    /**
     * Adds a new entry with a specific weight to the collection.
     * The object can be of any type, and the weight determines how likely it is to be selected.
     * 
     * @param {T} value - The object to be added.
     * @param {number} weight - The weight associated with this object.
     * @returns {WeightedRandom<T>} The current instance of the class, for method chaining.
     */
    addEntry(value, weight) {
        this.accumulatedWeight += weight;
        this.entries.push(new Entry(value, this.accumulatedWeight));
        return this;
    }

    /**
     * Removes an entry from the collection by its value.
     * Adjusts the accumulated weights of the remaining entries accordingly.
     * 
     * @param {T} value - The object to be removed.
     * @returns {boolean} A boolean indicating whether the object was successfully removed.
     */
    removeEntry(value) {
        const index = this.entries.findIndex(entry => entry.object === value);
        if (index === -1) return false;
    
        const weightToRemove = index === 0
          ? this.entries[index].accumulatedWeight
          : this.entries[index].accumulatedWeight - this.entries[index - 1].accumulatedWeight;
    
        this.entries.splice(index, 1);
        this.accumulatedWeight -= weightToRemove;
    
        // Update the accumulated weights of the remaining entries
        for (let i = index; i < this.entries.length; i++) {
            this.entries[i].accumulatedWeight -= weightToRemove;
        }
    
        return true;
    }

    /**
     * Adds multiple entries from an object where the keys are the values and 
     * the values are the corresponding weights.
     * 
     * @param {Object<string, number>} entriesObject - An object where keys are the entries and values are the weights.
     * @returns {WeightedRandom<T>} The current instance of the class, for method chaining.
     */
    addEntriesFromObject(entriesObject) {
        for (let key in entriesObject) {
            this.addEntry(key, entriesObject[key]);
        }
        return this;
    }

    /**
     * Selects a random entry based on its weight.
     * The probability of each entry being selected is proportional to its weight.
     * 
     * @returns {T|null} The selected entry or null if no entries exist.
     */
    getRandom() {
        const r = Math.random() * this.accumulatedWeight;

        for (const entry of this.entries) {
            if (entry.accumulatedWeight >= r) {
                return entry.object;
            }
        }
        return null; // should only happen when there are no entries
    }
}
#

Example:

const weightedRandom = new WeightedRandom();

weightedRandom.addEntry('apple', 5)
              .addEntry('banana', 3)
              .addEntry('cherry', 2);

console.log(weightedRandom.getRandom()); // Randomly logs 'apple', 'banana', or 'cherry' based on weight

weightedRandom.removeEntry('banana');

console.log(weightedRandom.getRandom()); // Randomly logs 'apple' or 'cherry' based on weight

weightedRandom.addEntriesFromObject({
    'date': 4,
    'elderberry': 1
});

console.log(weightedRandom.getRandom()); // Randomly logs 'apple', 'cherry', 'date', or 'elderberry' based on weight
#

it can be any object, like:

const weightedRandom = new WeightedRandom();

weightedRandom.addEntry(new ItemStack("raw_iron", 1), 38)
              .addEntry(new ItemStack("raw_iron", 2), 58)
              .addEntry(new ItemStack("industry:raw_titanium", 1), 63);
untold magnet
#
world.afterEvents.entityHitEntity.subscribe(({ damagingEntity }) => {
  if (damagingEntity.typeId === 'my:entity') damagingEntity.triggerEvent('exe:small')
})```this isn't working, i mean it cannot detect me when i hit the entity
#

the script should detect me when i hit the entity, also the entity will not take any damage

honest spear
untold magnet
#

the entity is not taking any kind of damage,

celest fable
honest spear
celest fable
glacial widget
#

for some reason this works without listing the coords in the if statment

world.beforeEvents.playerInteractWithBlock.subscribe((ev) =>{
    const {block, player, blockFace, itemStack:item} = ev
    switch(block.typeId){
        case "minecraft:standing_banner":
            if(block.x === -11 && block.y === 71 && block.y === 2){
            ev.cancel = true

            system.run(() => {
               console.warn("player is picking up the flag")
            });
        }
    }
});
inland merlin
#
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
    const {block, player, blockFace, itemStack: item} = ev
    switch (block.typeId) {
        case "minecraft:standing_banner":
            if (block.x === -11 && block.y === 71 && block.z === 2) { // Corrected 'y' to 'z' for the third coordinate
                ev.cancel = true

                system.run(() => {
                    console.warn("player is picking up the flag")
                });
            }
    }
});```
glacial widget
#

lol i didnt even see it

lyric kestrel
#

Titanium has a very small chance irl of being found within Bauxite

scarlet sable
#

I think I want to do create for bedrock but it's copyrighted

lyric kestrel
#

People are currently doing create for Bedrock

scarlet sable
#

Oh cool

#

Where can i see updates about it?

lyric kestrel
#

#add-ons message

#

They sometimes post it

#

They got permission from the Create Devs to do it

winter plaza
#
[Scripting][error]-Unhandled promise rejection: TypeError: Native type conversion failed.
import * as mc from '@minecraft/server';

mc.system.afterEvents.scriptEventReceive.subscribe(event => {
  const wg = event.id.split("power:")[1];
  const eventEntity = event.sourceEntity;
  switch (wg) {
    case "ball":
      shootPower(eventEntity, "wesl3y:projetil", null, ball, eventEntity.name);
    break
  }
});

export function shootPower(player, powerId, offset, eventId, name) {
  const location = player.getHeadLocation();
  common(location);
  function common(location) {
    const power = player.dimension.spawnEntity(powerId,location);
    if(name != null){
      power.nameTag == name;
    }
    if(eventId != null){
      power.triggerEvent(eventId);
    }
    const projectileComp = power.getComponent("projectile");
    projectileComp.owner = player;
    projectileComp.shoot(player.getViewDirection());
  }
}
#

help me

gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 2 errors:

<REPL0>.js:8:56 - error TS2304: Cannot find name 'ball'.

8       shootPower(eventEntity, "wesl3y:projetil", null, ball, eventEntity.name);
                                                         ~~~~

``````ansi
<REPL0>.js:8:74 - error TS2339: Property 'name' does not exist on type 'Entity'.

8       shootPower(eventEntity, "wesl3y:projetil", null, ball, eventEntity.name);
                                                                           ~~~~

Lint Result

There are no errors from ESLint.

untold magnet
#

i need a dynamic property helpbao_doggo_smug

#

if dynamic property is complicated, i could use tags

#

but

#

how can i make a system that will put a different tag for each entity?
first entity will get E0 tag
second entity will get E1 tag
if the first entity is dead the tag will be unused so when u spawn a third entity it will get the E0 tag

#

is it too complicated to do?

idle dagger
#

.

#

100k message

fiery solar
lyric kestrel
idle dagger
lyric kestrel
#

Ye, it does that a lot

cerulean cliff
#

u're still alive

naive tinsel
#

why when i place a ticking area a thousand blocks away from me and then load a structure in said ticking area, it says that it cannot place because its in unloaded chunks?

cerulean cliff
fiery solar
lyric kestrel
cerulean cliff
#

yep it dead

lyric kestrel
#

And I'm not great at C++, and I needed the 20gb+ it all used up to make a mod

naive tinsel
#

or does my player have to load them,

fiery solar
#

It depends on the system. The best thing you can do is keep trying to do a dimension.getBlock on a block in each chunk of your ticking area and wait until they all return a block

inland merlin
#

I would do loop, then have max check time

cerulean cliff
lyric kestrel
#

damn

naive tinsel
lyric kestrel
#

I'm trying to create an industrial add-on

lyric kestrel
#

ye

cerulean cliff
#

yep :p

shell pike
#

nice

lyric kestrel
#

Trying to figure out what ores I want to have as base

#

I have conveyers already done from a previous add-on I did, but I need to re-do the looks. They look horrible

cerulean cliff
#

it sounds really interesting, wish ya good luck ^^

lyric kestrel
#

Thank you

#

Trying to use JS for most of it

#

Since that's the best and fastest and most flexible

#

instead of JSON

inland merlin
#

Def dynamic

lyric kestrel
#

ye

cerulean cliff
lyric kestrel
#

Tin is definitely going to be there too

#

I don't need to do any scripting for that one though

cerulean cliff
#

what about cobolt?

lyric kestrel
#

Although, when I do the alloy part of the add-on, I'll definitely need to use scripting with tin

#

perhaps

#

You want to work together on this?

cerulean cliff
lyric kestrel
#

xD

cerulean cliff
lyric kestrel
#

fair

cerulean cliff
#

mp, bedrockrs etc

inland merlin
#

Most of us are busy with other projects, but somehow have time to answer questions here in our work hours lol

lyric kestrel
#

ye lol

#

I'm supposed to be making a simple titanium nugget for the weight script to drop, but I've been doing it for the past hour haha

#

I've mainly been talking or doing other stuff

inland merlin
#

Lol fair

lyric kestrel
#

I swear I'm not usually this slow xD

untold magnet
#

or just runCommand?

untold magnet
oak lynx
#

why did they add lore line limit 😭

wary edge
inland merlin
scarlet sable
#

didn't know you were active here

#

how are you doing?

cerulean cliff
#

oh heya I'm fine ^^

#

how about you?

scarlet sable
#

same

#

good to hear bao_ext_toldyouso

valid ice
distant tulip
#

this channel is surprisingly not active this day

wintry bane
#

Modularized code, what do you guys think?

wary edge
honest spear
distant tulip
honest spear
distant tulip
honest spear
distant tulip
#

lol

honest spear
#

good night to everyone who has night rn

wintry bane
distant tulip
#

gn

honest spear
scarlet sable
#

for falls under what in js?

distant tulip
#

loops

scarlet sable
#

ty

distant tulip
#

same as
do while
while
for each

rose light
#

[Scripting][error]-LocationInUnloadedChunkError: Trying to access location (-698.0, 95.0, -721.0) which is not in a chunk currently loaded and ticking. at colisionblockf (config/armas/armas_lib/armas_lib.js:108)
at <anonymous> (config/armas/armas_lib/armas_lib.js:20)

Is there any way I can check if that area is loaded, so I can give a return, to stop generating this error?

lyric kestrel
#

@shy leaf I changed the script a little bit and made the "lootTable" a bit more dynamic instead of just being for iron, and got rid of the rawTitanium const

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

world.beforeEvents.playerBreakBlock.subscribe((e) => {
    const { block, player } = e;
    const item = e.itemStack;
    const weight = Math.random();
    
    function lootTable(item, amount) {
        const item = new ItemStack(item, amount);
        return item
    }

    const pickaxe_level3 = item?.hasTag("pickaxe_level3") || ["iron_pickaxe", "diamond_pickaxe", "netherite_pickaxe"].some(type => item?.typeId.includes(type));
    const pickaxe_level4 = item?.hasTag("pickaxe_level4") || ["diamond_pickaxe", "netherite_pickaxe"].some(type => item?.typeId.includes(type));
    const pickaxe_level5 = item?.hasTag("pickaxe_level5") || item?.typeId.includes("netherite_pickaxe");

    if (block.typeId.includes("bauxite_ore") && pickaxe_level3) {
        let itemToDrop = null;
        if (weight < 0.38) {
            lootTable("raw_iron", 1)
        } else if (weight > 0.37 && weight < 0.58) {
            lootTable("raw_iron", 2)
        } else if (weight > 0.57 && weight < 0.63) {
            lootTable("industry:titanium_nugget", 1)
        } else if (weight > 0.62 && weight <= 1) {
            lootTable("industry:raw_aluminium", 1)
        }

        if (itemToDrop) {
            system.run(() => {
                block.dimension.spawnItem(itemToDrop, block.center());
            });
        }
    }
});```
untold magnet
#

hmm

amber granite
#

U are my sunshine

#

My only sunshine

amber granite
untold magnet
#
const inv = entity.getComponent('inventory')
const slot = inv.getSlot
const item = inv.getItem```how can i make it detect if the slot 0 has an item or not
#

if (slot(0) != null)?

amber granite
#

☠️

#

If u make it without the object u will make it standalone function

#

And that may make the function do unpredictable behaviour

#

standalone function = without this context

untold magnet
#

so how can i make the script detect if that slot is not empty?

lyric kestrel
#

Entites have inventories

untold magnet
#

its actually a furnace entity, putting items inside it will be detected using scripts

#

that is possible

#

so,

#

how can i detect if the slot is empty or not?

distant tulip
#

just equippable

untold magnet
distant tulip
#

yeah

#

get the item and check if it is defined

untold magnet
distant tulip
#

const item = invComponent.container.getItem(0)
if(item){
//...
}

untold magnet
#

it should detect it when that slot doesn't have an item

#

oh, yah right

#

my brain is on holiday rn

tardy wraith
#
import { world, system } from '@minecraft/server';

const afkPlayers = new Map();
world.beforeEvents.chatSend.subscribe(data => {
    const player = eventData.sender;
    const playerName = player.name;
    const message = eventData.message;
[Scripting][error]-Plugin [AFK System - 1.0.8] - [index.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined    at <anonymous> (index.js:4)
]
tardy wraith
#

again

distant tulip
#

always has been

tardy wraith
#

I had the same problem

amber granite
#

Add (0)
To inv.getSlot

distant tulip
untold magnet
#

so

const inv = entity.getComponent('inventory')
const slot = inv.getSlot ← useless?
const item = inv.getItem
if (!item(0)) { ,,, }```
tardy wraith
#

1.14.0-beta right?

distant tulip
#

yeah

tardy wraith
#

alr, I'm stupid

tardy wraith
#

I uploaded the wrong manifest

amber granite
#

U need to add (0) to the variable

#

Call the function in the variable itself

#

To avoid some error realted to the binding of this

untold magnet
#

i dont want to const each slot

amber granite
#

Then bind it to inv

#

Yeah

untold magnet
#

each slot will work differently than the other

amber granite
#

Show us the code

#

Of each slot

untold magnet
#

i mean, there are some dynamic properties that will happen for each slot

amber granite
#

U can fix that too with for loop

#

Then alright

#

☠️

untold magnet
#

i dont want to put the same dynamic property for all slots, if the first one got an item but everything else didnt, the first item will give the entity a dynamic property of 1,
after putting the second item it will not get any dynamic properties, i cant explain it right tho

amber granite
#

Bro i m talking with t17x

untold magnet
#

this will make the dynamic property works with all 3 slots at the same time

amber granite
#

Blud thought that i don't know how to write a loop

distant tulip
amber granite
#

XD

untold magnet
#

i want each one has it own section so i can put different dynamic properties for each one

amber granite
distant tulip
#

the variable is referring to the function

amber granite
#

Ah what ,__, ?

#

U mean the standalone function

distant tulip
untold magnet
#

hmmhmmmhmmmm

amber granite
#

It was worth it learn js ☠️ i m not useless after all

untold magnet
#

how can i detect a scriptevent inside of an interval?

distant tulip
#

why

amber granite
#

Yeah why

#

The event will trigger once and do its functions once

#

Even if it was in an interval

untold magnet
# distant tulip why

after the block gets a state of 8, it will set a dynamic property for the entity for once
similar to sending a scriptevent when the block gets the state 8

#

idk

amber granite
#

That make it useless and u won't get any additional effect by doing that

distant tulip
#

interval just make it sub to the event multiple time
you don't want that

untold magnet
#

as what i said, my brain is on a holiday today

amber granite
#

I don't get it , can u explain it correctly?

untold magnet
#

hmmm,

if (!item(0)) entity.setDynamicProperty('s0', false)
if (item(0).typeId === 'minecraft:stick') entity.setDynamicProperty('s0', true)```should set and reset the dynamic property if that slot has an item on it or not?
amber granite
#

Sorry what

untold magnet
#

if that slot doesn't have any item, it will reset the property
default is false, but when the slot gets an item it will turn on the property

amber granite
#

An item or a specific type of items ?

untold magnet
#

that slot doesn't have any items on it when the entity spawns, so it will be automatically set as false

untold magnet
untold magnet
#

even knowing, if the item has been replaced will reset the property

amber granite
#

Replaced item will need extra code

untold magnet
# amber granite Replaced ?

like u put a raw copper inside of a furnace, then u replace it with raw iron before it fully smelted will reset the smelling progress u know what i mean

amber granite
#

Yeah yeah

#

That will need extra code as i said

untold magnet
#

so what kind of codes are that?

amber granite
#

U need to save the last item type id

#

In a variable

#

And then check the type id if it was the same

#

If it wasn't

#

U will reset the dynamic proprety

#

That s all

#

If it was the same TypeID u won't need to replace the variable

#

Lemme give u an example

#
// Define the variable in global Scope or idk
if (!item(0) ) { entity.setDynamicProperty('s0', false) }
if (item(0).typeId === 'minecraft:stick' && item(0).typeId == PreviousItemTypeId) { entity.setDynamicProperty('s0', true);
PreviousItemTypeId = item(0).typeId;
 }```
#

@untold magnet

untold magnet
#

my brain isn't braining

amber granite
#

I should told u that the variable must looks like :

let PreviousItemTypeId = true;
#

Wait

untold magnet
#

that will not store the last item typeid

amber granite
#

The last true item right ?

untold magnet
#

PIT = item(0).typeId will be the same when u replace the previous item with the new one

amber granite
#

Like if the dynamic proprety will gonna be setted to false

#

It won't save the last item right ?

amber granite
#

Nah that s wrong

#

@untold magnet

#

U want me to explain how it works?

untold magnet
#

explain

amber granite
#

So let s say

#

The tested item is same type id as ur previous type id

#

And the previous id in the beginning will be true

#

So the the if statement will work

untold magnet
#

literally, my brain isn't braining

amber granite
#

So u know the difference between == and === right ?

#

== is not strict typed as ===

untold magnet
#

also im carrying about my health, i might have some issues in my chest

amber granite
#

So let s say u used
=== To compare string and boolean

untold magnet
amber granite
#

Go to the doctor

untold magnet
amber granite
#

Ok

untold magnet
#

tomorrow and after tomorrow

amber granite
#

._. u must

#

Go as soon as possible

untold magnet
#

its a small pain, not that huge

amber granite
#

The body health isn't something u want to mess with

#

So yeah

untold magnet
#

similar to that random chest pain, but way weaker

amber granite
#

May god heal u

untold magnet
#

and its not inside of my chest, just like the outside or near the surface

amber granite
#

Yeah u must go to hospital anyways

#

Anyways we were in the code right

untold magnet
#

I'll think about the code tomorrow

#

after recharging my brain with some braincells

amber granite
#

Yeah go to sleep

untold magnet
#

cyabao_ext_toldyouso

scarlet sable
#

does tag refer to nametag?

#

when talking about entities

wary edge
amber granite
#

Tag is like giving an id to some entity and if they have that id they will have specific behaviour for them

#

Or u can tag players to slplit them into teams

#

@scarlet sable

scarlet sable
#

But what does a nametag fall under?

distant tulip
#

entity/player are objects
so
entity/player property

scarlet sable
#

Ye i meant like which property

distant tulip
#

string?

scarlet sable
#

Bruh

amber granite
#

And so on

#

It s not falling under any other proprety or derived from another

distant tulip
#

that what i said 🤷‍♂️

amber granite
#

Yeah

scarlet sable
#

Oh

#

So it's actually string lol

amber granite
#

Yeah a string that we all agree to use it

scarlet sable
#

Fair

amber granite
#

For making some functions works with players and don't work with others

#

Or splitting them to teams

#

Or idk...

distant tulip
#

there is also the name property
this one only present in the player

scarlet sable
#

I'll try using the id property first

amber granite
#

id ?

distant tulip
#

nametag is changeable
name is not
use name to get the player actual name
in case any addon change it

scarlet sable
#

Then move on to getting a specifically named mob

scarlet sable
amber granite
#

The id can be change from world to other

scarlet sable
#

I'll use name then

#

Like minato said

distant tulip
#

id is better

amber granite
#

I think i ve seen somone uses id to get the world host

#

To make isHost function

scarlet sable
distant tulip
amber granite
#

Ok

scarlet sable
#

Oh there's Entity.nametag

#

I didn't see it lol

scarlet sable
#

Ye

#

I meant in jayleydev's website

#

I didn't see it there while scrolling

scarlet sable
#

So we can use the entity properties for a player

#

And the opposite?

wary edge
scarlet sable
#

Ok good

#

Ty

distant tulip
#

clearVelocity

scarlet sable
#

Yep it makes sense

#

All tho some stuff would be cool to use on mobs too

distant tulip
#

almost all of them can

scarlet sable
#

Can you like put items in a specific slot of the mobs inv?

#

Ao like the script takes the armor from your hand into the zombies helmet slot

distant tulip
#

you can
not the equipable slots

scarlet sable
#

Mhm

distant tulip
#

only with commands

#

replceitem

scarlet sable
#

Oh ye i forgot about that

#

Also out of context question but isn't it like 1:30 am where you live?

#

We need sleep bruh 💀

amber granite
distant tulip
scarlet sable
amber granite
#

Then

scarlet sable
amber granite
#

Then use ide or code editor

amber granite
scarlet sable
amber granite
#

Do u know iife ?

scarlet sable
scarlet sable
amber granite
#

No iife

scarlet sable
#

Wasn't mentioned so far

#

iife ik just I cap

amber granite
scarlet sable
amber granite
#

Vs or vscode

#

☠️ there is a huge difference

scarlet sable
#

Visual studio code

#

Vs

#

I'm taking W3school course

amber granite
#

No there is visual studio and there is visual studio code

scarlet sable
#

It's quite fun

amber granite
scarlet sable
amber granite
#

It really helped me

amber granite
scarlet sable
#

Blud is newbie so ye i will ask the weirdest questiona you can think of

amber granite
#

Anyways if u have high-end pc

#

U should install visual studio

#

And get used for it