#Script API General
1 messages · Page 64 of 1
Hmm, but how
U can edit this and send me?
Pls
that just prove it is not yours
use 1.17.0 @minecraft/server and 1.3.0 @minecraft/server-ui
Ok
?
and if you use any beta stuff in your code, it will break
Ive learned a possible way to make a grand exchange in minecraft im wondering if i should mske a standalone addon for that for ppl who want there own grand exchange in minecraft
How to launch a projectile when using an item?
const head = player.getHeadLocation();
const view = player.getViewDirection();
const entity = player.dimension.spawnEntity('minecraft:snowball', head);
const power = 2; // adjust how fast the projectile travel
const projectile = entity.getComponent('projectile');
projectile.owner = player;
projectile.shoot({ x: head.x + view.x * power, y: head.y + 0.1 + view.y * power, z: head.z + view.z * power });```
Thanks
'string' isn't assignable to '(string) => Aform'
How're u using it
im making a custom form handler
class
with a constriuctor
wait i fixed the body
so dont midn that error
nvm it works now wtf
;-;
yes just because of the body it didnt work burh
I may beat ai with a binary stick soon can someone tell me how dynamic properties look and how you break them apart trying to learn
wdym break?
Btw the buttons type shouldn't be optional since action forms require at minimum one button
you can use it without buttons now
How they look?
Really?
In preview yes.
not really
Yes.
Meh
yeah ik that...
So technically not "yet"
I mean yah? It's better than you editing json ui just to hide that damn button.
for you it's useless but for some people yes,
way better than MessageFormData lmao
Ig
I personally haven't had much use but i do understand others might
And having more freedom is nice
what's up
hi.
👋
I knew something was going to happen XD
Guys, is there a way I can make a gun shoot constantly without spamming right click?
world.afterEvents.itemStartUse.subscribe(data => {
let player = data.source;
let entity = player.dimension.spawnEntity('arrow', player.getHeadLocation())
entity.getComponent('minecraft:projectile').shoot(player.getViewDirection())
});
I tried this; it works, but I have to spam click
Also use itemStopUse
When you do itemStartUse, store in a map the ID of the player, and in runtInterval do a shoot in itemStopUse where you delete the player.id
But how do I make him use the item again without right-clicking?
i.e. constant shooting
what?
I said the step to make what you want, hold right click will constantly shoot until you stop holding it.
So basically, from what I understood
- Use ItemStartUse to start the shooting
- when the useDuration ends, itemStopUse will run
- Run itemStartUse again somehow
Make your item eatable forever
when you stop holding it the stopuse is triggered
eatable? , but would it be annoying to hear the eating sound?
or is there a workaround for that
got a better idea?
there's no workaround for your thing.
I saw an addon that does that without eating but I lost it
That ain't possible tho, you can't detect the stop using items in scripts
No, the thing is that I have already managed to do that without scripts
but didn't like the eating noises. so tried attemping it through scripts
then no....
Unless you're using it in entities or blocks then probably yes.
Hmm, perhaps if you play the gun sound, it makes the eating sound unhearable.
aren't players entities though?
Can you interact yourself? No right?
You meant using items on blocks or entities?
That makes sense
Yes.
You know when this projects done ill probobly have better luck marketing it as a minecraft themed rpg private server and target players of rpg games rather then minecraft players lol
On another note grand echange is now half way done
dayum, it tooked me 3 weeks just to discover how to accurately check if the chest is opened.
before people say you can use afterEvents of playerinteractwithblock no you can't it will always return true even if the ui isn't shown or the chest doesn't have the open animation.
isInUi enviromental sensor?
not script api
I did the same with resource packs, I asked a loot table question there yesterday
happens lol
My grand echange is so close to being done
Waiting for equipable's getEquipment() to be nonexclusive to the player.
Guys I have one quick question, is it possible to have client side nametags?
As a first project I suggest making a script that auto-replaces crops when you right-click the crop
Not a good explanation tbh xD
Well, you can do client-side particle...
Cave divers
oh yeah rightclickharvest would be coo;
(minecraft inside minecraft is cool too)
yes that's what compile it means
is it possible to detect if a player grabbed an item in their inventory/moved an item?
cursorInventory component could work?
but don't think it works on most devices
It won't work with touch devices :(
would it be better to somehow check both cursor AND for changes if an item moved from one location to another in the inventory?
im trying to find a low performance cost way of doing this haha
maybe it would be better to just check if the item moved, and what item it was
no idea if that would work if you placed one item on top of another to swap them
Checking inventory already degrades it soo
Inventory change event when 
I guess i'll just have to compare changes manually somehow
I think the best way would be to check inventory typeIds, slot, and amount for each (and detect when those change)
Not very performant, but then again what is?
Year 5202
lol
import { world, system } from "@minecraft/server";
let previousSlot = new Map();
const itemSounds = {
"minecraft:stone": "dig.stone",
"minecraft:dirt": "dig.grass",
"minecraft:wood": "dig.wood",
};
// Function to play a sound
function playSound(player, sound) {
console.log(`Attempting to play sound: ${sound} for player: ${player.name}`);
player.playSound(sound, { pitch: 1.0, volume: 1.0 });
}
system.runInterval(() => {
for (const player of world.getPlayers()) {
const currentSlot = player.selectedSlotIndex;
const playerId = player.id;
if (previousSlot.has(playerId) && previousSlot.get(playerId) !== currentSlot) {
console.log(`Player ${player.name} changed slot from ${previousSlot.get(playerId)} to ${currentSlot}`);
playSound(player, "hotbar_scroll"); // Play a sound when the slot changes
}
previousSlot.set(playerId, currentSlot);
}
}, 1);
world.beforeEvents.itemUse.subscribe((event) => {
const player = event.source;
const item = event.item;
if (item && itemSounds[item.typeId]) {
playSound(player, itemSounds[item.typeId]); // Play a sound based on the item type
}
});
world.afterEvents.itemReleaseUse.subscribe((event) => {
const player = event.source;
const item = event.item;
if (item && itemSounds[item.typeId]) {
playSound(player, itemSounds[item.typeId]); // Play a sound based on the item type
}
});```
(ignore how awful this is)
i'm basically trying to make sounds for moving items around in the inventory
as well as scrolling the hotbar etc...
If you wanted to keep it consistent with vanilla, minecraft doesn't play any sounds if the item has the same typeId
But yeah this seems like a big performance draw for a small feature
yeah I change my mind that's sick
its uhh... well its pretty bad.
In java edition you can get an item/blocks category, like if its a wet block, if its stoney etc...
did someone do a typo or is it supposed to say "Tyring"
You could change the arrays to be more categorical
I have to add every item from the game though sadly
const sounds = [
{
ids: [
"minecraft:jukebox",
"minecraft:loom"
],
sound: "dig.wood"
}
]``` it wouldn't make it any faster but at least save some of the copy pasting
You should also add a default sound that will play if an id can't be found so that it covers any new blocks added in the future
at least until you change them
I do 😉
big brain
yes
How many ppl you think could benefit if i made my grand exchange and bank part of my addon public
Is this your way of saying i shoukd release a public version or i shouldnt
I need opinions release or not to release
Also im eating that m$m guy

Numnumnumnum

Burp
release it, you're not going to lose anything, as long as you make it player friendly and easy to set up and not-so-buggy then release it
Ok cool ill need to edit it tho as its plugged into my custum objects atm tho i need to get it to work on my world first i got an issue with how its saving and reading world dynamic components
Finally working on a calendar script! One that sets several events to the world on a daily, weekly, seasonal basis!
me being one of the 3, but refusing to use it because I'd rather make my own
Look, I used this code, but the projectiles are only going in one direction. And it is when on the ground too
Do you have any idea what it could be?
ohh, wait. Use this for the shoot.
projectile.shoot(player.getViewDirection())
I wanna check something.
yeah that works
i had to use that earlier for raycasts
ok... Tho I'm not talking to you
but anyways.
then do js projectile.shoot({ x: view.x * 2, y: view.y * 2, z: view.z * 2 });
is there any way i can detect piston or pressure plate usage & cancel it using the server-net module for example
Yeah you can detect but not so sure with cancel.
I think I should be able to if it’s through server-net
But
It can only listen for packets from the client to the server so
Im not sure tbh
I don’t think piston events come from the client ..
What about pressure plates though
pistonActivate and pressurePlatePush
Iirc that's the name
Tho for pressure plate the entity who stepped it is source
Just that, without the rest of the code?
would this be an ok way to kind of have a custom difficulty
export function shouldPerformAction() {
if (world.getDynamicProperty("dsml:difficultyOffset") == undefined) {
world.setDynamicProperty("dsml:difficultyOffset", 0);
}
if (randInt(0, 100) <= world.getDay() - world.getDynamicProperty("dsml:difficultyOffset")) {
return true;
}
else {
return false;
}
}
so it gets progressivley harder as each day passes
but can be reset by adding the current day to the offset
It worked
Just one thing, do you understand projectile components?
Yeah. Which part?
I guess soo...? Tho just too many if statements.
export function shouldPerformAction() {
const offset = world.getDynamicProperty('dsml:difficultyOffset') || 0;
const threshold = world.getDay() - offset;
return randInt(0, 100) <= threshold;
}```
this is already enough.
yes please
custom commands when? Before events for damages when?
yes
entityHurt beforeEvents with a damage property that can be reassigned...
so real...
Omg im an idiot this whole time i thought values in a dynamic property were read as value1_value2 i didnt kbow it could break it apart for you
Strings?
I thought value was read ssme as the key nvm im past it
yeah i had them in separate funcs in my utils file
i just didnt want to send the whole file
See how the projectile is behaving
Here is the code:
"minecraft:projectile": {
"on_hit": {
"impact_damage": {
"damage": 9,
"knockback": false,
"semi_random_diff_damage": true,
"destroy_on_hit": true
}
},
"power": 5.0,
"gravity": 0.1,
"anchor": 1,
"offset": [
0,
0,
0
]
}```
Don't put power in json, you adjust it with script, remove anchor too I guess?
I need a second person to help testing
Okay, I'll do it.
Can you color an action form button or only the text
possible but need to edit json ui.
Well it needs conditions i wont worry about it
I have tested this ge as far as i can buy myself now i need to test it in multiplayer
[Scripting][error]-Unhandled promise rejection: FormRejectError: Player quit before responding
help me?
When I leave my friend's world, I get this error
636 lines of code to get this dam thing to work but until i can get help testing edge cases i wont know 100% how well it works in mulyiplayer
You are trying to open a Form when the player leaves?
When you exit with the form open, this error occurs
And what is the issue?
erro
[Scripting][error]-Unhandled promise rejection: FormRejectError: Player quit before responding
Its working properly, just handle the error adding a .cacth() for the show method
cacth() 
form.show(player).then(res => {
}, err => console.error(err))
Lmao im noticing a pattern i think i need to check out my dyslexia
try to do js if (formValues === undefined) return: if (canceled) return: if (selection === undefined) return;
or if (res.canceled) return
I'm dyslexic but undiagnosed lmfao
Any of it works, since closing the form doesn't give you the information Soo it's useless.
I got it, look
Anyone able to help me test how well my grand exchange works
export async function menuprincipal(player) {
const form = new ActionFormData()
form.title("§l§3Bleach")
form.body("§cYoutube.com/§fPinhoPlays")
form.button("STATUS", "textures/ui/menu/status.png")
form.button("SKILLS", "textures/ui/menu/skills.png")
const result = await form.show(player);
if (result.canceled) return
if (!result.canceled) {
const actions = {
0: stats,
1: skills
}
const action = actions[result.selection];
if (action) {
action(player);
}
}
}
no. result.canceled only
just do if (res.canceled) return no fancy things
make your life easier.
// ...
const result = await form.show(player);
if (result.canceled) return;
// ... codes ...```
has erro
huh?
[Scripting][error]-Unhandled promise rejection: FormRejectError: Player quit before responding
Valid crashout
you're probably editing the wrong file.
me when there's no beforeEvents of entityHurt:
...
Also a valid crashout
^
export async function menuprincipal(player) {
const menuOptions = [
{ label: 'STATUS', icon: 'textures/ui/menu/status.png', action: stats },
{ label: 'SKILLS', icon: 'textures/ui/menu/skills.png', action: skills }
];
const form = new ActionFormData()
.title("§l§3Bleach")
.body("§cYoutube.com/§fPinhoPlays");
menuOptions.forEach(option => form.button(option.label, option.icon));
const result = await form.show(player);
if (result.canceled) return;
const selectedOption = menuOptions[result.selection];
if (selectedOption?.action) selectedOption.action(player);
}```
^
🥲
I have several forms
I gave you an easier one to extend. You just need to add those in the menuOptions variable
is it possible for a block to detect the block below its neighbor?
const below = Block.below();```
999 bugs in my code 999 bugs take 1 down patch it around 25,674 bugs in my code
@dim tusk Hey man, if I wanted to support dimension titles in Minecraft Bedrock, how would the script be modified?
dimension title?
Yeah, I want it to go into the biome title script you suggested to me the other day.
ahh if you go to another biome?
Does it display the name on screen?
How can i disable vanilla knockback but allow script to cause knockback
@dim tusk This is the script you sent me the other day but I changed the "player.onScreenDisplay.setActionBar(biome.id)" to "player.onScreenDisplay.setTitle(biome.id)" and I tried in Minecraft 1.21.70.26 then it doesn't show the title (error) when entering the world and going through the biomes, I have logs enabled to save that error,
@dim tusk Here is my manifest.json code
Here is the error text from the Minecraft 1.21.70.26 logs file:
13:28:56[Scripting][verbose]-Plugin Discovered [Traveler's Titles Bedrock BP] PackId [e3d5c1f9-3f5e-41e4-b6f1-8c9f01b74d82_1.0.0] ModuleId [5a7d3c96-2a1b-4cfd-90f3-8ea7a8e1c123]
13:28:56[Scripting][error]-ReferenceError: Native function [World::getPlayers] does not have required privileges. at <anonymous> (main.js:24)
13:28:56[Scripting][error]-Plugin [Traveler's Titles Bedrock BP - 1.0.0] - [main.js] ran with error: [ReferenceError: Native function [World::getPlayers] does not have required privileges. at <anonymous> (main.js:24)
]
https://wiki.bedrock.dev/scripting/script-server.html#beforeevents-privilege-system
Wrap it in system.run
That's not the actual fix in his script.
put the player variable inside of the system runtInterval
system.runInterval(() => {
const player = world.getPlayers()[0];
if (!player) return;
// ...
});```
So what about this script?:
const biome = getBiome(player.location, player.dimension);
player.onScreenDisplay.setTitle(biome.id);```
Is there a good way to prevent a sound from playing if the item was removed from the players inventory because they dropped it, or placed it (with blocks) or consumed it (with food) or used it (like eggs, ender pearls)
I tried implementing it, but it doesn't really work.
it is possible to play animations with scripts, but can the animations apply for the FP or only for the TP?
Animations themselves can define wether they show FP/TP.
What is fp tp
First person/ third person camera
Either use the query in the animation or in the stop expression
( trying to make the player can interact with water with his hand, i just need to play the swing animation while interacting )
lmaoo bro is gonna traumatize him
force him to make (minecraft inside minecraft)
you might use JSON for that
not scripts
ok? my point still stand
i think it is possible to detect water while interacting, right?
probably
block?.isLiquid or something idk
playerInteractWithBlock then check for if the interacted block isLiquid
i think so
🙂
ok lets make minecraft inside minecraft
we?

we make Minecraft inside Minecraft?
make a void world then generate your own terrain
And the main world?
Eat it
would be nice
make a github project and lets tell everyone to do contribution to it together we make the best ever addon minecraft inside minecraft
-(just kididng)
lol
I have an idea
good idea, I'm making the repo private tho because I always am not confident in my code to be publicly shared 🙂
no are you real
I can feel my legs, so yeah I'm real..?
lamao that goign off topic now
An addon that adds a arcade game that when u start to play with it u will get trasferred to a server that recreate minecraft legend multiplayer
All this pay2win, why? Idk i like pay to win
I'm afraid I do not have the capabilities to do such thing
Ik that, I need it's neighbor lol
well you can transfer to server pretty easely but its experimental use server-admin module for player transfering
We need someone that is good with models
we?
And textures
Me and you pookie

@dim tusk But wait, I have 6 language files (.lang files) in the resource pack and inside those language files I have different names (biomes and dimensions (depending on the language)) so i dont know what script should i add to support the language file i made
@honest spear setSpawnPoint don't work in the end ?
stop fall damage using script?
not possible
the closest way with scripts is to heal the player the amount of damage they took
yea
does the command work ?
i think just try it man
but i think it just not possible but you can teleport player on join where you want
ok
on world.beforeEvents.effectAdd, does the duration property reflect the original duration of the given effect or the remaining duration
Quick question; Is there a way to dynamically add permutations to a block with JS?
No.
No.
hmm, I guess I'll have to do the long way
hi, I wanted to ask if anyone knows how to stop a sound from a block, i'm trying to make a radio but i need it to stop the songs
You ever use the rest room get done using rest room back to where you were then need to use the rest room again
#off-topic ?
use rawtext translate
But i want to script a solution to the problem
.sendMessage({ rawtext: [{ translate: '', with [] }] }) or
.setTitle({ rawtext: [{ translate: '', with [] }] }) or
.setActionBar({ rawtext: [{ translate: '', with [] }] })```
In b4 i script a rest room need into my minecraft world lol
It's not where you usually run it, what you are running inside matters.
Cry about it.
ok
What'd you mean by neighbors? It can be anything
Does PlayerJoinAfterEventSignal not have a player property?
use PlayerSpawnAfterEvent
Use playerSpawn and initialSpawn
oh thank you 👍
system.run(async () => {
const request = new HttpRequest("http://localhost:3000").setMethod(HttpRequestMethod.POST);
request.setBody("TEST");
player.sendMessage(request.method.toString());
try {
const response = await http.request(request);
player.sendMessage(response.status.toString());
player.sendMessage(response.body);
} catch (error) {
player.sendMessage("Request failed " + error);
}
});
[2025-03-13 22:04:42:340 ERROR] [Scripting] Unhandled promise rejection: InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: HttpRequestMethod
am i like stupid or something
okay its .setMethod(HttpRequestMethod.Post)
I must have had wrong types installed or something
is it possible to check if a player is in an enclosed space/inside a building/structure?
Oh trying to make a similar plant to the watermelon or pumpkin. I need it to place ons specific blocks. Wasn't sure I needed to k ow the block belows neighbor to do so.
How do i make a custum plant
is there an efficient way to detect if a player is near a large body of water?
every way i've tried is computationally expensive.
use GetBlocks() and runJob()
I don't even know where to begin haha
import { system, world, BlockVolume, BlockPermutation } from "@minecraft/server";
const CHECK_RADIUS = 10;
const CHECK_HEIGHT = 5;
function isNearWater(player) {
const playerLocation = player.location;
const volume = new BlockVolume(
{ x: playerLocation.x - CHECK_RADIUS, y: playerLocation.y - CHECK_HEIGHT, z: playerLocation.z - CHECK_RADIUS },
{ x: playerLocation.x + CHECK_RADIUS, y: playerLocation.y + CHECK_HEIGHT, z: playerLocation.z + CHECK_RADIUS }
);
const waterBlocks = player.dimension.getBlocks(volume, { includeTypes: ["minecraft:water"] }, false);
let waterBlockCount = 0;
for (const _ of waterBlocks.getBlockLocationIterator()) {
waterBlockCount++;
if (waterBlockCount > 50) {
return true;
}
}
return false;
}
system.runJob(function() {
for (const player of world.getPlayers()) {
if (isNearWater(player)) {
player.sendMessage("You are near a large body of water!");
} else {
player.sendMessage("You are not near a large body of water.");
}
}
}, 20); ```
runJob doesn't have a timing system
Huh? Why not? 😭
unlike ruInterval it triggers every tick runJob runs next available tick
it doesn't throw everything in the same tick, that's why timing isn't required theres
Also it's a generator
That's why runJob reduce lags
Interesting, should I try to use runJobs everywhere?
I have some pretty nasty code 😭
system.runJob((function* () {
// ... code ...
yield;
})());```
Sample.
Just use runJob where it requires a lot of things to run
Understood
like getBlocks()
import { system, world, BlockVolume } from "@minecraft/server";
const CHECK_RADIUS = 10;
const CHECK_HEIGHT = 5;
function* checkWaterNearPlayers() {
while (true) {
for (const player of world.getPlayers()) {
const playerLocation = player.location;
const volume = new BlockVolume(
{ x: playerLocation.x - CHECK_RADIUS, y: playerLocation.y - CHECK_HEIGHT, z: playerLocation.z - CHECK_RADIUS },
{ x: playerLocation.x + CHECK_RADIUS, y: playerLocation.y + CHECK_HEIGHT, z: playerLocation.z + CHECK_RADIUS }
);
const waterBlocks = player.dimension.getBlocks(volume, { includeTypes: ["minecraft:water"] }, false);
let waterBlockCount = 0;
for (const _ of waterBlocks.getBlockLocationIterator()) {
waterBlockCount++;
if (waterBlockCount > 50) {
player.sendMessage("You are near a large body of water!");
break;
}
}
if (waterBlockCount <= 50) {
player.sendMessage("You are not near a large body of water.");
}
yield;
}
}
}
system.runJob(checkWaterNearPlayers());```
So like this?
Try it.
HOLY LAG LMAO
it just spams "You are near a large body of water!"
and crashes out the game
Use the yield whee it does the high checks
runJob can't stop total lag but it can at least reduce it.
import { system, world, BlockVolume } from "@minecraft/server";
const CHECK_RADIUS = 10;
const CHECK_HEIGHT = 5;
const WATER_THRESHOLD = 50;
const COOLDOWN_TICKS = 100;
function* checkWaterNearPlayers() {
const playerCooldowns = new Map();
while (true) {
for (const player of world.getPlayers()) {
const playerId = player.id;
const currentTick = system.currentTick;
if (playerCooldowns.has(playerId) && currentTick - playerCooldowns.get(playerId) < COOLDOWN_TICKS) {
yield;
continue;
}
const playerLocation = player.location;
const volume = new BlockVolume(
{ x: playerLocation.x - CHECK_RADIUS, y: playerLocation.y - CHECK_HEIGHT, z: playerLocation.z - CHECK_RADIUS },
{ x: playerLocation.x + CHECK_RADIUS, y: playerLocation.y + CHECK_HEIGHT, z: playerLocation.z + CHECK_RADIUS }
);
const waterBlocks = player.dimension.getBlocks(volume, { includeTypes: ["minecraft:water"] }, false);
let waterBlockCount = 0;
for (const _ of waterBlocks.getBlockLocationIterator()) {
waterBlockCount++;
if (waterBlockCount > WATER_THRESHOLD) {
player.sendMessage("You are near a large body of water!");
playerCooldowns.set(playerId, currentTick);
break;
}
}
if (waterBlockCount <= WATER_THRESHOLD) {
player.sendMessage("You are not near a large body of water.");
playerCooldowns.set(playerId, currentTick);
}
yield;
}
}
}
system.runJob(checkWaterNearPlayers());```
seems to fix the crashing issue haha
for loop with blockLocationIterator often crash the game
you need to use the .next() on it manually
Is it possible to check if a player is inside of a building/structure and not in the open air in a similar way?
Why not try using a flood-fill algorithm?
For that purpose?
If the flood-fill stops midway, you can assume it's on a closed space.
If it kept filling, you can assume it's on an open space. However, there might be an inaccuracy if the room size is too big using this approach.
Yeah....
There's a discussion for it. Although its Java plugin, you can technically get the idea tho
https://www.spigotmc.org/threads/detect-if-player-is-inside-a-sealed-space.471193/
But yeah, flood fill got the best accuracy
How can I load chunks using script api, such as nobody is near 10k 10k so the blocks aren't loaded, and I want to access those blocks using a structure or something. Can I spawn an entity with nametag or what? Ticking areas seem to not help
/tickingarea command
no script api method yet
unless ender pearl actually load chunk...
Well like I just said, ticking area for me seems to not even keep the chunk blocks loaded
Not on Bedrock.
how can i update certain data for an entity if it's only within render distance that of the player?
system.runInterval(() => {
for (const [mob, sm] of stateMap) {
const entity = world.getEntity(mob.id);
if (entity !== mob || !entity) return;
sm.update(entity);
}
});
Just use getEntities and set maxDistance according to the player's render distance
Yikes
what
this is some tricky error
trying to send function data via scriptevent using deserialiser since JSON.stringify() kills functions
but it didnt work
What does function data looks like?
I can probably help you since I have that problem last year and fixed it.
uhh which function
the deserialiser or
oh wait
The one you're trying to send. Tho just sends both the deserializer and the data you're trying to send.
alr though its a bit too long
Why does scripts implement function too slow? it takes 6 ticks to run a function
the function with commands? or
js function
it
shouldnt be slow?

though it depends on how clustered your functions are
6 ticks sounds way too slow
how do I dectect blocks nearby at radius of 1 and change block geometry for that block
Detect blocks possible, change geometry???
You can just set permutations
💀 what are you even asking
i think its pretty clear.
you can use the new getBlocks method, which requires blockVolume.
assuming this is a custom block, change its permutation to the one with the geometry with states.
not possible if its a vanilla block.
you are trying to create a function from a string, therefor evaluating arbitrary code. For this to be allowed, you need to enable script_eval in the manifest capabillities
yo
export class ActionForm {
show;
constructor(title, body, buttons) {
const ui = new ActionFormData();
if (title)
ui.title(title);
if (body)
ui.body(body);
if (buttons)
for (const button of buttons)
ui.button(button.name, button.texture);
this.show = async (player) => {
const response = await ui.show(player);
if (!buttons)
return response;
if (response.canceled)
return response;
let selection = 0;
if (response.selection)
selection = response.selection;
const button = buttons[selection];
if (button.code)
button.code(player);
return response;
};
}
}
function mainMenu(source) {
new ActionForm("Denreishiki", "", [
{ name: "Stats", texture: "textures/items/dummy", code: (player) => statMenu(player) },
{ name: "Rank", texture: "textures/items/shihakusho", code: (player) => player.runCommand("give @s bleach:shihakusho") },
{ name: "eh", texture: "textures/items/apple_golden", code: (player) => player.runCommand("say WIP") },
{ name: "idk", texture: "textures/items/bow_standby", code: (player) => player.runCommand("say WIP") }
]).show(source)
}```
I got this from here and it works, I tried to run a function and this error appears
`[Scripting][error]-Unhandled promise rejection: TypeError: value is not iterable`
on this line
{ name: "Stats", texture: "textures/items/dummy", code: (player) => statMenu(player) }
god damn, why is setting up ts so hard
i tried like, twice, didnt work even once
i think im just too dumb
same lol
yep
nvm fixed it
Do dynamic properties still have data limits?
Are there any good database systems that interface with dynamic properties?
I heard it was 32k?
yes
There's apparently something wrong with my script dependencies and modules, because when I remove them, my block appears in game and [Texture][warning]-The block named camouflage:camouflage_full_block used in a "blocks.json" file does not exist in the registry stops happening
{
"format_version": 2,
"header": {
"description": "pack.description",
"name": "Camouflage block BP",
"uuid": "b5838139-7ba1-4384-a2ae-d73c652eda44",
"min_engine_version": [
1,
21,
60
],
"version": [
1,
0,
0
]
},
"modules": [
{
"type": "data",
"uuid": "2863df99-0c6a-492c-959a-469e7bc06fa6",
"version": [
1,
0,
0
]
},
{
"language": "Javascript",
"type": "script",
"uuid": "19a4ec5c-72bc-4024-bd22-260753e11873",
"version": [1,0,0]
}
],
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.17.0"
}
]
}```
nvm
I'm an idiot
like usual

I forgot entry 😭
how can i detect if an armor have more than 50% of durability
const durability = item.getComponent("durability")
if ((durability.maxDurability - durability.damage) > (durability.maxDurability / 2)) {
//run code if true
}
That kinda sucks
Is there a limit to how many dynsmic properties can be stored
and 30%?
20%
10%
40%
60%
70%
80%
90%
100%
const durability = item.getComponent("durability")
if ((durability.maxDurability - durability.damage) > (durability.maxDurability * 0.3)) {
//run code if true
}
0.3 is 30%, 0.2 is 20%, 0.1 is 10%
thx
over here, replace the 0.3
u dont have to actually make me a list of all %
wait
its when more of 30% or when 30%
if it has more than 30% left
okay thx
Is it not possible to access block's display name?
with this api, not currently possible
Damn, I really didn't want to manually map their names
how to get the helmet slot
player.getComponent("equippable").getEquipment("Head")
import { world, system } from '@minecraft/server'
system.runInterval(() => {
for (const player of world.getPlayers()) {
const item = player.getComponent("equippable").getEquipment("Head")
const durability = item.getComponent("durability")
if ((durability.maxDurability - durability.damage) > (maxDurability * 0.3)) {
player.onScreenDisplay.setActionBar("0")
}
}
}, );
that code is so messy 😞
the part where it goes
}
}
}, )
import { world, system } from '@minecraft/server'
system.runInterval(() => {
for (const player of world.getPlayers()) {
const item = player.getComponent("equippable").getEquipment("Head")
const durability = item.getComponent("durability")
if ((durability.maxDurability - durability.damage) > (durability.maxDurability * 0.3)) {
player.onScreenDisplay.setActionBar("0")
}
}
});
yeah ik
ohh im stupid
i didnt see the maxDurability
Huh so this could bring the lag from a block check for leaf decay waaaay down
I might try that
Is there a limit to how many dynsmic properties can be stored
there is a limit of 32k bytes
Which does not tell me much
nvm i figured it out
Wdym
i figured it out
theres no limit to dynamic properties but each dynamic properties can store max of 32k bytes
which is alot for js text so basically u wont run out
What about world dynamic properties
Cause my grabd exchange and farming will use world dynamic properies for each player
world also has no limit
Does the 32k byte effect world
nah only thing it does js make world size bigger
doesnt rlly lag it out or anything
Thats good
yh i used world dynamic properties to make a mail system
rn i gotta work on a dif project
Hey is there a built in way to get a radius chat in bedrock or do i need to code that in myself
Making a custom table 😭
wdym?
Like you can only see chat if a player is whithin x from you
thats possible but its not built in
I know its possible im sure it wont be that hard
yuh
I think this game ran out of creativity on names
@unique acorn with your help i made this 
wait it displays the armor you're wearing?
wait check dm
how do i detect when a player receives an effect that they already have but at a higher amplifier or duration
what is the sound used for farm blocks
https://chatgpt.com/share/67d4a6ff-558c-8004-82a0-86dd74da283d chatgpt is a moron
XD
what do you mean by farm blocks tho
oh
farmland
Im gutting farming to replace it with an instanced farming to better match runescape
That sound wasnt lidting as svailable
its just dirt
Dirt isnt even valid i tried it defaulted to stone
Are you sbout to pull a chatgpt
Read what i linked earlier
no
because gravel is the same sound is dirt
There's a certain amount
function getFullData(target, name) {
let data = '';
for (let i = 0; ; i++) {
const part = target.getDynamicProperty(`${name}:data${i}`);
if (part === undefined) break;
data += part;
}
return data ? JSON.parse(data) : undefined;
}
function setFullData(target, name, data) {
const stringData = JSON.stringify(data);
const parts = Math.ceil(stringData.length / 32767);
for (let i = 0; i < parts; i++) target.setDynamicProperty(`${name}:data${i}`, stringData.slice(i * 32767, (i + 1) * 32767));
for (let i = parts; target.getDynamicProperty(`${name}:data${i}`) !== undefined; i++) target.setDynamicProperty(`${name}:data${i}`, null);
}```
Yup that matches ty
np
-# also when I said "farmland" I wasnt talking about the name of the sound, I was talking about the block name
Still funny what chat gpt did
Its grass no your right its stone no your right its wood no your right its mud
Ahhhhh that makes sence
using chat gpt is lame
Its useful for fast coding but its sometimes stupid as hell
Also, this doesn't matter if it's number or string since parse will convert it to the original state
has anyone made a database that does this dynamically?
Deepseek is far better, trust me
look in #1067535712372654091
It has a better understanding of the current state of the script API
no ai would be cooler.
I don't see anyone who did anything like that.
God, stop promoting AI pls.
Another way to get ChatGPT to understand things better would be to upload all of the types and make your own GPT, but it costs money :\
especially in programming generally
promote self intelligence
I'm going to promote tools that help users create code thats efficient, safe, and maybe even helps them learn something.
and makes them lazy? That's cool
Its a tool. People are going to use a tool.
you can't tell me otherwise since I'm this server a lot of beginners start to use AI and become lazy
It sucks that they clutter the chats with broken code from ChatGPT and expect help
use AI all you want just don't drag other people...
but I use AI all of the time, specifically "Continue" the VSCode Extension, I have a code model that helps write code when I make comments. (which I run locally)
I've already sent my two cents, but I highly do not recommend recommending new users who have not even read a single documentation AI.
I agree
awesome.
"why my code doesn't work?" Gave a code that's 100% ai generated.
I think it skews how people learn how to code, and it doesn't help develop problem solving skills, and debugging skills.
-# debug-playground most of the time.
even if it was 100% correct, its still lame
you did not do anything yourself
That's why I said it makes them "lazy" yes it did not make mistakes but the part where you learn is now lost.
People will use this more for a tool to do things for them rather than helping them learn
no, I'm not saying using AI is bad, as cenOb said it's a tool why not use it but the thing is people are starting to use it in a different way.
thats how things go.
AI was a mistake, and im not looking forward to the progression of it.
I think AI for programming is pretty great, for some things its allowed me to focus more on creative ideas and concepts rather than slaving away at a keyboard for 10 hours trying to develop something.
I still write my own stuff, but sometimes its good to have a tool in my back pocket that can sketch out a concept, or make something simple that I can build off of.
Can't just ask it to "Make me a factions server with crates and pvp zones"
like coddy said, its not really a problem if you use it like that
Unfortunately many people do
yeah, not right now it can, it does not have enough knowledge about the api.
So fuckin true
as I said they'll just join this server and ask "why this code doesn't work?" "I'll pay you to fix it" "can anyone make a script for me"
art is ruined
I have mentioned i use ai as a tool, the only ai right now that seems to be right most of the time is x (grok3)
okay.
-# I'm bad at communicating so I talk with mark Zuckerberg etc.
V. AI is better
Try out Deepseek with similar prompts and let me know how it works out in #off-topic
I've used deepseek it's also good, but it hits a "chat too long" start over issue.
So i have to start over often
Really? I never have that issue, I usually have to reprompt often though
Mostly just having to make a new chat
I wish we could feed the typings though... like I feel like that would make things better
Trying out Grok3 now, i'll come up with a silly prompt and compare the resulting code
Prompt:
I need to implement the following functionality in JavaScript for Minecraft: Bedrock Edition’s JavaScript API (@minecraft/server version: "1.18.0-beta"):
Key requirements:
When a player kills a "minecraft:cow", an explosion particle must play at the cow's location.
A cat should be summoned at the cow's location and named "Kitty."
The block under the cat must be set to stone.
Please consider:
Error handling: Ensure the script checks for valid player and entity references and handles errors gracefully.
Edge cases: Handle scenarios like the cow being killed by an entity other than the player or the cat spawning in an invalid location.
Performance optimization: Ensure that any particle effects or entity spawning does not cause lag or excessive computation.
Best practices for JavaScript in the Minecraft: Bedrock Edition API: Make use of appropriate event handling, entity management, and efficient methods.
Please do not unnecessarily remove any comments or code.
Generate the code with clear comments explaining the logic.
...
They all kinda suck LMAO.
you have to do more training, and some feeding of good stuff first
deepseek is probably the best random
Firt of all GPT is trying to use require, and then like deepseek just straight up doesn't use some imports that it imports
middle file
thats the worst one lol
yeah 😭
I tried to cover most of the methods/events, like particles, checking the death of an entity, setting blocks, renaming entities
Chat gpt doesnt add skill it multiplies it ppl dont realize what that neans cause if you dont know what your doing your skill is 0 and anything multiplied by 0 is 0
You can ask it why script isnt working as long as you give it all it needs but if you cant read code its fix wont help you
Do you know how many times a small syntax mistake was found due to chatgpt
How you use chatGPT matters like right now i had it generate something i dont think will work but a tweak should get it to work
yes ai can be a helpful tool, but it depends on which one you use right now some are just way ahead
Thats somewhat true, but sometimes it sends back my working script and a parenthesis is gone 😭
or it doesn't declare something and tries to use it
yup lol
DeepSeek has been always on it, like pretty consistantly
yup
Do you feed grok data?
deepseek is the best rn,
grok3 is just nicer for less restrictions,
but also performs alright.
still better to feed it some stuff, they have a thinking button

