#Script API General
1 messages · Page 53 of 1
Am I just stupid or is there really no way to check for the difficulty in scripting?
There isnt.
There's an enum but not used.
I forgor to do a status update, so uh. await import(); works as per the script that has that
Like i need to get the relative path from the importer script's location to the imported script.
(Saying this incase you wanna use my importer class or make your own)
That's also on the web.... yea sorry mojang & minecraft kinda... i blamed yall even tho i didn't know how import works cuz of my ego
Bro went through an entire character arc over the course of twelve hours
A lore in the making
quick question mates
player.getAimAssist()
.set(
{
presetId: ":default",
distance: 10,
targetMode: AimAssistTargetMode.Distance,
viewAngle: { x: 0.25, y: 0.25 }
}
);
Is this how it works?
-# Is this everything i need to do?
W Admin is playing ZZZ
Haha.
Yeah, that should be correct, except for presetId. Should be namespace:id.
yea i was still thinking about a good namespace, anyways thanks :D
How do I convert queued_ticking into JS?
"minecraft:queued_ticking": {
"looping": false,
"range_interval": [30, 40],
"on_tick": {
"event": "remove_block",
"target": "self"
}
}
system.runInterval(() => {
// code
}, 20); // runs every 20 ticks
thx
You're welcome
Should use custom components.
That way you can also use the tick component.
But doesn't that run every tick?
The tick component has an interval property.
How do i set a block permutation using scripts?
im making a spawner for skyblock and when i stack them into a single block, it only drops one instead of how many ive put in
import { BlockPermutation } from '@minecraft/server';
block.setPermutation(block.permutation.withState('<name>', <value>);
block.setPermutation(BlockPermutation.resolve('<block name>', { <name>: <value>, <name>: <value> });
thx
how can i detect if a player has the inventory full?
js const inventory = player.getComponent('inventory').container; if (inventory.emptySlotsCount === inventory.size) {}
inventory.emptySlotsCount === 0
thx
That works too
Reverse
Add !==
yours don't
that won't work too
Actually tho nah. That doesn't work much
Yeah just use minato's
really? Hm okay then
It would flag if even just one slot is full
K
inventory.emptySlotsCount === inventory.size
mean you have 27 empty slot
inventory.emptySlotsCount !== inventory.size
mean you have less or more than that
it is alr
ahhh....
/**
* This event fires for each BlockLocation destroyed by an explosion.
* It is fired after the blocks have already been destroyed.
*
* @param {Object} event - The event object
* @param {Block} event.block - The exploded block
* @param {Dimension} event.dimension - The dimension of the explosion
* @param {Entity | undefined} event.source - The entity that caused the explosion (if any)
* @param {BlockPermutation} event.explodedBlockPermutation - The permutation of the exploded block
*/
world.afterEvents.blockExplode.subscribe(({ block, dimension, source, explodedBlockPermutation }) => {});```
Quick question, is this correct?
the @params
-# I rarely touch param comments lol
anyway to stop a player from swimming?
where is the hunger system coded?
The hunger bar isn't accessible unfortunately, both get and set isn't possible
disable the movements? The player can swim if there is just water and when they sprint.
seem ok
maybe is there a way to stop sprinting? I want to have it so the player is able to jump and move in water but not swim
if only isSwimming wasn't Readonly like isSneaking
disable the forward movements and make your own movement
using inputinfo and applyKnockback
tho inputinfo is still in beta
nice... 15 more to go
sound like a bad idea
then I dunno 🤷
do some hacky ways to disable swimming
im just gonna have it constantly push them down if they are swimming
Make them sneak
If they sneak
They can't sprint
And if they can't sprint
They can't swim
If they are swimming then make them sneak
.isSneaking = true
you can sneak while swiming tho
during swimming yes. But when trying to swim no
t
if (selectedIndex !== undefined) {
const selectedItem = selectedIndex < 4 ? equippableComponent.getEquipment(armorSlots[selectedIndex]) : inventory.getItem(selectedIndex + 9);
if (selectedItem) {
const enchantableComponent = selectedItem.getComponent("minecraft:enchantable");
const name = selectedItem.nameTag || selectedItem.typeId.replace("minecraft:", "").replace(/_/g, " ");
const displayName = name.charAt(0).toUpperCase() + name.slice(1);
if (enchantableComponent) {
const enchantmentOptions = [
{ name: "Sharpness", type: "minecraft:sharpness" },
{ name: "Unbreaking", type: "minecraft:unbreaking" },
{ name: "Fire Aspect", type: "minecraft:fire_aspect" },
{ name: "Knockback", type: "minecraft:knockback" }
];
const modalForm = new ModalFormData()
.title("§l§dAdd Enchantment")
.dropdown(` \n§dSelect an enchantment to add:\n\n§dItem Selected: §5${displayName}\n`, enchantmentOptions.map(option => option.name))
.toggle("§d§lConfirm Enchantment?", false);
modalForm.show(player).then(modalResponse => {
if (!modalResponse.canceled && modalResponse.formValues[1]) {
const selectedEnchantment = enchantmentOptions[modalResponse.formValues[0]];
const enchantment = { type: new EnchantmentType(selectedEnchantment.type), level: 1 };
const enchComp = selectedItem.getComponent('enchantable');
enchComp.addEnchantment(enchantment);
player.sendMessage(`§d§lSuccess§5 >§r§d You added §l${selectedEnchantment.name}§r to §d${selectedItem.typeId}`);
}
});
} else {
player.sendMessage("§d§lError§r§d§l >§r§d This item is not enchantable.");
}
}
}
});
}
Why is it not adding the enchantment?
because enchantments don't have minecraft: namespace
It's just name
like instead of minecraft:sharpness it's sharpnes
and you need to set the item back into the slot to save changes to the itemstack.
how would I do dat
after editing the itemStack, use the setEquipment method.
try {
player.getComponent('inventory').setItem(player.selectedSlotIndex, selectedItem);
} catch (err) {
world.sendMessage(`Error: ${err}`)
}
why this not work?
use the setEquipment method on the equippable component you have.
someone know the name of the sound for an wrong command/answer like the boom
of the note block i think
player.playSound("note.bass")?
yah, but remember that it also changes based on sound below
Guys, are theese the right npm modules?
those are betas
Yes, I know. i use them for "chatSend" e.t.c
You don't want the preview versions unless you use Preview. Otherwise you just need the stable beta.
like 1.17.0-beta.1.21.51-stable
Yup
Does the version contains stuff like chatSend?
is it possible to use ts to read json file?
I dont think so
i thought it was possible for the files only in the same folder of the scripts
Thengs :D
What's the method for making a sign honeycomb i forgot ir
is there an afterEvent that return when the player change its spawnpoint?
Why then you can get player system info?
only WASD, jump and sneak
other than that no
Probably not
You can cache their spawnpoint and check every now and then in an interval
block.getComponent('sign').setWaxed(true) but wait, lemme double check
Yeah
It is that
Also here take a look. https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.BlockSignComponent-1.html#setwaxed
I mean... if an import works but i dont really know how import would work in that case, also you can just do: js export default // json object
For example:
export default {
apiKey: 'something'
}```
I think an import would also work for a normal json file
In any way you'd have to use either:
import data from './data.json';
console.warn(data.someProperty);
Or ```js
import * as data from './data.json';
console.log(data.someProperty);
Oooor:
import data from './data.js';
console.warn(data.someProperty);
Or ```js
import * as data from './data.js';
console.log(data.someProperty);
If you use the `export default` method
All should work
So just use what is easier for you
you can't read json files in scripts folder, use a bundler instead
The big bad devil.
Well just a better way is to use export default
since we're getting a game pause next update will that also mean we'll get more control over the in game time?
Guys, how can I implement a system for naming an entity with the ability to have a new line?
Does the "itemstack" of an item contain dynamic properties?
I think that the scripts will also stop, since system.currentTick will not change during the pause.
entity.nameTag = 'line1\nline2'
You can use dynamicProperty on ItemStack if its max quantity = 1
I know this
That's not what I'm wondering
For example, if an item has dynamic data, will the dynamic data be deleted if I clone this item with a script?
no
well dynamic property is exclusive to one pack only from when it's been saved
it uses the manifest uuid saved in db file in the world
What happens if we delete that file?
idk, havent tried it
You will break your world, since this file contains almost all the information about the world
it looks like this
how does that work?
using like webpack?
Yeah even make your own simple bundler
All you have to do is resolve dependencies
Aka remove any import calls and just put everything it import's into the same file
Can I stop fishing rod damage if I grab a player with it?
Nah anything damage related is not possible with scripting api
Not now at least
You can use damage sensors tho
Huh?
And use some property + damage sensor + event + scripting api
The first 3 are related to the player entity
Meaning youll need to edit the player.json
Which will make your addon inportable with other addons that might use it
There are lots of examples in the #1067869022273667152 channel so take a look.
How do you detect the healing potion?
system.run(() => {
block.dimension.spawnEntity("eidolon:healing_potion", { x, y, z });
block.setPermutation(block.permutation.withState('eidolon:brazier', 9));
});
}
Is it possible to test if a player has opened an entity?
For example, a player opens a chest in Minecraft
PlayerInteractWithEntity/PlayerInteractWithBlock
both have their listener variants in before (read-only) and after (regular) events
for chests, there is a sample
import { world } from "@minecraft/server";
world.beforeEvents.playerInteractWithBlock.subscribe((eventData) => {
const { player, block } = eventData;
if (block.typeId === "minecraft:chest") {
// code for player that is interacting with a chest
return;
};
});
So is it possible to test the closing of the entity?
some NPC interaction or what do you mean?
Chest minecart
Ui Open and close
you can't really detect if player has close some inventory atm
This is sad
how i can create a block instance?
You can't, kind of. You'll have to call a method that returns a Block class.
alr ty
oh
is there a way to add an argument to a custom component for a block?
Anybody online lol
No. Use block tags.
Kk
Are there anyway to add interaction to mobs?
"minecraft:interact": {
"interactions": {
"on_interact": {
"target": "self",
"filters": {
"test": "has_tag",
"operator": "=",
"value": "slayer"
},
"event": "bossfight"
}
}
},
This doesn't work
Just use the playerBeforeInteractWithEntity?
Nvm I'll stay on no script
Then please use #1067869022273667152
Yey, I'm the 100k message
Hey @dim tusk, can you check if your list of docs issue is included in here? https://github.com/JaylyDev/scriptapi-docs/issues/
some yes
the example for awaitTicks() it's awaitTick() without s
That’s fixed
I guess yes? imma just check some of my screenshots if any
the after events of playerEmote
the example used emoteId instead of personaPieceId
filed a bug on that
Can you set multiple different states with one setPermutation
Yes
block.setPermutation(BlockPermutation.resolve(block.typeId, {
"name": "value",
"name2": "value"
}))
how do i spawn a structure again?
hey guys! so i'm using Poggy's template for double plant, and for some reason, just modified, registration of custom component, beforeOnPlayerPlace doesnt trigger, only onPlayerDestroy works, any clues y?
world.beforeEvents.worldInitialize.subscribe(initEvent => {
initEvent.blockComponentRegistry.registerCustomComponent('v360:double_plant', {
beforeOnPlayerPlace({block, permutationToPlace, cancel}) {
const above = block.above()
if (!above.isAir) {
cancel === true
return
}
above.setPermutation(permutationToPlace.withState('v360:double_plant', 'upper_bit'))
},
onPlayerDestroy({ block, destroyedBlockPermutation }) {
const below = block.below()
if (below.typeId === destroyedBlockPermutation.type.id)
below.setType('minecraft:air')
}
})
})```
don't destruct when canceling
that's why poggy didn't destruct it because the cancellation won't work.
aaaaaa
also that's not how you set a value. It's always =
i didnt know it wouldn't work y destructing
=== is comparing
so i should make index file and everything exactly like in the template?
what are you trying to do in the first place?
double plant
I mean, can't you just copy the component ID on every block?
like, 1 single custom component for all blocks that have custom components?
Destructuring bad.
yeah
i ahvent thought of that
tho it depends if you want those blocks to have a plant thingy
and if being honest, idk what destructuring means in scripting
Custom compoments are supposed to be reused by multiple items/blocks.
i have 1 custom component, v360:double_plant for all of my double plants
i did everything according to the template, but beforeOnPlayerPlace still doesnt work, only onPlayerDestroy works
i cant understand what am i doing wrong
Did you register it in your block? Any content log?
Ohhhh nvm. Youre doing === true not cancel = true
no i already changed it
just copy-pasted template code
No idea. Open a post then with your updated code. Are you using an item proxy?
and the upper bit is not getting placed, and the event is not getting canceled when there's a block above the plant
try doing console.error()
oh
right
its probably broken with item
i have an item block placer...
nice mojang
Tada.
It doesn't work on them btw
hi everyone
hi
system.runInterval(() => {
world.getDimension("overworld").getEntities({
location: {
x: 508, y: 75, z: 15
},
volume: {
x: 0, y: 0, z: 0
}
}).forEach(e => {
e.runCommandAsync("say in block")
})
})```
How do I change this to only get entities who are standing exactly inside of the block location, and not entities who are only touching the blocks.
(Currently when placing a block at the defined location, and you stand on top of it/next to it it will detect it as if you're standing inside of it)
In addition, I also want it to work with a wider volume (e.g. volume.x = 10) which means using maxDistance instead of volume will not work
This video is about the Walking Tree creepypasta sighting!
WARNING! Jumpscares are often in these videos! You have been warned!
► I'm an author! Check out my books!: https://www.stingrayproductionszone.com/my-books
► Give a big like and ...
Can I do it with scripting now?
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Yo
be patient
mhm, is it possible to make the fishing time faster using scripts && vanilla fishing rods ?
no
im looking for good ideas for the fisherman hat,
Trying to be
But
I haven't really slept the last 2 days
Kinda
why
I am operating from yesterday's sleep
(Which was around 3 hours of sleep)
Based
How am i based
¯_(ツ)_/¯
people say based to anything
Cool
Whats going on yall
With?
It really isn't our responsibility that you have a deadline.
Yo sup smokey
I know, I'm sorry
But nathan is bored and wants to join this convo so i decided why not
Anyway, i kinda wanna send data across addons but securely
I believe his point is your just fishing from the channel specifically not me
Thats a bit hard too do
Nahnah it isnt
I got good encryption
It isn't cryptographic
But its pretty good
You have to decrypt with an encrypted api key
My problem is
The api key is sent with the command in the /scriptevent command
Which means even if you didn't decrypt
Any other addon can just reconstruct the command and call the api of the main addon
And get the response
Look into http encryption and you can use the same public and private key systems
I would suggest server admin secrets, but that doesn’t seem to work well here
Tbh i dont even know how those work XD
Never looked into them
I'll look into those too
Thanks also!
Also realistically who gains anything from this?
No one...
Just variables that aren’t shared or defined in the main code- they’re in a separate file, and are interpreted when the code is ran. Good for stuff like passwords and the like
Realistically theirs no reason to encrypt things like that, because the normal player cant access script events let alone read them or modify addons within a world
Complex ipc doesnt need such encryption atm tell it become more radicalized
And becomes more common
Oh sick, also i heard that their is like such things to steal scripts from servers is that real?
Is that like why you'd use that
Never heard of it
I've heard of it but it doesnt seem possible
It’s mainly for if you have other people editing your addons and don’t want your sensitive information available to them
Since nothing related to them should be sent to clients
Ahh figured
Like, your login information for a voting site, say, so you can tally votes. You have your password & email as secrets, so then the other coders can just call the secrets vote_email or something without ever seeing the real email address
Ahh i should incorporate that to my firebase api later then
Is the actual data just stored in a json somewhere in the server files?
Note that it’s only available on BDS, because you need to define the variables in a separate file (which is only available on BDS)
I wonder if it reads irt
Do you know if it does?
What’s irt
I was more thinking of external programs modifying the file
Hmm, that may be possible, given that it’s just a file
Never tested it, so
Hell, I’ve never used the secrets regardless, so
I might test it later and see if it modifies in real time
Lmao same
By chance, does your firebase do cross-server communication (e.g. a ban database that can be accessed across multiple servers)?
Mine?
The API thing you mentioned
I’m just looking for something that communicates cross server for global network management
It doesnt cache anything so everything is read irt, which kinda slows it down
But im planning on a v2 that has a ttl system
Neato
The api is very minimal tho just set and get lol
Do u want the git link? Btw
Sure!
https://github.com/Nathan93705/BlockBase/tree/main
from last i tested speeds are roughly 100-140ms to get data (its a bit slow but for an external db its neat)
I also plan on minifying v2 into 1 file
I’ll take a look later, thanks 🙏
hello, how can I store integer value in block
Wym
i have energy pipe that store energy and i want to store how much power it contains
Also idk if its worth it but it might be faster, if you run all the servers on local network, you can host your own database such as mysql, and have a nodejs webserver act as a communicator taking http requests from the addons and interacting with the databse
It would most likely be faster than firebase since its ran locally
Yeah, I'm hosting through a third party service, so
Would love to self host but I don't have the resources to do so
it is possible to detect when the player shoots an arrow using a bow right?
Yes.
which component?
itemCompleteUse?
not component
and its itemReleaseUse
Documentation for @minecraft/server
it shouldn't detect spam clicking right?
it will.
alright ty
but you can check for the use duration with the useDuration property
ya i see
cant script access lootable?
Only via runCommand.
screw it, im bored imma make reverse geyser, add java to bedrock
what is that?
-# I'm clueless asf
geyser is a protocol translator, it lets bedrock players join java servers
ahhh...
😈
import { world, system } from '@minecraft/server';
const TELEPORT_DISTANCE = 5;
const TELEPORT_OFFSET = 1.2;
system.runInterval(() => {
const players = world.getPlayers();
players.forEach(player => {
const entities = player.dimension.getEntities();
entities.forEach(entity => {
if (entity.typeId === 'minecraft:sheep') {
const distance = Math.sqrt(
Math.pow(player.location.x - entity.location.x, 2) +
Math.pow(player.location.y - entity.location.y, 2) +
Math.pow(player.location.z - entity.location.z, 2)
);
// Si la oveja está cerca del jugador
if (distance <= TELEPORT_DISTANCE) {
const viewDirection = player.getViewDirection();
const newPosition = {
x: player.location.x + viewDirection.x * TELEPORT_OFFSET,
y: player.location.y + 0.8,
z: player.location.z + viewDirection.z * TELEPORT_OFFSET
};
entity.teleport(newPosition);
player.runCommandAsync(`tp @e[type=minecraft:sheep] ${player.location.x} ${player.location.y + 0.8} ${player.location.z} facing ${player.name}`);
}
}
});
});
});```
I need the sheep to always see the player, but this command doesn't work. Does anyone know how to do this?
do u know how to give them propertys
Entity properties have to be predefined first on their json files
That means you would have to edit player.json
folks, is it best to use playerPlaceBlock or itemUse when tracking the blocks a player places?? they both work i was jsut wondering on peoples preferences??
That depends, but I think its better you use playerPlaceBlock
itemUse can fire even if the block was not successfully placed
it certainlky does seem more concise, plus the PlaceBlock does expose the block item
is there a way to get player's locale (language)?
and maybe possibly get a translated string based on the key in the lang locale file
there's rawMessage
Documentation for @minecraft/server
im trying to apply it on server body forms
from
- get.HouseKey
- get.ActionHouse
to
- Get a house key
- Get a house.
hmmmm...
it supports rawMessage
yes
you know what imma make my own language system (not based on player's current selected locale)
my storage keeps running out while live editing addons
where does all of this data come from?
and how do I free it back
Your content log?
ty btw
how do I link a variable in teh behavior pack with an element in the resource pack?
Use entity properties
(You are gonna need to edit the player.json file tho)
ahhh I see
But here is how to link it:
player.setProperty('namespace:dangImLinked', true);
Also
Tip
It will not work on simulated players
is there a way to modify blocks before they load in the game....
Uh no
ass
Probably not
i have this idea in my head
and i want it
but i have to modify every block in the world
well basically, the thought is to have all blocks in the world be barries, and they turn back to their normal form once the player interacts with them
You can pre do this
any ideas?
!!!
Snippet
what a kind young man
😭
i really just need a toggleable way to make blocks invisible
btw was there an update to the manifest file?
I'm having a hard time getting my pack detected
Nah, just make sure you have the correct version tho
what's the latest?
im so lost on how to do this i thought this would be way easier just not performant
@minecraft/server => 17.0.0-beta
@minecraft/server-ui => 1.4.0-beta
Nah its not easy and certainly not performant but i am trying to use my knowledge
i really appreciate your help/input
Here
It isn't complete and won't save stuff like inventory, you have to make a serializer and deserializer for those. And also i dont actually set the block back when you interact with it because thats also complicated, and also this doesn't really manage ticking areas or does it go far. It just loops in the 50 by 50 range around all players and does it's thing. Implement that logic and you should be good to go.
Whats going on yall
do you have a manifest I can see?
idk what's the problem with mine
All good, implemented that https encryption protocol.
Sure
my recipies keep overlapping when I scroll in the crafting table; anyone know a fix for this?
#1067869374410657962
Appreciate it thxs
Oh neat im doing the same thing i was yesterday too lol
ty
i have your same issue, ever found a fix?
Allows for intractable, customizable forms created by the user
Ah cool
ohh
is it a new thing?
Been around since 1.19.50 or so
Remaking a java server in typescript is interesting tho lmao
@granite badger why are there blank squares in your docs
I see
ad block
I accidently pushed empty div elements from prototype code
Lol
Good luck to you lol
Indeed but it's for the sake of java joining bedrock
Its not on vanilla sadly lol
Im developing it as a plugin on SerenityJS
So far i got cross chat working and im working on chunkloading rn
isSprinting is true or false right?
Ah sad..
Well best of luck to you!
Yeah
ty
this is script is really cool
it's very clear
function thirst(){
if(system.currentTick %20 === 0){
const playerCount = world.getAllPlayers();
playerCount.forEach(player => {
const state = player.isSprinting;
if(state === true){
world.sendMessage("player is sprinting");
}
world.sendMessage("player is not sprinting");
}
)
system.run(thirst)
}
system.run(thirst);
}
mb
this in theory should work?
what are you trying to do?
tho why bother making a delay if there's a built-in delay in runtInterval?
Just trying to detect when a player is sprinting
Ye just forgot to remove it
system.runInterval(() => {
for (const player of world.getPlayers()) {
if (player.isSprinting) {
// ...
}
}
});```
as simple as this
try to space that out a few ticks... like 5
But I want each player to have a set of variables later
Basically this is the start of thirst system
that what he was trying to do here
system.currentTick %20 === 0
-# i think?
What I'm confused about is what variable
use dynamic property or an object variable
each player has thirst data saved?
const thirst = {};
thirst[player.id] { duration: 10 };
const thirst = JSON.parse(player.getDynamicProperty('thirst') || '{}');
thirst.duration = 10;
player.setDynamicProperty('thirst', JSON.stringify(thirst));```
So dynamic property allows to store data for each player separately?
Yah and it's saved even if the player left
Oh nice
tho you can't access if the player isn't in the world obviously
i thought I had to make like a system that creates a var for each player
It is not saved if the player left
so yeah, not a good idea
const thirst = JSON.parse(player.getDynamicProperty('thirst') || '{}');
thirst.duration = 10;
player.setDynamicProperty('thirst', JSON.stringify(thirst));```
Whats Json.parse tho?
It is a native function in JavaScript that takes a string and parses it as JSON. The resulting value is an object you can manipulate
JSON. parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string.
const InJSON = '{"key":"value"}';
const Obj = JSON.parse(InJSON);
console.warn(Obj.key); // "value"
So obj became an object with the InJson's elements inside?
Yea, you could think of it that way
Can someone help me create a script that makes a sound sound when I touch a block?
please
and add a score to a scoreboard
sound and add score
define "touch a block"
Walk on?
Ye lol
touch a block with my character, or when I am near a block
Like from all sides?
Near and touch are very different
walk on it? interact with it? like a cactus?
Cactus doesnt do anything when u interact with it?
I am creating a Pacman map, and the balls that are eaten are blocks, so I want a script that does that function, that when you touch the block, or are close to it, it makes a sound and adds a score to the scoreboard
I'd personally just recommend making entities
Command blocks can do that I think
yeah , but it better with script
commands slow
I use a block but it passes through, it is not concrete or solid.
Oh you coukd just detect if the block at the player's location is that block
Crazy
Real
that's the funny part, why ask in scripts if they can do it on commands? 🤷
😦
import { world, system } from "@minecraft/server";
const checkInterval = 10; //run every 10 ticks
const r = 0.4; //radius to check for blocks, adjust it until it make sense
const targetBlock = "minecraft:gold_block"; //block to detect
const soundEffect = "random.orb"; //sound to play
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const { x, y, z } = player.location;
//scan a small area around the player
for (let dx = -r; dx <= r; dx++) {
for (let dy = -r; dy <= r; dy++) {
for (let dz = -r; dz <= r; dz++) {
const block = player.dimension.getBlock({ x: x + dx, y: y + dy, z: z + dz });
if (block && block.typeId === targetBlock) {
player.playSound(soundEffect);
return;
}
}
}
}
}
}, checkInterval);
i think it is better to hard code the places to check (8 dir around the player feet, 8 around the head, up and below), but i don't have time to make that
Btw why block and Block.typeId?
Isn't block.typeId enough?
should use getBlocks
blockVolume is out of beta.
it is beta
its not
it is
I literally just used it in my stable script.
Documentation for @minecraft/server
my npm is outdated 😅🤦♂️
yeah, you should add a try catch tho, that function can throw errors
Oh I see

