#Script API General
1 messages ยท Page 41 of 1
what the
where are your if statements
import { world, GameMode } from "@minecraft/server";
/** @type {import("@minecraft/server").BlockCustomComponent} */
const CreativeModeOnlyBlockComponent = {
onPlayerDestroy(event) {
if (event.block.typeId === "jay:coal_ore" && event.entity.typeId === "minecraft:player") {
entity.runCommandAsync("execute @s ~~~ say broke coal ore");
}
}
}
plus that event is wrong anyway
it's player not entity
and block doesn't exist
import { world } from "@minecraft/server";
world.afterEvents.itemUse.subscribe(event => {
const itemStack = event.itemStack;
if (itemStack.typeId === "minecraft:diamond_sword") {
const itemData = itemStack.getComponent("minecraft:display_name");
if (itemData) {
itemData.setLore(["Custom Description 1", "Custom Description 2"]);
}
}
});
help
it should be like this:
import { world, GameMode } from "@minecraft/server";
/** @type {import("@minecraft/server").BlockCustomComponent} */
const CreativeModeOnlyBlockComponent = {
onPlayerDestroy(event) {
if (event.destroyedBlockPermutation.type.id === "jay:coal_ore") {
event.player?.runCommandAsync("say broke coal ore");
}
}
}
@dull shell
yeah its still not working im not sure
import { world, GameMode } from "@minecraft/server";
const CreativeModeOnlyBlockComponent = {
onPlayerDestroy(event) {
if (event.destroyedBlockPermutation.type.id === "jay:coal_ore") {
event.player?.runCommandAsync("say broke coal ore");
}
}
}```
i removed the thing up top
cache if the position xyz in that location was a cake
im trying to make it so when I break my custom block it runs a command but im not getting any errors logs
wdym
i want the player to get added a score when the block is blocken
Did you register the custom component? Did you use it in your block.json?
import { world, GameMode } from "@minecraft/server";
const CreativeModeOnlyBlockComponent = {
onPlayerDestroy(event) {
if (event.destroyedBlockPermutation.type.id === "jay:coal_ore") {
event.player?.runCommandAsync("say broke coal ore");
}
}
}
world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
blockComponentRegistry.registerCustomComponent(
"jay:coal_ore_component",
CreativeModeOnlyBlockComponent
)
})
then in your block.json add
"minecraft:custom_components": [
"jay:coal_ore_component"
]
{
"format_version": "1.21.40",
"minecraft:block": {
"description": {
"identifier": "jay:coal_ore",
"menu_category": {
"category": "construction",
"is_hidden_in_commands": false
}
},
"components": {
},
"minecraft:custom_components": [
"jay:coal_ore_component"
]
}
}```
Put it inside "components", not outside of it
amen ๐
thank you guys sm
so then to add more just keep copy and pasting it?
then changing it from jay:coal_ore to wtv
Is it possible to attach a sign to a wall?
well yes thats what i assumed
however ```js
export type BirchStandingSignStates = Pick<BlockStateSuperset, 'ground_sign_direction'>;
Dont seem to support anything but the direction itself
I had to settle on this
):
Nuh uh
yuh huh
Noooooo!!!! Why not let me resolve it for you??? Why resolve it (fades away like Thanos even tho he not evil)
what do you suggest?
I mean, could it work? ```js
block.setPermutation(block.permutation.withState("cardinal_direction", "west"));
ill need to try that
good night
does anyone know what reach the player has since ik it changes depending on if you're sprinting, walking or still
Wadahel
Real
Because I'm a good guy, I'll help you BUT if ever you're using it again... I won't anymore.
Lmao "minecraft:display_name" maybe in a different universe after Flashpoint occurs lol
(You'd only understand if you watched the flash up to season 4 I believe)
item.nameTag & item.setLore have been real quiet since his code appeared fr
Worst part is he is setting the lore to the component (that does not exist)
import { world } from "@minecraft/server";
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
const equipment = source.getEquipment('equippable');
if (itemStack.typeId === "minecraft:diamond_sword") {
itemStack.setLore(["Custom Description 1", "Custom Description 2"]);
equipment.setEquipment('Mainhand', itemStack);
}
});
I don't think lore needs you to regive the the item,... but whatever.
I think you need it too since you're modifying the item
I don't know tbh, because I rarely use lore ask @valid ice he's addicted to it
I mean, iirc I think nameTag & lore don't need you to regive the item. Other things like enchants & durability and stuff like that requires regiving the item.
I used it not long ago and I didn't need to regive the item.
I wonder why?
ContainerSlot ItemStack difference
Thanks but I don't need to cache it... I fixed it in under 3 minutes, I just used this since it returns air Soo if it doesn't exist put 7 instead because max is 6 block.permutation.getState('bite_counter') || 7
Yes very simple fix
Uhhh I think containerSlot returns the index of the itemstack in the inventory
Not sure tho
No. ContainerSlot is different than ItemStack
It's like getEquipmentSlot and getEquipment
Moyang be confusin' sometimes fr
(Love yall tho)
Tbh what you said doesn't make any sense because you're saying when we modify items you don't need to set the item back to slot so it shoudl work globally then....
Imma test it really quick I'm on my phone so it's good
ContainerSlot is the present instance of the slot like slotIndex 0
Idk man. I said "iirc"
ItemStack is a clone of an item
K....?
I didn't ask for the difference........ I know that they are different.................. I thought you were asking so I gave you my assumption.
Ima go now cuz I gotta learn some good'ol heavy duty backend. (Php). Why do I call it that? Cuz it's syntax makes -1% sense! ๐
I tried it.
And..... It doesn't work without setting the item back to the slot
I luv how I can open mc fast but my internet is as slow a turtle
cus its all ItemStack...
Yes I know I just want confirmation
ok
getItem, getEquipment Method:
Purpose: Retrieves a read-only copy of an item's data
Behavior: Provides a snapshot of the item without enabling direct modifications
Recommended Use: When you need to inspect or reference item properties without altering the original inventory item
getSlot, getEquipmentSlot Method:
Purpose: Allows direct modification of an item's data within the inventory
Behavior: Returns a ContainerSlot instance that enables immediate and persistent changes
Recommended Use: When you need to update, replace, or manipulate the item in its original inventory slot
Key Distinction: getItem offers a non-destructive, read-only view, while getSlot provides a direct interface for inventory item manipulation.
Always choose the appropriate method based on whether your intention is to read or modify inventory items
Unnecessary butt k
This is essential: you should never retrieve a copy of an item, modify it, and then put it back
you should never? Wym?
Are you saying when you just want to set a lore into an item you literally need to use getEquipmentSlot or getSlot to such a simple thing?
if (item) player.dimension.spawnItem(item, player.location)```
why is this giving me a bunch of items?
Are you running it continuously?
Even if you put 1 only but you run continuously it will give you more than that
just on click in playerInteractWithBlock
Can I see it?
oh yeah sry
const blockAbove = block.above();
const blockFaceValue = blockAbove.permutation?.getState("sci:block_face");
const position = redstoneOreParticleSpawnPositions[blockFaceValue];
const playerMainHandSlot = player.getComponent("equippable").getEquipment("Mainhand");
const honeyFilled = block.permutation?.getState("sci:honey_filled")
system.run(() => {
if (block?.typeId === "sci:bee_nest_mini" && playerMainHandSlot?.typeId === "minecraft:honey_bottle" && honeyFilled === false && player.isSneaking) {
block.setPermutation(block.permutation.withState("sci:honey_filled", true));
if (player.getGameMode() === "survival") {
if (playerMainHandSlot.amount === 1) {
player.getComponent("equippable").setEquipment("Mainhand", new ItemStack("minecraft:glass_bottle", 1));
} else {
itemStack.amount--;
player.getComponent("equippable").setEquipment("Mainhand", itemStack);
const item = player.getComponent("inventory").container.addItem(new ItemStack("minecraft:glass_bottle", 1))
if (item) player.dimension.spawnItem(item, player.location)
};
};
}
if (block?.typeId === "sci:bee_nest_mini" && playerMainHandSlot?.typeId === "minecraft:glass_bottle" && honeyFilled === true) {
block.setPermutation(block.permutation.withState("sci:honey_filled", false));
}
});
});
What's the purpose of the if (playerMainHandSlot.amount === 1)??
i stole it from something else in my script
i was feeling lazy
but also it ensures it still runs even when it is the last item in the slot
As I said, ContainerSlot is specifically designed for directly modifying item data. Its usage is not complex, and the steps are actually fewer than retrieving an item's copy, modifying it, and then reinserting it
Is there a way to kill a player with a minimum health component through scripts cause I tried overding that component through json but it didn't work
what allows a mob to break blocks in a script?
for anyone looking fo the answer in the future it's minecraft:break_blocks
Thats the json component
getEquipment is adding 2 lines only ๐ญ
Are you setting it with component groups? You can't override health inside of components only
so when you define a really really large variable in the beginning of a script, and rarely use it, is it filling up a chunk of memory all that time for no reason?
Yes I used component groups so one for a normal health and one for a minimum health
I feel like that's memory leaking...
Does the event run? If yes and it can't trigger means minimum doesn't work on the player just use the damage sensor and disable fatal and remove once you're done
it is not
yep
That's why I said I feel because I never did that in my life
how does this make any sense at all
is it better to load it at the beginning of a script or load it once you need it?
let's say you need to access it 10 times in one session but most of the time you won't need to access it.
isn't loading it and unloading it 10 times bad for performance?
in general it is better to pre-load stuff that may effect performance
if i preload everything, i am putting unnecessary load on the memory, if i don't, i am adding extra work for the CPU
what variable are we talking about here
a large array of objects
How many kilobytes?
for an achievements system
i dunno
Look at the file size
currently the file containing the array is 49 kilobytes but it will be larger
even a 1mb shouldn't be a problem to preload it
i also have another file for a similar system that is 66 kilobytes
so i shouldn't worry about preloading them all
no
is the file size the amount of memory used?
no
or does it get compressed?
so how to calculate memory?
Memory is just variables. You can create a 10 line code that creates an array of 1,000,000 objects that takes up half the memory
In regular js there is such a thing as Blob, with which you can find out the size of a variable, but as far as I know this does not work in scriptAPI
let's say it's just a constant that doesn't change or get defined again throughout the process. will it consume exactly 49 kilobytes of memory
I think a little more. Since this is not just text, but an object with methods and properties
only properties
no
but in general it stays constant?
if this is not true/false then there are methods
good to know
as long as the size of these methods is negligible
Modern amounts of RAM are sufficient to accommodate your variable, but it seems to me that the debugger may complain about using too much memory
What does this variable look like?
you can use process.memoryUsage() in node js to get the memory usage
I think the problem is more in Minecraft. Will it allow the use of a large amount of memory?
well it's not an array anymore, i change it into a string for ease of editing, and i have a function that converts it back into an array, so it's hard to let how does it look when it's loaded
but if i have to guess it looks like this: js [ { id: string, name: string, icon: number|string, require: [string] reward: undefined|string conditions: [string] } ]
In short. Even if you have problems using memory. Do you have another option to do this?
what do you mean?
The fact that you are trying to solve a problem that has no solution. You're already using the best option
i figured preloading large constants is best for cpu, but i thought the game was smarter for dealing with memory
but if 50kb is nothing for modern RAMs I don't really care much
I have one variable weighing +- 30 kb and everything works fine
it is not 50kb
memory storage is not same as disk
but it shouldn't be a problem in this small scale
i know it's a little larger because of object methods but it's still negligible
one thing i am afraid of, when i import that constant to different scripts, does it take a chunk of memory for each one of them?
not sure how the import work tbh
let me look into it
i think it does, because if i mutate an imported object or array, it obviously doesn't affect other scripts
unless the export loaded it once and the imports return a reference to the same object ๐คทโโ๏ธ
@honest spear do you have any knowledge regarding this?
do you think you can provide me more context
- whats you want to achieve
- whats is unexpected
- why do you think it should happen in different way
i don't think i understand?
@honest spear
same file imported from different files has same isntance
so no copy of the module is created
if thats what do you mean
so does that give the importing files the ability to mutate the original module
he is importing a variable from another file and he is asking if calling that variable use any memory or just refer to the same
no there is no way to mutate module object
its freezed
so how can my computer keep track of different versions of the same module if it isn't copied?
a mutated version for each file importing it
there are no different versions (one script = one module)
...
let's say i have a file containing one exported object.
and i have 10 other scripts importing that same object.
now there is 10 mutated objects,
how are they handled by memory?
objects are passed by reference so its only one object
they are probably referring to the same obj that got exported
well there could be some cases when exported value is different, but only when you reassign that exported object
so am i referencing the 10 imported objects or the 1 exported object?
like i said there is only one module instance for one file so doens't matter how many times and where do you import it its still all the same
so if exported object is "export const" then there is only one object in total of that type
also you can just test it if you don't believe me
ยฏ_(ใ)_/ยฏ
i Know that, i will try to explain what i mean by an example:
when i import the object {fish: "large" }
and then mutate it to {fish: "medium" } in one file, and then i import it to another file, and mutate it to {fish: "samll" }
how does the memory look like at this point
in all cases the memory would look like absolute mess bc thats how JS works, but anyway the object would remain the same
you are editing the same variable
i am not worried about the original object, i believe you that it doesn't get mutated
it does gets
but mutability doesn't means its not the same object
here is example
my concern is the memory, does it have copies of it or not?
pointer for that object is the same
but there were some copies bc you manipulated with string
and strings are bytes in memory
That's what i wanted to know
so in general it's best if i don't import large objects to multiple files.
no
in general don't use large strings
don't*
object in memory has dynamic size
and object pointer it self is relatively small
computer memory is a real pain, good thing we don't have to worry about it in js
and other high level programming languages
let data1 = {test: "test"};
let data2 = data1;
data1.test = 5;
console.log(data1); // {test: 5}
console.log(data2); // {test: 5}
the object is the same even you you changed the property
Well looks like you kinda worry tho
ยฏ_(ใ)_/ยฏ
lol
my bad
np if you have any more questions just ping me anytime
these questions come to me while coding and i can't help but feel bad for not optimizing something that's really obvious
thank you
just imagine how bad would JS be if it would do the copies like that
๐ node_modules ๐
while (true) 
obj = {};
while(obj) obj = {obj};
while (false)
|| Very helpful btw ||
ohh, such a gentleman
int *ech = (int *)0x0;
*ech = 0;
``` 
Sir...this is Scripting channel not general programming channel.
that would throw a syntax erorr
||There are no other languages than JS in this universe||
False! Polish exists
"Nah, we speak JS";
console.log("You didn't say anything");
"well but you read the source code";
"once you print then its not a JS anymore so its not understandable";
oh ye mb
Installation for @minecraft/server-gametest
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
sorry to be annoying but what the hell is going on
i need that
what is this for a language
nvm its c++
off-topic
or c ๐คทโโ๏ธ
yep
how do i see what item the player is holding? i'm trying to hook onto playerBreakBlock to see if they have certain equipment on
let item = player.getComponent("equippable").getEquipment("Mainhand")
thank you so so much ^^
i do feel kinda bad asking so many questions lmao
i appreciate all the help i'm being given
this was @server-net so its script api, not off topic
WTF... faceLocation in PlayerInteractWithBlock is Vector3 Absolute world position and faceLocation in PlayerPlaceBlock is the final delta from center of block. Thus making my class useless for what I need... I can fix, but dang...
No wonder this stuff is still beta.. and they did not even provide faceLocation in the blockRegistry version of place block, which would be dope
Its an easy fix, annoying, but easy fix.

