#Script API General
1 messages · Page 74 of 1
wdym how to use
you just adjust the number in the main file
if you're using the latest version i think he made it weird and called it keys or some shit
up, imma do smth
yeah this changes their name
so player.name returns default name, while player.nameTag returns name tag
yeah
ok thanks
Nah
entity.nameTag = "aaaaaaa"
});
You cannot directly change it since its not a method and instead a property. You need to use the above
so how do i change the name of specific player? like for example
i will use playerSpawnAfter event
that returns player right
yeah
so i can directly do it?
you'd just get the player then change it to whatever
Yeah. parameternameofevent.player I think
world.afterEvents.playerSpawn.subscribe((data) => {
const { initialSpawn, player } = data;
if (initialSpawn) {
return player.nameTag = `[Noob] ${player.name}`;
}
});```Something like this
ok thanks
You might have to give them a few seconds to actually spawn in though
just decided to test it to make sure, left one is name and right one is nametag so yeah lol
It does return when the player spawns. You don't need to give time. That's with the playerJoin
Yeah, I just mentioned about giving them time since a few things I've wanted to do with the player when connecting doesn't run as the player hasn't technically loaded in yet
If it's not needed then fair enough
But nameTag isn't a method, but a property
i don't get all the ins and outs of the script api yet lol.. i just know enough to get me through it 🤣
i'm actually stuck where i am with knowledge rn and it's a pain because i can't improve 😭
How to fix
let item = wand.getComponent("minecraft:enchantable").getEnchantment({id: "unbreaking"}).level
console.log(item)
What's the problem?
getEnchantment(enchantmentType: string | EnchantmentType)
not an obj
Send code fix use unbreaking
well as minato mentioned.. it's not an object like you've written it to be.. it only accepts a string
Fix code send
I'm not fixing it for you lol
let item = wand.getComponent("minecraft:enchantable").getEnchantment("unbreaking").level
console.log(item)
yeah
No
welp, there's your issue then -_-
the content logs says enchantable component doesnt exist
it only gets enchants applied to the item
Ok
💀 lol
just... put a ? on component
wand.getComponent("minecraft:enchantable")?.getEnchantment("unbreaking")?.level
can't read that for shit lmao
Bro any app for code in mobile?
quickedit
Screenshots are hard to read, and photos even more so. This is especially true if you are using bridge or another tree editor, as this format obscures the JSON format.
We can help you best if you copy and paste your code here, or send it directly as a file.
how do i give someone a mending book?
with scripts
ofc
const item = new ItemStack ("minecraft:enchanted_book")
item.nameTag = "Mending Book"
inventory.addItem(item)```
i don't think you can.. it's just an enchanted book but i don't think we can get the exact data for the books
dang
Bro how data file open in androad 14
zarchiver
Anyone from india
idk if it would work but maybe getting the "enchantable" component and then add the enchantment to it:
const book = new ItemStack ("minecraft:enchanted_book");
book.getComponent("minecraft:enchantable").addEnchantment({type: "minecraft:mending", level: 0});
inventory.addItem(book);
Why do I get this error?
[Scripting][error]-Error: Failed to set property 'test:upper_block_bit' on block 'minecraft:air' at onPlace (blocks.js:144)```
```js
onPlace(event) {
const above = event.block.above()
const permutation = above.permutation
if (!permutation.getState("test:upper_block_bit")) {
above.setType("test:door")
above.setPermutation(permutation.withState("test:upper_block_bit", true))
}
}```
acode
🙂 the block you are trying to edit it permutation is air
But I set the type of the block (as you can see in the code part)
This is best i think
What app even is this?
??
What app is this?
Not app this is webApp
Just tell the name bruh
fast coding in this app in mobile
You are the most annoying thing I have seen
They are asking what application or website this is.
he's indian and his english is bad af, he just doesn't understand you lol
How can someone not know what "name" is?
someone whose native language isn't english
One more
I think he is just trying to be really annoying
lol
Wait can someone translate my sentence?
ig he's also too dumb to do that
Got it. Its bridge
But this isn't bridge
Yes bro
@uncut sail what is name of this webApp in video
maybe he understand that way
I send link parasnal you ok
send name here
इस वेबऐप का नाम क्या है?
the translation may be janky
Minecraft Creator Tools
nice
Bro i undarstand english Okkkk
I undarstand English too
use can use acode or helix on ter,ux
I do use acode. But it feels annoying to run a termux command
ye
Ty. This is exactly what I was looking for this entire time
No joke
Bro do you know this webapp?
Man, pls forgive me. What did I do wrong?
btw this, what u think
function getDirectionalGridXZ (r, x, z, X, Z) {
let [ax, bx] = (Z + X > 0) ? [r, -r] : [-r, r];
let [az, bz] = (Z - X > 0) ? [r, -r] : [-r, r];
let result = [];
let lerp = (a, b, t) => a + (b - a) * t;
const dx = bx - ax
const dz = bz - az
const iLen = Math.abs(dx); // Steps for x-axis
const jLen = Math.abs(dz); // Steps for z-axis
const xSign = Math.sign(dx)
const zSign = Math.sign(dz)
for (let i = 0; i <= iLen; i++) {
result[i] = [];
for (let j = 0; j <= jLen; j++) {
const xVal = ax + x + xSign * i;
const zVal = az + z + zSign * j;
result[i].push([xVal, zVal]);
}
}
return result//.map(row => row.join('\t')).join('\n');
}```
As shown in this
Bro how make cable like lead
What?
Pls learn some english
i read his messages with indian scammer accent 
🤣
You not undarstand my very good english
U mean rope physics?
Yes, I am very dumb. I don't undarstand English
Yes
This is achieved through a process known as varlet integration.
It is very simple, you can learn it on YouTube.
Ok don't say sorry ok
The guy above me is 100% a troll or someone's alt
i was abt to say it, no one can truly be like this
I don't believe someone can be so intelligent like him
Starting a new series on one of my favorite subjects, Verlet Integration. I think you'll like this one.
There's a minor code error here. It won't break anything, but see if you can spot it.
Support Coding Math: http://patreon.com/codingmath
Source Code: http://github.com/bit101/codingmath
he's Albert Einstein's reincarnation
Fr
He also created some English words like for example, "Undarstand"
Not this words made me this created by donal darmp
I prefer acode
i mean, ik my english is bad, I'm aware of it, but not THAT bad
nah he's a bait
he fooled us
Donald darmp is truly a president of all time
Fr. But it's not April fools
This logic use in minecraft it is working or not?
Acode does not provide information like Helix
there are other aspects in which score is better
Yes, it is simple math and can be used anywhere.
He used VI in that
Bro why say this
O
Yeah I know hindi
That not nice
Are you able to detect how much damage an item should do??
for example if i enchant a sword with sharpness it does 8 damage
so i want its right click move to also do 8 damage. Just wondering.
not possible
How are you going to get the item damage
Keep mind custom items
Welp, i guess it depends on his use case
Idk but i saw someone doing it
i mean that sounds simple enough but like he said, how would I get the item's damage?
YESSSSSSSSSSSSSSSSSSSSSSSSSSS
I've fixed the last thing I need for my wedge blocks to make them properly good now
I now just need to make some recipes, make the code a bit cleaner, and make a new file for those that want to add their own block textures!
That last one will be a later-on feature hopefully 🤞
// List items and prices
const itemsPrizes = new Map([
["minecraft:dirt", 1],
["minecraft:oak_log", 2],
["minecraft:cobblestone", 3],
["minecraft:coal", 4],
["minecraft:coal_block", 40],
["minecraft:iron_ingot", 8],
["minecraft:iron_block", 80],```
why is oak log not working?
ive tried naming it just minecraft:log aswell
By chance, does anyone know how to activate an addon that requires the creator's key?
Wdym?
How does the setLore works? The lore goes above the display_name
pls help
Did you check in game?
yes
You check the console?
above? It's below the display name.
Sorry for bad english
I can use [{translate: 'line1'},{translate: 'line2'}]?
Lore isn't translatable.
Hmmm
i got it ty
This will work? {translate: 'text.evolution.success', with: ['item.ne:sharingan1' + ' -> ' + 'item.ne:sharingan2']}?
is startup on beta?
yes.
system.beforeEvents.startup.subscribe(({ blockComponentRegistry, itemComponentRegistry }) => {
will something happen in later updates if i use worldinitialze for now?
i heard it was deprecated, but if startup is in beta
idk which to use
i mean, will the addon break? the thing is that im making something for the maketplace
or wil, it be fine if i don tuse 2.0.0?
if you stay on 1.18.0 no.
ok thanks
world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry, itemComponentRegistry })
what's wrong now?
Script versions I think?
i mean, why doesnt it recognixes world initialize
then what do i use? startup is on beta

What script version you use?
@meager pulsar
is it possible to make a chest-GUI with script api?
like know when player takes out an item and cancel
1.18.0
yes and no...
Anyone know how to set an armor stand pose via script?
world.afterEvents.itemUse.subscribe((event) => {
const player = event.source;
const item = event.itemStack;
const playerData = PlayerData.load(player.name);
for (const quest of QUESTS) {
let isCrafted = item.getDynamicProperty("crafted") || false
if (quest.type === "craft" && quest.itemTypes.includes(item.typeId)) {
if (!isCrafted) {
playerData.updateQuestProgress(quest.id, playerData.questProgress[quest.id].progress + 1);
item.setDynamicProperty("crafted", true);
}
}
}
});
can someone please tell me why the dynamic doesn't work?
You have to set the item back into the inventory.
You're grand, man
Use worldinitialize then
The deprecated thing is just a reminder to prepare for it's removal in v2
im using beta, so how would i do player join
world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
if (!initialSpawn) return;
// ...
});```
thank you
didnt work
wait
it works ty
How do I set my scripts to TS in bridge. v2?
change .js to .ts
how would that work? in the manifest you have to specify js or ts
idk how to specify that
like, right here
do i just change the entry point?
The itemStack.hasTag uses 'minecraft:tags' item component?
id guess so
because items are like floating entities when dropped
so you can tag them
I think that you need to change "language" to typescript
its not a valid value tho
Try to change the main from .js to .ts
did that, got an error but i think i know how to change it
it just says now, as i change it to "typescript" and entry point to "main.ts" that it is usng an unsupported runtime
Anyone know?
alr, i found out that the only language supported is js
ty for the help
Only support js, just compile ts to js.
yes, strictly use the namespace when checking items with tags.
Like 'ne:tag1'?
yeah, even vanilla tags, include the Minecraft namespace ItemStack.hasTag('minecraft:<name>')
How i set The tags exactly, i dint understand The wiki
any ideas?
a component group for every possible scale
and you trigger an event for the entity using scripts
oh hell nah xD that takes forever
item json
I'll just wait until the custom component is in stable maybe with that I can change the scale
probably not
'-'
sorry, not probablly, 100% sure
Is there a way to detect if a player is starving?
not directly
theres no hunger apis
Right so what things in scripting is currently deprecated just so I know?
why
Wym why?
.isValid() method (changed to .isValid)
worldInitialize before/afterEvents (changed to worldLoad)
and iirc there also was a few changes in custom component registery?
We just got started with v2, so you can relax for a bit
Yh but I just wanna know whats been deprecated in 1.18 so I know what to prepare thats gonna get removed so I can change it now than later
these should be everything you should know
oh and there has been a change in applyKnockback too
Brilliant thank you
this is quite useful
Quite useful but also very concerning theyve deprecated a lot of stuff in 1.18. I dont appreciate that
Are there work arounds for the script components theyve deprecated @woven loom?
they weren't deprecated, just changed the way they're registered
world.beforeEvents.worldInitialize.subscribe -> system.beforeEvents.startup.subscribe
instead of registering them in world, now it's on system
beforeEventsStartup
What about the item use
just use itemUse event lol
world.afterEvents.itemUse
@dense forge do you mean itemUseOn?
it is not the same as itemUse
itemUseOn is not the same as itemUse bruh
and use playerInteractWithBlock to replace itemUseOn
@dense forge
itemUse = using an item
itemUseOn = using an item ON a block
this was the same as playerInteractWithBlock, that's why it got deprecated
Still concerning how much has been deprecated
And your saying the button after and befire events will also now have to be system @warped blaze ?
Yeah I currently just have the server options managed by admins only
That's useful mmm
DimensionTypes.overworld/nether/end
It was removed hmm
so are we forced to use the string one
just use (Entity || Block).dimension
ikr
Is there a good way to calculate damage done to an entity taking into account armor, status effects, sheilds, etc?
sadly no
i mean
Map each item what they do
you could try reverse engineering the damage
reduced damage * whatever the armor and enchantment they have
but it sounds way too painful
The hard part was to make it compatible with custom armor 😭
Still possible to calculate it
-# I've done it. Checking each item attributes 😭
I can't beleive that we still can't make a single complete feature with addons
bruj
we lack combat related stuff

man why dont we have attack damage attribute and other stuffs
when theres lava movement for whatever reason
We need EntityAttributeComponent expansion
especially attack damage attribute, its relatively simple in bedrock since items add damage on top of players' attack damage value
waiting applyDamage() to have itemStack options
me waiting for entityHurtBeforeEvent
the options for applyDamage should include toggles for what factors should be included in the calculation
ikr
actually it would probably be better to have a separate calculate damage function
so that you can apply any additional modifications as needed
whats worse is that applyDamage has way too many unbearable stuff when you look inside
like mace's breach actually affecting damage done by applyDamage
yeah that's pretty egregious
There are some options for that.
damage-type cause
entityAttack includes all factors.
magic ignores armor points
override ignore I-frame
void ignore everything aside I-frame
wait
oh that's good
some damage type factors have stuff like ignoring totems, shields, etc
its hard to figure out which does what stuff
(I was very sleepy when I saw so i could be wrong) When i checked Script API general Minato was saying in this chat, something like IAfterEvent. Like is there even a I variant of events?!
You could always test. Each damage cause won't change overnight
I?
all i know is that maceSmash does nothing but ignore shields
and magic ignores everything except protection
entityExplosion not causing shield knockbacks
@valid ice does the chest gui work with 2.0.0-beta, I cant get it to work
Idk but is there any variant of events? If so I didn't knew
also why tf does mace smash attacks (not applyDamage) work by adding on top of player's attack damage attribute???
im so confused
sonic_boom damage cause ignores enchantment like protection and armor points, but still takes into account resistance
yeah at least those follow how its supposed to work like
but it gets mad confusing when its used in applyDamage
or damage command
heres another funny thing
Lots of stuff needs to be experimented on. Still, this small difference in mechanics could be utilized to approximately guess how many armor points, resistance, and enchantments an entity has.
damage command can apply 0 damage while causing knockback and iframes
but applyDamage doesnt
and applyDamage's boolean return only checks if the entity was truly damaged instead of checking whether the entity can take damages
meaning that armor stands return false
you can still do applyDamage(0.000001)
do you know about herobrians chest gui?
yeah i know that like I have used it in the past in cant get the small chest gui to open for some reason
Is there a way to detect if a player is riding a mob in script api?
yeag
hold on
i have the code
player.getComponent("minecraft:riding")
that
for 2.0.0-beta since it uses .isValid
Object.defineProperty(Entity.prototype, "isRiding", {get: function() {
return this.getComponent("riding")?.isValid??false;
}})
if (player.isRiding == true)
could've removed that == true 😔
shhh
do you what the component is too acess the ender chest of a player
no sorry
alr
Not possible with scripts, even setting isn't possible
Tho commands can
I forgot but someone made a way to check what the item has in that slot using replaceitem
ok thank you
/**
* Checks if a player is riding a specific entity type.
* @param {Player} player Player to check if riding an entity
* @param {string} entityType Type ID of the entity to check, example: "minecraft:horse"
* @returns {boolean}
* @example
* import { world } from "@minecraft/server"
*
* const player = world.getPlayers()[0];
* const isRidingPlayer = isRidingEntity(player, "minecraft:horse");
* @throws If player is not a Player.
* @throws if Player doesn't have a `riding` component
*/
function isRidingEntity(player, entityType) {
if (!player || typeof player.getComponent !== 'function') {
throw new Error('Invalid player object provided. Player must have a `getComponent` method.');
}
const riding = player.getComponent('riding');
if (!riding) {
throw new Error('Player does not have a `riding` component.');
}
if (!riding.entityRidingOn) {
throw new Error('Player is not riding any entity.');
}
return riding.entityRidingOn.typeId === entityType;
}```
Muauahah

xd jk I just had this in my code
I... Hate this.
lol
nevermind i lost my words
ikr I needed it as of my use case
Yes... Thank you!!
I just copied off my code.. so
Could be Out of subject
Yo bro I saw you asking already before 
nvm
ok
Didn't he give you the link before?
dw
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
const Interacter = ev.player;
const location = Interacter.location;
if (isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132})) {
ev.cancel=true;
}
})```
what this does is stop people interacting with blocks like enchantment tables & more but i need players to be able to open chests and shulkers, any ideas?
im quite new to scripting so
//check if has certain tags;
if (player.hasTag("allow_interaction")) return;
//check if on creative mode
if (player.getGameMode() == "creative") return;
block.location
const interactable = [
"minecraft:chest",
"minecraft:barrel"
]
if (interactable.includes(ev.block.typeId)) return;
Not player.location, maybe you meant that?
you could add block type check
this looks correct
how exactly do i integrate this to the existing one?
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
const Interacter = ev.player;
const location = Interacter.location;
if (isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132})) {
if (interactable.includes(block.typeId)) {
ev.cancel = true;
}
}
})```
i done it a diffrent way and it still worked
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
const Interacter = ev.player;
const location = Interacter.location;
const interactable = [
"minecraft:trapped_chest",
"minecraft:barrel"
]
if (isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132})) {
if (interactable.includes(ev.block.typeId)) return;
else ev.cancel=true;
}
})```
anyone see a flaw that will come back to bite me?
block outside bounding box [ 103 -38 21 ] — [ 22 35 132 ] is still interactable
try merging if checks into one
and use !
he wants to make other block, except chest and shulkerbox can't be interacted
i know
gimme a sec
Ig you mean like this?
if (!checkExpression) ev.cancel = true;
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
const Interacter = ev.player;
const location = Interacter.location;
const interactable = [
"minecraft:trapped_chest",
"minecraft:barrel"
];
const condition = isPointInBoundingBox(location, {x:103, y:-38, z:21}, {x:22, y:35, z:132}) && !interactable.includes(ev.block.typeId);
if (condition) ev.cancel = true;
})```
or
world.beforeEvents.playerInteractWithBlock.subscribe((ev) => {
const Interacter = ev.player;
const location = Interacter.location;
const interactable = [
"minecraft:trapped_chest",
"minecraft:barrel"
];
if (interactable.includes(ev.block.typeId)) return;
const condition = isPointInBoundingBox(location,
{ x: 103, y: -38, z: 21 },
{ x: 22, y: 35, z: 132 }
);
if (condition) ev.cancel = true;
})```
The ItemStack constructor is defined as:
constructor(itemType: ItemType | string, amount?: number);```
` itemType` is either an `ItemType` object (from `@minecraft/vanilla-data`) or a string ID (e.g., `"minecraft:bed"`).
It doesn’t accept a data value or auxiliary parameter to specify data = 14 correct?
Is there a new way to register block custom components? WorldInitalize seems to be depricated in stable
🍌
I'm Sorry, what?
system.beforeEvents.startup.subscribe(({ blockComponentRegistry, itemComponentRegistry }) => {
blockComponentRegistry.registerCustomComponent('<name>', {
// ...
});
});```
Ahh, sorry I just woke up from a nap, so yeah it doesn't accept data, script api doesn't support data's in general.
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]
yall know how to convert the type id of an entity to its display name? e.g. minecraft:panda -> Panda
Remove the prefix -> Split the name -> Capitalize each word -> Join it with space
I think you can use the translation with entities
Just items has weird keys
Well if they just want to show the name
, the function returns lang key not the result itself
I mean RawText
What i said
I'm guessing making recipes with js is not possible?
in crafting table, no
i did try this before and it works on brewing stand with iventory component
which means it may be possible with furnace?
"A lot of the early APIs had an I prefix from a different coding convention that we removed with newer APIs since it's not really a common pattern in TS" as a dev said.
like IPlayerSpawnAfterEventSignal
what even is the difference between IPlayerSpawnAfterEventSignal and PlayerSpawnAfterEventSignal?
I've had this question for a while but keep forgetting to ask xd
i see
"I" see
lol
/**
* function that capitalizes typeId (example: the_end -> The End)
*/
function formatTypeId(string) {
return string.split('_').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
};
what is the limits of a string dynamic property?
how much can i write? and is it by char or byte?
and is the string formatting utf16?
32k bytes
so 16k chars if its utf16?
most js engines use utf16 for formatting
some chars take up more then 2
yeah, ik, this is the problem
utf8 can go up to 4bytes per char, i dont know about utf16
and if a char which is more than 1 byte, minecraft would still expect a string of length 0x7fff or not
dp uses utf8
yea, NBT
but doesn't really matter bc it counts bytes
in most cases is one byte for ANSCII chars
avoid tricks to make life easier 👍
the encoding is like this
1xxxxxxx
110xxxxx 10xxxxxx
1110xxxx 10xxxxxx 10xxxxxx
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
1 to 4 bytes
yea, and ANSI is 7bit encoding
so all ANSI chars are in one byte for utf
yeah
i wonder if it breaks the structure when we use any control chars
have u tried doing that ?
i know zero at the end is trimming char in C++ so sometimes it breaks in api as well
like Escape sequences?
like saving a string with all 0-127 chars
Key stores normally uses control chars to function
Well i have no idea
if the dp include them it doesn't get saved
actually give me a sec, i need to test this more
no error either
@weary onyx
https://stirante.com/script/server/1.18.0/classes/ExplosionAfterEvent.html
https://stirante.com/script/server/1.18.0/classes/Dimension.html#getentities
https://stirante.com/script/server/1.18.0/classes/Entity.html#addeffect
Documentation for @minecraft/server
Documentation for @minecraft/server
Documentation for @minecraft/server
so it saves ?
can u try filling 32k
it does not
@woven loom
can't really tell
they all pass but u+0000 (Null)
Null key do appear to be saved but it is either empty or the app i used can't display it
is there a way to detect left click with scirpts instead of using animation controllers? I dont want to modify my player.json so my mod works with other mods
I've been searching everywhere on this server with the search feature lol
can you disable entity hit sounds?
cuz thats what not letting me do that methode
I wanted to see if they couldare escaping those special characters or not. Since the limit is 32k bytes, using one of these characters 32k times should result in an error because escaping would increase the final size.
not sure
let me test that
[Scripting][error]-Error: Maximum string size exceeded (131072/32767) bytes for dynamic property 'test' at <anonymous> (index.js:11)
all of them trigger it
what u did
const char = String.fromCodePoint(0x0001);
const string = char.repeat(32768);
0x0000 didn't trigger it
didn't you want to see if they can break the limit
hm
does anybody know what are the molang variables to put in the MolangVariableMap to spawn a block breaking particle with a certain block ID?
Not possible unfortunately.
hm are you sure? is there a way to see the content of that particle json?
is texture atlas deterministic?
MolangVariableMap just provides colors and changes the value of the variable as number and block breaking particles are based on block texture
but you can make your own custom particle.
yes but the block textures atlas coordinates ARE molang variables
if i could see the vanilla particle json, making a custom one with exact same physics would be easier
I mean yes, but how are you gonna define texture?
by giving the right UV. if atlas is constant in its vanilla section the it should work
thats a big if however
look into the warden dig particle
is there a place to see all the vanilla definitions?
Downloadable from: https://github.com/Mojang/bedrock-samples/releases
bedrock.dev archive: https://bedrock.dev/packs
GitHub (RP & BP) : https://github.com/bedrock-dot-dev/packs
Example particles: https://aka.ms/MCParticlesPack
Java Edition's Vanilla Packs: https://mcasset.cloud/
thanks
how do I get the block a player placed?
Like the vector location of it
I tried doing blockFace with offsets but there has to be a better method
PlayerPlaceBlock -> block.location.
is there a means to check if a player is in a lava block? there's Entity.isInWater but there's nothing like it for lava, and just checking their location for lava typeId doesn't work quite right because of corners
Understandable, Bedrock either requires you to overengineer for a simple solution but have an easy thing for a complex problem.
Not via scriptAPI unless you get the location but as you said, edge cases.
aw that is not what I wanted to hear, alright
Are you willing to use Beta? Assuming this is a vanilla block.
import { world, Direction, BlockPermutation, system } from '@minecraft/server';
// --- Configuration ---
const restrictedBlockIds = new Set([
'minecraft:stone_button',
'minecraft:lever'
]);
const restrictedSlabs = new Set([
'minecraft:cobblestone_slab',
'minecraft:oak_slab'
]);
// --- Script Logic ---
/**
* Handles the playerInteractWithBlockBefore event to restrict ceiling placement for buttons/levers.
* @param {import('@minecraft/server').PlayerInteractWithBlockBeforeEvent} event
*/
function checkCeilingPlacement(event) {
const { itemStack, blockFace } = event;
if (!itemStack) return;
if (restrictedBlockIds.has(itemStack.typeId)) {
if (blockFace === Direction.Down) {
event.cancel = true;
}
}
}
/**
* Handles the playerPlaceBlock event to enforce bottom placement for specified slabs.
* @param {import('@minecraft/server').PlayerPlaceBlockAfterEvent} event
*/
function enforceSlabBottomPlacement(event) {
const { block } = event;
if (!restrictedSlabs.has(block.typeId)) return;
system.run(() => {
const permutation = BlockPermutation.resolve(block.typeId, {
'minecraft:vertical_half': 'bottom'
});
try {
block.setPermutation(permutation);
console.log(`Set slab at ${block.location.x}, ${block.location.y}, ${block.location.z} to bottom`);
} catch (error) {
console.warn(`Failed to set slab to bottom: ${error}`);
}
});
}
// Subscribe to the events
world.beforeEvents.playerInteractWithBlock.subscribe(checkCeilingPlacement);
world.afterEvents.playerPlaceBlock.subscribe(enforceSlabBottomPlacement);
console.log("Ceiling Placement and Slab Restriction Script Loaded!");```
Its a vanilla block yeah, and beta
I would use PlayerPlaceBefore event and change the permutationToPlace
I'm trying to recreate the Minecraft Beta 1.7.3 slab placement
that stuff exists?!???
Documentation for @minecraft/server
yeah but it's only in beta api
I haven't the foggiest clue why it still is in beta but stable for Custom Blocks.
How can I make it so all blocks never get waterlogged?
I can think if a really bad way to do it, but I assume there is an easier way 😭
https://stirante.com/script/server/2.0.0-beta.1.21.80-preview.27/classes/PlayerPlaceBlockBeforeEvent.html#permutationbeingplaced
https://stirante.com/script/server/2.0.0-beta.1.21.80-preview.27/classes/BlockComponentPlayerPlaceBeforeEvent.html#permutationtoplace
😭 Ok..now I see why it's still in beta...can't even have consistent names.
I would just cancel water bucket interaction.
when you place blocks into water, they waterlog though
thats what I am trying to prevent
Check for player place block, check block.isWaterLogged(or whatever its called), unwaterlog it.
Documentation for @minecraft/server
maybe you can just check if its being placed in water, then set it not to be waterlogged
function enforceSlabBottomPlacement(event) {
const { permutationToPlace, block } = event;
if (!permutationToPlace || !permutationToPlace.type?.id) {
console.warn(`Invalid permutationToPlace: ${JSON.stringify(permutationToPlace)}`);
return;
}
if (!restrictedSlabs.has(permutationToPlace.type.id)) return;
try {
const newPermutation = BlockPermutation.resolve(permutationToPlace.type.id, {
'minecraft:vertical_half': 'bottom'
});
event.permutationToPlace = newPermutation;
console.log(`Set slab at ${block.location.x}, ${block.location.y}, ${block.location.z} to bottom before placement`);
} catch (error) {
console.warn(`Failed to set slab permutation: ${error}`);
}
}
world.beforeEvents.playerInteractWithBlock.subscribe(checkCeilingPlacement);
world.beforeEvents.playerPlaceBlock.subscribe(enforceSlabBottomPlacement);
console.log("Ceiling Placement and Slab Restriction Script Loaded!");```
I think im doing this wrong...
It's called permutationBeingPlaced for the world event, permutationToPlace is for custom components.
TypeError: 'permutationBeingPlaced' is read-only
Wait what...
I think im dumb hold on
you cannot reassign it like permutationToPlace
they are not the same btw, we used to only have BetapermutationBeingPlaced which is read only, we got permutationToPlace after custom components came out.
i assume BetapermutationBeingPlaced is going to get deprecation
i dont really get it
I think its because im canceling the event? maybe instead I need to pass the permutation when its placing? idk
There is still a pretty decent visual delay, and I dont think thats supposed to happen
system.run add a one tick delay
assign the new permutation to permutationToPlace
like this?
Is there a way via scripting to check what armor a player or entity has equipped? Specifically, I'm trying to check if any given player has the custom head armor that I'm working on.
event.permutationToPlace = newPermutation
for player use equipment component
for entities use testfor command with hasitem property
BlockComponentPlayerPlaceBeforeEvent is for custom block components, not the vanilla world event
you are right, my bad
i've already implemented some functions to see the charsize in rust
damn working with utf8 is hell
but i really prefer that over the web
///Gets the size of the char by seeing its first byte considering it as a utf8 byte
pub fn char_size_init(mut b: u8) -> u8 {
if b < 0x80 {
1
} else {
b &= 0b1111_0000;
let mut n = 0;
while b != 0 {
n += 1;
b <<= 1;
}
n - 1
}
}
///Gets the size of the char at the given start point backwards
///Example
///rust
///let v = vec![b'a', 0xc3, 0xa0, 0xc3, 0xa7]; //'aàç'
///char_size_backwards(&v, v.len()-1); //2
///char_size_backwards(&v, v.len()-3); //2
///char_size_backwards(&v, 1); // 0; Invalid Byte
///char_size_backwards(&v, 0); //1
///
pub fn char_size_backwards(vec: &GapBuffer<u8>, spoint: usize) -> usize {
if vec[spoint] < 0x80 {
1
} else {
let mut bcount = 0;
while bcount < 4 {
//These 2 lines check if some of the 3 first bits in the byte are 1, if so, theyre a continuation byte defined
//by utf8. Check https://en.wikipedia.org/wiki/UTF-8 for more information
let mut c = vec[spoint - bcount] & 0b1111_0000;
if c > 0b1000_0000 {
let mut n = 0;
while c != 0 {
n += 1;
c <<= 1;
}
return n - 1;
}
bcount += 1;
}
0
}
}```
char* actually, i think the std::string in c++ is length based
It looks like you're talking about the EntityEquippableComponent class (https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/entityequippablecomponent?view=minecraft-bedrock-experimental), but that class doesn't seem to exist on entities or players that I have been able to find...
it does
but as i said, it doesn't work for entities
works for players only right now.
it used to work for entities I believe
they disabled it though because there were issues? I forgot.
no sure, i am kinda new
maybe in the old api
Players is exactly what I'm interested in. Any idea why this is throwing a TypeError?
system.runInterval(() => {
const players = world.getAllPlayers()
players.forEach((player) => {
world.sendMessage(String(player.getComponent('equippable').getEquipment('head')))
})
}, 20)
Head, not head
capitalize the H
Perfect, that worked. Thank you!
function enforceStairsBottomPlacement(event) {
const { block } = event;
if (!restrictedStairs.has(block.typeId)) return;
try {
// Get the current permutation to preserve other states
const currentPerm = block.permutation;
// Create a new permutation based on current states, only changing upside_down_bit
const newPermutation = currentPerm.withState('minecraft:upside_down_bit', false);
block.setPermutation(newPermutation);
} catch (error) {
console.warn(`Failed to set ${block.typeId} to bottom: ${error.message}`);
}
}
For some reason this doesn't set the permutation correctly
Is it possible to make script only run when someone logs in?
use the enums instead of raw strings
jsut use the unicode ranges it will save lot of time
damn, no, i was writing a text editor in terminal
for performance i had to store things in a Vec<u8>, the equivalent to Uint8Array
in case it was a gapbuffer as you can see in the params
i just want to know:
when should you use commands/functions and when should you use scripts
like cus scripting can do all the stuff commands can do
but ppl still use functions in scripts for some reason
so is there any benefit?
People use it because it is simple, while those who are lazy or do not want to write too much use commands. Others use it because there is no API available for that specific thing.
Performance varies according to the use case.
yeah my impression is that commands are laggier than scripts. but is that the case?
the only case i can recommend commands for is where there is no native functions for it, most stuff do
as waveplayz said, sometimes commands can be shorter like the hasitem property
yall think we are ever going to get block dynamic properties?
from what i heard functions maybe faster, but not when calling them from script
doubt
no
would be nice.
itll be too much info to store in the db
it is not about that
probably not
okay instead of that, I hope we get to be able to edit vanilla blocks in the future so we can add states to them.
yeah
i really dont think so
if that's the case, they could do some kind of lazy loading
what do you think its about?
just load the ones on the loaded chunks
but i really think a db could handle it easily
is there?
i mean you can store vectors in the db
so maybe
well, we can store them as numbers
it would cost lesser
i havent really use dynamic properties so i kinda dont know how they work
because if theres no limit, you can just store each vector3 as a property
how will the game handle that, does breaking the block remove the dp? what if you moved it with piston? lot of things to consider and it is not even that good of a thing, just give us onBlockUpdate and let us handle it our self
probably its a nosql database
and getDynamicProperty just gets it from the db
and set just sets
if it didnt remove it, then there wouldnt be a difference between world dynamic properties and it.
i mean its just in the db folder
so just look inside
��ξ:<��������� ��������,( ��������1�
��
�config�activation_range���@�deactivation_range���@
�key_item�Count�Damage���Name�minecraft:trial_key�WasPickedUp��
�loot_table-�loot_tables/chests/trial_chambers/reward.json�override_loot_table_to_display���
�data �items_to_eject����� �rewarded_players������state_updating_resumes_at��������id�Vault �isMovable�x�����y�����z���� ��������6���� ��������9 �������,( �������1�
���Findable� �Items����� �LootTable:�loot_tables/chests/trial_chambers/intersection_barrel.json
�LootTableSeed�����id�Barrel �isMovable�x#����y�����z�����
�� �Items����� �LootTable2�loot_tables/dispensers/trial_chambers/chamber.json
�LootTableSeed�����id �Dispenser �isMovable�x$����y�����z�����
��
�config�activation_range���@�deactivation_range���@
�key_item�Count�Damage���Name�minecraft:ominous_trial_key�WasPickedUp��
�loot_table5�loot_tables/chests/trial_chambers/reward_ominous.json�override_loot_table_to_display���
�data �items_to_eject����� �rewarded_players������state_updating_resumes_at4��������id�Vault �isMovable�x$����y�����z�����
�� �Items����� �LootTable2�loot_tables/dispensers/trial_chambers/chamber.json
�LootTableSeed�����id �Dispenser �isMovable�x.����y�����z�����
uh
does anyone know the limit?
that was in a folder in db
ítÕÇïåDJl%1bBÒB)8à¤X9Ä1Þ¼0]˲,ÛJl)H8gKvi@Ȥ
hx÷£°N·gÇò(Â)]Ø
´Ûn.»Ý-^!Ú¹óî<£-{þó$ùÓ½#i&óûîï#UD]jè);äzɼò¿^¯·ÿ~s÷{Uëßkä÷
ÖOô§ûx¿±×Û¯Oñ÷çÍߨ[Ú tÿ$¸¥ÂMgÒ1ʾ2£bÔîYÞ±]~é¦íSMªVd¡£ý
]{÷«Ê°,ÚöËgGû¶ϧRißäöeÒ?£q9IØß¬$½¡p0õwÆëü¡è¨$÷Ç1R6\ÆBðÔùUk1kwøbñH8h¡Dâ±
ëBuC=¡
½¾H4s«J÷|JhǬÜ×.õã wjý8òèçcw»Cí¨DJ:¦j³$¯EiË1}{~ɧ-QÛåò¹µÅj;£¶Ù´Ï´Dûþb·7[ÙÞÊOÛb´ÏvɧEåHÌþàëáZ´;¢Àºd+z
;CáPûhØ×ÓÌýLÐ}âõhÜßÓÏñïcÔ£ÿ#¸´°K[ûÇ,¥ºü+
âå®x$èNöâ:Èðuú¡p¯#
âRå$,Aµ» }:ÉuÁXÜÖ;¢þ®HØìêÊø;U¸w]@Ç)Xg½8H¨ÃM.w4Éñ�uPlYäZ{OQ²Ñ!½OzÜT¯<^OsmhyT×ÐkCËäÚP¿FËßQ¿Fù;V¸µt²iòkW==¨esð¥±Þg+Ü/½[ùYá¦èÌ[W.÷g
m»Q~áÙÚ(Û5ÆÍûýdkÔ®±³NÐv奱øéÞIGê9úLï¤IãØó^×[Òó£[²çà~øá?w?%#@?«°dOáãáP4naÄPÅ5éúc1_{¿úBÎæ×Gý¡Ô$ÐÜh$&uS©½Ñ®MòÕEêôíbiàÆdDJ<.mVO,øÕï?]õå¼E¦Ç©©E¦wt(¯9a=, 7mÂUÂU
pÕ§
«v³pÕ§
«Î}Ò[ ²§ÄórÃ:q\ßıMu(«8zñÖ»ý¿d}<½I;Þ*øAfÃ~ È~Þ¦;äQñ£8~LÀñÙm+8Ù54úÂ,Ð7"Òw=èAýèÛçÁQêÆêÆ})ê©ûÝ6PfNÝÚênnu!²uÿ¶M¤îßµ¥S÷Fut;x¨òÈf¿ÇyÝ2}ïl}aæô½«U ï[A_lGß"}ïnM§ï=ü÷ÞVºt¬áÖ?~Âúï^fá?]&ø^ Ûaø£ËDÿÑáÿôòþo¥!òÜ&yyaÈû¸W ï /Aö#ïÿêÈû¤yÈû¥Æ»Çº
.̺çÓÎ}A]lGݺiçØÂtêÆòÔÅÍ2Ô·
Ô
Sw¾²Ì ãv±í=}¿½M£/ÓÀ?üðsþWeÿôtÿÞö?Øß¯@ý?e¥=Ó(L1ßÈÑé¥ÛÄè´5¿_ÙâÙ9åHú¢|tÚME§ÈÑéÞ¢SytzkLS&î!
~øá/Y¿AT\õ[2Ñ.QéþnUbN!Uâ+ø¨4°&~)G¥¤Q)Ì<}·A8Sé¨ÃJlw¦òÍÕIêª)I멳.ýeyOß#«SôýÁè{s3è3§ïöf¾·4¾Ù¾w^-yw6§SwW3OÝ»®V©ë¡'¤LÉKüxr03Çð¬FÃSalá¯VþFaâÇ·^:ÇñIÐp<Z(.9w<p³P& EÀñ%ãclã{ÛEÏ>*?Çð}íILhþJ_XüÛiÊÞ®ÿ3ysý
úxËþÓYûô¹~GS´MÃp]°8{ÞF³w£ìßsXöOγÿêLþÈIù~~ßÇà2ÿßÉ~7ï_Røïç~¿ ¿O¥í_´þtû¼?ãÿù|¶ò¿W⯿Ù'ÜKµÀµ¸®;ú®Dz,4Ç5´ÇB!xx^ 9GwÛNÃùµv¤:KÅâ_/]TÉÇ/$ÃãÎ×ÐSwȼt^²ÌzC½Îúó~#o½×ª?·ÞÄkn^ÉÌßû;(Ë-¯û+XT<QÙWfTzÐ=Ðû¶«Q1a{kTD9²{ÿ(NòßFeßßk»9ö¼6 ëGÛs%=GçªÊuý®ú2l'UÙ´aÕó»S!
just a lot of bytes
surprised you didn't get a auto timeout