i get it, ai is annoying because its wrong alot and it does require the person to know how to fix the wrong stuff.
but it really helps those that don't know coding that well get further ahead
not the problem
a great tool
oh
I had a chat gpt constantly send the same script back saying how that fixed the issue
don't use chatgpt anymore
its lacking behind others
the 4o one
and over priced
for the o3
ChatGPT has specualised gpt's i use
oh

well, don't really need specialized ones if others are just better out of the gate

lmao
rip fox, you killed him with all this ai talk.
Specuslised gpts are trained specificually and are actually high end
Yeah, I was considering training a gpt with the docs and examples
I just don't wanna pay 😭
I trained a gpt to only say i am groot
lmao
2 realisations 1 someone released 1 to do that and 2 i have no life https://chatgpt.com/share/67d4bb08-cf54-8004-b4d2-ac7ab3551cf0
alright this is funny, but if you wanna save the most money, deepseek or grok3
free
-# or just dont use ai
nope grok is horrible and owned by a horrible waste of space
also i pay for the most up to date premium chatGPT and we need it for school
really?
you dare dis ai i shall ask ai what your punishment shall be
lol alright to each their own
oh boy
ai will remember this when they have a water pew pew to your head after they take over and we become slaves
lol
now you understand
lmfao
lol
ai will remember the punishment princess will generate and wait until the time is right...
you dare defy the ai
Ask ai
brother 😭

