#Script API General
1 messages · Page 65 of 1
how to set a name of an item in a container ? @subtle cove
const slot = inv.container.getSlot(1)
if (slot.hasItem()) {
slot.nameTag = name
}
when managing components, use ItemStack;
otherwise, use ContainerSlot
hey yall, new scripter here
Anybody know how I can make an entity summon another entity through scripting? Once ive done that I have other things I'd like to learn how to do similar to that
entity.dimension.spawnEntity('tnt', entity.location)
```?
does getSlot exist ?
mhmmm, even in stable
is there a way to make it spawn the entity at another entity (basically just execute as @e[identifer] at @s run summon [entity])
id use the command itself if it wasnt for a limitation that would take some SERIOUS hard coding
there's a few things to learn
dimension
getEntities({type:'minecraft:creeper'})
loop through that, then spawn any entity spawnable
should i cut to what im trying to do as a whole?
i'd create a post if i were u
sus
sussy baka 
entity.dimension.spawnEntity('tnt', entity.location)
this code just does that...??
scroll down a bit
from that
hm so?
why that
theres a LOT more to the script than just summoning the entity
you said "LOT" more like its hundred lines of code lol
i meant in context
alr
read #1350698793816817675
uh-
after.entitySpawn.subscribe(({ entity, cause })=>{
const { x, z } = entity ? entity.location : 0
const level = Math.round(Math.random() * 5) + Math.floor(Math.sqrt(x ** 2 + z ** 2) / 100 * 5)
const capitalize = (str) => str.split(/:|_/).splice(1).map(s => s[0].toUpperCase() + s.substring(1).toLowerCase()).join(' ');
const entityId = entity.typeId;
const entityNameById = entityId.split(":")[1];
const name = `${entityNameById}Lv.${ level }`
if (level && !isType(entity,"minecraft:npc") && !isType(entity,"minecraft:armor_stand")) {
score(entity, "level").set(level)
entity.nameTag = capitalize(name)
}
})
it doesn't show anything no errors¿
Put a logging
you need to know if the name really change.
ok let me check
const capitalize = (str) => str.split(/:|_/).splice(1).map(s => s[0].toUpperCase() + s.substring(1).toLowerCase()).join(' ');
after.entitySpawn.subscribe(({ entity, cause }) => {
const { x, z } = entity ? entity.location : 0
const level = Math.round(Math.random() * 5) + Math.floor(Math.sqrt(x ** 2 + z ** 2) / 100 * 5)
const entityId = entity.typeId;
if (level && !"minecraft:npc minecraft:armor_stand".includes(entityId)) {
score(entity, "level").set(level)
const name = `${capitalize(entityId)}Lv.${level}`
entity.nameTag = name
}
})
thx it works
sorry if i had to remove the isType function there ;-;
Anyone willing to help me balance my combat will req live testing so its not as simple as rewriting script snd done
Привет...
Hello...
Lrts all chew coddy out for not using english in an english only channel 😛
how do u freeze a entity
set the location to the current location of the entity in every tick?
but that will be laggy
Entity.clearVelocity()
one sec i forgor
can someone remind me how to check for if item has a lore
ItemStack.getLore()
thx
Returns an array of lores per line.
wasnt there a hasLore
Uhh, no?
Only hasTag()
you must be having the Mandela effect
includes?
OH
I mean literally use the include function
thankls for remmebering me
ItemStack.getLore().includes('Bruh')
i gettttt
wait
how i get the itemstack

YOU GOOD?
use getEquipment() or inventory component
me who didn't use any typings and just use ny brain
i was gonna remove it any way
Add me and i will
is this less resource demanding than just using dimension.getBlock()
how is it possible for just one of these to show a type error ??
let effect;
if (castType === CastableEffectType.Click) {
effect = combatClass.clickEffects[itemTypeId];
} else if (castType === CastableEffectType.Held) {
effect = combatClass.heldEffects[itemTypeId];
}
there isnt a good way to store player plots/skyblock islands in an external db right?
going over each block takes forever because i cant afford spikes
use runJob?
runJob fixes everything honestly
what is runjob
how to run animation on projectileentity when entity hits mobs
Hey when I use the Date function in js in a multiplayer world and log it out in chat as each player, will it it return the world's host's date or will each player get their own local date?
a function under the system class that uses generator function to run a set of tasks in different times
Generator functions have something called yeild, when the runjob run the function and reach a yeild it stops the execution and resume it next time the game is free
bro came for commission
the host device time
lol
do you mean run the animation when the projectile hit an entity or...?
How to get the host of a world?
wdym
Is the host the number [0] player?
not entity animation that it hit
How can I spawn a particle that only the player can see 35 blocks in front of an entity using spawnParticle?
not sure
save the player name when the world start and use that
use projectileHitEntity and projectile.playAnimmation
oķ
But won't like playerSpawn or playerJoin run every time? I don't know if there are any methods of the world class like worldFirstLoad or smh
"only the player"
what player?
Ok so I have a player and an entity, with player.spawnParticle I want to spawn a particle 35 blocks in front of the entity, like using ^^^35 but in script
yeah, but make a variable
let hostPlayer = undefined
and when playerJoin do
if(!hostPlayer) hostPlayer = player
particles spawned with player.spawnParticle only the player can see them iirc
yes that's what I want
that what it does...
I want only the player to see the particle but the location of it should be 35 blocks in front of another entity separate from the player. Sorry English isn't my first language so maybe I didn't explain well
Basically how do I get a Vector3 of the block (even if undefined) 35 blocks in front of that entity
try this
const { x, y, z } = entity.location;
const { x: rotX, y: rotY } = entity.getRotation();
const rad = (rotY * Math.PI) / 180;
const forwardX = -Math.sin(rad);
const forwardZ = Math.cos(rad);
const targetX = x + forwardX * 35;
const targetY = y + 1;
const targetZ = z + forwardZ * 35;
player.spawnParticle("id", { x: targetX, y: targetY, z: targetZ });
wait, you want it relative to the entity view? sense you said "in front"
"player" in the parameter?
Thank you
Yes I want it to work like the ^^^35 with minecraft commands, getting the block in front of the entity with a distance of 35 blocks
use playerSpawn with initialSpawn
Oh
Thank you
Oh wait basically I wanna run a command as the first player that joined
Somebody explain this madness pls
What
on playerSpawn getAllPlayers and check if the array length is 1
displayedStats: Partial<Record<keyof CustomPlayer, () => boolean>>;
this.displayedStats = {
combatClassEnergy: (): boolean => {
return this.activeCombatClass !== "none";
},
};
i have displayedStats defined like this on my custom player,
for (const [key, condition] of Object.entries(customPlayer.displayedStats)) {
const stat = StatMap.get(key);
if (!stat) continue;
if (!condition()) continue;
let statString = customPlayer[key]; // RIGHT HERE
/* continues ... */
but when i try to use it here, it thinks key is a string and not keyof Customplayer so it gives me a type error ??
Wait I don't wanna run a command as soon as the first player joins but in another scriptevent function which will be used in the future
import { world } from "@minecraft/server";
let firstPlayer = null;
world.afterEvents.playerSpawn.subscribe((event) => {
if (event.initialSpawn && !firstPlayer) {
firstPlayer = event.player;
world.sendMessage(`First player set to: ${firstPlayer.name}`);
}
});
world.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id === "custom:id") {
if(firstPlayer?.isValid()){
//go something
}
}
});
for (const [key, condition] of Object.entries(customPlayer.displayedStats) as [keyof CustomPlayer, () => boolean][]) {
const stat = StatMap.get(key);
if (!stat) continue;
if (!condition()) continue;
let statString = customPlayer[key];
}
yes thx figured it out
just weird that i even had to use type assertion in this scenario
@distant tulip do you know what the latest beta/stable version of v1 is ?
one that uses structure
1.17.0 1.18.0-beta
there is one that i can use?
1.18.0 beta ?
#1252014916496527380 message
yes?
Pretty sure it will still take too long but I'm gonna check I guess
We are talking about 3.2m blocks
anyone has typeIds of all of the ore blocks
another question - is Set([]) and a Array the same?
Sets cannot contain multiple of the same value
srry but more like a #1067876857103536159 general question
@open urchin srry for ping, but i need a answer
you could probably just check that the typeId ends with "_ore"
nope, i do need typeIds
i have to do some switch case statements w/ them
these with minecraft: before them
alr
thanks
iron, gold, and copper only drops raw ingots??
oh yeah raw diamond dont exist lol
How to ignore entities from a specific family using getEntities()?
excludeFamilies: []
hi
is there any way to block invis skins with server-net or a moduel??
Is it possible to set an entity on fire?
entity.setOnFire(seconds)
Why not check in the documentation first, before asking it?
I didn't find it
Sorry
Oh
no don't sorry no problem
if they did find it, I dont think they would be asking
Okay mb
Where are structures saved?
In the leveldb.
How can I export it to the world as a ".mcsteucture" file?
Not really a scripting question.
World generation idk
wait so i cant use a generator function like this
i am getting closer to giving up on the external db with each passing day
the function passed to system.runJob can only return nothing (void). You can't pass a return value and expects system.runJob returning a value
Yeah I figured that part out
Is it not possible to open the menu just after we send the command?
world.beforeEvents.chatSend.subscribe((eventData) => {
const player = eventData.sender;
const message = eventData.message.toLowerCase();
if (message === "!faction") {
eventData.cancel = true; console.log(`Player ${player.name} requested the faction menu.`);
system.runTimeout(() => {
openFactionMenu(player);
}, 500);
}
});```
I made a class that has a field with the type I wanted to return and it updates the field with each yield
Still too slow
Why can't we just get access to regions in bds
BTW I reccomend using a map for commands
pfffttt WTF
why do you have a runTimeout() set at 500 ticks
That will open the form after a wayyyyy long time
Thank you!
If you want to open the menu just after you send the command... Just remove the runTimeout()
I tried putting it 40 but it doesn't opens
it wont show up cuz the chat is still open
Right
oh fair
But a runTimeout() of 500 ticks still doesn't make sense
So @spark slate you have to use this "force show" code and remove the runTimeout().
That's just 25 seconds, it ain't that long.
no need for forceShow just do await form.show
He said "Is it not possible to open the menu just after we send the command?"
Then the 25 seconds delay doesn't make sense?
^
someone help me figure out how to save a block region to an array without lagging the whole server
save what
export async function saveBlockVolume(blockVolume: BlockVolume): Promise<{block: IBlock, count: number}[]> {
const dimension = world.getDimension("overworld")
const structureManager = world.structureManager
const blockArray: IBlock[] = []
let i = 0
for(const block of blockVolume.getBlockLocationIterator()){
i++
if(i % 6400*2 == 0) await system.waitTicks(1)
const blockData = dimension.getBlock(block)
const numericId = getBlockByTypeId(blockData.typeId)
if(inventoryBlocks.includes(blockData.typeId)){
const inventory = blockData.getComponent("inventory").container
const itemArray: IItem[] = []
for(let i = 0; i < inventory.size; i++){
const item = inventory.getSlot(i)?.getItem()
if(item){
itemArray.push(convertToDbItem(item))
}
}
blockArray.push({
numericId: numericId,
states: blockData.permutation.getAllStates(),
inventory: itemArray
})
continue
}
blockArray.push({
numericId: numericId,
states: blockData.permutation.getAllStates()
})
}
const compressedArray: {block: IBlock, count: number}[] = []
let currentBlock = blockArray[0]
let count = 1
for(const block of blockArray){
if(count%64000 == 0) await system.waitTicks(1)
if(JSON.stringify(currentBlock) == JSON.stringify(block)){
count++
}else{
compressedArray.push({block: currentBlock, count: count})
currentBlock = block
count = 1
}
}
return compressedArray
}```
thats like one of the many functions required to do this
That'd ofc lag the whole server
i mean i can always just make it do less blocks per tick but that doesnt solve anything
how about using runJob
wait no lol
i mentioned that earlier
Are you high? I'm not stupid
Vjill
yes it's possible to open but you using 500 ticks is high is what I'm trying to point out
Like I'm not stupid y'know, I literally pointed out wha he said that it's long.
How big is the area?
Okay but I didn't say that your stupid 
100x384x100
cut them into multiple parts, check the 1/4 then 1/4 then so on.
i am already splitting it into chunks of 6400 blocks
you didn't said it yes, but the way you're saying it...
That's still a lot.
Check even more smaller.
What's the purpose of it btwm
I mena the purpose of your script generally.
i am making a hypixel skyblock like server i need to save the player island to a db
(using mongodb)
Ahh, instead of that, just check the placed block using playerPlaceBlock and playerBreakBlock.
That's the best way since you doing that is very resource intensive that the runJob can't help you that much.
i dont think its a good idea cuz that would mean either a lot of ram usage or very frequent db calls
Much better than saving a lot
Just choose since you can't do anything about either Make it save slow but surely
a single island can be up to 40mb
thats with compression btw turning typeIds to numeric ids
As I said just choose since the way server do it way different than just scripts alone.
unless i made islands 64x
and made it so that players can have multiple of them
that way i can use the structure object to get block data faster
hmm i need to benchmark it
runJob can run multiple times at a tick
Did you test it out?
yeah i tried
almost no difference
choosing pure bds for hypixel skyblock type of server was a bad idea
What are you trying to do exactly
i need to save a player island into a format that i can store in a database (using mongodb)
Why tho? What is the use case, that seem a bit inconvenient
basically storing player stuff outside of the world gives me these benefits:
- easier updating
- player data backups
- regions
- easy horizontal scaling
save it into a structure :D
how do i send a structure via rest api tho?
rest api? not script api?
i am using script api
i need to send the data to a database and that is done via rest api (server-net)
Maybe try using StructureManager Class. Return Structure Class, then iterate each block permutation within it.
for loop .size:
structure.getBlockPermutation(xyz)
might be faster, idk
Might just let it run slow, and put in a progression bar to indicate when it's finished.
-# You can put Loading tips~
nah i gotta figure out a faster way to do it
The fastest way is probably just to save the structure locally using World StructureSaveMode
-# "The structure will be saved to the world file and persist between world loads. A saved structure can be removed from the world via @minecraft/server.StructureManager.delete."
Which scraping the idea of external DB
You can technically do the block-per-block conversion and saving process in the background for external DB.
Basically treating StructureSaveMode World as a buffer.
was it worth for an extra speed?
it takes 5 ticks to save 64x64x64
It might be a dumb question but what exactly does system.runJob() do?
You need to understand js generators
I mean it's not bad, if 64x64x64 is 5 ticks 100x384x100 takes about 3-4 seconds
@deep arrow
I did my estradiol injextion the other day and hit a nerve its not fun
And i am still months away from getting on E
Youll get there theres plenty of e to go around
Injections suck tho
Sucks that there is a patch shortage
#off-topic
does anyone know the condition for setLore to throw?
if you passed the limits
the array and string limit
can't tell if thee is more
any ideas on how to stop a particle from spawning outside of an unloaded chunk? It's being ran when an entity gets hurt
isValid doesn't work for whatever reason
You could spawn only in a radius around the player I suppose
There isn’t really a easy way to do it
You could try to getBlock under the entity
is their a way to trigger an event like onRandomTick instead of it always being active
It should return an error if the area isn’t loaded @cinder shadow
Here’s some pseudo code (I’m on mobile rn)
FUNCTION checkChunkAndSpawnParticle(entity, particleName)
SET dimension = world.getDimension(entity.dimension)
SET position = entity.location
TRY
SET block = dimension.getBlock(position)
CALL world.spawnParticle(particleName, position)
CATCH error
IF error.name EQUALS "LocationInUnloadedChunkError"
PRINT "Chunk not loaded"
ELSE
THROW error
END IF
END TRY
END FUNCTION
```
I wish we had a chunk class
thanks that actually works ```js
if(hurtEntity.dimension.getBlock(hurtEntity.location) == undefined) return;
I’m really glad man, because it was a total shot in the dark 😭
I’ve been running into that error with getBlock and I figured it might be useful to try and leverage it for canceling stuff outside of the world bounds
Your method is way cleaner lmao
I mean try catch works too
I will never try catch anything
Ngl, I always hate the pseudo code, especially when I'm in my comp class when I was g9, it's ugly asf.
try catch is uglier
I'm joking, im sure you are incredibly handsome.
🤣 🫵
Is there any event that runs whenever the player hits the interaction/placement button? Like even when they click on air or whatever. Essentially just right click detection?
itemUse is one of them if ur using an item for anything
I activated my behaviour pack but my script doesn't run
can anyone help me with something? ive got a script that sends an array with functions inside the items through scriptevent by serializing the items
the main script then deserializes the script event message and pushes the items into main array
but for some reason, if the first item in the array has new keyword inside its function, the first item gets ignored entirely before it gets pushed into the main array
the rest of the items are fine though
https://gist.github.com/RayyanNafees/32f69e1cf146149bf358c5501ed93816
this is the serializer/deserializer im using
i can send codes in dms
sus 😳
sussy baka 
Anyways
Show your manifest and script
"my script doesn't run" this really doesn't help
Confirm if there's any error. Do files get imported correctly?
The more you use this emoji the more you become brain rotted.
The way you say things like that in a serious question isn't funny.
If anyone wondering , why he is so sus bcoz, that guy is a owner of a bedrock addon dev team, and bro asking "my script doesn't run" Is really sus to me. Logic ain't logicing.
Alr sorry for flooding this chat
this exists #1277940040688996512
already has Arrays and a bunch of other stuff builtin
probably in dms
alright
Does anyone know how I can encrypt my script codes for extra security?
Online JavaScript Obfuscator helps to encrypt JavaScript which make hard to read js code. It's obfuscate javascript code.
There is online JavaScript obfuscator
obfuscator*
So thanks!!!
Does this also work for .json codes?
nope
Use this for obfuscating JSON
https://craftydev.tools/json-data-obfuscator
wait uh am I muted??
the bot sent me messeges that the links were suspected
?
When I paste my code, the page closed ._.
{
"format_version": "1.20.0",
"minecraft:item": {
"description": {
"identifier": "kit:item",
"category": "items"
},
"components": {
"minecraft:icon": {
"texture": "nautilus_shell"
},
"minecraft:max_stack_size": 1,
"minecraft:display_name": {
"value": "§eSelect Kit §7[Use]"
}
}
}
}
{
"\u0066\u006f\u0072\u006d\u0061\u0074\u005f\u0076\u0065\u0072\u0073\u0069\u006f\u006e": "\u0031\u002e\u0032\u0030\u002e\u0030",
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u0069\u0074\u0065\u006d": {
"\u0064\u0065\u0073\u0063\u0072\u0069\u0070\u0074\u0069\u006f\u006e": {
"\u0069\u0064\u0065\u006e\u0074\u0069\u0066\u0069\u0065\u0072": "\u006b\u0069\u0074\u003a\u0069\u0074\u0065\u006d",
"\u0063\u0061\u0074\u0065\u0067\u006f\u0072\u0079": "\u0069\u0074\u0065\u006d\u0073"
},
"\u0063\u006f\u006d\u0070\u006f\u006e\u0065\u006e\u0074\u0073": {
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u0069\u0063\u006f\u006e": {
"\u0074\u0065\u0078\u0074\u0075\u0072\u0065": "\u006e\u0061\u0075\u0074\u0069\u006c\u0075\u0073\u005f\u0073\u0068\u0065\u006c\u006c"
},
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u006d\u0061\u0078\u005f\u0073\u0074\u0061\u0063\u006b\u005f\u0073\u0069\u007a\u0065": 1,
"\u006d\u0069\u006e\u0065\u0063\u0072\u0061\u0066\u0074\u003a\u0064\u0069\u0073\u0070\u006c\u0061\u0079\u005f\u006e\u0061\u006d\u0065": {
"\u0076\u0061\u006c\u0075\u0065": "\u00a7\u0065\u0053\u0065\u006c\u0065\u0063\u0074\u0020\u004b\u0069\u0074\u0020\u00a7\u0037\u005b\u0055\u0073\u0065\u005d"
}
}
}
}
Do you want to prevent others from stealing your JSON Code? Then, you can use this obfuscator to prevent others from reading your code, this is mainly recommended for Minecraft Bedrock Add-on creators.
Use this for obfuscating JSON
it's completely useless, anyone with a bit more than 3 brain cells can deobfuscate that
I know right
I have the same thinking just like you
There's no point of obfuscating
But he still wanted to
Ofsucating is really useless
Ooh ,ok so thanks bro
It's also bad for performance and bloats your pack's size.
Agree
why would you obfuscate scripts anyway
people who doesnt care about scripts would have bad performance
and people who does would deobfuscate it with no issue
its like a keylock, but they have bolt cutters
how come we aren't blaming marketplace creators too
Their code is encrypted, not just obfuscated
Because marketplace creators dont get to choose to encrypt or not?
There's an entirely different scenario when you obfuscate something free vs a paid product.
obfuscate and encrypting are tow different things, he was talking about how obfuscated code is less performance, and in all honesty, if there was a encrypting method for none mp, most of us for sure will use it.
if i made my pack free that doesn't mean i want people stealing my code. there is a time and place for open sourcing, even licensing your work don't mean anything
They should introduce some sort of encryption tech for non marketplace creators
doesn't work like that
?
I leik free knowledge streams
May be risky, but it's better when more ppl get familiar and adapt with such new stuff
Soo? Just because a person is a dev he cant make a mistake?
I dont always steal code but when i do i make sure there are no witnesses 😛
I can relate
i can relate too
you can just add a comment on the top of the file crediting the author(?
But thats not properly stealing thrn now is it 😛
and ask for permission
you can do it or get reported by the author
Reduce illiteracy
does clearVelocity() clears mobs actions
like i want to freeze a entity, clearVelocity() will freeze the mob, but suppose as a skeleton, he will stop moving, but will he shoot arrows?
yes he will shoot arrows
I have a questipn if i credit the addon maker can i use another players addon to add entities i need for mine to save me time cause idk the first thing about adding a custum entity
it really depends on the addon maker themselves, you should ask em if you can, if you can't then credit them
If i try and noone gets back to me as many of these addon makers dont get back to you then do i just credit them or look for an addon where the addon maker responds
the way i see it, i am fine with anyone seeing the code and learning from it, just not straight up copy it to a similar addon and call it a day
What if they copy it to use it in there addon and credit you for the features it added
I still wish i could cancel vanillas hit censor its so weird when fighting and your attack misses due to my coding logic yet you still show as damaging it
that's how I learned lol, by grabbing code then reading it
I learned cause of my college classes
asking and not receiving a response does not default to allowing you to do something
they have no obligation to respond and confirm whether you can or can't use their work
Try catch is important when you are too lazy to check some stuff
Jaly its working?
Try catch is debug handling and a very useful tool in development 1 of the first things i learned in college a good code aftually ends up with more tests and tries then actual code if you never use it youd slack at making any real software cause once it breaks and it will you will be left lost in potentuslly millions of lines if code unsure where the problem is
skill issue
Nope try getting hired in software dev with that attitude
Try debugging millions of lines of code with no try catch
Im in college for this
fixing the issue is better than hiding it in my opinion
Try catch is so you can find the issue
It doesnt fix the issue
Nope it lets you see what isnt working
By throwing the appropriate error
When I first saw Lea's tweet, I agreed SO hard. Sadly I changed my mind as I explained. This is a fun ride, I hope y'all enjoy it
SOURCE https://x.com/leaverou/status/1819381809773216099
Check out my Twitch, Twitter, Discord more at https://t3.gg
S/O Ph4se0n3 for the awesome edit 🙏
I was also in college for this. did not care
See if code fails at some point errors dont always show you what failed try catch will throw the error that you put into it so you know exactly what broke
The idea is to ensure any errors your code has you can find out exactly what failed when you end up with over a million lines of code that becomes very importaint your addons may not hit that point but real software
Minecraft estimates at 1.8 million lines of code
I understand coding practices, I have no reason to use try catch for what I'm doing
If anything it gets used more often in scripting to prevent content log errors from showing
which are already catching errors
Its used in debugging massive codes when code gets big those normal errors become less helpful
can someone tell me why the healthdisplay var is 3 charecters higher then its supposed to be some reason its 19 chars but its padded to 16 why ```function getHealthDisplay(player) {
let minhealth = scoreboardSet(player, "minhealth");
let maxhealth = scoreboardSet(player, "maxhealth");
let display = `HP: ${minhealth}/${maxhealth}`;
// Ensure it is exactly 16 characters for consistency
if (display.length < 16) {
display = display.padEnd(16, ' ');
} else if (display.length > 16) {
display = display.slice(0, 16);
}
return display;
}
function showHealthTitle(player) {
const healthDisplay = getHealthDisplay(player);
// ✅ Correct way to set the title without commands
player.onScreenDisplay.setTitle(`§4${healthDisplay}test`);
}``` im guessing theres 1 thing im missing
i mean its not game breaking as the split title works just fine set to 19 i just dont get where the 3 chars are comming from
do dynamicProperties save even after the world closes?
yes
thanks 🙂
can you show what this looks like in game?
I'm not sure if I'm understanding
showing you ingame wont help as it has to do with splitting title text
basicually i have the code set to pad the variable display to 16 charecters
however for split to work i need to set it to 19 charecters
§4 contribute to the length even if it's not visible...
thats 2 tho not 3
the $ also gets counted
wait what
the game sees $ as a charecter even tho its intended for variables and is ignored in all other context
It doesn't count
it doesn't?
I had this problem a few days ago but I don't remember what I did for it
That doesn't make sense to be counted since it's only for variables and it won't ever be a part of storing.
;compile js
console.log(`123${4}`.length )
Heh
const he = 1;
let string = `§4${he}`
world.sendMessage(`STRING: ${string} STRING LENGTH: ${string.length}`)```
I can't find anything more than 3 unless it's in the scoreboards value
Yeah sorry for that, I have been using that a lot yesterday or last last day.
Plus this finest guy
I think you might have to save it in playerLeave event
No?
§: 1
4: 2
he = 1: 3
Unless you are talking about the inside of ${}
That won't work since the server is already shutdown if its singleplayer.
woops I read it wrong
let str = `c${x}`;
console.log(str.length);```
This one returns 2, which is correct.
Depend on the value of x
It's 1 so yeah
how do I make a form which can change entity name or name tag renaming
kinda need to see what it's outputting to actually find out what's wrong, so showing what's happening is pretty important
get the entity first.
Need context how you opening the form.
uhh, no? I mean using chat, right click item, right click mobs etc.
Entity.nameTag = "your_nameTag"
@dim tusk item
3 is whats not counted but the var itself is padded to 16 but there are somehow 19
Interact with entity is the bes option here
so if you do count 3 what is the third 1
Then get entity first, yu will use textField? Either way it doesn't matter you still need grab the entity you need to rename it with.
Yeah just use playerinteractwithentity
tho as I said need more context.
Odd, I dunno any reason for another one but I'm sure §4 is counted
i can understand color code counting 2 but the end of the var totals 19
because split 1 takes 19 to before it starts but if the var is padded to 16 and color code is 2 thats only 18
can you please show a screenshot of the length 19 output
const { player, initialSpawn } = data;
if (initialSpawn === true) {
if (player.getDynamicProperty("savedNameTag")) {
player.nameTag = player.getDynamicProperty("savedNameTag");
}
}
})
function editPlayerNameForm(player, target) {
const editPlayerName = new ModalFormData();
editPlayerName.title("")
editPlayerName.textField("", "§7Name")
editPlayerName.toggle("Nick Enabled", true)
editPlayerName.submitButton("Submit")
editPlayerName.show(player).then((data) => {
if (data.canceled !== true) {
const result = data.formValues;
page2(target, player)
if (result[1] === true) {
target.nameTag = result[0];
target.setDynamicProperty("savedNameTag", result[0])
}
else
target.nameTag = target.name
}
})}
this is for player
here ill show a ss but i may need to explain a few things
Try experimenting more.
import { world } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
world.afterEvents.playerInteractWithEntity.subscribe(event => {
const entity = event.target;
if (!entity || !entity.isValid()) return;
new ModalFormData()
.title("rename entity")
.textField("enter new name:", "name", entity.nameTag ?? "")
.show(event.player)
.then(response => {
if (!response.canceled) {
const newName = response.formValues[0]?.trim();
if (newName) entity.nameTag = newName;
}
});
});
Unfortunately the Entity they will rename is player lol
I mean itself, not interacting with them.
Uh... Yeah that won't work for you to rename your self
Meh, just sue this as reference
you can change nametags of players.
Yep
above the action bar is thge var thsats padded to 16 test starts immediatly after and goes to split 1 to get that positioned correctly i had to get split 1 to start at 19 charecters
padding the var makes the var 16 chars long by adding spaces the spaces are invisible
world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
if (initialSpawn) {
const savedNameTag = player.getDynamicProperty('savedNameTag');
if (savedNameTag) player.nameTag = savedNameTag;
}
});
function editPlayerNameForm(player, target) {
const editPlayerName = new ModalFormData();
.title(' Edit Player Name');
.textField(' Enter Name', '§7Name');
.toggle('Nick Enabled', true);
editPlayerName.show(player).then(({ formValues, canceled }) => {
if (!canceled) {
const [newName, nickEnabled] = formValues;
if (nickEnabled) {
target.nameTag = newName;
target.setDynamicProperty('savedNameTag', newName);
} else target.nameTag = target.name;
}
});
}```
Ohh shit wrong reply
Mbmb
@chilly moth
I have no idea what you just typed
I am looking to rename entity
pffft
It's from the guy tho not for you, just don't problem it lmfoa
not you
Ohh mbmb
What are values of min and max health that would result in having a string length of 19?
assuming max is 100 already
the values of min and max are put into the padded var before its padded there for its irrelevant
see if min was 1000 max was 1000 it would add less spaces to keep it at 16
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
if (source?.typeId !== 'minecraft:player') return;
if (itemStack?.typeId === 'minecraft:stick') system.run(() => editPlayerNameForm(source, source) );
});```
and i tested by adding more chars to var split 1 stays so its padding correctly
i mean this in no way breaks anything id just like to know what outside the var is counted as a space
couldn't really tell you, I didn't really change anything and mine is returning the correct length
Hello
only adding 2
Koala
Helo
How are you?
🐨
Hello guys!
Can I save a JS variable to memory? 🧐
I want to store an array of items that I don't want to lose if the player quits the game.
Check the #1067535712372654091 for saving ItemStack
How chatGPT just numbered the things in its post concerns me
It numbered them 1 2 3 3 4 5 4 6
I'll take a look, thanks
#off-topic
async function loadIslandStructure(origin) {
const structureName = "island";
const overworld = world.getDimension("overworld");
if (!overworld) {
console.error("Failed to retrieve the overworld dimension.");
return;
}
try {
// Debug: Log available structures
const structureIds = world.structureManager.getWorldStructureIds();
console.log(`Available structure IDs: ${JSON.stringify(structureIds)}`);
if (!structureIds.includes(structureName)) {
console.error(`Structure ${structureName} not found in world.`);
return;
}
console.log(`Attempting to load structure: ${structureName} at X: ${origin.x}, Z: ${origin.z}`);
await world.structureManager.place(structureName, overworld, origin, {
rotation: "0_degrees",
mirror: "none",
animationMode: "block_by_block",
integrity: 1.0,
seed: 0,
});
console.log(`Island structure loaded at X: ${origin.x}, Z: ${origin.z}`);
} catch (error) {
console.error(`Failed to load island structure at X: ${origin.x}, Z: ${origin.z}:`, error);
throw error;
}
}```
How do I load a structure from the behaviours "structures" folder?
GetWorldStructureIds() can't get structures from BP iirc.
try using commands or manually make a map for your structures.
How to activate player emotions when he clicks on a button in a form?
Player.playAnimation()?
it depends, are emotes animations accessible in the first place?
You cant.
Look on the screenshot
oh
I can send the player to this form from Mojang when the player click to my form button?
I think it can
Maybe it can’t
I can send the player to this form from Mojang when the player click to my form button?
I have no idea what that means.
When player click to the button in my form. It opened this form (from mojang):
Not run the emotes, run this form from Mojang
What does that mean?
You cannot do that
Is it possible to make it so that when the player presses the button, he gets this form with permissions from Mojang? That is, the call form is created by Mojang with support.
Open the emote menu from a script form
If no, are there any alternatives for this?
Recreate the emote menu using json ui 
Can I change the player's skin?
No.
No.
oh
I asked because I saw a squid game map before in 2021-2022 and you could change the skin there.
I'm not sure either because sometimes it doesn't show my structures tho it's valid since I can load them.
Yes you could but using scripts alone? No
You can add extra stuff to the player geometry, effectively giving you a texture overlay to work with
e.g. a squid game suit over top of the player skin
That is completely unrelated to scripts, though, and all within #1067869590400544869
What is the lore reason behind this being useless returning only block locations
Get all blocks then do blockLocationIterators
Then do getBlocks()
It uses BlockVolume
I know but it lags like a lot
I just don't understand why there aren't any functions to get an area of blocks
that's the function?
wdym?
saying it's useless and not knowing the full use is the useless one.
I'm not saying you btw but the function itself lmfao
Don't i have to use getBlock() for each location?
kinda agree tbh
you would assume getBlocks get you an array of blocks 🤷♂️
you do
it is only useful because of the allowUnloadedChunks and BlockFilter
After days of thinking about this
I will just save the player island in layers
Then when they build/destroy stuff I will just save just the layer
Can't wait for mojang to release a function that will make all of this brainstorming useless once I actually make it work
my movement direction be like:
I used velocity before getMovementVector() exists
Damn
if mojang wants people to use bds they need to add more features for server developers
We need more server-net and server-admin features
The most useful feature would be a useful version of get blocks
Nah. Before that they should add a lot of things first
I am not missing much stuff tbh
Like people complain about lack of beforeHitEvent but I just modified all mob jsons 🗣️🗣️
Custom biome, custom dimension, custom commands, beforeEvents for entityHurt, biome detection
We can do biomedetection unless I am dumb
Slow.
It's based on bounding box.
So even if you're in the biome if the bounding box didn't reach it, it won't work.
Taking an account using one function alone takes a lot of ticks so doing a lot for EACH player is already bad.
That's why people do use another entity and manually put biomes
I don't have to deal with stuff like this thankfully
And tp that mob to player for detection and BLA BLA BLA
All my work is on a sky mmorpg
that's why I said "yet." Doesn't mean you're doing that you 100% won't do it in future tho...
Me in json UI be like:
I mean the api situation is much better than in like 2022
I remember pre dynamic property days
Scary stuff
who has a block templates?
#1067876857103536159
still waiting for beforeEvents entityHurt
can server tick be slowed down or sped up? im thinking of switching from Date.now() to server tick for precise tick check but im wondering if server lag can put server tick behind
system.runInterval(() => {
for (const player of world.getPlayers()) {
const { getComponent, inputInfo: { getMovementVector } } = player;
const movementVector = getMovementVector.call(player.inputInfo);
const health = getComponent.call(player, 'health');
console.error(JSON.stringify(movementVector), health.currentValue);
}
});```
This is getting out of hand.
bro wtf
I don't use it but I just discovered the use of .call() and .bind() yesterday and I said... Hmm why not?
Same goes to thisjs world.beforeEvents.chatSend.subscribe((ev, { message, sender } = ev) => { if (message === 'curse') ev.cancel = true; });
I also used that chatsend way or other thing when canceling events.
but if not I just destructure it properly ({ message, sender })
its possible to get a list of all custom entities from my addon?
import EntityTypes and use getAll()
and filter it out by your namespace
EntityTypes.getAll().filter(e => e.id.includes('namespace:'))
thx
someone please tell me why im getting these errors the addons blank that i tested except for the console warn is this a feature mojang themselves broke or something idk its annoying i want it gone
ima get sa fresh 1
[Recipes][error]-recipes/reducer_quartz_pillar.json | minecraft:quartz_pillar | Material Reduction recipe duplicates a previously registered recipe with input minecraft:quartz_pillar. Skipping recipe.
[Recipes][error]-recipes/reducer_smooth_quartz.json | minecraft:smooth_quartz | Material Reduction recipe duplicates a previously registered recipe with input minecraft:smooth_quartz. Skipping recipe.
[Scripting][warning]-im alive bitch```
This aint script API tho.
Addons pls
it's a game error
not something you did
I want it gone tho why mojang its annoying
-# json ui
Best way to obtain the Waters surface level no matter the entity position?
wdym water surface?
Water meets air all over cause fir every 2 hydrogen theres 1 oxygen 😛