Can't fix the not providing it for custom components tho.. which is why I have to do my slabs in the regular events... (cause I am providing vertical positions)
Documentation for @minecraft/server
you need to provide more info
onPlaceBlock.. not interact
What are you trying to do exactly?
Slab, that can be placed horizontal or vertical and depending on where you click on a block. So think of a block divided as a 4x4 grid... so that the middle means flat - just use the block face, but the edges can place it perpendicular, etc.....
I've made my block with with Interact (1st time, cancelling all tho), but there is a weird visual lag when placing a block, like it undoes a regular placement... I can see it.
That seems like a simple thing. Just cancel block placement via beforeOnPlayer place custom component. Grab interaction faceLoc -> set block.
I did
I am testing via using the block placement right now... I will change it back to the other to show later... I made a class that can take either event and pull out the information and configure, so there is one function to do the work either way.
But still the blockRegistry component for placing a block does not have faceLocation at all... like they forgot (or did not remember that I think outside of all the boxes)
https://stirante.com/script/server/1.16.0/classes/PlayerPlaceBlockAfterEvent.html
Im blind...where does it show faceLoc?
Documentation for @minecraft/server
Before Events
Beta
Ideally...this all would have been a block trait.
I use the block trait... my strictly vanilla version does not need the scripts at all... whatever block face you stick it on is where it goes, vertical or hoizontal
but in order to do like real slabs I can add the vertical half... but for the vertical slabs, I need a non-provided horizontal-half
thus, I need face location to tell me where they clicked and I can figure it out myself
and then for special placing, I use the information of where clicked and the block-face trait of the slab they clicked on (if added to another of same type) for more fun stuff
Believe it or not, this is all for my Auto-Sifter Add-on.... cause can sift concrete powder... and powder needs to become concrete if water touches... thus you can make slabs from 1 to 15 height... so need a way to place them... I am loving workin on this tho
After working... will re-use code for my actual more-slabs add-on
Can I somehow load unloaded chunks using coordinates of block in it?
You can, you have to use the /tickingarea command.
You just need to add the tickingarea (using dimension.runCommand), then wait for the block you need to access to get loaded.
Is there a way to drop items with scripting?
I imagine
I also need to know about summoning entities with this but-
I have been looking a lot at the documentation and that's given me many answers, but I don't know what I don't know and am unsure where to begin
dimension.spawnItem()
dimension.spawnEntity()
thank you so so much
Hey Quick question
I want a function to return true otherwise false if the player is holding an item with data but idk how, I don't want to use tags for thsi
function waterBottle(player) {
try {
player.runCommand('excute at @s[hasitem={item=potion,location=slot.weapon.mainhand,data=0}] run ...');
return true;
}
}```
Kinda like this lol
I just want it to return true or false lol
just make a new itemstack and use isStackableWith
Small snippet? Lmao, I'm lazy today
I'm lying that I'm lazy, I don't really know how to use that shi at ALL...
how laggy are permutations?
like a lot of them
like 200,000
wait
wrong channel
This is more of a #1067876857103536159 question. And to answer, its 65536 is the recommended limit.
import { Player, ItemStack } from "@minecraft/server";
/**
* Checks if the given player is holding a water bottle.
* @param {Player} player Player to check.
* @returns {boolean} True if the player is holding a water bottle.
*/
function isWaterBottle(player) {
const heldItem = player.getComponent("inventory").container.getItem(player.selectedSlotIndex)
if(heldItem?.typeId == "minecraft:bottle") return false
const bottle = new ItemStack('minecraft:bottle')
//clear unnecessary data that will interfere with isStackableWith
heldItem.nameTag = undefined
heldItem.setLore()
heldItem.clearDynamicProperties()
if(heldItem.isStackableWith(bottle)) return true
}
wait... is minecraft:bottle for empty bottle
Permutation is limited you can't have 200k
yes it's supposed to be minecraft:potion
not limited just break the addons
im running 400k as i speak (optimizing in progress)
alr
test that and let me know
Oh yeah...
Maximum Amount Per Block
A block cannot have more than 65,536 permutations (equivalent to 4 states with 16 values each). Exceeding this limit will result in a content log error and some states being absent from your block.
Maximum Amount Per World
A world should not have more than 65,536 block permutations registered (not necessarily placed). Exceeding this limit will result in the following content log warning:
World with over 65536 block permutations may degrade performance. Current world has XXXXX permutations.
That's why I said you can't have 200k
of course, that makes sense
Even if the block states is past the limit, you can't apply that state on the block
in the same block, yeah
Hmm, that's what I'm saying earlier
I'll test it later I have exams โ ๏ธ
I kinda remember... Potions aren't stackables
๐คทโโ๏ธ maybe this mean that don't matter either
function isWaterBottle(player) {
const heldItem = player.getComponent("inventory").container.getItem(player.selectedSlotIndex);
if (!heldItem || heldItem.typeId !== "minecraft:potion") return false;
const bottle = new ItemStack("minecraft:potion");
heldItem.nameTag = undefined;
heldItem.setLore();
heldItem.clearDynamicProperties();
return heldItem.isStackableWith(bottle);
}
system.runInterval(() => {
for (const player of world.getPlayers()) {
console.error(isWaterBottle(player));
}
});```
Did I do something wrong? It still returns false even if I'm holding every type of potion
log all these
heldItem.typeId
heldItem.isStackableWith(bottle)
bottle.isStackableWith(bottle)
to the console?
How do you dynamically get the id of a block ?
Elaborate.
It returns false
All of them
if (block.typeId === "minecraft:tnt")
world.sendMessage("kaboom")
no
damn looks like I'll have to use /give then
Still experimental:
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/itempotioncomponent?view=minecraft-bedrock-experimental
i tried this but it didnt work, do u know why?
const regenPot = ItemStack.createPotion({ effect: "poison"});
Ah, has to be capitalised. My bad.
Can anyone point me to a resource to read up on how node.ja works for a Minecraft addon? How to setup so that none native code can work etz?
minecraft doesn't use NodeJS
Minecraft: Bedrock Edition uses its own version of JavaScript, which is based on QuickJS. It uses the ECMAScript module (ESM) system for organizing and loading code, which allows for a more modular and organized approach to writing scripts for the game.
https://wiki.bedrock.dev/scripting/api-environment
Thank you. Question thorough. How are other people able to use node.js modules on addons to use things like fs-extra if node dont work?
someone have access, pls merge this,
I swear, there is only one thing I wanna ask you, how the hell do you have coloring?
In the console.warn
alien JSON.stringify...
You're pretty late
Welp
const result = {}
switch (typeof value) {
case "boolean": return result[S.c + key1 + r] = value;
case "number": return result[S.s + key1 + r] = value;
```here's how
function isWaterBottle(player) {
const heldItem = player.getComponent("inventory").container.getItem(player.selectedSlotIndex)
if(heldItem?.typeId == "minecraft:bottle") return false
return Boolean(player.runCommand('testfor @s[hasitem={item=potion,location=slot.weapon.mainhand,data=0}]').successCount)
}
Thank you so much bro!
can playerInteractWithBlock cancel placement?
Yea
Has anyone ever noticed that the debugger does not work normally on Linux. What should i do?
Has the debugger ever worked on Android apks?
https://github.com/Mojang/minecraft-debugger/?tab=readme-ov-file#ensure-that-the-minecraft-bedrock-edition-client-can-make-loopback-requests
You have to enable the UWP loopback, not sure how that's gonna work on linux
Linux doesn't have UWP apps
It's more like APK port with libs
The game connects, but the debugger session crashes immediately
it is mostly for servers development
no?
what's a good way to implement lots of chat commands without a massive switch case?
hmm?
he said in Linux
you can try using a map with the command as the key and a function callback as the value
i mean how are you going to work in game with the debugger there?
there is no official bedrock version there
well yeah he probably can't but the debugger isn't made mostly for servers
outside of bds and in game development?
what?
i mean is there a use case for it excluding those
Ah, that's smart. Thanks for the idea!
for the debugger? no cause it's literally made for minecraft
huh... that what i said, no?
there is no minecraft bedrock there so that only leave us with servers
He is saying that if you use it, you will be using it in a BDS environment prior to production or release of your pack for Realms, if shared for Realms, because you can't utilize the tool to test, and debug your code if running your pack directly on Realms.
I don't think that's what he's saying at all
bruh
that is exactly what i am saying
ok well that just doesn't make any sense whatsoever then
why are you saying a server?
you can develop packs for realms on a normal world yk
Hello guys, i have a scripting performance question
I'm just entering here, and all I can say is that the debugger is for Minecraft itself. It's not server specific
i've seen that you were having a conversation about something similar with Yaser.
but my case is slightly different since im not loading constants. so
I have a clans system (for factions) and i have a question.
This is the structure of my Clans:
type ClanRole = 'owner' | 'veteran' | 'member'
interface ClanMember {
role: ClanRole;
name: string;
power: number;
joinDate: number;
lastActivity: number;
}
export interface Clan {
displayName?: string;
id: string;
shield: number;
creation: number;
members: ClanMember[];
isPublic: boolean;
owner: string;
claims?: string[];
friendlyFire: boolean;
}
The storage im using is Dynamic Properties, saving the stringified objects there.
The data will be constantly edited during the play time, some properties such as displayName, shield, isPublic, friendlyFire, members, could be constantly changing.
So my question is, is it a good practice to cache all the clans when the world starts? (Im 100% sure it won't be more than 100k clans, 100k clans is actually too much for the average players that play on the server where im using this)
Or what's my best option for this case?
wow uh
I would definitely not
which of those fields in the Clan interface are most often accessed?
I mentioned them on the message
ah I see
and claims might be also modified constantly but not much since claims have a price and it's very high.
what is shield exactly? Out of all those it seems the most active one
I'm assuming a value that can change very quickly?
it's actually one of the less used. It's the time for the faction's shield to expire (The thing that protects the faction's claims)
Ah ok
members, conditionally, will change everytime a player joins / leaves, to adjust their power, displayName, isPublic and friendlyFire can be changed at any time by the owner. The shield can change everytime someone buys it in the faction but as i said it's expensive so won't occur very often
Yeah so we don't spam here
#1316413003838783488 In case you want to help with this issue go to my post please! ๐
while having the option to use the debugger, how?
wdym?
we are talking about using the debugger in Linux, as far as i know the only option is using it with bds sense there is no bedrock for Linux.
unless the un-offecial version can run with the debugger
Another Linux L. Windows stays superior.
bad ragebait
stop it...
Gigacorp hegemony reigns supreme
why wouldn't it?
Wdym
like did you have an issue try to reset it?
I mean I want the cooldown will be reset if I hit entity
how do i get the face of a block that the player was facing when they broke it?
if timer = whatever is the normal state set it to restart
and player hits of course
how do i make my item name tags always show
like when its on the floor it will say the nametag of the item
It's an #1067869022273667152 thing not script api
It's nameable component the always_show should be true
It didn't work... I made my own :)
function isWaterBottle(player) {
const testfor = player.runCommand('testfor @s[hasitem={item=potion,location=slot.weapon.mainhand,data=0}]').successCount
if (testfor > 0) return true;
else return false;
}```
but how on an item?
Ohh, create own entity... Wait I'll give you one
-# if I cns find it
Since you can't access the item entity file
heh?
Wait I'm stupid what do you mean item? Like in inventory or the entity
nameable component when
i mean like when i drop an item i want its name to be displayed above it on the ground
2030 lmao
Then you need to overwrite the entity file of the entity entity since you can't access it so make your own...
{
"format_version": "1.13.0",
"minecraft:entity": {
"description": {
"identifier": "minecraft:item",
"is_spawnable": false,
"is_summonable": false,
"is_experimental": false
},
"components": {
"minecraft:tick_world": {},
"minecraft:hurt_on_condition": {
"damage_conditions": [
{
"filters": { "test": "in_lava", "subject": "self", "operator": "==", "value": true },
"cause": "lava",
"damage_per_tick": 4
}
]
},
"minecraft:nameable": {
"always_show": true,
"allow_name_tag_renaming": true
},
"minecraft:physics": {},
"minecraft:is_hidden_when_invisible": {},
"minecraft:pushable": {
"is_pushable": false,
"is_pushable_by_piston": true
}
}
}
}```
or use particles to display a name
Or that
confusion
wait nvm i thought of a way
Can you detect you're in the village using scripts?
no
Animation controller here I go
how do i get all entities in the overworld again i just remember it being world.getAllEntities()
Documentation for @minecraft/server
Does anybody know how I could summon particles and sound by script when being hit for example it triggers?
How can I change a player/entity skin? I'm trying to do that with simulated players but to no avail.
player i dont think u can... For entities skin_id or mark_variant components but the skins should be already defined in the resources.
I mean I can try and do a sample of it I just don't know the code for it.
But also I'm kind talking about custom ones too not just any of the skin that the simulated player has. But I can give it a shot ig.
if you are talking about dynamically changing skins, that not possible in any way in minecraft bedrock.
Like changing the skin to something that isn't in the entity's resource is not possible in any way
#1216415516751822889 message not like this?
Exactly, all those skins are pre-defined in the zombie's RP.
That's why he has a limit of skins, numbers, he doesn't load any skin he wants from nowhere
If you wanna do that
So I can't exactly do that? Just to be clear
What is in the video you can do it
Yes I want to do that
by modifying the zombie's RP
You create a ModalFormData with a slider that has all the possible mark_variant values or skin_id values and set the entity's component like this to that value .
So to be sure I have to modify the simulated player resource pack. But nobody has ever done to players correct?
For some reason the onPlace custom component hook is refusing to pass an argument to my function
It's returning undefined
bridge makes it look like a javascript error, as the IDE is not even acknowledging the data type that the hook should be passing to the function (but doing it for other components)
Yeah, i don't think player skin is managed by any component. The change of the skin must be client-side and then the skin data (That we can't access or send yet through scripts yet) is sent to the server
To do what's in the video here's a function:
import { Entity, Player } from '@minecraft/server'
import { ModalFormData } from '@minecraft/server-ui'
function changeSkin(player: Player, entity: Entity, possibleSkins: number[], component: 'mark_variant' | 'skin_id'){
new ModalFormData()
.title('Change Skin')
.slider('Skin ID', possibleSkins[0], possibleSkins[possibleSkins.length - 1], 1, possibleSkins[0])
.show(player).then(response => {
if (response.canceled) return;
const skinId = response.formValues[0] as number
entity.getComponent(component).value = skinId
})
}
import { Entity, Player } from '@minecraft/server'
import { ModalFormData } from '@minecraft/server-ui';
function changeSkin(player, entity, possibleSkins, component) {
new ModalFormData()
.title('Change Skin')
.slider('Skin ID', possibleSkins[0], possibleSkins[possibleSkins.length - 1], 1, possibleSkins[0])
.show(player).then(response => {
if (response.canceled)
return;
const skinId = response.formValues[0];
entity.getComponent(component).value = skinId;
});
}
And here's in javascript
Usage:
changeSkin(player, entity, [0, 1, 2, 3], 'mark_variant')
So the entity's skin is changed by it's mark_variant component and it has 4 possible values (0,1,2,3,4)
FIGURED IT OUT
world.getDynamicPropertyTotalByteCount()
For me returns 6200373 how do i convert that to MBS? what is that number? i don't understand in what digital storage form is that
And also, does this affect the performance in any way?
I have this line of code.
let playerEquipment = (player.getComponent("equippable")).getEquipment(EquipmentSlot.Mainhand);
getComponent is returning an entityComponent, but .getEquipment requires an entityEquippableComponent and is not running. is there some way to fix this issue?
I know I can't cast in javascript but what can I do to get the equipment?
Does anybody know how to trigger something when punching?
This shouldnt throw if its JS not TS.
how do i test when my snowball breaks? like hits a block
you are correct. i looked at the error message closer and it was getting past that part. bridge was having the issue, not minecraft
they work!!
projectileHitBlock afterEvent
Documentation for @minecraft/server
what's the difference between world.getPlayers() and world.getAllPlayers()?
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]
Installation for @minecraft/server-ui
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]
I would split each clan into their own dynamic property, so that when you read from that dynamic property, the data isnโt so large
Well this is in bytes so 1000 bytes = 1kb , 1000kb = 1mb
so it looks like yours is
6.2mb roughly
Absolutely it impacts performance. You are reading and storing large data to possibly change only a single value. You need to reconsider how you store your data using Dynamic Properties. Remember, Dynamic Properties don't need to be used to design a database that is Monolithic. Due to the uniqueness of how Dynamic Properties work, there are far more efficient ways to make a database, with less complexity.
What's the format for using permutation.resolve()? I'm trying to set a permutation on a block while not resetting other permutations, and it seems like this is what I need to do it
I haven't been able to see someone using .resolve() for multiple permutations in this server
I think you misunderstood it... Using resolve reset the rest and set what you defined, maybe you mean withState()? Like you only modify that state while retaining the other ones
You need to use withState if I understood correctly.
world.getPlayers accepts entityQueryOptions and getAllPlayers does not.
Documentation for @minecraft/server
withState... I see
anyone know what i can do to make it so my scripts update live instead of me having to reload the world manually everytime
Just /reload?
yeah thatโs just me doing that
Thats as best you can do.
so i canโt just make something automatically reload my scripts in an interval?
You can create a websocket server that you can connect the game to. On save in vscode you could trigger your websocket server to send the reload command.
You can also use the debugger and have it set as a shortcut i guess.
It'll get quite annoying though imo, having it reload on save each time.
what if i just wanted it running in a world
i suppose a command block running the reload command could work
Nope.
Command blocks don't have the proper permission level.
couldnโt i also just have something reload the world using runCommand?
No, that doesn't work. Only the player, debugger, or websocket server can trigger the /reload command.
why does the afterEvents.playerSpawn not detect player switching dimensions?
because the player isn't respawning
but does it not spawn the player..?
there's a specific event for dimension changes: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/playerdimensionchangeafterevent?view=minecraft-bedrock-stable
nope, the player just gets transferred
ohh I didn't see they added that thank you
a lot of new events since I coded last time
world.beforeEvents.chatSend.subscribe(({message,sender,cancel})=>{
if(message == `mh! getGuide`){
cancel = true
system.run(()=>{
sender.runCommand(`give @s mh:guide`)
})
}
```whatยดs the right way to call this event? and what version of minecraft-server do i need to use?
latest version is 1.17.0-beta
Don't destructure the cancel property from the event object. Doing so stores the Boolean into a variable, so if you attempt to change the variable for cancel later on in the event, then you are only changing the Boolean to the variable and not the actual property in the object.
In other words, it will fail to work.
is there an stable versiion?
Not for chatSend.
can I use beforeDataDrivenTrigger event?
system.afterEvents.scriptEventReceive.subscribe((event) => {
const sourceBlock = event.sourceBlock
const source = event.sourceEntity
const target = source.target;
const message = event.message;
try {
switch (event.id) {
case "toro:set_property":
SetProperty(source,event.message);
break;
}
} catch {
}
});
function SetProperty(Source, Details) {
let detailsSplitter = details.split('/');
let propertyName = parseInt(detailsSplitter[0]);
let propertyType = detailsSplitter[1];
let propertyValue = detailsSplitter[2];
let propertyMin = detailsSplitter[3];
let propertyMax = detailsSplitter[4];
if (propertyType == "float")propertyValue = parseFloat(propertyValue);
if (propertyType == "int") {
propertyValue = parseInt(propertyValue);
propertyMin;
propertyMax;
Source.SetProperty(propertyName, Math.min(Math.max((propertyValue),propertyMin),propertyMax));
}
if (propertyType == "float") {
propertyValue = parseFloat(propertyValue);
parseFloat(propertyMin);
parseFloat(propertyMax);
Source.SetProperty(propertyName, Math.min(Math.max((propertyValue),propertyMin),propertyMax));
}
if (propertyType == "string") {
propertyValue;
Source.SetProperty(propertyName, propertyValue);
}
}```
Can anyone tell me what's missing in this?
The content log kept saying that the system was undefined.
You gotta import it.
import { system } from "@minecraft/server";
Also, check your spelling in your code, it's case-sensitive ๐
you didn't even had to- ๐
Alr thanks.
Just to be sure, since inputPermissions is read-only, we have to set them via commands?
no, it's just the object itself read-only, but you can set its values โโvia methods or properties. like this: js player.inputPermissions.movementEnabled = false
@dusky pulsar
Ah makes sense thanks ๐
Ngl it hurts my EYES ๐
even so
you should support here, Jane have a scriptophobia
it is like you using JSON ui, at least she is trying
No I'm not talking about the code I'm talking about she didn't code block it
```js
// code
```
ah, yeah
-# cough cough that's my code cough I fixed it since she sent that version of it
Since it's not explicitly said in the docs (or I'm blind), we can listen to the response of an HTTP request right?
With
await http.request(req).then((response) => { })
import { ItemStack } from '@minecraft/server';
dimension.spawnItem(new ItemStack('minecraft:stick', 1, location);```
^ how would I make this summon at a set location like 0:0
-# itโs probably really obvious but Iโm stupid lol
import { ItemStack } from '@minecraft/server';
const location = { x: 0, y: 0, z: 0 }
dimension.spawnItem(new ItemStack('minecraft:stick', 1), location);
Wow itโs really that simple Jesus I need to learn more anyway thx
which is more stable?
player.runCommand
or running the command in the dimension
or tick.json
It is more stable to use API methods
ight
I got Windows but i think Linux is way better if you want to have more control over your OS
-# but well, its way more complicated
However,
can i make a SimulatedPlayer following a targeted Player? when i tried to, it just walked into the endless... .
by the way, im not that experiented with the gametest api
yes kal'tsit.
There's navigateToBlock, navigateToEntity, navigateToLocation. So the keyword is "navigate" instead of "move" ig
Is there a way to make an entity invulnerable with ScriptAPI ?
I don't believe so but there are so many smart people here...
no
effects ๐คทโโ๏ธ
I get an error saying that the value is outside the range of my property in the player, but this does not happen with entities, only with the player and with all the properties, can someone help me?
share your property and script
Property:
"a:bar": {
"type": "int",
"range": [ 0, 21 ],
"default": 21,
"client_sync": true
},```
Script:```js
system.afterEvents.scriptEventReceive.subscribe((data) => {
data.sourceEntity.setProperty(data.id, data.message)
})```
Command:
```/scriptevent a:bar 9```
try Number(data.message)
your welcome
Can anyone help me
i just fell in love with you for knowing her name
Anyways, Thanks.
Seems to be my fault because i wasnt looking enough
Is there a way to give the player a custom component without using player.json?
Entities don't have custom components, what are you trying to do?
I've done this before using player.json but wanna rewrite it. I wanna check the player's inventory to see if they have an item with a custom tag. If they don't have that item, I wanna apply a status effect
System.runInterval -> getPlayers -> check -> apply effect.
Okay so there is a function for that, thank you!
getPlayers -> get inventory component -> loop through the items -> check tags -> apply effect
anyone know why server-net only sends out one request per startup, i start the server the requests sends after that, nothing
its just very annoying
Can the enchantments on an item be modified through scripting? Resolved
What is this issue with Bridge and how do I resolve it
main.ts
import * as server from "@minecraft/server";
^ "Cannot find module '@minecraft/server' or its corresponding type declarations. (2307)"
manifest.json
{
"module_name: "@minecraft/server",
"version": "1.18.0-beta"
}
Missing an entry
Or the version isnโt good
Just add
โentryโ: โmain.tsโ
To the manifest module
Why does that resolve the issue?
Idk
Lol
But apparently you need it for it to work
And then you need to make a main.ts in your scripts folder
Yeah, I have a main.ts file and I already have "entry" in modules. I think it's the dependencies section
What does the dependency look like then
This
Try setting โbeta-apiโ in the config to โtrueโ
That would be upcomingcreatorfeatures
Sorry
I think
Can I access structure properties to scripts? structures in Minecraft like villages
No
Uhuh
Probably cus I played the game where she came from
je, I already thought something like that
Is there any hacky ways to get the entity height?
Like, entity height as in hey a creeper is roughly 1.5 blocks tall.
Not sure if this would work, but try comparing the head location and the location
im trying to get today's date by this code but the output is off by 1.
String(date.getDate()).padStart(2, "0")
It always returns UTC in Minecraft, btw
Potentially a workaround! Thanks.
Is there any way to get the equippable component from an entity or is it just borked? All it returns is undefined
equippable component is broken on entities rn
Bedrock wants to get in my way huh ๐ญ
It's broken for a long time
Oh dang
Use replaceitem, equippable works only for players rn
So, I'm not crazy!
Was driving me nuts all night long lol.
it's your content log files
oh right
Guys does setDynamicProperty stack? For example, setting two properties with the same ID. Would this give out errors or ignores it?
You will simply overwrite the previous value. For example, here the final value will be 2:
world.setDynamicProperty("id", 1)
world.setDynamicProperty("id", 2)
#1067876857103536159
my bad muscle memory to come here ๐
show code
anyone know yet? i'm still in need of this information
you gotta show ur code dude
import * as net from "@minecraft/server-net";
const data: any = {
"table": "test",
"columns": [
"name VARCHAR(30)"
],
"time": null
};
const url = `http://localhost:3000/api/v1/sql/create`;
console.log(url);
const req = new net.HttpRequest(url);
req.method = net.HttpRequestMethod.Post;
const sent_time = Date.now();
console.log("Sent Time:", sent_time);
console.log(req.body);
data.time = sent_time;
//@ts-ignore
req.setHeaders([new net.HttpHeader("data", JSON.stringify(data))]);
const httpClient = net.http;
(async () => {
const res = (await httpClient.request(req));
console.log(res.body);
console.log("Recieved Time:", Date.now() - sent_time);
})();
i'm not sure what is wrong with it
i just changed it to test create
well your only sending it once
What does this do
which part are you wanting to always send or whatever
you want it to happen every tick?
what do you want it to do?
Idk I just ask
im asking him lol
its either somethign in the server.properties or mojang being mojang and limiting us again but, it wont send when you reload this is just in the index fike
Oh bruh
im just storing a few things externally
are you doing /reload from the client or from the bds console?
bds console
hmm
can you scroll up the bds console a lil
could u see what i was showing?
there's something about server properties
yeah
ah nvm that's something else
that's pretty weird
might be a bug idk
can you restart the node app and then try /reload in the bds?
take a look here
its almost as if theres just nothing canceling the last packet
yeah here 1 sec
its server sided
not the node app
yeah
try chucking a system.run around the req part
see if that does anything
damn that is strange
it has 3 things that mention 3000, 2 are established, so the network request isnt completed so i think its just not reciving it, do i do net.http.cancelAll after i recieve a response?
2nd one is after stoping the server
default:~/dev/server$ sudo lsof -i:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 5531 root 21u IPv6 482034 0t0 TCP *:3000 (LISTEN)
node 5531 root 22u IPv6 483338 0t0 TCP localhost:3000->localhost:36118 (ESTABLISHED)
bedrock_s 5554 root 13u IPv6 484354 0t0 TCP localhost:36118->localhost:3000 (ESTABLISHED)
default:~/dev/server$ sudo lsof -i:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 5531 root 21u IPv6 482034 0t0 TCP *:3000 (LISTEN)
you sure your http request is set up right?
honestly don't know sorry dude
I assume it's a bug
my bad, my pc crashed
hope it gets fixed soon
player.dimension.fillBlocks({ from: volumeA.get(player), to: volumeB.get(player) }, text[2])
is this the right way to use BlockVolumeBase?
volumeA,b are vec3
that or
const volume = new BlockVolume({ x: 1, y: 0, z: 0 }, { x: 0, y: 0, z: 0 })
with BlockVolume imported
it does not let the code after return null run, and also if the function will return nothing
ohhh... thanks....
yo
why does setScore not work in scoreboardPlayerMaxHealth
const scoreboardPlayerHealth = world.scoreboard.getObjective("health")
const scoreboardPlayerMaxHealth = world.scoreboard.getObjective("maxhealth")
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const playerHealthComp = player.getComponent(EntityHealthComponent.componentId);
if (!playerHealthComp) return;
const currentHealth = playerHealthComp.currentValue;
const maxHealth = playerHealthComp.maxValue;
scoreboardPlayerHealth.setScore(player, currentHealth);
scoreboardPlayerMaxHealth.setScore(player, maxHealth)
}
}, 1);```
playerHealthComp.maxValue -> playerHealthComp.effectiveMax
Looking for public Bedrock servers, anyone have recommendations?
I recommend reading the rules
or just go to #off-topic
How to check player health?
if (health.current <= 0)```
is this right?
health.currentValue
hi there, is there a easier way to get entities from ray but creating some kind of area?
for instance instend getting entities fron a straight line on ray, get entities from from a area like a cone? so as farther more blocks to get entities will be included?
Do you want to make the ray radius larger?
I think yes, I want to causa damage to entities inside this cone, so getting straight line will only get part of them, farther entities that is slightly located to both sides from my line of view will not be included
function getEntitiesFromLargeRay(dimension, fromLocation, direction, rayLength = 64, options = {}) {
let entities = []
options.maxDistance = options.maxDistance || 1
for (let i = 0; i < rayLength; i++) {
options.location = {
x: fromLocation.x + direction.x*i,
y: fromLocation.y + direction.y*i,
z: fromLocation.z + direction.z*i
}
entities = entities.concat(dimension.getEntities(options))
}
return entities
}
Usage example:
let entities = getEntitiesFromLargeRay(word.getDimension("overworld"), {x:0, y: 0, z: 0 }, {x: 0.5, y: 0, z: 0.5}, 10, {maxDistance: 5})
- dimension - player.dimension
- fromLocation - player.location
- direction - player.getViewDirection()
- rayLength - The name speaks for itself
- options - EntityQueryOptions
great starting point, I will work on that, thank you
that won't work due to Unloaded Area error
Use tickingarea ๐คท
Nope, getEntities will just return an empty array if you try to get entities from unloaded chunks
import { world } from "@minecraft/server";
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
const equipment = source.getComponent("equippable");
if (itemStack.typeId == "dlvn:pokeball_pokemon" && itemStack.getLore().includes("Pikachu Level 5")) {
source.runCommandAsync(`say foi? ` + itemStack.getLore().replace("Pikachu Level ", ""));
}
});
why doesn't "replace" work?
Yea, it returns a string[].
So what do I do?
Have to sort through each string in the array until you find the specific string you are looking for, then replace and apply to your message.
import { world } from "@minecraft/server";
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
const
equipment = source.getComponent("equippable"),
test = itemStack.getLore();
if (itemStack.typeId == "dlvn:pokeball_pokemon" && itemStack.getLore().includes("Pikachu Level 5")) {
source.runCommandAsync(`say foi? ` + test.replace("Pikachu Level ", ""));
}
});
I tried like this, but it didn't work
just use filter()
How do you use a filter?
if (itemStack.typeId === "dlvn:pokeball_pokemon") {
// Locate the specific lore containing "Pikachu Level"
const lore = itemStack.getLore();
const pikachuLore = lore.find((line) => line.startsWith("Pikachu Level "));
if (pikachuLore) {
// Extract the level from the lore
const level = pikachuLore.replace("Pikachu Level ", "");
source.runCommandAsync(`say foi? ${level}`);
}
}
How, thanks
but I wanted it to be from the lore itself, because when I use the same item, but with the description like "Charmander Level 5", I will have to create another filter
// Define a lookup object for lore patterns and their handlers
const loreHandlers = {
"Pikachu Level": (lore) => {
const level = lore.replace("Pikachu Level ", "");
source.runCommandAsync(`say Pikachu is at Level ${level}`);
},
"Charmander Level": (lore) => {
const level = lore.replace("Charmander Level ", "");
source.runCommandAsync(`say Charmander is at Level ${level}`);
},
// Add more handlers as needed
};
if (itemStack.typeId === "dlvn:pokeball_pokemon") {
const lore = itemStack.getLore();
for (const line of lore) {
// Check each lore line against the handlers
for (const key in loreHandlers) {
if (line.startsWith(key)) {
loreHandlers[key](line); // Call the handler dynamically
break; // Stop checking further handlers for this line
}
}
}
}
That is about as good as you are gonna get in terms of efficiency. Based on your concept.
How do I test if a player has al 4 pieces of netherite armor in their inventory
inventory or equipment
Very helpful, thank you
I donโt know how to do that
import { world, system, Dimension, EntityInventoryComponent, } from "@minecraft/server"
const ascensionArea = {
x = 9999,
y = 99,
z = 9999
}
const lookAt = {
x = 10003,
y = 100,
z = 9999
}
world.beforeEvents.chatSend.subscribe(data => {
const sender = data.sender
const message = data.message
const senderInventory = data.sender.getComponent(EntityInventoryComponent)
world.getDimension("overworld").getPlayers()
if (message.startsWith("!") && message.substring(1).toString().toLowerCase() == "ascend") {
if (world.scoreboard.getObjective("coins").getScore(sender.scoreboardIdentity) >= 100000 && world.scoreboard.getObjective("kills").getScore(sender.scoreboardIdentity) >= 25) {
sender.teleport(ascensionArea, { facingLocation = lookAt })
}
}
})```
I want the command to run only when they have all 4 pieces of netherite armor in their inventory as well as 100k coins and 25 kills
that was a question...
Oh, what?
What do you mean by that
Inventory?
I donโt care if theyโre wearing it i just want them to have them
Also am I using vector3 correctly
you want to test if the armor is in the armor slots or inventory in general
Inventory in general
const inventoryComponent = player.getComponent("inventory");
const inventory = inventoryComponent.container;
const netheriteArmor = [
"minecraft:netherite_helmet",
"minecraft:netherite_chestplate",
"minecraft:netherite_leggings",
"minecraft:netherite_boots",
];
// Keep track of armor pieces found
let foundArmor = 0;
for (let slot = 0; slot < inventory.size; slot++) {
const item = inventory.getItem(slot);
if (item && netheriteArmor.includes(item.typeId)) {
foundArmor++;
}
}
if (foundArmor === 4) {
//...
}
Thank you!!
Am i using vector3 correctly btw
By making an object with x, y, and z
And using that as the vector
yes
Ok great
hurt.typeId.split("dlvn:")[1].toUpperCase()
When I use "toUpperCase" it capitalizes the entire word, I only want the first word.
exactly...
Yeah i said the code won't work in it's current status that doesn't use tickingarea... It's obvious you have to use one
hurt.typeId.split(/:|_/).slice(1).map(s=>s[0].toUpperCase() + s.slice(1)).join(" ")
I try to do this if he doesn't equip the armor, it equips him by itself but I can't do it
let result = hurt.typeId.split("dlvn:")[1];
result = result.charAt(0).toUpperCase() + result.slice(1).toLowerCase();
Lmao i just realized someone already did it
can properties, components (specially mark_variant), and tags not be accessed from a projectile that has hit an entity as ive tried this and I either get an error or undefined?
world.afterEvents.projectileHitEntity.subscribe((data) => {
const {dimension, hitVector, location, projectile, source} = data
if(projectile.typeId == 'cc:blaster_proj'){
const lev = projectile.getProperty('cc:level')
const level = projectile.getComponent('minecraft:mark_variant').value
const levels = projectile.getTags()
world.sendMessage(`${lev} | ${level} | ${levels}`)
}
})
try using before events of entityRemove you can't acces the projectile's data especially if it has the destroy_on_hit
you could use the projectilehitentity if you don't have that but if you do just resort using the entity remove
Its it open source
What can simulated player do
simulated players are like real players but you can anything what a player can do. Sometimes
e.g, breaking a block
https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server-gametest/simulatedplayer?view=minecraft-bedrock-experimental document about them
thanks for the info, that gives me an idea so I can still use projectileHitEntity and not have to use entityRemove ๐
you removed the destoy on hit or other way? kinda curios
Why is Minecraft throwing an error at the line of code with the x variable on it const buttonLocation = { x = 10003, y = 101, z = 9999 }
]```
It invalidated my ENTIRE main.js
But it didnโt throw any errors for the other files that had the exact same kind of object
Iโm using it as a vector3
And my file has all of itโs brackets matching up so it should be fine
are you sure that part was the one who make the error
I moved where the variable was and it still throws the error at the x object value
can you share the whole snippet atleasst?
can't help you if you just give me thaat object
world.afterEvents.buttonPush.subscribe((data) => {
const buttonLocation = {
x = 10003,
y = 101,
z = 9999
}
const spawn = {
x = 0,
y = 64,
z = 0
}
const button = data.block.location
if (button.x === buttonLocation.x && button.y === buttonLocation.y && button.z === buttonLocation.z) {
//if (button === buttonLocation) {
world.sendMessage({
rawtext: [
{
text:
`ยง5${data.source} HAS ASCENDED`
}
]
})
world.getDimension("overworld").playSound("mob.enderdragon.growl")
world.getDimension("the_end").playSound("mob.enderdragon.growl")
data.source.teleport(spawn)
}
})```
I dunno how much I should send so I sent the whole darn thing
nah you good i'll try what you gave
I think Iโm gonna remove the playsound tho cuz I can do that with a command block
Canโt omit the tellraw because of source name
byw the ยง5${data.source} HAS ASCENDED works?
โฆit invalidates the entire main.js, I couldnโt even test
yeah i forgot wait
oof i checked documentation
it only have source
Wdym
data.block.location is not valid
Bruhโฆ
Then how am I supposed to get the name of the person through a /tellraw nesting in /execute
that's not how you use object
โฆโฆ..
it should look like this
const vector3 = { x: 0, y: 0, z: 0 } ```
you used colon not equals
Well Iโm gonna get some ice cream brb
i just noticed it mybad
Please tell me how to get username of player through /execute /tellraw
nvm im wrong you can get the location of the button lmao
that docs doesn't include it that's why i assumed
and also you can get the name using source.name
world.afterEvents.buttonPush.subscribe(({ source, block }) => {
const spawn = { x: 0, y: 0, z: 0 };
const buttonLoc = { x: 0, y: 0, z: 0 };
if (block.location.x === buttonLoc.x && block.location.y === buttonLoc.y && block.location.z === buttonLoc.z) {
world.sendMessage(`${source.name} ascended!`);
source.teleport(spawn);
}
});```
can someone help rq
state your prblem
basically im (this is just an example ik its not correct) im trying to get the name from player 1 that matches the ID of 1, and display it as a button name
wait i might know
nvm im dumb
I deleted destory_no_hit and remove_on_hit and added
"set_last_hurt_requires_damage": true,
"destroy_on_hit_requires_damage": true
along with a despawn component group to make it more accurate
figured it out, wrong scoreboard obj lol
Hey so I finally got my scripts to work but uhhhhhhhhhhhh
[Scripting][error]-ReferenceError: Native function [ScreenDisplay::setTitle] does not have required privileges. at <anonymous> (goToAscend.js:47)
So how do I elevate the script permissions?
using before events?
Wrap the part of the code with system run
Ok so system.run bypasses this?
Is there a way for me to naturally set the script permissions higher?
Like for example wtf is permissions.json
This also happens with source.teleport
ok so modifying things before it happens isn't possible that's why we add system run since it will happen next tick
that's not what it means. In beforeEvents, they run before the game tick (as implied by the name) in a read-only state, so that means you can't call functions that modify the world or anything inside it. You can check which functions don't have "permissions" by checking the function description, where it'll say something like "this function can't be called in read-only mode". By using a system.run, you delay that code till the next game tick, where the state is read & write, so it has the proper "permissions"
Oh, ok
That makes sense
Does that also delay the rest of the code though, including the event.cancel
you don't have to wrap all your code in a system.run
only the stuff that can't run in a readonly state
event.cancel can't be delayed otherwise it does nothing
Yeayeayea but if event.cancel is at the end of the world.beforeEvents.chatSend function will system.run delay it until message has already been sent
Oh
no, only the stuff inside of the callback is delayed
Thanks for the help
no problem
Also
Does system.run need the () => {}
In the parentheses
Or can i just directly put the sender function into the system.run
system.run(() => {
// code
});```
So it does need it
Even if the nested parentheses are empty
runtInterval and runTimeout too
Why isnโt data.cancel = true working
I even put it at the start of the world.beforeEvents function and it doesnโt stop my message from being sent
Send the code
import { world, system } from "@minecraft/server"
const ascensionArea = {
x: 9999.5,
y: 99,
z: 9999.5
}
const lookAt = {
x: 10003.5,
y: 99.5,
z: 9999.5
}
world.beforeEvents.chatSend.subscribe(data => {
data.cancel = true
const inventoryComponent = data.sender.getComponent("inventory");
const inventory = inventoryComponent.container;
const netheriteArmor = [
"minecraft:netherite_helmet",
"minecraft:netherite_chestplate",
"minecraft:netherite_leggings",
"minecraft:netherite_boots",
];
let foundArmor = 0;
for (let slot = 0; slot < inventory.size; slot++) {
const item = inventory.getItem(slot);
if (item && netheriteArmor.includes(item.typeId)) {
foundArmor++;
}
}
const sender = data.sender
const message = data.message
world.getDimension("overworld").getPlayers()
if (message.startsWith("!") && message.substring(1).toString().toLowerCase() == "ascend") {
if (world.scoreboard.getObjective("coins").getScore(sender.scoreboardIdentity) >= 100000 && world.scoreboard.getObjective("kills").getScore(sender.scoreboardIdentity) >= 25 && foundArmor === 4) {
system.run(() => {
sender.teleport(ascensionArea, { facingLocation: lookAt })
})
} else {
system.run(() => {
sender.onScreenDisplay.setTitle({
rawtext: [
{
text:
"You can't\nascend yet"
}
]
})
})
}
}
})```
Itโs a lot
Two things I want to fix from this too though
- How do I close the playerโs chat immediately upon sending the command
- I want to check for at least 1 of every netherite armor piece is in their inventory
Why oh Why... If I cancel the playerInteractWithBlock Event, where the space that I touched from is air, so can take the block normally, why do I see a quick blip of it, then it disappears... is it me, or has anyone else noticed this? Is this why it is still beta?
So this really looks bad when I place those pink slabs connecting them, because it shows the default placement then switches to the new permutation placement
Does not matter too much between if I let the interact or the placeblock event handle it... only one that does not do that is the block's BP file...
Probably because place block triggers before interact.
You should use beforePlayerPlaceBlock and see if it still occurs.
According to the afterevents ordering anyways, I presume beforevents have the same ordering.
According to my testing where I actually show that stuff on the screen. The the player interact with block, the before event, happens before the player place block, before event. And on top of that, which kind of makes sense, if you cancel the interact event, it will not do the place event. So you're saying that the documentation says it should be the other way?
That was voice to text so if anything is off blame Google because I do not talk. Funny
it's just a visual desync between the client and server
cause the client predicts that the block will be placed, so it renders it, but then the server cancels the event, so it gets "un" rendered
Yeah, well that sucks
Anyone quick question, how do i get the item in the armor slots of the player
i forgot what method that was
Why you're rwatextibg the setTitle can't you just do it directly?
const equipment = player.getComponent('equippable');
const head = equipment.getEquipment('Head');
const chest = equipment.getEquipment('Chest');
const legs = equipment.getEquipment('Legs');
const feet = equipment.getEquipment('Feet');
And you can't detect armor with an inventory component use equippable component
import { world, system } from "@minecraft/server";
const ascendPos = { x: 9999.5, y: 99, z: 9999.5 };
const lookAtPos = { x: 10003.5, y: 99.5, z: 9999.5 };
const netheriteArmor = [
"minecraft:netherite_helmet",
"minecraft:netherite_chestplate",
"minecraft:netherite_leggings",
"minecraft:netherite_boots",
];
function hasFullArmor(player, armor = []) {
const equip = player.getComponent('equippable');
const head = equip.getEquipment('Head');
const chest = equip.getEquipment('Chest');
const legs = equip.getEquipment('Legs');
const feet = equip.getEquipment('Feet');
return [head, chest, legs, feet].every(item => item && armor.includes(item.typeId));
}
function getScore(player, objName) {
const obj = world.scoreboard.getObjective(objName);
return obj ? obj.getScore(player) || 0 : 0;
}
world.beforeEvents.chatSend.subscribe((data) => {
const player = data.sender;
const msg = data.message.trim();
if (msg.toLowerCase() === "!ascend") {
data.cancel = true;
const hasArmor = hasFullArmor(player, netheriteArmor);
const coins = getScore(player, "coins");
const kills = getScore(player, "kills");
if (coins >= 100000 && kills >= 25 && hasArmor) {
system.run(() => {
player.teleport(ascendPos, { facingLocation: lookAtPos });
});
} else {
system.run(() => {
player.onScreenDisplay.setTitle({
rawtext: [{ text: "You can't\nascend yet" }],
});
});
}
}
});
Only just now getting to this, I spent WAYYYYY too long working out some incredibly simple logic that I couldโve just ignored but it was throwing errors and buggin me so I fixed it
But thanks
Btw you can't close the chat forcefully unless you damage the player which is annoying asf
Didn't test it so don't expect it would work immediately ๐ญ
Also you forgot to add the netherite armor array to this line which is why it grayed for me
const hasArmor = hasFullArmor(player, netheriteArmor);
It's already defined outside the chatsend
It was grayed which means it wasnโt used in the code
Wha-?
It would work still
What software are you using
Ohh, copy it again
So I added the array
I modified it lmao
Oh
I keep editing the message and you copied the first version lmao mybad
Also the dude who sent me the first script to check for if the armor was in the inventory at all it worked fine but I could just have 4 netherite boots and it passed
Canโt it just check the entire inventory?
Ohh you're checking it if it's on the inventory only not wearing it?
Oof
Sorry bout that
You literally said it up here ๐
But that wasnโt really true
Sorry my grammar and I forgot to type that you can't detect wearing it with just inventory component โ ๏ธโ ๏ธ
Uh-huh
I read it as โyou canโt detect inventory, only armor slotsโ
function hasFullArmor(player, armor = []) {
const inventory = player.getComponent("inventory").container;
let armorCount = 0;
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
if (item && armor.includes(item.typeId)) {
armorCount++;
}
}
return armorCount === armor.length;
}```
Yeah I just retain your old one :)
I would do it myself but I already tried for like an hour earlier to get the inventory on itโs own and didnโt turn up anything of worth
But the issue with that one is, like I said, i could hold 4 netherite boots and pass the test
But i could probably just add an [i] somewhere
Hmm wait
Trust me, i would know, i have done STRENUOUS testing for the last like 4 hours
Before that, I had dinner, and before THAT, more testing!
Iโm so glad itโs Saturday tomorrow
Pretty much today my iPad was suffering from all the extremely stressing testing where I had 3 applications open at once and usually like 20 players on my world at the same time all day
But at some point I have to set the world to invite only because of world breaking exploits from the main.js getting invalidated
Am I just a nuisance here?
Am I asking for too much?
Should I leave?
I like the help ;-;
It's no in my notes to say the word... Impossible
And I've been doing this for a long time and don't expect I don't know any solution
Ok well I finished my entire laundry while waiting and watching yt
I made a function that takes a date and returns the date as "8d, 3h, 2m"
But if I do long dates, like a year, it'll say "-1y" and idk why
does anyone know why this happens
function hasFullArmor(player, armor) {
const inventory = player.getComponent('inventory').container;
const foundArmor = new Set();
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
if (item && armor.includes(item.typeId)) {
foundArmor.add(item.typeId);
}
}
return armor.every(piece => foundArmor.has(piece));
}
world.beforeEvents.chatSend.subscribe(ev => {
if (ev.message === '!test') {
ev.cancel = true;
const netheriteArmor = [
'minecraft:netherite_helmet',
'minecraft:netherite_chestplate',
'minecraft:netherite_leggings',
'minecraft:netherite_boots'
];
if (hasFullArmor(ev.sender, netheriteArmor)) {
ev.sender.sendMessage('Full set of netherite armor');
} else {
ev.sender.sendMessage('Not full set of netherite armor');
}
}
});```
done
send the code
do you use the ticks or the date.now?
or whatever you used
Ttthhhhaaaaaaannnnkkkkkssssss
nothing is impossible to me blud..
-# unless I'm really that stupid that idk any way lmao
The more I get solutions from u guys the more I have issues with my own requests
I have no idea how I was supposed to phrase that
export function getTimeRemainingString(endDate) {
if (endDate === null) return "Permanent";
const now = new Date();
endDate = new Date(endDate);
let years = endDate.getFullYear() - now.getFullYear();
let months = endDate.getMonth() - now.getMonth();
let days = endDate.getDate() - now.getDate();
let hours = endDate.getHours() - now.getHours();
let minutes = endDate.getMinutes() - now.getMinutes();
if (minutes < 0) {
minutes += 60;
hours -= 1;
}
if (hours < 0) {
hours += 24;
days -= 1;
}
if (days < 0) {
const prevMonth = new Date(endDate.getFullYear(), endDate.getMonth(), 0);
days += prevMonth.getDate();
months -= 1;
}
if (months < 0) {
months += 12;
years -= 1;
}
const timeComponents = [
years ? `${years}y` : "",
months ? `${months}mo` : "",
days ? `${days}d` : "",
hours ? `${hours}h` : "",
minutes ? `${minutes}m` : ""
].filter(Boolean);
return timeComponents.join(", ") || "Mute expired";
}
i use new Date() then a function that takes the time set from a form and adds that to the date, the returns the date and sets to db
how do you use it? what's the format?
nvm i get it now..
-# i think?
but in a readable format
can you give me the really2 long dates you used that it gave -1y?
i want to recreate or test it
sure one sec
can someone explain me why this is wrong
why is it not registering the component
custom components are registered in regular script files in the BP/scripts folder
Is there a way to cancel all momentum for the item thatโs summoned with this?
import { ItemStack } from '@minecraft/server';
const location = { x: 0, y: 0, z: 0 }
dimension.spawnItem(new ItemStack('minecraft:stick', 1), location);
I considered just tping the item to the location to do it but I thought there may be a better way
this might work
const itemEntity = dimension.spawnItem(new ItemStack('minecraft:stick', 1), location);
itemEntity.clearVelocity();
How to detect if the player used the item and when I stopped using it
When you use it, you get a tag, when you stop, you lose the tag.
https://jaylydev.github.io/scriptapi-docs/latest/enums/_minecraft_server.EntityInitializationCause.html
Yo which one is the cause for entity getting spawned by spawner?
I can't really test rn cuz I'm working on some web thing and I am using most of my device ram on that thing and yeah ๐
world.afterEvents.itemUseStart
Thnk
You're welcome
Does anyone know or can anyone test it for me rq & thanks in advance!
Why is it not working?
mc.world.afterEvents.itemStartUse.subscribe((eventData) => {
const player = eventData.source;
const item = eventData.itemStack;
player.sendMessage("Start")
});
mc.world.afterEvents.itemStopUse.subscribe((eventData) => {
const player = eventData.source;
const item = eventData.itemStack;
player.sendMessage("Stop")
});
ReleaseUse
Why event is not working?
world.beforeEvents.playerPlaceBlock.subscribe(event => {
const player = event.player;
const block = event.block;
if (block.typeId === "minecraft:dirt") {
summoned(player);
event.cancel = true;
}
});
First is correct, second should be itemReleaseUse
Well the problem probably lies in the summoned(player); function, show us it's code so we can help you.
It didn't work
Share the error.
Nothing appears in the Log
Well show me the code you used anyway
mc.world.afterEvents.itemStartUse.subscribe((eventData) => {
const player = eventData.source;
const item = eventData.itemStack;
player.sendMessage("Start")
});
mc.world.afterEvents.itemReleaseUse.subscribe((eventData) => {
const player = eventData.source;
const item = eventData.itemStack;
player.sendMessage("Stop")
});
Well do you do the import like the following:
import * as mc from "@minecraft/server";?
If not then that's the error
It should work otherwise
Yes, I used import * as mc from "@minecraft/server";
I can use itemUse, to detect when to use
But the problem is to detect when to stop using it.
entityWest = block.dimension.getEntities({maxDistance:6,location:{x:x - 27, y:y, z:z + 3},type:"minecraft:player"},tags:("start_mission");
How do I put a tag filter and scoreboard in this const?
For tags, add the 'tags' array to the object passed into getEntities.
To filter by scoreboard, we need to filter the array elements, removing entities who do not match the condition.
entityWest = block.dimension.getEntities({
maxDistance: 6,
location: {x: x-27, y: y, z: z + 3},
type: "minecraft:player",
tags: ["start_mission"]
}).filter(function filterByScore(entity) {
return getScore("missions", entity) == 3;
});
Thanks