#Script API General
1 messages · Page 21 of 1
Sure...but in Nikkis case...it is unlikely shes writing a lib for other users
Still good to sanity check yourself too
no i mean when writing scripts for your own addon
yeh ik
does anyone have a code that changes x angle (in Entity.getRotation().x) to x and z in vector3
I have this bit still in my program meant to ... remind me to fix it, if it ever does break
mine just broke for some reason
The x-rotation to x and z coordinates? That doesn't really make much sense
The y-rotation I could understand
isn't what x/y means diff
waaait
const {x, z} = Entity.getRotation()
i mean like
one for where looking up/down , other for body angle
You're wanting an atan2 function of some kind(?)
yeah that
cant believe i forgot about that even though my first ever project used it 💀
Actually, atan2 would be the reverse process—turning a position into an angle. You want to turn an angle into a position
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)
Nah, pulled up my calculator on Windows and crunched it
ah
Although I do recall pi up to maybe the 8th 18th digit
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?
I actually don't know what console.error does. Other than log something
Its the same as .warn or .log
It does
my logs have to say warn
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
nothing shows up when I use... I tried them all... or does the log say warn.. I forgot..
Pre 1.21.30, .log will only log to the file. Post 1.21.30 it will display in the gui
oh
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
yay
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
i use try catch only if there is a lot of things that can go wrong
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
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}
Smokey... is system.run same as system.runTimeout with a 0 tick delay?
interchangeable?
one tick
isn't system run, end of current tick
This may be relevant: https://learn.microsoft.com/en-us/minecraft/creator/documents/systemrunguide
so you are saying timeout defaults to one if less than one?
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
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
pro tip: store the y property from player.getRotation() and incorporate that in your calculations to make it faster
I see. It is just that I take in a parm for the delay, and have 2 lines (if), when I could just have one.
what if -1... all hell breaks loose?
ye im just making the structure
I should at least error check that
im organizing it later
Minecraft finds a new timeline where the executed function happened in the previous tick, then forcefully transports the user to it
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
So...I can build a timemachine add-on....
Sprunkles tells a joke... it is a new day....
I'm not that bad of a drag! Am I? 
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
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.
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...
that nice
i was adding "none" option as a default value that don't don anything
Yea, I figured it out because I could not accept that as an option lol. My brain wouldn't allow it.
you just " figured it out" lol
how do you even do that
usually by mistake
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 😂
Should negative one everything... see what happens... I'd like to buy that for -1 dollars....
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.
you should add it as a note in some of the docs
as they say, necessity is the mother of invention...
August 31st is when I discovered it. Just checked my commit on GitHub lol.
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
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.
Would prove to be handy in the doc specific to the example shared using the drop-down lol.
You can contribute to the wiki... see Llama/Smokey
Description
Demostration of showing another Minecraft UI form after a player confirms or cancels the dialog.
Credits
These scripts were written by FrankyRayMS
That's actually a bad practice
getBlock() returns undefined if the block is an unloaded chunk.
While the Block class that isn't valid anymore can be tested with isValid()
Does someone know some workarounds to make something like "world.beforeEvents.entityDie"?
Cuz only the afterEvents exists
Cancel all damage via damage sensor, apply damage & needed effects via entityhurt/entityhit events
- damage sensor: cancel fatal damage
- fake the health reduction.
K, thx I'll try
i didn't know that, i guess try is useless to me now
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
Feel free to post math questions in the #1067535382285135923 channel.
What's 9 + 10?
-# well you asked for it, so...
Uncalled for. You can keep comments like this to yourself, especially since you are are over an hour behind the conversation.
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)
so question then, is there a way to check a 6x6 for blocks and place a block on any valid block within const of valid blocks to be checked and make the placement random that pulls from another const of blocks. similar to the flowers/grass spread when bonemealing a grassblock?
if that makes sense
Ok.
ahh, i see... basically recreating a bonemeal
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
Isn't bonemeal use radius?
...in spherical shape
Smokey—I mean, Llama has bonemeal script: #1067870355814895687 message
Hey, if anyone can help me that'd be great!
How can you script something like this (if it's even possible):
- Place a block down and it detects the exact same block to the left or right of it
- 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
- 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
- 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
Thanks 
but right and left will be relative to where the player is standing/facing....
Not the block?
not sure y ou can test for texture. You may need to keep a property in there to stand for texture.
Alright, but the right and left needs to be relative to the blocks position, is that possible?
it matters because if I am facing west... north is my right
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
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?
are you trying to get it to not look the same?
if it is a block, there is a auto way for that
I'm trying to make a block change to a different one so that it connects seamlessly with the block next to it.
Really? What's it called?
well connected blocks, is not the same thing as variation/randomness
Iif I recall correctly.. it is done via blocks.json
you can look at code for connected blocks like that above.. it will have kinda what y ou need
Sort of like fences but instead of geometry changing, it's the texture.
Alright, thanks! 
search the discord.. Kaioga and Smokey have githubs with code and check #1067535712372654091
Thanks! 
how to displays an advancement-like "toast" message to all targeted players?
how to test how far above the ground the player is?
Good morning
how many dynamic properties can an entity have?
and how do i delete an existing one
as much keys you can get from 32k bit
there's no limit on the amount of dynamic properties
there's a limit on the sizes
keys too
yeah sizes is key & values
you will run out of keys eventually
set it to undefined
I just finished updating Kai's fence template, this will give you what you need 🙂
also check out my post here for how I did a vertical connected glass https://discord.com/channels/523663022053392405/1283097531349209172
Thanks! It's so hard since I don't know how to use scripts 
still limited
essentially infinite
dm me if you need a hand, I'm happy to help if I can
i don't even know if the game can handle a little bit of all that
Thanks, will do!
there's a higher chance the monkeys will type hamlet than you running out of keys
lmao
yeah but it is still limited 🤷♂️
if you made a new key every planck time (which is about 10^-43) seconds, it would still take 4.553 × 10^295880 seconds to max it out, which is about 1.438 × 10^295873 years
bruh i know the extend
when someone ask if there is a limit say there is but you won"t ever reach it (i guess i was supposed to say that too)
Yeeeess lol
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
items with cooldown category and cooldown length defined in the item can have cooldowns
though you cant add your own cooldown on vanilla items
Ah ok tyty, that was what I thought lmao
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?
dynamic properties
duplicate chat, move the copy to the right, filter all none achievements messages, modify its appearance, and replace the fade animation with an offset animation.
wait, this is the script API channel, then use player.sendMessage("your message" )
You have two methods
@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
@amber granite j didn't get it
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
}
ohh that make sense
just a
entity.triggerEvent('exe:despawn')
uh, wait
that script will not spawn the entities, right?
What ?
No
@untold magnet
U need increase the variable inside the event whenever the mob spawns
i tried putting the limit 3 to see if it works or not, it's not working
hmm
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
anyone help me with #1283463196728102953
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
Could do damage sensor for fatal damage
Can you show me it? I need an example please
https://wiki.bedrock.dev/entities/invulnerable-entities.html#using-damage-sensor
I feel like it’s easier to use this
It has damage sensor stuff in it
hello
maybe in before placing, do a count and if over 49, cancel placement or change permutation to not do the spawn part
but that is for loaded chuncks
so tech can have more than 50 in world if move far away
if no loot needed, can add event that cets client group with instant despawn component... can call that event outside anywhere
No I wanted it to make it so It can survive /kill at 1 HP then after 1 second or 2 they're able to be killed again
no one but a player can survive /kill
Min hp mobs
Just by adding a min: on
minecraft:health
value: 20
min: 1
They can survive /kill
Idk but it's there
I would not count on something like that as permanent
In java edition on a mod if you do/kill they won't die by after a few seconds they become damageable again
if I do a /kill @e[whatever selectors]... it is because I am testing and they better f'n die
Wanted to recreate it
No
/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
Not even with despawn and environment sensor and damage sensor can kill it?
Well, those are not killing the entity. Despawning simply removes it
I imagine the .remove method in scripting can remove it just fine too
But I need to it die after a few secs by being able to deal damage to it tho
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
put the real kill event in runTimeout.. with a 40-60 tick delay
Aw this article is useless here.
I thought it would have had a section for what I described
ACTUALLY I needed this thank you anyways I'll just use a different means of invincibility
I needed transform thing for my other mob
Do you know how I can make it so once they reach a certain Health they transform because I don't know how to do it
I would credit anyone that could help me with it
With my addon
try the environment sensor.... see if a filter for health, then run an event to do what you want
Is it possible to receive an effect and have it not appear in the effects hud? Are they hidden?
you mean a hidden effect?
i think it's only possible using like 5 ticks
idk
yes, you receive it but the game doesn't tell you that you have the effect
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
for example 1 second?
hmmm, is there a way to detect the amount of entities? like if there're 3 entities at the loaded chunks it will be detected
i mean
Use getEntities
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||
how exactly?
for (const entity of block.dimension.getEntities()) { ,,, }and?
Use the entity filter options to grab just your entoty then check the array length
block.dimension.getEntities().filter(50)?
@untold magnet
im reading the docs
ik
using the script does it count the time in ticks?
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);
})
}
i dont think i had to use this if i can detect how many entities are in the world
if the script detects 50 mobs it will run a function
or seconds?
What ?
I can told u that , that s the most effecient way to do it
Because after exceeding the limit of 50 the event won't ever trigger= more performance
@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
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
my brain not braining
- put if statement inside the playerPlaceBlock event
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......
X2 my brian isn't braining
reusable code...
if you say so.... whatever
Yeah
my brain for sale
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
U mean whether to handle the total of 50 mob for the whole world
Or 50 mob spawning ability for each player
spell out the rules
@untold magnet
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
is it really important to have a limit?
And.. if you are looking at API docs, no way you cannot find the entity filter options....
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
It is your add-on, that is your decision
yah, i did some searches
Yes because
You are bedrock player
Bookmark this, like it was the link to your bank... https://jaylydev.github.io/scriptapi-docs/
And others are bedrock's players too,
That means they are likely to be playing or android or ios ( mobiles )
now go into the dimension class, find the getEntities method
bro the block that will use entities is quite expensive to make,
☠️
make sure you are on right version.. but any should be fine for this one
Ok then
that is his choice....
and none will keep using it, its for the start only
So , 50 blocks in total is the limit across all the players and in the whole world?
Or every player can spawn 50 mobs
i better make no limitations, u can have infinity amount of entities, but W H Y
U want to limit bro
50 for all players
the entire world has a limit of 50 entities
...
it will
Hmm no other factors will kill it right ?
so chickens.... and cows added to your block and players.... all just 50?
- Did u write an playerBreakBlock event or other events like blockExplode to hande that ?
only /kill, and i think i can make it undieable by making it health 1
just run a thing.... killing random over 50
i dont have to bro
Why ?
in that case of lag, loaded is what is important
i can make a system that will automatically kill the entity after it is out of the block
So if u break the block ur system will detect that
And kill the entity
Is that system is made with script api ?
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?
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
It is made with script api right ?
yup
- that s smart , i really made events for all those cases ☠️
I mean that s the smartest thing i ever seen today
the block will use onTick anyway, so i can teleport the entity if u pushed it with a piston
Then make that system decrease the global mobsNum when u kill the entity
if the entity is NOT in the block it will be auto killed... that is what you wrote.... it is not logical... how did it get outside of the block....
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
Why didn't u tell me ☠️
U could save me a lot of time
🤨
after breaking the block, or exploding it
or using other addons that somehow will teleport nearby entities
U know the chunk loader i made
i did
i think?
then have the entity use an enivro sensor and if it is not in_block then despawn
No u didn't ☠️
give me a sec
There really isn't an icon, but the effect also keeps coming and going, as I want to do it with night vision, it doesn't look good.
Then lemme write u a code for that
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);
Just have the entity despawn if it is in minecraft:air.... you can do that in the entity's json... no extra work needed
i did
na, what will happen when u replace the block somehow?
the block will not be detected
i did it like this
doesn't the new block spawn a new entity
I didn't understand what that means
const block = entity.dimension.getBlock(entity.location)
if (block.typeId !== 'minecraft:dirt') delete.function.com
it is like TNT, it is a block with an entity
simply it will detect everything except the dirt block
dm
the tnt block will turn into an entity after lighting it up, that can be easily done for me
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
im putting entities on my custom blocks to do work like custom { storage or furnace or chest }
okay, I'm lost.... this is all over the place.... have fun guys
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
No errors in [code](#1067535608660107284 message)
i forgot this bot exists
command?
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
@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.
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.
my hands telling me to do it, but my brain is disagree
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
depends on your challenge level and love it solving problems
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
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?
How can one get the riders on an entity? Resolved
- try setting blendOutTime
- wrap
creeper.playAnimation(...)withsystem.run()just in case
try a different animation, pretty sure animation.creeper.swelling requires variables otherwise u aren't going to even notice it
^
whats server-editor module
Is there a good way to read through all the script documentation to understand it better?
how do you go from reading pages like these to actually using all of this stuff in scripts?
its a different website
it doesnt really explain anything
ooough
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 #1283731287475097644
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
location.runCommandAsync 😅
?
what
location is the const of the block location
it is just a vector3
there is no runCommandAsync in it
do
const {x,y,z} = block.location
block.dimension.runCommandAsync(`fill ${x} ${y} ${z} ${x} ${y} ${z} air`);
or use fill native method
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
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
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
do setItem
Sadly doesn't work and neither does it work with the text at the very bottom of the post
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
how
actually no its setEquipment
so you mean ```js
item.setEquipment
- get equippable component from player
- get slot, and in this case, it would be "Mainhand"
equippableComponent.setEquipment(slot, item)```
EntityEquippableComponent#setEquipment
Yey
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 ?
No
thats were i got it from 🙂
ohkkk
thanks, aww man, now i have to do all those equippabble thing again
is the new script fine ?
no
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
yeah that
Yo any help will be absolutely appreciated!
const block = ...;
block.setPermutation(block.permutation.withState('facing_direction', ....));
umm, #1283731287475097644 ?
@shy leaf sorry for ping,
d u know anything about dynamic property?
Thanks very much! I'll test it
sure
"hey" was to test if the event was working
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)```
is "dragon" a array or object?
const rayResult = dragon.dimension.getEntitiesFromRay(
{
location: dragon.location,
}
)
try this
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
const entitiesArray = ["0", "1", "2", "3", "4"]
const options: EntityQueryOptions = { ??? }```
u,h
have you checked the doc i sent you
idk what should i use, im completely lost
ya, i haven't understood almost anything
also are you using typescript
javascript
then that aint no javascript thing
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()
})
const entities = player.dimension.getEntities({
type: "namespace:typeId"
});
console.warn(`${entities.length}`);
heres an example
o
you cant simply use nameTag for items
really?
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
you can also get what item is that exactly
really?
i thought that way would work best
yeah
item.getComponent("item")?.itemStack.typeId
the typeId is for the nameTag?
playerPlaceBlock.sub(({ block }) => {
block.dimension.spawnEntity('my:entity', block.center())
const entity = block.dimension.getEntities({ type: 'my:entity' }).?```
the item id
like minecraft:dirt
oh but am tryna get the nameTag
'dragon' is an object. Also this didnt work either. I added both location and direction parameters but doesnt seem to work either. I did this, seems to work:
const rayResult = dragon.dimension.getEntitiesFromRay(
dragon.location,
updateRay
);```
not id
oh alright
i was unsure if it was a object or array
yeah ill clarify next time, but thanks
yeah np
do you know how to set a block on fire? typescript blockRayResult.block
use .setType()
@glacial widget do you know how I can obtain the FOV of an entity?
Update: nvm i figured it out
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());
}
}
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
Can ActionFormData buttons be created automatically or are they manual?
They can be dynamic yes
Yes, you can add lore, or dynamic properties to set a specific value if needed.
Can you give me an example?
Ok, I realised I said it very badly.
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
});```
I see, thank you
{
"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?
You would have to create your own loot class. But you could make your own setup I suppose.
own loot class?
well, code you can tap into for repeated use.
We can't use json loot tables into js (as far as I'm aware)
sorry, for acting ignorant, I haven't done add-ons in a few months xD
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
hmm, I think I might do that
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)
So yeah you can do anything
With events
thank you
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 )
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
Make a new post
done
is there any way to automatically set max players?
dont think there is a way
not sure about BDS though
alr
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 :¬)
you could use some optimization here 
(j, rest well)
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
}
}
haha
the function doesnt have the name
ill just do it hold on
I could shorten this part into it's own constant as it's being called 3 seperate times item?.hasTag("pickaxe_level5") || item?.hasTag("pickaxe_level6") || item?.typeId.includes("netherite_pickaxe");
I forgot to put it in for Discord
There, it's in now
I'll look into how I can get it to work in the later morning
I'm happy with what I did today, even if it took me 5 hours or so just for this
I haven't used JS in 5 months
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
This is where i wish we had better loot table support
ikr
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?
is the maxDistance option in EntityQueryOption for x and z directions or for xyz?
no
xyz
a circle
theres cursor component for inventory
in preview? iirc
but its also very limited
not what he is asking for
that one related only to the item
if there is something it is probably in the editor api
why it set me back to my previous pos?
do you have other packs enabled? or did you use teleport methods?
nahh i don't
its just main.js on the scripts folder
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);
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
maybe its problem with wifi or something
is there anything wrong in that script?
the entity is not taking any kind of damage,
nahh man, local have a problem with wifi?
Well it works for me me tho 😅
mmm...
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")
});
}
}
});
Checking y twice?
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")
});
}
}
});```
Titanium?
Sounds so sick
Yes, I'm wanting to slowly make an industry type add-on
Titanium has a very small chance irl of being found within Bauxite
I think I want to do create for bedrock but it's copyrighted
People are currently doing create for Bedrock
#add-ons message
They sometimes post it
They got permission from the Create Devs to do it
[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
Debug result for [code](#1067535608660107284 message)
Compiler found 2 errors:
[36m<REPL0>.js[0m:[33m8[0m:[33m56[0m - [31merror[0m[30m TS2304: [0mCannot find name 'ball'.
[7m8[0m shootPower(eventEntity, "wesl3y:projetil", null, ball, eventEntity.name);
[7m [0m [31m ~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m8[0m:[33m74[0m - [31merror[0m[30m TS2339: [0mProperty 'name' does not exist on type 'Entity'.
[7m8[0m shootPower(eventEntity, "wesl3y:projetil", null, ball, eventEntity.name);
[7m [0m [31m ~~~~[0m
There are no errors from ESLint.
i need a dynamic property help
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?
Events
I wouldn't use tags for this. You can just store the entity ID in a world dynamic property that corresponds to the block location.
You don't even have to store anything on the entity
There's over 300k
Was 99998 before my last 2 msg
Ye, it does that a lot
u're still alive
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?
haven't seen you in Amthyst for months qwq
You have to wait for the chunks to actually load
That's because it's not being worked on anymore
yep it dead
And I'm not great at C++, and I needed the 20gb+ it all used up to make a mod
i wait like 20 ticks, is that not enough?
or does my player have to load them,
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
I would do loop, then have max check time
yep it was bad... welll we all moved on now... most of us are now on the mp lol
damn
hm okay. ill have a go at that then. Thank you
I'm trying to create an industrial add-on
marketplace?
ye
yep :p
nice
Currently for my add-on, I'm doing the ores and such
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
it sounds really interesting, wish ya good luck ^^
Thank you
Trying to use JS for most of it
Since that's the best and fastest and most flexible
instead of JSON
Def dynamic
ye
tin and aluminium are candidates Id love to see :p
Already have aluminium planned
- 38% chance of Aluminium
- 37% chance of 1 Iron
- 20% chance of 2 Iron
- 5% chance for Titanium```
Tin is definitely going to be there too
I don't need to do any scripting for that one though
what about cobolt?
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?
uiii thats gonan be interested
xD
istg Id love to but I'm so busy with other stuff
fair
mp, bedrockrs etc
Most of us are busy with other projects, but somehow have time to answer questions here in our work hours lol
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
Lol fair
I swear I'm not usually this slow xD
entity events/set_property?
or just runCommand?
entity_spawned?
why did they add lore line limit 😭
Stability and screen space
They became people's databases lol, and I'm sure because they knew item dynamic properties were coming
yo lucy
didn't know you were active here
how are you doing?
Me fr
this channel is surprisingly not active this day
fr
Modularized code, what do you guys think?
Not bad, seems like my ADK LIB
Still to active for me tho, i have no idea what is happening
there is a notepad++ user above that you can bully to switch to vscode
Well i was also notepad++ user, but so far vscode is way batter, and you will get used to it for sure, trust me switching is good choice
nodepad++ lol
lol
good night to everyone who has night rn
I use vscode. But opening it on NP++ is faster lol
reasonable
for falls under what in js?
loops
ty
same as
do while
while
for each
[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?
block.isValid()
@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());
});
}
}
});```
hmm
What the problem doc ?
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)?
☠️
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
so how can i make the script detect if that slot is not empty?
Entites have inventories
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?
if (item(0)??) { ,,, }?
just equippable
u can detect items inside the entity inventory, right?
@distant tulip ,
const item = invComponent.container.getItem(0)
if(item){
//...
}
it should detect it when that slot doesn't have an item
oh, yah right
my brain is on holiday rn
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)
]
chatSend is beta
again
I had the same problem
Add (0)
To inv.getSlot
use beta api
so
const inv = entity.getComponent('inventory')
const slot = inv.getSlot ← useless?
const item = inv.getItem
if (!item(0)) { ,,, }```
1.14.0-beta right?
yeah
alr, I'm stupid
getSlot can also work
I uploaded the wrong manifest
Wait
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
the entity have 3 slots
if (!item(1)) { ,,, }
if (!item(2)) { ,,, }```
i dont want to const each slot
each slot will work differently than the other
i mean, there are some dynamic properties that will happen for each slot
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
Bro i m talking with t17x
this will make the dynamic property works with all 3 slots at the same time
Blud thought that i don't know how to write a loop
that actually true...
XD
i want each one has it own section so i can put different dynamic properties for each one
Wait what
the variable is referring to the function
hmmhmmmhmmmm
It was worth it learn js ☠️ i m not useless after all
how can i detect a scriptevent inside of an interval?
why
Yeah why
The event will trigger once and do its functions once
Even if it was in an interval
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
That make it useless and u won't get any additional effect by doing that
interval just make it sub to the event multiple time
you don't want that
as what i said, my brain is on a holiday today
Ah what about putting the code of the scriptevent inside ur function or idk
I don't get it , can u explain it correctly?
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?
Sorry what
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
An item or a specific type of items ?
that slot doesn't have any items on it when the entity spawns, so it will be automatically set as false
some specific items
Yeah that s correct
even knowing, if the item has been replaced will reset the property
Replaced ?
Replaced item will need extra code
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
so what kind of codes are that?
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
my brain isn't braining
I should told u that the variable must looks like :
let PreviousItemTypeId = true;
Wait
that will not store the last item typeid
The last true item right ?
PIT = item(0).typeId will be the same when u replace the previous item with the new one
Like if the dynamic proprety will gonna be setted to false
It won't save the last item right ?
What ?
Nah that s wrong
@untold magnet
U want me to explain how it works?
explain
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
literally, my brain isn't braining
also im carrying about my health, i might have some issues in my chest
So let s say u used
=== To compare string and boolean
like a blocked blood channel
Go to the doctor
after 2 days, if the pain is still happening randomly i will go
Ok
tomorrow and after tomorrow
its a small pain, not that huge
similar to that random chest pain, but way weaker
May god heal u
and its not inside of my chest, just like the outside or near the surface
Yeah go to sleep
cya
No it means tags tags. Name tags have their own
No
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
I see
But what does a nametag fall under?
entity/player are objects
so
entity/player property
Ye i meant like which property
string?
Bruh
It s proprety to the players object same as player position is a proprety for the player
And so on
It s not falling under any other proprety or derived from another
that what i said 🤷♂️
Yeah
Yeah a string that we all agree to use it
Fair
For making some functions works with players and don't work with others
Or splitting them to teams
Or idk...
there is also the name property
this one only present in the player
I'll try using the id property first
id ?
nametag is changeable
name is not
use name to get the player actual name
in case any addon change it
Then move on to getting a specifically named mob
Ye
The id can be change from world to other
Ok
I'll use name then
Like minato said
id is better
If you say so
only possible if the script run in the first world load
Ok
...
Btw since player is a sub group of entiries
So we can use the entity properties for a player
And the opposite?
No
some don't work
for example setVelocity
clearVelocity
almost all of them can
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
you can
not the equipable slots
Mhm
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 💀
☠️ learn js
i only sleep for 5 to 6 hour (i wake up without any alarm after that)
I started today
Then
Oh wow
I'm around 30% in
Then use ide or code editor
Lemme test u
I can't focus without 6h min
Do u know iife ?
Ide?
Iife?
No iife
Integrated developments editor
I use vs if that's an answer lol
No there is visual studio and there is visual studio code
It's quite fun
Learn from
modern js website
Theres a logo difference?
It really helped me
Lol blud said logo difference
Blud is newbie so ye i will ask the weirdest questiona you can think of