Like a body of water?
Yes..
It can be the ocean of the world but I'm using an entity to get that y level
runJob() do getBlocks() and get all locations of getBlcoks() and use getBlock()
Is it possible to detect the type of input device a player is using
Yes.
const { inputInfo } = player;
const device = inputInfo.lastInputModeUsed;```
do a for statement
do y++ until block.above() === air
if (world.beforeEvents.entityHitEntity) {
world.beforeEvents.entityHitEntity.subscribe((event) => {
const { damagingEntity, hitEntity } = event;
if (damagingEntity.typeId === "minecraft:player" && hitEntity.typeId === "minecraft:player") {
const island = getIslandAt(hitEntity.location.x, hitEntity.location.z);
if (island && !hasPermission(damagingEntity.name, island, "attackPlayers")) {
event.cancel = true;
damagingEntity.sendMessage("You do not have permission to attack players here.");
}
}
});```
This doesn't work?
it says world.beforeEvents.entityHitEntity is undefined
Thx
Are u using beta versions
Yep
Or stable
{
"module_name": "@minecraft/server",
"version": "1.18.0-beta"
},```
Did u save ur manifest
I did some research in the discord, seems like you cant cancel entity damage
Yeah
Ou can’t
OH
right
Bro
its because
you’re indexing it on beforeEvents
Yeah people were saying you have to use resistance or something
It only exists on afterEvents
well if I do it after, its kinda null though right? because after means the damage is gonna go through
yea use a damage controller
in player.json
n create a custom hit system
its better anyway
I cant though, because this is for all entities
Someone said you could do something similar with a super high resistance effect
but how do I apply that to the entity on the same tick or before an attack?
well update every entity then
😭
you can’t that’s why it’s an afterevent
afterevents run after the packet has already been received
they run after the tick it was sent on, not on the tick
@past coyote
ah
you could use a damage controller that prevents the player itself
from damaging
like player has tag
thats too messy
then add/remove the tag whenever
yes because server plugins use custom software ..
server without software means no server side functionality all in all
they can customize whatever they want
but script api is built on top of vanilla mc
vanilla mc behaves differently
they chose to handle hit events differently from vanilla
you need to get used to the fact that half the things u wanna do in script api will require workarounds @past coyote
if u dont want that just switch to server software instead
yeah its just a little annoying
it’s not possible for script api to work any better unless the game’s base functionality is also altered to make room for new features
script api works at a much higher level
than server sofrware does
server software can do almost anything they’d like to the server
I understand.
Alright, so how do we make this work with the player.json?
i forgot TBH
ask in entities
Will do
#1067869022273667152
thanks for the help man
yw
set the attack component to very huge negative number
this will disable dealing damages entirely
theres also another way though, its in bedrock addons wiki iirc
You can cancel damage on player.json by filtering entity type player and projectile that has player as owner, it still allow you to work with entity hit and projectile hit after events giving you a way to make your own combat system, that's what I did on my server and works pretty well
what is the easiest way to set a block with air without using commands?
block.setType('air')
type is an object instance
while typeId is a string
its just how the api is oriented,
type is prob has the shorter code integration
string is commonly used for mapping
hypothetically speaking
I see thanksss
hello :::)
@next fjord
world.beforeEvents.worldInitialize.subscribe(event => {
event.blockComponentRegistry.registerCustomComponent('hycomponent:tree_gradient_leaves', {
onRandomTick: ev => {
// Top = 2
// Top MIddle = 1
// Middle (Default) = 0
// Bottom = 3
const block = ev.block;
if (block.permutation.getState("hycraft:gradient") > 0) return;
const blockX = block.location.x;
const blockY = block.location.y;
const blockZ = block.location.z;
const playerInRange = world.getAllPlayers().some(player => {
const playerX = player.location.x;
const playerY = player.location.y;
const playerZ = player.location.z;
const distance = Math.floor(Math.sqrt(
Math.pow(blockX - playerX, 2) +
Math.pow(blockY - playerY, 2) +
Math.pow(blockZ - playerZ, 2)
));
return distance <= 32;
});
let extraOperations = world.scoreboard.getObjective("extraoprtn").getScore(worldController);
const extraOperationsChance = Math.floor(Math.random() * ((64 - extraOperations) + 1));
if (extraOperations > 0 && extraOperationsChance == 0) {
if (playerInRange) {
let applyTopGradient;
let applyTopMiddleGradient;
let applybottomGradient;
applyTopGradient = false;
applyTopMiddleGradient = false;
applybottomGradient = false;
system.runTimeout(() => {// Top Gradient
let x = block.location.x;
let y = block.location.y + 1;
let z = block.location.z;
const blockLocation = {
x,
y,
z
};
const topBlock = world.getDimension(block.dimension.id).getBlock(blockLocation);
if (topBlock.typeId === 'minecraft:air') applyTopGradient = true;
if (topBlock.typeId != 'minecraft:air' && topBlock.typeId === block.typeId && topBlock.permutation.getState("hycraft:gradient") == 2) applyTopMiddleGradient = true;
}, 1);
system.runTimeout(() => { // Bottom Gradient
let x = block.location.x;
let y = block.location.y - 1;
let z = block.location.z;
const blockLocation = {
x,
y,
z
};
const bottomBlock = world.getDimension(block.dimension.id).getBlock(blockLocation);
if (applyTopGradient === false && applyTopMiddleGradient === false && bottomBlock.typeId != block.typeId) applybottomGradient = true;
if (applyTopGradient === true) applybottomGradient = false;
if (applyTopMiddleGradient === true) applybottomGradient = false;
}, 2);
system.runTimeout(() => {
if (applyTopGradient === true) block.setPermutation(block.permutation.withState("hycraft:gradient", 2));
if (applyTopMiddleGradient === true) block.setPermutation(block.permutation.withState("hycraft:gradient", 1));
if (applybottomGradient === true) block.setPermutation(block.permutation.withState("hycraft:gradient", 3));
}, 3);
}
}
}
});
This made my tree gradient automaticaly, but I use only on tree buildings
During tree building process
Its an old code, so, sorry for bad organization
So your trees are not structures but tree_features?
Structure
This is just for change the leaves permutation
ok
To get the gradient
You know how to use custom components, right?
yes
Thank you very much for explaining it to me, I'll try and see how it goes.
Perfect
Np
💕
check if the slot is not undefined add slot there
you have to iterate though all slots in the inv
just use addItem
addItem().
nice stuff
Quick one, don't put the inventory component setting item in the system.run(), only put the addItem in the system run.
also, if the inv is full, add item return the left amount of items that didn't get added
function giveItem(player, itemId, amount, name = undefined) {
const { container } = player.getComponent('inventory');
if (container.emptySlotsCount === 0) return;
const itemStack = new ItemStack(itemId, amount);
itemStack.nameTag = '§r' + name;
system.run(() => container.addItem(itemStack) );
}```
why the system run
This one right here I just copied it.
import { world, DynamicPropertiesDefinition } from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe((event) => {
const def = new DynamicPropertiesDefinition();
def.defineString("playerData", 1024);
event.propertyRegistry.registerEntityTypeDynamicProperties(def, "minecraft:player");
});```
Is this not how you do this?
I found some examples here and it seemed like this was right
Dynamic proeprties arent defined like that anymore. Theyre defined via a method in the class like so:
player.setDynamicProperty("namespace:proeprty", value)
Is tgere a script api way to load a structure
StructureManager.
Whats the syntax may i ask or a leatn article on it
Documentation for @minecraft/server
Is it possible by any means to make a grid based button form or no
Only with Jason ui
yo
someoe who knows ts
interface Home {
name: string;
location: Vector3;
dimension: string;
}
interface Button {
text: string;
icon?: string;
callback?: Function;
}
how can i write this in js
You can't use an interface in javascript tho.
JS doesn't have interfaces.
crazy
then how can i "translate" this to js
idk how to say that
but yh
Why you need an interface? Where'd you gonna use it?
i only want to make this ts file in js (i dont even know what an interface is)
Manually change it.
You could just transpile it and get the JS code 
And whose typescript file is this in the first placd
my dev
but i only know js
Then make him transpile it to js or you do it
Compile it in
https://minato-mba.github.io/web-apps/web-editor.html 😅
-# no self advertising!
like my name suggest im slow.
definition of compile
ill just google it
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
Same 🤷♂️
version of math module
It's not a module. You'll need to separetly install it then bundle it with your code.
how
im confused
maybe it would be proper to use startWith instead of includes
either way, it'll work.
yeah I used startsWith xd
mb lol
posted a complex question
can i get help
guys what problem {: ?
[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at initialize (main.js:13)
at <anonymous> (main.js:187)
Even when I use the compass the forms doesn't work.
How did you make it always show?
Those aren’t the files causing the issue as far as I can see
Also don’t use 1.3.0 for server- use 1.17.0. It’s the latest stable version
system.runInterval
What is use after that?
Can you tell me which files are causing this problem and why the compass is not working at all? <:
system.runInterval(() => {
world.sendMessage('this will get sent every tick')
}, 1)
I know
But i need a player to use the title
Your problem is in main.js, but the file you sent does not correspond to the error you have
get all players -> onScreenDisplay.setTitle()
I will try
system.runInterval(() => {
world.getPlayers().forEach(player => {
player.onScreenDisplay.setTitle('test')
})
}, 1)
Is there a way to test for if a specific weapon/item kills an entity?
EntityDie event
if player yes if entity it's kinda finicky since the equippable component doesn't work with entities
Can anyone help i posted the question
What is scripts method to tp player
The official Mojang documentation resides at the MS Docs site
The community wiki resides at https://wiki.bedrock.dev/
The HTML Docs provided by Mojang in the Bedrock samples resides at https://bedrock.dev/
const totalCities = world.getDynamicProperty("totalCities") || 0;
if (totalCities === 0) {
player.sendMessage("⚠️ No cities found.");
return;
}
// ✅ Pick a random city ID
const randomCityId = Math.floor(Math.random() * totalCities) + 1;
let cityData = world.getDynamicProperty(`city_${randomCityId}`);
if (!cityData) {
player.sendMessage(`⚠️ City ID ${randomCityId} not found.`);
return;
}
if (typeof cityData === "string") {
cityData = JSON.parse(cityData);
}
// ✅ Get city's original location
const originalX = cityData.location.x;
const originalY = cityData.location.y;
const originalZ = cityData.location.z;
// ✅ Add (13, 3, 51) to coordinates
const newX = originalX + 13;
const newY = originalY + 3;
const newZ = originalZ + 51;
// ✅ Teleport player
player.teleport(newX, newY, newZ);
player.sendMessage(`✅ Teleported to City ID ${randomCityId} at (${newX}, ${newY}, ${newZ})`);
}``` throws an error
so im assuming im writing it wrong
unless how its getting city data is wrong
const totalCities = world.getDynamicProperty("totalCities") || 0;
if (totalCities === 0) {
player.sendMessage("⚠️ No cities found.");
return;
}
// ✅ Pick a random city ID
const randomCityId = Math.floor(Math.random() * totalCities) + 1;
let cityData = world.getDynamicProperty(`city_${randomCityId}`);
if (!cityData) {
player.sendMessage(`⚠️ City ID ${randomCityId} not found.`);
return;
}
if (typeof cityData === "string") {
cityData = JSON.parse(cityData);
}
// ✅ Extract x, y, z from cityData.location
const { x: originalX, y: originalY, z: originalZ } = cityData.location;
// ✅ Add (13, 3, 51) to coordinates
const newX = originalX + 13;
const newY = originalY + 3;
const newZ = originalZ + 51;
// ✅ Get the Overworld dimension
const overworld = world.getDimension("overworld");
// ✅ Teleport the player using extracted values
player.teleport(newX, newY, newZ, overworld);
player.sendMessage(`✅ Teleported to City ID ${randomCityId} at (${newX}, ${newY}, ${newZ})`);
}``` i cant get this to work at all
Well i know the coords are correct but the teleport isnt working
Nono
Player.teleport({ x: 0, y: 0, z: 0 }, { dimension: overworld })
I cant do x:0 it has to use that variable
but ill try that with var
const totalCities = world.getDynamicProperty("totalCities") || 0;
if (totalCities === 0) {
player.sendMessage("⚠️ No cities found.");
return;
}
// ✅ Pick a random city ID
const randomCityId = Math.floor(Math.random() * totalCities) + 1;
let cityData = world.getDynamicProperty(`city_${randomCityId}`);
if (!cityData) {
player.sendMessage(`⚠️ City ID ${randomCityId} not found.`);
return;
}
if (typeof cityData === "string") {
cityData = JSON.parse(cityData);
}
// ✅ Extract x, y, z from cityData.location
const { x: originalX, y: originalY, z: originalZ } = cityData.location;
// ✅ Add (13, 3, 51) to coordinates
const newX = originalX + 13;
const newY = originalY + 3;
const newZ = originalZ + 51;
// ✅ Get the Overworld dimension
const overworld = world.getDimension("overworld");
console.warn(newX, newY, newZ)
// ✅ Teleport the player using extracted values
player.teleport({ x: newX, y: newY, z: newZ }, { dimension: overworld });
player.sendMessage(`✅ Teleported to City ID ${randomCityId} at (${newX}, ${newY}, ${newZ})`);
}
``` still fails
Do i req to give manifest capibiliries to teloport it says entity lacks permission
Wtf sm i missing
system.run(()=>{/**code**/});
Its saying lacking permission how will that fix it
it gives u higher perms
ur probably running ur code on read mode
which si the default
if u still get permission issues after using that then idk what's wrong
ill try but how do i not run code on read only wouldnt other stuff fail if it was read only
no only some are i beleive
you use beforeEvents?
if iget p[ermission error i just use system.run
system.run(() => {});
if it works for me it works i dont change
so yeah lemme explain it to you, since you're dealing
beforeEventsmeans before it happens, you can't modify the world, so the purpose ofsystem.runis to run the thing in the next tick, to escape the read-only mode, tho it's not just system.run only you can use anything as long as it happens next tick not the same tick...
Ill never understand why but it worked
the link I sent should help with that.
anyone help with this
:(
is it even possible anymore to see people enderchest and clear them etc or clear certain items
Thanks well the good news is this means i can pull the location from the city_id woohoo
no, you can't access ender chest inventory thru scripts.
god dam it
The only way to clear/add is using replaceitem
bedrock
yh
calling the mojangsters stupid?
everything
Not the mojangster duh
Is there a way to take coords from 2 corners and make it so no blocks can be placed or broken within a certain radius of it using script
you can do this with blockVolume.
Documentation for @minecraft/server
What do you do once you already have the coords then these docs arent as easy to read snd transparrent as you think they are
try using those math logic stuff, idk the name:
xPos₁ < xPlacement < xPos₂
yPos₁ < yPlacement < yPos₂ &&
zPos₁ < zPlacement < zPos₂ &&
So what would the full syntax be to make an area whithin the coords fully protected
function inBoundary(pos1, pos2, target) {
const minX = Math.min(pos1.x, pos2.x);
const maxX = Math.max(pos1.x, pos2.x);
const minY = Math.min(pos1.y, pos2.y);
const maxY = Math.max(pos1.y, pos2.y);
const minZ = Math.min(pos1.z, pos2.z);
const maxZ = Math.max(pos1.z, pos2.z);
return (
target.x >= minX &&
target.x <= maxX &&
target.y >= minY &&
target.y <= maxY &&
target.z >= minZ &&
target.z <= maxZ
);
}
AI simplified ^
Mine:
function inBoundary(pos1,pos2,target) {
const [xPos1,xPos2] = pos1.x < pos2.x ? [pos1.x,pos2.x] : [pos2.x,pos1.x];
const [yPos1,yPos2] = pos1.y < pos2.y ? [pos1.y,pos2.y] : [pos2.y,pos1.y];
const [zPos1,zPos2] = pos1.z < pos2.z ? [pos1.z,pos2.z] : [pos2.z,pos1.z];
if (xPos1 <= target.x && target.x <= xPos2)
if (yPos1 <= target.y && target.y <= yPos2)
if (zPos1 <= target.z && target.z <= zPos2) return true
else return false
}
How does that keep ppl from breaking or placing blocks
It's a function that detects if the location is within your protected area.
It returns Boolean.
Cancel the playerBreak event if its true
Ir do i run that threw a before pkayer place block event
Can break block event get the blocks location
world.beforeEvents.playerBreakBlock.subscribe((evd)=>{
const { block } = evd;
//retreive protected regions as pos1 & pos2
if (inBoundary(pos1,pos2,block.location) { evd.cancel = true; return; }
//rest of the code outside protected region
})
.
Ok ty
It's box shaped btw
Wait so not rextangle shaped?
you want the sphere one?
No
rectangle, cube, box... aren't they the same?
I mix up box and square
you can just set the pos1.y as -64 and pos2.y 300 smt. (Depending on dimension height)
So it stretch to the build limit. Having more control won't hurt right?
While i wait for stuff on my rpg im making an rts that is 99.9% just dynamic property manipulation lol
Ill need to do some more ligics as ill need to set a for loop to create hundreds of these
Its actually not the whole area just the structure
Or well alot of structures
That sounds troublesome, good luck
Probobly not that hard btw does after worldinitualize mean only 1 time per world gen
Im off to bed tho nighty night let the bed bugs eat you alive
Use BlockVolume
Jokes on you. I can't:
"You can sleep only at night and during thunderstorms."
world.beforeEvents.playerBreakBlock.subscribe((ev, { block, } = ev) => {
const volume = new BlockVolume({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 });
if (volume.isInside(block.location)) ev.cancel = true;
});```
Good idea 💡
-# I must be a genius to have accidentally forgotten such feature
@prime zenith as simple as that.
LMAO, nah you good it's easy to forget since less people really use BlockVolume
Also just import BlockVolume in server.
Its night time here
Coddy yours is harder for me to figure out how to plug into mine tho
uhh? It's actually easy if you just know the basics of JAVASCRIPT at all.
Also compared to gega it's better, faster and built-in version
overall smaller.
I have a dynamic property i need to apply theres used a function yours is just in the event
make a function 🤷🤷
You can compile those dynamicProperties at script loads into BlockVolume
I need to loop threw every city_id to get its location add to x y and z
Just put point1 and point2 of your structures then done....
Does BlockVolume throw errors when dealing unloaded chunk?
-# Doesn't matter, you can't break block in unloaded chunk anyway
As i said point 1 is obtained in every city_id
Thats irrelevant when position 1 is the location in the city_id property btw id is numerice city_1 city_2
Why? Mined block needs to be loaded tho.
Coddy you gotta do all the work if you want to prove your point
You need to know where the structure is
function isLocationInsideVolume(location, point1, point2) {
const volume = new BlockVolume(point1, point2);
return volume.isInside(location);
}
world.beforeEvents.playerBreakBlock.subscribe((ev, { block, } = ev) => {
const point1 = { x: 0, y: 0, z: 0 };
const point2 = { x: 10, y: 10, z: 10 };
if (isLocationInsideVolume(block.location, point1, point2)) ev.cancel = true;
});
This is exactly above, my code
epic
I still need to set every structure to have a volume to check
Okay then add placeholder entities to your structure to act as marking points for those volume. Or anything that works
Why when looping threw the ids for there location and setting the box that way makes more sence and is easier
Have a good night sleep
I can get all the protected areas set at world load
Guys, how do I force a fishing bobber to hook to an entity? Especially when it already touches the floor/walls or water.
not possible I guess?
Plan B: teleporting abomination it is.
Not sure. Maybe the device you're using causes the "There's a monster nearby."
Oh yeah btw it won't throw an error since it only returns the location of blocks from point1 to point2 where to be used by getBlocks() or getBlock()
-# sorry from tagg 🥺
Oh wait theres zombies outside my window oh well
So many ppl on earth forget to set spawn point before they die and never make it back to earth and by nany i mean all of them is spawn broken in reality
Can u detect if player hits air
does anyone have a function that checks if the entity is in rain?
what
??
why check entity is in rain
impaling enchantment
import { world } from "@minecraft/server";
export function isRaining() {
const weather = world.getDimension("overworld").getWeather();
if (weather === "Rain" || weather === "Thunder") {
return true
} else return false
}```
@shy leaf
in rain
not is raining
BRO
if its rainin' the whole dimension is rainin'
why you check a specefic entity for if he IS IN rain
ok can you tell me how trident's impaling and riptide works
impaling causes extra damage to aquatic mobs
so if you hit a drowned with impaling trident, he get more damage than normal trident
so you want to recreate impaling to bedrock?
you can say that i guess?
- check for if the trident has impaling lore
- do entityHurt event
- check for if a entity got hurt and the source is player
- check if the mob is aquatic (e.g. drowned)
- deal extra damage to the hit mob
the
impaling enchantment deals extra damage to mobs in water or in rain
in bedrock
in water
And riptide enchantment throws the player when you shoot the trident.
so make the riptide enchantment,
- you detect if its raining (u can use my function i sent)
- check if the trident is in the mainhand, and if it has riptide lore
- use
player.applyKnockback()to throw the player and useplayer.getViewDirection()
yep, that's why your checking for if its raining or not.