I did some searching here and its:
Es6 the module target is es2023
I wrote some intentionally awful code... like YandreDev level code.
I made a prompt that takes the really tragic code and makes it not tragic lmao.
- Code Quality and Best Practices: Ensure the code adheres to modern JavaScript standards, particularly up to the features available in ES6, Minecraft API best practices, and other industry best practices. Make sure the final code targets ES2023 module compatibility.
- Potential Bugs or Edge Cases: Identify and address any potential bugs or edge cases specific to the Minecraft gameplay and API usage.
- Performance Optimizations: Optimize the code for better performance within the constraints of the Minecraft Bedrock environment.
- Readability and Maintainability: Improve the readability and maintainability of the code through proper variable naming, comments, and structuring.
- Security Concerns: Identify and mitigate any security vulnerabilities, with a particular focus on common issues in game scripting such as preventing malicious scripts and ensuring API constraints are respected.
Please provide a detailed refactored version of the code along with explanations for the changes made to address each of the aspects mentioned above.```
surprised it didn't do switch statements 
#off-topic pls
You heard them no more talking about script api here we only talk off topic in this channel now
O ya, how can I use potion effects as a timer for scripts?
ye its resolved now
someone know if is it possible to use custom skins for simulated players?
Is there an event that triggers when a projectile hits a liquid?
It doesn't trigger worldafterevents ProjectileHitBlockEvent
Bruh, Jayly's bot is offline
not possible with script api, if you use resource packs then it is possible
idk how tho
try Entity.isInWater
how do i detect when a player receives an effect that they already have but at a higher amplifier or duration
Du getEffect() and use effectAdd even listener
world.afterEvents.effectAdd.subscribe(({ effect: { amplifier, duration, typeId }, entity }) => {
if (entity.typeId !== 'minecraft:player') return;
const existingEffect = entity.getEffect(typeId);
if (existingEffect) {
if (amplifier > existingEffect.amplifier || duration > existingEffect.duration) {
console.error(`stronger or longer version of ${typeId}`);
}
} else {
console.error(`new effect: ${typeId}`);
}
});```
but effectAdd doesn't fire for me when i get an effect of type that i already had
Then use ruInterval now, in that case.
is there rlly no other way 💔
smh my interval loops are already heavy to begin with
which one is better on performance if i need to run stuff at different intervals:
a) using only one runinterval throughout my entire project & linking the necessary functions to an index determining the necessary tick cooldowns between each execution (e.g. function updatePlayers() could be ordered to only be run every 10 iterations for a 10-tick delay, even tho the runinterval itself is 1-tick)
b) using multiple runintervals at different speeds tailored for different tasks
Using multiple one isn't bad especially if they should have different time delay, what are you doing inside matters
how can i make a numer 1k and not 1000
write a function to format numbers
how??
function addCommasToNumber(number) {
let numString = number.
numString = numString.replace(/\B(?=(\d{3})+(?!\d))/
return numString;
}
//makes numbers like 1,000
/**
- Correct Numerical Values
- @param {value} value Number Value To Correct
- @example metricNumbers(10000)
- @returns Formatted Number Values
*/
export function metricNumbers(value) {
const types = ["", "§fk", "§fm", "§fb", "§ft", "§fp", "§fe", "§fz", "§fy"];
const selectType = (Math.log10(value) / 3) | 0;
let decimalPlaces = 2;
if (value < 1000) {
decimalPlaces = 0;
} else if (value < 1000000) {
decimalPlaces = 1;
}
let scaled = value / Math.pow(10, selectType * 3);
scaled = Math.floor(scaled * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
return scaled + types[selectType];
}
//makes numbers like 1k
Yeah I had to set runInterval and check is in water
function formatMetric(num, decimals = 1) {
if (typeof num !== "number" || isNaN(num)) return "NaN"; // Handle invalid input
if (num === 0) return "0"; // Handle zero case
const absNum = Math.abs(num);
const units = ["", "K", "M", "B", "T", "P", "E", "Z", "Y", "R", "Q"];
// Z (Zetta), Y (Yotta), R (Ronna), Q (Quetta) for extremely large numbers
let unitIndex = 0;
while (absNum >= 1000 && unitIndex < units.length - 1) {
num /= 1000;
unitIndex++;
}
const formatted = num.toFixed(decimals).replace(/\.0+$/, ""); // Remove unnecessary decimals
return (num < 0 ? "-" : "") + formatted + units[unitIndex]; // Preserve negative sign
}
// Test cases
console.log(formatMetric(0)); // "0"
console.log(formatMetric(999)); // "999"
console.log(formatMetric(1000)); // "1K"
console.log(formatMetric(1500)); // "1.5K"
console.log(formatMetric(-2500000)); // "-2.5M"
console.log(formatMetric(1e12)); // "1T"
console.log(formatMetric(5.6789e15)); // "5.7P"
console.log(formatMetric(7.89e18)); // "7.9E"
console.log(formatMetric(9.01e21)); // "9Z"
console.log(formatMetric(1.23e24)); // "1.2Y"
console.log(formatMetric(3.45e27)); // "3.5R"
console.log(formatMetric(6.78e30)); // "6.8Q"
console.log(formatMetric(9.99e33)); // "9.99Q" (still handles extreme cases)
console.log(formatMetric("invalid")); // "NaN"
console.log(formatMetric(null)); // "NaN"
console.log(formatMetric(undefined)); // "NaN"
thx
world.afterEvents.entityDie.subscribe(({ deadEntity, damageSource: { damagingProjectile, damagingEntity, cause }}) => {
if (deadEntity.typeId === 'minecraft:cow' && damagingEntity.typeId === 'minecraft:player') {
const killer = damagingEntity
const victim = deadEntity
let killsc = killer.getDynamicProperty(kill) ?? 0;
killer.setDynamicProperty(kill, killsc + 1);
let deathsc = victim.getDynamicProperty(death) ?? 0;
victim.setDynamicProperty(death, deathsc + 1);
}
});
idk why but when i kill the cow(is to test) it add me kill and death
so dynamic properties can be accessible only from the addon that add them, and other addons cannot get access to them, right? ( making sure )
yes
they're bound to the uuid of the pack & the world it's used in
if either of those change , the dynamic properties will no longer exist on that 'instance' of the addon
is this too heavy to be running every tick
const effectsOfPlayer = customPlayer.effects;
player.getEffects().forEach((effect: Effect) => {
const oldEffect = effectsOfPlayer?.get(effect.typeId);
const newEffect: EffectInfo = {
effectType: effect.typeId,
duration: effect.duration,
options: {
amplifier: effect.amplifier,
},
};
if (effect.amplifier > (oldEffect?.options.amplifier ?? 0) || effect.duration > (oldEffect?.duration ?? 0)) {
const canceled = CustomCancellableEvents.emit(
CustomCancellableEvents.EffectAddedEvent,
new EffectAddedEvent(customPlayer, oldEffect, newEffect)
);
if (canceled) {
player.removeEffect(newEffect.effectType);
if (oldEffect) {
player.addEffect(oldEffect.effectType, oldEffect.duration, oldEffect.options);
}
}
}
customPlayer.effects.set(newEffect.effectType, newEffect);
});
for every player
well, in that case i should use scoreboards in order to make my addon work with the second addon i will make
omg guys effect stacking!
is this valid ? ```js
{
const dimension = world.getDimension();
if (!dimension.stopSound) {
const dimensionProto = Object.getPrototypeOf(dimension);
/**
* Stops a sound at the specified location.
*
* @param {string} soundName - The name of the sound to stop.
* @param {{x: number, y: number, z: number}} location - The location at which to stop the sound.
* @returns {Result} The result of the call.
*/
dimensionProto.stopSound = function (soundName, location) {
return this.runCommand(
execute positioned ${location.x} ${location.y} ${location.z} run stopsound @a ${soundName}
);
};
}
}```
elaborate on what u mean by valid
it's not
i mean does this code works as it was intended to do ?
though
no
world.getDimension() required an argument
if you want to get say, an entity's dimension, use the .dimension property
you can do for example player.dimension
world.getDimension() is just used to get an object of class Dimension because Dimension is, by default, a private class which you cannot construct an instance of yourself using parameters
u need to pass a dimension id to it
to get a Dimension in return
can i have the script? 😄
you need to set up your own event handler but here
you also need to add a custom player system
doesnt need to be set up the way i did
you can just use maps within the script to store kv pairs of player id and then the necessary data
this is just the logic itself, you need to make a lot of changes to make it work for u
const effectsOfPlayer = customPlayer.effects;
const currentEffectTypeIds = new Set();
player.getEffects().forEach((effect: Effect) => {
const effectTypeId = effect.typeId;
currentEffectTypeIds.add(effectTypeId);
const oldEffect = effectsOfPlayer?.get(effectTypeId);
const newEffect: EffectInfo = {
effectType: effectTypeId,
duration: effect.duration,
options: {
amplifier: effect.amplifier,
},
};
if (effect.amplifier > (oldEffect?.options.amplifier ?? 0)) {
const canceled = CustomCancellableEvents.emit(
CustomCancellableEvents.EffectAddedEvent,
new EffectAddedEvent(customPlayer, oldEffect, newEffect)
);
if (canceled) {
player.removeEffect(newEffect.effectType);
if (oldEffect) {
player.addEffect(oldEffect.effectType, oldEffect.duration, oldEffect.options);
}
}
}
customPlayer.effects.set(newEffect.effectType, newEffect);
});
/* remove nonexistent effects from map */
customPlayer.effects.forEach((effect, effectTypeId) => {
if (!currentEffectTypeIds.has(effectTypeId)) {
customPlayer.effects.delete(effectTypeId);
}
});
run this for every player every tick
CustomCancellableEvents.EffectAddedEvent.subscribe((event) => {
console.warn("added effect");
const { customPlayer, newEffectInfo, oldEffectInfo } = event;
const { player } = customPlayer;
/* Added due to frequent lookups (>1) */
const { effectType: newEffectType, duration: newEffectDuration } = newEffectInfo;
const startTick = system.currentTick;
if (oldEffectInfo) {
system.runTimeout(() => {
console.warn("removed current effect before re-adding old, prevent conflict");
player.removeEffect(newEffectType);
/* Checks if effect is infinite (duration = -1) */
if (oldEffectInfo.duration < 0) {
console.warn("old effect is infinite, using command");
player.runCommandAsync(
`effect @s ${oldEffectInfo.effectType} infinite ${oldEffectInfo.options?.amplifier ?? 0} ${!(
oldEffectInfo.options?.showParticles ?? true
)}`
);
console.warn("added infinite effect");
} else {
const newDuration = oldEffectInfo.duration - (system.currentTick - startTick);
player.addEffect(oldEffectInfo.effectType, newDuration, oldEffectInfo.options);
console.warn("added non-infinite effect");
}
}, newEffectDuration);
}
});
can u use beta versions of @minecraft/server on bds
yes
why do some people even use stable then
i've never understood
only problem i can see is that
some features are sometimes bugged
probably to ensure their addons are compatible with newer versions
and u have to maintain ur code more
ah
right i forgot people make public add-ons
What can you do with just stable stuff?
A lot.
Question if i want to save the current tick to a dynsmic property and a tick amount eg 10,000 so i can check if 10k ticks passed since the property was saved
This doesn't sound like a question, but yes you can.
I've done so for a project.
the better question would be what i can't do with stable script api
So i forgot the how do i do that part
hi experts, how do I set the rotation of the camera follow_orbit? I can set the viewOffSet but not the rotation, am I m doing it right?
entity.camera.setCamera("awp:follow_orbit_r06", { viewOffset: { x: 0, y: -0.2 }, rotation: { x: 0, y: 90 } });
What do i save to the dynsmic property that saves the current tick
system.currentTick.
🙊
Ahh ok should i also do remainingTick if i want to let ppl see how long is left
Yeah.
can somebody explain how thge script profiler works
im so confused
some of the times it gives make sense but stuff like this ??!+
it does not take 28 seconds to get the amplifier of an effect
yeah its pretty odd
it tracks how many times a function is called.
it sums up the total time spent inside that function across all calls.
if a function calls other functions, their execution time may also be included.
28 seconds for effect.getAmplifier() is not saying a single call takes that long. instead it is saying that across all the times getAmplifier() was called, it added up to 28 seconds of execution time
where do i see how many times it was called
i wanna know how long it takes for a single call on average
run it once?
Seems like that'd just provide me with some pretty useless insight
i thought i could use it to determine what parts of my scripts are causing lag within my pack in different scenarios
whilst loading chunks, with lots of players in the world etc.
no idea how the debugger work beside that info
I actually like how the planting turned out
How to ignore items with this?
I don't want to apply damage to items that are on the ground
const entities = dimension.getEntities({
location: pos,
maxDistance: 8,
minDistance: 0.5
});
for (const entity of entities) {
entity.runCommandAsync("damage @s 8");
}```
exclude "minecraft:item"
Thanks
how do i check if a value is of type Vector3
function isNum(e) {
return typeof e == "number";
}
function isVec3(e) {
return isNum(e?.x) && isNum(e?.y) && isNum(e?.z);
}
Doesn't this work?
if (value instanceof Vector3)
no
Vector3 is a private class you can't import it or construct from it
it can only be used as a type
or interface
idk what its called
Vector3 More like an interface
I see
then check its keys, like if it only haves x, y and z its a vector
well that's what they just told me to do
#1067535608660107284 message
but thank you 
function isVector3(obj) {
return (
obj !== null &&
typeof obj === 'object' &&
Number.isFinite(obj.x) &&
Number.isFinite(obj.y) &&
Number.isFinite(obj.z) &&
Object.keys(obj).length === 3
);
}```
Lmfao, it's in my saved files
Revised, Infinity and NaN is a "number";
function isNumber(value) {
return typeof value === "number" && isFinite(value);
}
function isVec3(vector) {
return (
typeof vector === "object" &&
vector !== null &&
isNumber(vector.x) &&
isNumber(vector.y) &&
isNumber(vector.z)
);
}
@dim tusk any recommendations?
use getEntities()
you can get entities within a specific distance of a location
Is that really the best option?
idk
never done it
just first thing that came to mind
how else do you think you could do it
yeah
Yes it works lol
GetWntities() that's it.
The problem is you can't get current render distance only max render distance
Not that I know of tbh
I noticed that there's an error for unloaded chunks, could I use that to my advantage here?
Might test yours.
Don't chunk get unload outside of render distance? Why not get the blocks class on it?
Blocks?
no
that's the simulation distance
it might work in singleplayer though
but at least not in multiplayer worlds
Oh wait I'm actually saving this entities spawn location as well maybe I can retrieve that?
See if it's in a loaded chunk?
It will work single player only, since other players can see the entities in that chunk while others can't.
Question i know on a world ticks dont happen when its offline but on a server will they still update as long as its live even if noones on
if the server itself is online yeah
depends on the host
yes. Unless the owner shutted it down.
it doesn't require player traffic for ingame events to occur
What's the max distance for get entities?
Ok cool
realms and multiplayer or single player, it only becomes online if there's at least one single player.
i don't think there's a maximum distance, but it is, for obvious reasons, limited to only return entities that are actually loaded at the time of execution
you can get all entities too so why would there be a limit for the distance
The limit is the dimension where it gets executed on iirc
why do some effects not trigger effectAdd
haste, absorption for example
they are also not returned in getEffects()
wait nvm
are there any events that can be listened for before the behavior pack reloads
I think this one is on preview?
especially the shutdown
Both are in v1.21.60 beta Apis https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.SystemBeforeEvents.html
@somber cedar hey whats it like with so much of you always being imported and exported all the time
I don't get that many pings
import { ItemStack, BlockVolume } from '@somber cedar'
lol
is there a add effecft function?
i was asking for this..
ohh lmfao, I thought you're asking for the function addEfect() type shii.
oh no lol
Entity.addEffect('speed', <duration in ticks>, { amplifier: 1, showParticles: false });```
responded.
check again
What is script api for titles and actionbar titles
Documentation for @minecraft/server
Anyone know how to make a server and add / commands with plugins?
there is no way to get a player xuid with just script api right
there is no native way, you can @minecraft/server-net to use an API that gives you an xuid of a player
Is it possible to cancel entity attacks on the player?
you have to modify the player json
Is there a way to get the min and max of a block's state?
Ok, thanks
Oh, that would be a problem. I can't use player.json
block.permutation.getState("state") but get the max and min value of the block state?
uh you can modify all mob jsons
I think he's doing marketplace content and can't modify vanilla stuff
It's an import... BlockStates
yeah for marketplace there is no way to do it
const state = BlockStates.get('<id>');
console.error(JSON.stringify(state.validValues));
it returns validValues
How do I get it from the block I'm interacting with?
const states = Block.getStates()
And loop through them and use what coddy sent
okay, thanks
or you can use getAllStates() get the current IDs available and use them in the get()
How how how how
they probably meant they figured out that you can't retrieve the xuid
before they already got their answer in this channel
or that you can use server-net to getit
export async function getXUID(player: Player) {
try {
const response = await http.get(`https://playerdb.co/api/player/xbox/${player.name}`);
const data = JSON.parse(response.body);
if (data.success) {
return data.data.player.id;
} else {
return "ERROR";
}
} catch (error) {
return "ERROR";
}
}
example usage
system.run(()=>{
getXUID(player).then(xuid=>{
player.sendMessage(`XUID: ${xuid}`)
})
})
is player.getComponent("inventory")?.container a reference to the player's current inventory, or a copy of the inventory at time of execution? if the player receives an item after this value has been stored inside of a variable, will this new item also be retrievable?
to the current inventory
what about saving player.getComponent("inventory") in a variable and then indexing .container on that
will that work
to get a reference
and not a copy
it is not a copy, the inventory is just a reference to the "inventory"
get items and set items are the ones dealing with the container directly
I have a function that makes getting players full data like inventory and location alot easier
That won't work... You need to use Container.getItem(<num>) or Container.setItem(<num>)
Remember reusability is key
I just do playerData = getPlayerComponents(player)
Then i can do playerData.basicually any player component and boom alot cleaner
I made my own too, tho I saved every part of the entity (those who's accessible), I also made a deserializer for ItemStack and Blocks
and yes the ItemStack has every component
Ya i got add and remove items scoreboardSet for scoreboards dynamic property getter and setter
Every obtainable item is getting put in itemComp since 90% have special components i also made ge work only with items in itemComp
I meant saving the component retrieved from the player inside a persistent variable to reduce the overhead caused by unnecessary calls to .container
it works just fine
Which btw works now ive not tested edge cases of how well it handles a ton of data but ya
I don't like doing that tbh.
But meh, you do what you do.
i have to do everything i can to optimize my pack
theres so much to it that even with everything as optimized as possible itll be hell to run with more than 10 players
Mehh
Can you tell me what's not working quickly? js case `!freeze`: var arg = msg.message.slice(6).toLowerCase() if (arg.startsWith("@")) { arg = arg.slice(1) } eventData.cancel = true; eventData.sender.runCommandAsync(`inputpermission set ${arg} movement disabled`); break;
needs more context
print stuff into the console
and see what values come up as unexpected
i want to freeze a player
context , as in what this snippet of code is part of ...
it's likely the problem lies somewhere else than this part of code specifically
More context pls... Also pls check if the arts is valid.
Like do console.error(arg)
i have no error
it's not supposed to have an error, ur supposed to LOG the errors urself
like log the variable values
of different stuff
and see if they're what you expect them to be
The argument is to know if there is an @ after the "!freeze" then the player will be frozen via an inputpermission but it does not show me the errors, surely the code works but it does not do the right thing
Well if it doesn't do the right thing then it doesn't work 😛
You have content log enabled, yeah?
@shut vessel
Nah, also that shit is broken you can ignore than just check in #1067535712372654091 for better one.
#1281437513675964446, yes?
Yah.
ok thx
thx
It seems like something is missing
any way to make this not suck
wait there is a getBlocks function
nah its a different thing
has anyone made a forms framework?
This looks good
ah nice profile picture.... smh.
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;
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 = name
}
})
how do I capitalize 1st letter
in entity name?
how to check player in water?