Is getBlocks out of beta yet?
.-.
troll
not trolling
read?
if you are not trolling...
read
scroll up
to be fair I said blockVolume was out of beta, not getBlocks
sorry I saw block volume and thought about getBlocks
it is
I haven't touched scripting api in a few months
nice
blockVolume came out of beta before getBlocks
when did it come out of beta?
if getBlocks is stable that mean the other way around too
well yeah, getBlocks couldnt become stable if blockVolume wasnt
doesnt make sense
yep
not that long ago, recently. Im not sure which update
Well...i think some events were marked stable but the listeners were marked beta.
One question, what do you think of those people who steal maps from other creators and nodify them?
The block I use can be transferred without problems, I mean it is not solid, there is no problem, right? the script will work anyway
how do i get the namespace of the item that is in my hand?
console.error(ItemStack?.typeId)
case 'blc:teste':
const itemName = player.itemStack?.typeId
player.runCommandAsync(`say ${itemName}`)
break;
undefined
No, you need to get the slot first
where are you using it?
It worked here, thanks
how do i remove the "you have been kicked" like on the hive when someone gets banned
@dim tusk I'm managing to return the entity ID, but I want to remove "minecraft:cow" and leave just cow
How can I do this?
String.replace('minecraft:', '');```
let itemName = selectedItem?.typeId
itemName = String.replace('minecraft:', '');
?
change the String with the itemName
How can I detect when an entity is in the same position as the player?
system.runInterval(() => {
let players = world.getAllPlayers()
for (let player of players) {
if (player.dimension.getEntities({ x: player.location.x, y: player.location.y, z: player.location.z }).typeId == 'entity:entity') {
//code
This doesn't work
getEntities returns an array, not a single entity
getEntities returns an array of Entity.
^
I was 500ms slow.
That still returns an Array. You need to loop through it.
As what they said it's an array.
like how you do the getAllPlayers()
is an average tps of 19.84 good?
I was calculating my tps and it kept bouncing between 19.70-20.20 I'm not sure if this is a good sign or not? should my tps be consistently above 20 or is fluctuations below 20 okay?
What is getLore() for?
check the list of lores of the items?
like this?
It returns an array of lores
what is lores?
when you hover the time in inventory there's a little purple thingy
attack damage?
just search it lol
can you modify a players speed with script without using the speed effect?
Yes you can modify the players movement attribute, just note that you will need to do it constantly as any manually changes in speed ie: sneaking or sprinting resets the value to the default.
can u write a code in game with modalFormData textfield?
What?
is it possible to run a code ingame with modalFormData? for example if u want to execute sending message or more complicated code like opening a form?
idont know whats wrong with my script but everytime that i call getDynamicProperty() on a Player class, the game crashes
whats the actual proper way to handle it anyway
Yeah it should be, you should be able to set or get a property using object["text"]=test or to use a function object"text" I think that’s right be if not I can look through my addon that uses this to find syntax. Or incorporate the text into a function or other stuff using the variable.
@charred gorge If u have, maybe u could drop it here and mention me. This would be a great help for me. Cause I've been planning to update my addons into importing the codes in game. Its like if I want to add new button. Ill just inport the code in game.
No I don’t have the function that you are looking for, I was just showing you how to execute a function/property using text you’re going to need to code it yourself. I was referring to my own code which I can show you parts if you want; however it probably won’t be a ton of help though, my code in parts does what you are doing but has a pile of other aspects.
how do i use the variables from molangVariableMap in my particle's json?
i used v.example_name.speed but nothing really happened
send your particle.json and script
hold up a sec
const dash = new MolangVariableMap();
player.dimension.spawnParticle("dby:dash_manual", {x: player.location.x, y: player.location.y + 1.2, z: player.location.z}, dash.setSpeedAndDirection("particle", 0.1, player.getViewDirection()))```
in game it would fly off very fast and face a random direction
try manually setting them.
how so?
Change the 0.1
alright lemme try
it did send me these errors
[Molang][error]-particles/dash_manual.particle.json | v.particle.speed | Error: unable to find member variable .speed
[Molang][error]-particles/dash_manual.particle.json | v.particle.speed | Error: unhandled request for unknown variable '.speed'
[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_x | Error: accessing a variable that doesn't currently exist in this entity: variable.particle
[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_x | Error: unable to find member variable .direction_x
[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_x | Error: unhandled request for unknown variable '.direction_x'
[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_y | Error: accessing a variable that doesn't currently exist in this entity: variable.particle
[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_y | Error: unable to find member variable .direction_y
[Molang][error]-particles/dash_manual.particle.json | v.particle.direction_y | Error: unhandled request for unknown variable '.direction_y'```
try changing from particle to a different name
It might be sensitive that's why
it didn't work, i changed the particle to dash
Did you use snowstorm?
yep
Yo hol up
I haven't messed with velocity in scripting api for a whilr
While*
Would a good'ol player.getVelocity() work?
Perfect answer:
I'll test
you can use forEach to loop it
get the whole velocity?
const velocity = player.getVelocity();
Math.sqrt(velocity.x ** 2 + velocity.y ** 2 + velocity.z ** 2);```
-# not sure if this is the right math lmfao... That's why I failed math
why? for of do the same, and can be better in some cases
@celest abyss btw
{ x: player.location.x, y: player.location.y, z: player.location.z }
player.location is already a vector3
so just use it directly
btw what you did here is:
you made an empty object
parsed it
gave it a key and value
then stringfied it and stored it for a player right?
it is faster and work for lot of types
Array Map String Objects and so on
yeah
btw is this the right understanding?
yeah
hmm
ngl you scared me
but why not just store the number directly
he said before he wants to store an object so that's why I gave that to him
how? xD
btw are custom effects possible?
No.
that sucks
system.runInterval(() => {
for(const player of world.getAllPlayers()){
const thirst = JSON.parse(player.getDynamicProperty('thirst') || {})
thirst.hydration = 100;
if (player.isSprinting === true){
thirst.hydration -= 1;
}
player.setDynamicProperty('thirst', JSON.stringify(thirst));
}
world.sendMessage(thirst.hydration)
}, 40)
is this syntax correct?
nvm I forgot the ' at '{}'
how do I detect when a player eats a certain type of food?
I think that one of the events detects that itemCompleteUse maybe and then you just check what item was used in the interaction.
The issue is the item disappears after you complete use.
world.afterEvents.itemUse.subscribe((event) => {
const { itemStack, source: player } = event;
// Prevents errors if something weird happens
if (!player || !itemStack) return;
player.sendMessage(`You used: ${itemStack.typeId}`);
});
I tried this
but it causes multiple detections
and I doubt it would work with a filter
and even if I don't finish the interaction it counts as a complete one
update: it's all working now
If you're in creative, for whatever reason interactions that don't fully use the item have a chance to repeat
I noticed this when I was working with potions
same thing happens with food
I wonder if anyone had made a physics engine with script api
what you mean by that ?
why would anyone make a physics engine that works at the rate of 20 times / s
🤔
nah it was because I had the subscribe inside the runInterval
so it would subscribe multiple time's in the same interaction
How do I get an entities inventory because people say to use getComponent('minecraft: inventory').container but it doesn't pop up on the bridge auto completions
People have
can you send your script?
Thats a very bad idea
It's literally nothing besides a custom component with me getting the source entity then adding get component with the inventory but their is no auto completion for container or inventory
Yeah that's correct
that's how you get it...
It doesn't show up on the bridge auto completion tho
yep I figured it out the hard way lmao
That doesn't mean it doesn't exist
Don't ALWAYS trust bridge
you want that if you long press it still run a command not just once?
I don't know anything about it so how could I do it without any auto completions
you can just make the item usable or eatable and use startUse and stopUse
I'm not just gonna do what I do with Roblox scripts and blind eye my code
Are you that lazy to at least search the docs?
nah I fixed it dw
I used the completeUse
I do but they still don't make sense to me because I'm very NEW to script API
fair enough but as I said what you did is correct
that's how you get the inventory
don't sweat it too much
It maybe not updated
How when I'm literally trying to make something that's important in my mods function but I can't because I can't find the auto completions which makes it way harder for me because I have to keep going back and forth looking at different things
And plus I'M CODING ON XBOX WHICH MAKES IT EVEN HARDER
i mean it kinda depends on person, I'm literally in a phone and I perform fine
you install bridge on Xbox?
No I use the website duh
Ohh sorry if I ask since there's an app version of it 🤷
Ik
Used to use VSCode but my laptop broke so I can't anymore
That's why I think VSCode is way better than bridge in every way
I had 6 years of experience on VSCode and now I can't use it anymore
And it obviously has been updated they update the auto completions almost every time Minecraft updates, it USED to have the auto completions for it working but NOW it doesn't for SOME reason and why TH does the changelogs say "changed from string to T" WTH IS T
@distant gulch you're making a custom container?
No?
Custom Block Component
coding on Xbox???
Yes?
is that a thing
If you wanna pay 3$ then yes
isn't it better to use your phone
alr
To even get mods on Xbox you have to still spend that 3$
It was on sale for like 0.79$ before
But I bought it when it was 3$
free apps don't stick for long
There's a free trial for it
For 24 hours
I used to keep creating Microsoft accounts to use it before I actually bought it
What will it do?
When you click on the block without anything in your mainhand that's all it will detect
It's for my keycard reader but I made a separate script from the actual key card reader script so it wouldn't take up more
Needs to soley only detect when you're holding NOTHING
Because other items/blocks already activate the "Keycard Level num+ required" and the empty mainhand doesn't because it detects when an item is being used on it
world.beforeEvents.playerLeave.subscribe(ev => {
const player = ev.player;
let combatEndTime = player.getDynamicProperty("combatTime");
if (combatEndTime && Date.now() < combatEndTime && player.hasTag("pvp")) {
system.run(() => {
world.sendMessage(`${player.name} combat logged`);
player.addTag("combat_logged");
playerLeaveInCombat(player);
})
}
});
failed to get property 'nane' at anonymous
Player becomes invalid once they leave- and a system run delaying the code by a tick makes it run after the player has left.
how can I fix
Define the player name before using it (outside the system run)z
And you cannot add a tag or run that function
hmm, is it possible to make my entity look at the player using scripts?
like getting the player from view distance, and somehow applying rotation to the entity to make it look directly at the player,
I've seen something similar with block entities
With just command blocks
Probably possible
i can do applyRotation something to make the entity rotate, but I'm trying to understand how to do it exactly.
get the direction vector of entity location and the target locations
I mean subtract them
function faceTarget(e, t) {
const dx = t.x - e x, dy = t.y - e.y, dz = t.z - e z;
const yaw = Math.atan2(-dx, dz) * 180 / Math.PI;
const pitch = Math.atan2(dy, Math.sqrt(dx * dx + dz * dz)) * 180 / Math.PI;
e.applyRotation({ x: yaw, y: pitch });
}```
what's yaw and pitch?
Hi yall
I dont remember how can i take a item in a placed shulker box(slot 2)
let 2 = ???
const inventory = Block.getComponent('inventory')?.container;
const item = inventory.getItem(2);```
And if i want to know if the item is enchanted and with what?
It returns an ItemStack, just do getComponent('enchantable')
Okay thx
Can i ask something else?
you can do hasEnchantment(), getEnchantment() or getEnchantments()
ye?
search internet...
Is it possible to give a person a shulker box pre loaded without structure block?
nope...
Sad
best way is to place a shulker box then put items and so Block.getItemStack()
you can get the items Inside
Too much work
Thx
how do I randomize an action?
like instead of a monotone -1 operation from a var it could do -1 or -2
again it was done with Math.random
i, will just make it block not entity,
less issues, less bugs, less lag, good for my brain health
hm, is it possible to detect catching a fish or anything from the sea using a fishing rod?
test
entity remove event maybe
but is a fish caught by a fishing rod considered an entity, or is fishing just an event that gives you a loot table?
entity remove cuz the bobber
but then you get the bobber
maybe item use, then
the item given is a physical item that gets pulled to you though....
that's probably how
before item use-> scan & save inventory
after item use -> compare against before event's inventory to see changes (what was caught)
was going to say that
but it has issues because of a player fishing, then picking up another item, then catching or not catching a fish and then it's a false positive

yeah idk
The events would both run when they reel in
ah true
So you'd be comparing the inventories within a tick of each other or so
so it's a split second
but that tick is possibly enough for the item to not reach the player
The best course of action is to remake the fishing system from scratch 
world.afterEvents.playerCatchFish
does anyone have a db manager?
a
😉
I would just listen for the fishing hook being removed and then the item being spawned in a certain range from that position
I remember doing a system for that but I don't remember in what part of my computer it is now
does block.above() returns air or undefined?
the only thing i am trying to do is add a low chance to get an extra fishing pool item when u catch something using the vanilla fishing rod, while equipping a custom hat.
It's always undefined if it's air
no?
in my case yeah I guess?
huh
huh?
uh... i just said no
@untold magnet
import {system, world} from "@minecraft/server";
world.beforeEvents.entityRemove.subscribe((event) => {
const hook = event.removedEntity;
if (hook.typeId === "minecraft:fishing_hook") {
const loc = hook.location;
const date = Date.now()
const dimension = hook.dimension
const id = system.runInterval(() => {
const id2 = system.runTimeout(()=>system.clearRun(id),20)
const items = dimension.getEntities({type:"minecraft:item", location: loc, maxDistance: 1})
for(const item of items){
if(date - (itemSpawnDate.get(item)??0) < 100){
console.warn(`Caught item: ${item.getComponent("item").itemStack.typeId}`);
system.clearRun(id)
system.clearRun(id2)
return
}
}
});
}
})
const itemSpawnDate = new WeakMap()
world.afterEvents.entitySpawn.subscribe((event)=>{
if(event.entity.typeId !== "minecraft:item") return;
itemSpawnDate.set(event.entity, Date.now());
system.runTimeout(()=>{
itemSpawnDate.delete(event.entity)
},20)
})
Hi ae
hi there, how can I find structures saved with structureManager? I mean, is it available in any folder that I can download? cannot find it
It's saved in db folder like all structures
Hi
and there is no way to extract it? any tool that can handle it or vscode itself with a plugin?
thats so good, thanks for the help, i appreciate it but, is it random or sometimes it just doesn't work?
it doesn't send that log, sometimes
sometimes it works
sometimes it does not work
increase maxDistance: 1 and try?
it works perfectly fine now
maxDistance: 1 → maxDistance: 3
3 is a bit too much
What's this?
read the messages for context?
wait, what if my friend is fishing and i was equipping the fisherman hat, my friend will get the extra drops without having to equip the hat, the script should get the player who is fishing to make it work only for him and make the loot spawn directly at him.
lemme send u the updated one.
world.beforeEvents.entityRemove.subscribe((event) => {
const hook = event.removedEntity;
if (hook.typeId === "minecraft:fishing_hook") {
const loc = hook.location;
const date = Date.now()
const dimension = hook.dimension
const { x, y, z } = hook.location
const id = system.runInterval(() => {
const id2 = system.runTimeout(()=>system.clearRun(id),20)
const items = dimension.getEntities({type:"minecraft:item", location: loc, maxDistance: 2})
for(const item of items){
if(date - (itemSpawnDate.get(item)??0) < 100){
if (fisherman_hat === true) if (Math.random() <= 0.1) dimension.runCommandAsync(`loot spawn ${x} ${y} ${z} loot "gameplay/fishing"`)
system.clearRun(id)
system.clearRun(id2)
return
}
}
});
}
})```just help me make it work only at the player who is fishing and equipping the hat.
why don't you just subscribe to the spawnEvent inside the hook event?
it's a beforeevent, so the event listener should fire in the same tick
then it's easier to test items since you don't have to do that date map thing
yeah i guess that would be better
when the hook spawn tag it with the player id
or maybe the hook do have player as owner?
either way, it should be that hard to add
u can edit it freely,
cuz my scripts skill isn't that good on this section
yo @dim tusk how can i return the id of the item with the shulker box thing
bc it dosent work
i have to manually update the docs for v2.0.0-beta
wonder what builder class is
Knowing how script API 2 interacts with the world is pretty important
check the minecraft/server docs and look what i wrote
guys, with the v2.0.0-beta
"It doesn't work lol" -Jayly 2025
what do u think the upcoming features will be
Stable chatsend 🙏
yes
Your import Exec is looking for a file called plugins.js in the core directory
./modules/core/plugins/index.js
I changed
It itself replaces aliases with this path
there is no extension at the end, it should look for index.js itself
[lndrs@lndrs-pc bp]$ pwd
/home/lndrs/.var/app/io.mrarm.mcpelauncher/data/mcpelauncher/games/com.mojang/development_behavior_packs/bp
So are you saying there is a plugins.js file in the plugins directory??
The import doesn't say anything about the extension, it know that the index.js file should be inside this folder. But even after manually adding the index.js to path it doesn't change anything, it still doesn't want to use this file.
Everything starts working only after renaming all the index.js files in the project is for something else
like main.js
What does your manifest look like??
nvm fixed
Excellent news, what was it??
idk
I renamed all the index.js files to others and everything works
for some reason, after running the build task with tsc-alias, the code does not find files with the name index.js
how to make blocks items to be unstackable
I think when you define a block you set max stack size
there's no max_size in blocks components, how is that?
This is a #1067869136606220288 question.
I think he want to make it with script
Idk if it’s possible
Hello here, i just want to ask if I have 2 custom ui installed in my world. can i run the ui one at a time? 2 addons for different ui?
custom json ui?
yess i want to call 2 forms one at a time
you can make ur ui's conditional based on title
Yo
I am trying to make a foolproof way of detecting when someone lands
I kinda got the velocity of someone jumping.. aka (y = 0.42...)
player.getVelocity().y >= 0.42
But that still would flag for someone launched
Oh yeah right i can just increase the number and do some more operations
player.getVelocity().y < 0.43
For anyone wanting to detect when someone landed completely foolproof
I think at least
Kinda have been testing too much
I'm sure jumping and that jump swim in water are much less then 0.43
Jump is 0.42
And that "jump swim" is 0.34 i think
set max_size to 1 in the item json of the block
thats it
guys actually im doing scripting after a lot of month
can any one tell me what has changed within these months
just fuck around and find out
how to set item durability? cuz
because what
cuz it says its read only
ya
wdym "yeah"
i wanna change the durabilityy of a item
you are misunderstanding what it says.
so what does it mean?

for helping
