#Script API General
1 messages ¡ Page 108 of 1
oh I didn't
So I should runTimout on the console.warn?
Oh, I will try it rq then
also, is that 1 tick thing new? becuase my code was working perfectly in 1.17.0
No idea. It's been like that for as long as I know.
man....
TYSM!!!!!
I Literally was stuck on this stupid problem for like 4 hours
Tysm so much!
Some rider component check, perhaps...
If I double-click quickly to use the shortcut to store the item effectively from the inventory, it executes the event 4 times. How could I solve this effectively?
Hotbar and Inventory
But idk how that's doubled
Try troubleshooting how many times that method got triggered
If idk where that's triggered i just put a stack tracer inside the event
console.error(new Error("trace").stack)
it runs 4 times when i use the game shortcut
player.addEffect supports infinite time?
not afaik
you must use commands
i lost track of it but afaik preview does allow infinite
Only preview?
i havent touched addons for a while so i forgot
by the way, since item lore supports RawMessage, how does text limit work now?
since last preview
oh sorry
i thought you were asking since when we had support
np
btw, wasn't the limit increased to 255 characters per line?
i remember something like it
not sure but it did increase
100 lines i think?
and/or 1000 characters per line
the docs probably didnt update
Guys
Is it possible to change the player rot using scripts?
Because tp is kinda janky
And i cant change the camera rot for first person
player.setRotation
most of the time, your question can be answered by simply looking in the docs
Well, not this time
setRotation only work on none player entities, use tp
Its not possibleđ
Sorry guys
This question is pointless anymoređ
Damn that is very odd, after testing both lookAt & the setRotation methods are unsupported for players. So yeah I guess theres really no better solutions
and keepVelocity in teleport options are also unsupported, lovely
Guys, I have a question
Does running system.runInterval causes lag?
depends on use case
if you have multiple runInterval running at once filled with cost intensive works, then it will cause lag
I love scripts
is there a way to know pushed blocks previous location?
BlockPistonComponent does have getAttachedBlocksLocations function, you can use those
locations and the piston location and isExpanding and do a bit of math to get the previous location.
but that fail if the block is pushed from behind the piston (using slime blocks)
What about the beforeEvent, iirc there is a before event for piston event
No there isn't
It got removed
Bruh
yes, A while ago
Who
me
Idk
me

there's a fourth one???
Not YET
Where
yes. But he has a work
Maybe
-# a fifth one??
Maybe we have a sixth one đ
Oh no
wth
what's going on here ???
You're right
100â%â
No
WTH
Discussing the problem https://discord.com/channels/523663022053392405/937091818603048971
doesn't look so bad
show manifest.json
oh..
?
Well, I run two intervals, One is related about guns and players, and the other refers to an entity detecting if there is a block above it
you can't use getScoreboard right after running code in V2
its prolly better to run only one interval if it runs all the time
why?
i didnt even make this
đ
Great, but would it cause lag to run two intervals? (Just asking that perhaps something like that happens in the future)
what's diffrent
just put this file instead of yours
.
why is there 7 minato's đ
bc
sorry, 6
they're all gay
someone skipped a number
no
If you're not going to do something yourself, go to the guy who made it.
ye
but he blocked me
ill just ask chatgpt
im sure it wont make it 10x worse
with two intervals, the script environment has to deal with two stuff
instead of dealing with the codes all at once (with only one runInterval)
in theory yes
supposing each runInterval runs in parallel or in multi threads, which the implementors can do if they want, no it wont
but i got no idea how that is implemented
the thing is that runninh with a lot of intervals you have to paralelize them all
while making simply a single 1 it will judt execute that single one without the need to paralelize
so in theory and so far as i know about the scripting, yeah it would lag
maybe cause more overhead actually
the lag would be caused due to your function implementation
runInterval simply runs a function every X ticks. That is, if you have two intervals with a delay of 1 tick, then the functions in them will be executed in turn every tick.
but how is that handled? a cpu cant do 2 things at the same time
I wish PlayerLeaveBeforeEvent had the cancel: boolean property
what it can do is stop 1, go to another, stop that, go back, and keep like that
multithreading
đż
Microsoft is able to train its own AI but not able to Minecraft's Script API better
based
holy hell
i heard microshit?
Yessir
Micro$oft*
Why dont they just add
- Workers
- readJSON function
- fs (but kinda downgraded ofc)
so much goof things they could do
so something like
runInterval(a);
runInterval(b);
runInterval(c);
is no different than
runInterval(()=>{
a();
b();
c();
});
isnt it?
well basically yes
with fs you could simply modify other things than the addon itself
like, your addons could literally write other addons
let me correct. a simple function that gives me the current path or filename
i think we can do so with bundlers
no workers its because theyre using quickjs, as far as i know, quickjs doesnt have as well
still, I would love to read json files or having workers
right quickjs...
read json files is just, more bundlers
BUT they could add it...
just a basic readJSON(path: string): Promise<Object> function
i heard micro$hit?
but probably they won't because i dont think it is spec of js
that would probably be a thing quickjs would have to implement
for me thats dementia
no reason to import json files
like no other language does that
its a great config file ig
i mean, thats not a problem of the std to handle
but webdev usually lacks those
except it is, bundlers and runtimes all hacked their own JSON import support
webdev lacks of fs
thats a problem just on javascript community
literally no other language have an issue like this
i dont see any std on any other languages importing specifically json
or files for configs
having access to nbt is already a no-no for the devs
cus json isn't centered on those other languages
I used it once
cuz they make other languages free to use what they want
đł
Use YAML instead!
yml is based
PNPM is using YAML, PNPM is based, so YAML is also based.
that is half true, you can use any formats you want but its just most eco conventions are overwhelmingly json
thats just on js community
i use a lot of code written in rust and c++, they dont use json
ye and js mostly revolves around the community
ghostty, kitty and alacritty, 3 terminals, none of tjem use json
js being weird as always
Does that really works in Mc?
try it, let us know
it doesn't
fuck
my code doesnt work i dont know why
Most of languages prefer YAML. Only Python prefers TOML and JavaScript using JSON.
Is there a way to detect when an item is crafted? And block it
No, but you can detect when an item gets into an inventory
And how? With a hasitem?
that works but you can use playerInventoryItemChange event
What version of the API is it for?
2.1.0 or higher
Ok, Can something be done when the item is detected, which items were needed to craft it?
well you can remove it
Good afternoon, does anyone know if I can register Minecraft:timer with Scripts API?
And mark_variant values
"egg:pre_hatch_timer": {
"minecraft:mark_variant": { "value": 2 },
"minecraft:timer": {
"looping": false,
"time": 10,
"time_down_event": {
"event": "egg:spawn_state",
"target": "self"
}
}
},
Example, this one is 10 seconds and Mark Variant 2
You can set mark variant's value via script
Timer you can modify only via component groups.
hey guys im a little new to scripting and i wanted to make something simple where if a certain player broke a block the world would send a message but everytime the player breaks something the message will say the block broken is minecraft:air (btw i changed "username" to a real username)
``import { world, system } from "@minecraft/server";
world.afterEvents.playerBreakBlock.subscribe((event) => {
const block = event.block;
if (event.player.nameTag === "username") {
world.sendMessage(user just broke ${block.type.id}!);
}
})``
because it's AFTERevents, so it happens after breaking, when the block is already air
use event.brokenBlockPermutation.type.id
o awesome tysm
do yk how i could change it so the text is a little nicer and js says the block isntead of minecraft:oak_leaves
also js to get a better understanding what does permutation do and how could i find that in the documentation
you need to use beforeEvents if you want to use the broken block name
Is there a restriction in format version for "minecraft:cooldown" in scripting? I'm trying to get an item's cooldown component but it's format version 1.10
should work regardless of the format version, I think
I wonder if it's freaking out because it's a vanilla food item
It only returns the compostable component
ah
this component only gets the cooldown when it's attached to food
not the "minecraft:cooldown" component
How can I detect if player isnât holding an item?
const heldItem = player.getComponent(âminecraft:equippableâ)?.getEquipment(EquipmentSlot.mainhand);
if (!heldItem) {
âŚ
}```
Or
```js
const heldItem = player.getComponent(âminecraft:equippableâ)?.getEquipment(EquipmentSlot.mainhand);
if (!heldItem.typeId === âminecraft:airâ) {
âŚ
}```
?
try it
first one
so this cooldown component is useless in scripting
food has a built in animation that you can't get rid of, it's cooldown is automatically applied when you start eating, not when you've finished eating the item
I can't even disable it with "can_always_eat": false because it's forced to true when in peaceful
crashing out on Minecraft food
I'm back!
aww mkay...!
oh SICK, getCooldownTicksRemaining DOESN't EVEN WORK
nvm it does, eventData.cancel makes it so getting the cooldown will be 0, but it will still set the cooldown
I'm kinda out of options, I tried syncing the timing of the food cool down to a dynamic property, but they are incredibly inconsistent for some reason
Why we can't just get the cool down component and why it's locked to food that always triggers before you've eaten it is beyond me
hey guys im a little new to scripting and i wanted to make something simple where if a certain player eats food the world would send a message but i cant seem to get the food detection quite right (btw i changed "username" to a real username)
world.afterEvents.itemCompleteUse.subscribe((event) => { if (event.source.nameTag !== "username") return; if (event.itemStack.hasComponent("minecraft:food")) { const item = event.itemStack.typeId world.sendMessage(`user just used ${item}!`); } });
Vanilla food items do not have the minecraft:food component because mojang....
oh lol
also do this when you want to send a code
what component was it for food? did it ever exist?
hm?
Taking shots in the dark here, but would it be possible to detect Horion commands through detecting when players open chat or send a message which doesn't reach the server somehow? Any ideas appreciated!
Sadly you cannot- the messages never reach the server so scripts canât detect them
I'm too scared to install the software to run enough tests, but would this even apply to detecting them opening chat, typing, or having Minecraft register the message send button on the client, even if the server doesn't see it? Of course we don't have access for keybinds, but if there's some "isTyping" thing, and they regularly do that without sending a message I could work with just that
There is no isTyping or anything like that- only way is if they stand still for extended periods of time, which would be very inaccurate due to, say, them tabbing out or something
And the client canât pass data to the server, save for very specific instances, so seeing UI buttons pressed or testing chat being opened would always be very inaccurate
I see. Thanks so much for the input, I'll keep looking for ideas.
There has to be something out there to catch it. I know any large scale release would let them patch it rapidly to avoid detection, but I'm working small scale here
I have even considered "captchas" which require them to type .eject while joining as I've heard it must be injected from the main menu before doing anything? This fell apart because people can change prefix
o then wat can i do to detect if the item being used is food or eaten?
Best way that folks have used to catch it is, well⌠testing for the hacks. You really canât check if the client is installed or commands are used. And modules canât be detected if they donât ever use them or are smart about it (they usually arenât)
(item.hasTag("minecraft:is_food") && item.typeId.startsWith("minecraft:")) || item.getComponent("food")
I don't remember exactly what the tag should be
wait the cooldown component can't even be read in a before event, so it's impossible to actually check whether the item is being used off of it's cooldown
I give up
this components a mistake
mk I got it finally.. had to use the itemCompleteUse event
hmmm still a little confused on this ig
you could just make an array of every food item
and list every food item?
ehhh i js feel liek theres gotta be a better way to do it
Laziness is bad.
yea thats wat i thought but i cant rlly find another way to do it
find the common factor of all foods and detect that
??
like this?
did you try it and see if it works?
@hazy kraken
yeah
it doesn't
so whats the common factor?
you find it
I have no idea but if there's a will there's a way
if it's not doable then list all food manually
i js made a fat list with all the food types
@harsh dawn
now just do const isFood = foodItemTypeIds.includes(item.typeId) and you're done
o cool
yea I got it there I was js wondering if there was another way
Does anyone know if it is possible to detect items in the crafting table slot?
no methods in script-api, unfortunately
only inventory, equipment and cursor
is it possible to get if a block was stopped mining?
no
has anyone figured out how to check for duplicate lines on item lore with RawMessage?
im currently fiddling with the new RawMessage argument for item lore and i cant seem to filter out existing lores and avoid interfering with other lore texts
since its a RawMessage and not just string, i cant compare it nor use .filter() or .includes()
or should i just stringify an object in RawMessage and compare with that? i dont know if stringifying existing lore works
hey guys im a little new to scripting and i was wondering what the difference was between event and eventsignal classes because i see this pattern a lot
signal is for managing callbacks of the specific event, it has un/subscribe methods
also some event subscribes have interfaces for filtering options
man when are they adding that
i dont even think they will add support for bedrock so make a block stay in its broken state if it was being mined
:/
cant say theyll never do it
it might not be their top priority
but it could happen one day
me for breeding component:
ill really appreciate minecraft for that lol
ask @warm drum
bro he asked like a thousand times for y'all to stop pinging him lol
poor guy
it's his fault
change his name
*Name your self Script API
*gets asked about Script API
*angry because he got pinged
const view = target.getViewDirection();
const pos = target.location;
const forwardX = Math.floor(pos.x + view.x * -3);
const forwardY = Math.floor(pos.y);
const forwardZ = Math.floor(pos.z + view.z * -3);
target.runCommand(`tp @s ~~0.1~`)
player.teleport(forwardX, forwardY, forwardZ, {
dimension: dim,
rotation: target.getRotation()
});``` what wrong with `player.teleport` ?
teleport takes Vector3 object as first argument
but in that code, youre giving three Number objects, which is wrong
so you should be doing
player.teleport({
x: forwardX,
y: forwardY,
z: forwardZ
}, {
dimension: dim,
rotation: target.getRotation()
});
tysm
lol
Does anyone have formula to minecraft bedrock's strength extra damage formula
wanna made teaser

yea idk for what to use
but this work
world.beforeEvents.itemUse.subscribe(function tes(e) => {
const {source,itemStack:item}=e;
if(item?.typeId==="minecraft:stick")system.run(async()=> {
const hud=source.onScreenDisplay,cam=source.camera
const lpos1= {x:-199,y:126,z:536};
source.onScreenDisplay.hideAllExcept()
cam.fade({fadeTime:{
fadeInTime:1,
holdTime: 1,
fadeOutTime:1
}})
await system.waitTicks(30)
cam.setCamera("minecraft:free",{location:lpos1,rotation:{x:0,y:150}})
await system.waitTicks(10)
cam.setFov({fov:30,easeOptions:{easeTime:3,easeType:"InOutCubic"}})
await system.waitTicks(50)
source.sendMessage("what is that??")
await system.waitTicks(40)
cam.setFov({easeOptions:{easeTime:3,easeType:"InOutCubic"}})
await system.waitTicks(70)
cam.setDefaultCamera("minecraft:third_person",{easeType:"InOutCubic",easeTime:2})
await system.waitTicks(40)
source.onScreenDisplay.resetHudElementsVisibility()
cam.clear()
world.beforeEvents.itemUse.unsubscribe(tes)
})
})
prototype, i wanna made more duration for my addon
cool
is it possible to get the current ticking areas in the world?
No
tp or input permission
clearVelocity
system.runInterval(() => {
const overworld = world.getDimension('overworld');
const nether = world.getDimension('nether');
const the_end = world.getDimension('the_end');
const entities = [...overworld.getEntities(), ...nether.getEntities(), ...the_end.getEntities()];
for (const e of entities) {
if(e.typeId === "minecraft:player") continue
e.clearVelocity()
}
});
stable module
it's pausing mid air
Guess what I am doing with this function only.```js
function parseLocation(location) {
let [left, right] = location.split(':');
if (left.includes('.')) {
const [namespace, value] = left.split('.');
left = ${namespace}:${value};
} else if (!left.includes(':')) left = minecraft:${left};
if (right) {
if (right.includes('.')) {
const [namespace, value] = right.split('.');
right = ${namespace}:${value};
} else if (!right.includes(':')) right = minecraft:${right};
} else right = left;
return [left, right];
}```
quick swap mainhand / offhand?
lol you said guess, so...
you could use left = left.replace('.', ':');
Yeah, I just realized that... Thanks!
i think he wanted to freeze players, that script seems to freeze everything but players
.
i am confirming to serty that clear velocity won't work
.
oh mb
it just slows things down isn't it?
seem so
altho Serty is talking about beta api (it is the one that have player support for clearVelocity)
i was using stable model so that what i was able to test at that time
If there's anything happening in the area, then u can get the rough location especially when there's entity there
Ending up learning a bit to write one myself lmao, but thank you
did you check the player velocity?
How to use rawText
{ text: `§rDimension: §5`, translate: dpDim1},
This doesn't show the dimension text, only the translation
how can I get strings parts in custom commands?
I need the radius in code
as a variable
like get the input
after the first param
{
rawtext: [
{
text: "Dimension: "
},
{
translate: ""
}
]
}
Custom components V2 is already in stable?
??
also how to filter out player's id
like get the player according to player id i have
({ sourceEntity: e }, radius, name)
Thanks
thanks
-# @lapis heart đ
Nice
Thx
I mean like an api that tells you the ticking area names in script api
theres no method for that.
terrible stuff
thank you very much
also
how to get the player according to player id i have
By player's ID you mean Entity.id or his XUID?
Then use World.getEntity(id)
It's a fascinating method. Very useful
@warm mason If i remember correctly... You shared a stomp mechanic function, Which applies knockback like stomping. Is that script still being shared? I can't find
what is xuid?
Xbox Unique Identifier - ID binded directly to Xbox's account.
nvm it says Playfab there
Don't use PlayFab, it's spoofable.
If you can't use XUID, use entity's identifier.
It's pretty fast and easy.
đ
Iâm trying to download an addon for editor. How do I add the addon to editor mode
Try #1339727065846648906 or #1340055990053244938
function getDirection(vector1, vector2) {
let distance = Math.sqrt((vector1.x - vector2.x) ** 2 + (vector1.y - vector2.y) ** 2 + (vector1.z - vector2.z) ** 2) || 0.001
let direction = {
x: (vector2.x - vector1.x) / distance,
y: (vector2.y - vector1.y) / distance,
z: (vector2.z - vector1.z) / distance
}
return direction
}
/**
* @param {Entity} entity
*/
function bossStomping(entity) {
const entities = entity.dimension.getEntities({ location: entity.location, maxDistance: 5 }) ?? []
for (let target of entities) {
let direction = getDirection(entity.location, target.location)
applyKnockbackUpdated(target, direction.x, direction.z, 5, direction.y * 0.5 + 0.5);
target.applyDamage(5, { cause: "entityAttack", damagingEntity: entity })
}
}
world.afterEvents.itemUse.subscribe(event => {
if (event.itemStack.typeId !== 'minecraft:stick') return;
bossStomping(event.source)
})
function applyKnockbackUpdated(target, dirX, dirZ, horizontalStrength, verticalStrength) {
const horizontalForce = {
x: dirX * horizontalStrength,
z: dirZ * horizontalStrength
};
target.applyKnockback(horizontalForce, verticalStrength);
}
This also launches up the player.. and sometimes, It can't find the entity.
In my case, i am using player as the target entity, and stick as a stomper
help
npm bot not work
https://www.npmjs.com/package/@minecraft/server?activeTab=versions
https://www.npmjs.com/package/@minecraft/server-ui?activeTab=versions
Contains many types related to manipulating a Minecraft world, including entities, blocks, dimensions, and more.. Latest version: 2.1.0, last published: 19 days ago. Start using @minecraft/server in your project by running npm i @minecraft/server. There are 77 other projects in the npm registry using @minecraft/server.
which one you guys prefer?
// v1
const at = Player.stat.at('<location>');
at.set(10);
at.add(); // optional values inside
at.sub(10);``````js
// v2
const get = Player.stat.get('<location>');
Player.stat.set('<location>', 10);
Player.stat.add('<location>');
Player.stat.sub('<location>', 5);```
V2
V2 looks better
when you aren't looking at anything while typing and look up to see ```js
dimension.setBlockType(blockLocation, 'mciniweacft'syr)
What is the best approach to tick a water source block after placing it?
right now I just get a cube of water that isn't flowing
try placing flowing water instead
#1400838877190553752 message
v1 imo
but needs adjustments
wait, isn't var a keyword?
we can use it as a variable name?
or is it just for an example
obviously its just an example
is there a way to add a crosshair for a player while riding an entity?
how would i make this script make it so that a particle is constantly emitting a particle on a block. The wiki was no help and i have zero experience with scripts at all
this is what my manifest has for script modules rn
thanks ill ask there
... You dont need to search for the player
SourceEntity is the player, when executen by ins
Is there a way to detect player pressing sneak while he is riding an entity? With the dismount disabled.
both the event and player.isSneaking do nothing
what about Player.inputInfo?
Does setPropertyOverrideForEntity() persist between reloads?
I feel like it wouldn't.
RawMessage support for item lore is one of the best thing that could ever happen in the histroy of scripting api
i really love it
Hello everyone, can we defined the item arrow identifier and projectile arrow identifier separately, using api?
Please help
you can change the default text?
what do you mean by default text?
like the default lore for the items
english->korean via rawmessage set item lore?
well uh
yeah you can use RawMessage on it
which has translation and other stuff
that's very helpful I should try and make that
can you change the layout too?
the layout?
how is the lore structured? from the name to the status
I want to to extend the when in main hand part
oh
add another custom status for the item
const damage = stats.damage ?? 0;
const atkSpeed = stats.attackSpeed ?? 0;
let existingLore = item.getRawLore() ?? [];
const mainhandStr = { rawtext: [{ text: "§r§7" }, { translate: "sweepnslash.item.modifiers.mainhand" }] };
const damageStr = { rawtext: [{ text: ` §r§2${damage} ` }, { translate: "sweepnslash.attribute.name.attack_damage" }] };
const atkSpeedStr = { rawtext: [{ text: ` §r§2${atkSpeed} ` }, { translate: "sweepnslash.attribute.name.attack_speed" }] };
function isOurLine(raw) {
const str = stringifyRawMessage(raw);
return (
str.includes("sweepnslash.item.modifiers.mainhand") ||
str.includes("sweepnslash.attribute.name.attack_damage") ||
str.includes("sweepnslash.attribute.name.attack_speed")
);
}
const itemLore = existingLore.filter((line) => !isOurLine(line));
if (existingLore.length >= 100) return;
if (stats.skipLore) {
itemSlot.setLore([...itemLore]);
} else {
itemSlot.setLore([...itemLore, mainhandStr, damageStr, atkSpeedStr]);
}
this is how its structured
How do I get the dimension name from the dimension an entity is in? entity.dimension returns [object Object]
Is there sth like entity.getDimension()?
stringify it
JSON.stringify(entity.dimension)
Ty
that just turns it into string
It returns {"id": "overworld"} so I guess I can just do entity.dimension.id to get the string I need right away
I mean I don't just guess
oh yeah I forgot
yeah you can do that
is fine is fine
i think i forgot to post this function too
function stringifyRawMessage(msg) {
if (!msg) return "";
if (msg.text) return msg.text;
if (msg.translate) return msg.translate;
if (msg.rawtext) return msg.rawtext.map(stringifyRawMessage).join("");
return "";
}
idk how to make this better but it works for now
...actually, hold on
ok nvm it didnt work
youre passing an object that dimension argument does not take
it needs a Dimension prototype so ```js
const dimension = world.getDimension(target.dimensionId)
player.teleport(target.location, {dimension})
Oh ty that's a good idea
or that way
i don't really understand how to utilize playerSpawn and playerJoin.
i just want the command executed once the player join or respawn
the player isn't in the world yet on playerJoin
playerSpawn is when the player actually spawns in the world
put everything in playerSpawn
world.afterEvents.playerJoin.subscribe((player)=>{
const X = player.source;
if(X.hasTag("Custom.Member")){
X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
}else{
X.addTag("Custom.Member");
X.runCommandAsync("Effect @s Resistance 15 4 True");
X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
X.runCommandAsync("Function Custom/World_Config");
X.runCommandAsync("Function Custom/Settings");
}
});
world.afterEvents.playerSpawn.subscribe((player)=>{
const X = player.source;
if(X.hasTag("Custom.Member")){
X.runCommandAsync("Effect @s Resistance 15 4 True");
X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
X.runCommandAsync("Function Custom/Settings");
}
});
world.afterEvents.itemCompleteUse.subscribe((event_data)=>{
const X = event_data.source;
const item = X.getComponent('equippable').getEquipment('Mainhand');
if(item?.typeId=='minecraft:milk_bucket'){
X.runCommandAsync("Effect @s Health_Boost Infinite 4 True");
X.runCommandAsync("Effect @s Regeneration 10 4 True");
X.runCommandAsync("Effect @s Saturation 5 0 True");
X.runCommandAsync("Function Custom/Settings");
}
});
only the itemCompleteUse is working
have you tried having content logs on
either learn raw coding style or use [typings](#1067535608660107284 message)
Does anyone know a way to set the dynamic property of stackable items?
yes
you can't
Does anyone know how I can register a custom component? I'm using the 2.0.0 API, but the script I had no longer works.
import * as mc from '@minecraft/server';
import * as ItemComponent from "./test/sistema/items.js";
import "./test/sistema/title.js";
import "./test/sistema/commands.js";
import "./test/sistema/menu.js";
// import "./test/sistema/chat.js";
import "./test/tree_stats.js";
import "./combat/basics.js";
mc.world.beforeEvents.worldInitialize.subscribe(event => {
const itemComponentRegistry = event.itemComponentRegistry;
//Kagune
itemComponentRegistry.registerCustomComponent("ts:system",{onUse: arg => {ItemComponent.menu(arg.source);}});
itemComponentRegistry.registerCustomComponent("ts:kagune_kaneki",{onUse: arg => {ItemComponent.kagune_kaneki(arg.source);}});
itemComponentRegistry.registerCustomComponent("ts:kagune_touka",{onUse: arg => {ItemComponent.kagune_touka(arg.source);}});
itemComponentRegistry.registerCustomComponent("ts:kagune_tsukiyama",{onUse: arg => {ItemComponent.kagune_tsukiyama(arg.source);}});
});
world.beforeEvents.worldInitialize -> system.beforeEvents.startup
Thank you, I love you đđ
đ
The closest thing you can approach is by using item's lore and saving it with paragraphs (§).
I didn't even know @minecraft/client is a thing
Its not.
Someone just made a post
Just an internal thing
We can't use it
The things that we can use are in the wiki
DW tnx, it's still not useful cause container.contains() or container.find() doesn't recognise the item if you change the item's lore or dynamic property or nameTag
I could loop through all the slots but this would prolly cause lag as the function runs every second
That's why I said the closest thing, if you don't want to use lore, then you have to make your item unstackable.
Aight
Why does this send me to the same dimension I'm in everytime even tho I was in the overworld but the console warning said target.dimension is "minecraft:nether" js console.warn(target.dimension) player.teleport(xyz, world.getDimension(target.dimension));
player.teleport(xyz, {
dimension: world.getDimension(target.dimension)
});
Oh wow, thank you!
isn't the dimension property already a Dimension class instance?
like
It's a string.
yeah, that's why i was concerned
this is essentially what should make you unconcerned
okay now I'm really lost wtf
oh
ig target isn't an entity
Probably some weird converting.
i supposed it was
this is interesting
client sided stuff
Nope.
I complained about this way way back and there's no fixed yet.
That wouldn't work.
Oof, not wouldn't more like don't...
My current project is full of shity work arounds cause of the key binding limitations
It's also the fact that it works before... i was so confused and mad that it doesn't anymore.
it's like they literally separated the dismount button ID to the sneak button itself.
Was this when they made the player hitbox shorter on sneak
I'm not entirely sure but there's a chance that it is...
I need a professional to actually say the reason why they did that đđ
It's frustrating asf...
Let's mass ping navi
-# jk
I feel scammed
It may be incorrect because it's not actually checking if the entity is on the ground, it's just checking if their velocity is 0
just check if velocity is 0 instead LMAO
scammiest method
Well I'm trying to use it for my custom falling block
But entities do not fall at the same speed as the falling block entities
So I'm trying to set gravity to false and appy impulse at a close equivalent
Not to mention the entity desync this game has throws off all of the position checks
Mhm
whats the difference between ItemStack.type.id and ItemStack.typeId
They're the same but it seems typeId assumes Id without namespaces as 'minecraft'
thanks
guys, i need some help. so i have a block, let's call it block A, and i have block B. when block B is destroyed, i spawn a particle, and i want that particle to travel to the block A, if it's present in a 48 block radius from block B, kind of how particles go to creacking heart when you hit the creacking
is there any way to do this without any lag?
What's onswing event and how to use it?
It's on preview for now
nevermind
What do you guys think about using block class for server ui icons?
so instead of using individual isometric screenshots, it uses what the inventory uses
it would be nice if it could be calculated properly
like form.button("Crafting", craftingTableVariable);
and what is craftingTableVariable equal to?
block class
i think a BlockType would make more sense
you will get an error
Technically you can do this by modifying JsonUI so that it supports rendering items via AuxId, but you can't get the exact ID of a block/item so you can't do this.
BlockPermutation
i have a question
if anyone has tested this case, please tell me so
anyway so if you register custom commands with synchronous functions as their handlers, but they require some asynchronous logic, and you have to wait for that logic before returning a CustomCommandResult (or undefined)
and you use a .then/.catch block to do this
does the API accept this or only strict synchronous results?
Only sync results, and yes cmd result or undefined is what it's limited to, it doesn't accept promises/async results
In my case, I tried to do awaition there, it's my 1st encounter where awaition cannot be done in there so gota use system.run
what's on swing mean?
when the player swing his arm
Right/left click
it triggers everytime the player's hand moves
you can get the direction of block A to block B and just mult it
umm, is it possible to take an ingame screenshot using commanda or scripts?
Not possible.
its possible only via jsonUi by adding that screenshot button
ig
Yes, but you can't force a player to take a screenshot using scripts or commands.
i see
ah that's sad
thanks for letting me know tho
@granite badger
@minecraft/server-gametest documentation link takes you to @minecraft/server-ui
what new feature is that?
wha-
sounds like a problem to me
we really need the this on bedrock... it would be so nice to be able to just grab skins, player heads and more
yeah would be nice, now they've made skin apis for bedrock i don't see why they couldn't do it at some point
i guess the fact they're not storing user-uploaded skins is a big reason as to why they probably wouldn't
half the time it'll just resolve to a default character
at least we should be able to get the skins of active players in the current server/world
you can with server-net but cant really do much with it
yeah but i mean with just the @minecraft/server module
cant really do much with it sadly if you cant show it in forms or set skins
Imagine JavaScript without async or promises
Such a pain.
Is saving an entity's inventory possible with stable API?
Save it in a structure.
But how can I make it modular kinda without making the size of the world go up crazy
Where do I get MinecraftEffectTypes from?
I see other people importing files like "./vanilla-data.js" and I heard there was a way of getting the vanilla data from the minecraft server but it's a pain to figure out unless I'm just not seeing it
I thought there was a package like "@minecraft/vanilla-data" or something
nevermind i guess it is a thing.. i just tried it in npm đ¤ˇââď¸
it's not a package that ships with the client, so you'll need to compile it into your source if you intend on using it
How would I compile it into it?
using some form of bundler is the easiest way
https://github.com/microsoft/minecraft-scripting-samples/tree/main/ts-starter is an example using ts etc
so i do actually have to make it into a script file?
i have typescript.. it's just weird that i can install it as a npm package but i have to bundle it?!
Or you can drag files directly into your project.
alr yeah, i just moved it into my project.. easier way i guess
You can always make these enumerations constant to take a small boost.
is world.beforeEvents.chatSend.subscribe() still beta?
Yes.
anyone have any idea why this dont work
theres no error and the commands are not showing up in chat
not useable either
it is imported to my main file too
it used to work
now i was coding other stuff and realised its broken now
we might get gta 6 before stable chatSend event đ
EntityHurtBeforeEvent & EntityDieBeforeEvent:
Custom Keybinds:
equippable component for entities
entity.target
why downvote?
because it won't work for phones. It will only be useful for a small circle of people
not read-only entity.target
player hunger component
custom keybinds/custom buttons then
It's out of beta?
This will also require changing the UI, which will take a very long time.
It's out of beta for a longer time, it's not that hard component to implement, also it does not really change through the time.
no, it was out in 1.21.100
It's just extended abstract class of a EntityAttributeComponent, it took them that long to implement a simple hunger system?
I thought it's been a long time.. uhhh.
yeah, first introduced in 1.21.90.26
Kinda late for this little component, to be honest.
block.setDynamicProperty
uhm, does a custom slash command function count as a read-only mode?
i tried to use spawnSimulatedPlayer() inside it and got a privilege error
Yes, it does.
yeah that too
Hey I have like a solution for that I'd plan to post in dev-resources later
Is it using "subject": "target"?
Basically if you remove (i forgot I'd check my PC later), the is it attack behaviour component of the entity with an event and add it later it looks for the last entity that hurt it
So I use like entity.hurtafter event,to check whether it was it's target that hurt it, and it's random depending on damage
Yh
huh
You can also use the reset_target in events property to remove the entities target and apply a damage of 0 from it's new target to it
I like the idea but I use entity.target for other things like monsters hurting you remotely.
Aight
Woah, So that using that you can set a entity's target and it will attack the selected entity?
anyone able to help i cant find the cause
is there any way to force a player to open an inventory from like an entity or something?
No
ok thx
Is there any way to make a custom command capture the entire string, even with spaces, without needing to use quotes, like /tell <player> <message>?
No.
Yh
If I am setting the target by causing the damage without the target hurting the entity first I apply a knockback of 0 in all directions - it cancels the bounce that happens when an entity is hurt
2 whole days and i still dk what to do i beg sm1 help
Open a post!
that works?
oh wait
i was thinking of somethjng else nvm đ
Does anyone know if itâs possible to make it so when a player places any door in water it will not water log it like in Java and if possible to do it using stable scripts or changing the door behavior so it canât be water logged
hey i got a quick question about custom command
can you do them in js are they only in ts ?
also is it available in 2.2.0-beta ?
gugugua
Umm what
TS is not an entirely different language, and its available on stable
do u understand what ts is
typescript
No not you
soz
not really
okay tks
Itâs basically an extension of js that adds explicit types and enums interfaces and a lot of other stuff
it compiles to js
function configFormOpener({ sourceEntity: player, sourceType }) {
if (!(player instanceof Player && sourceType === CustomCommandSource.Entity)) {
return {
status: CustomCommandStatus.Failure,
message: "Target must be player-type and command executor must be entity"
};
}
system.run(() => configForm(player));
return {
status: CustomCommandStatus.Success
//message: "Successfully opened Sweep 'N Slash configuration menu for " + player.name
};
}
system.beforeEvents.startup.subscribe((init) => {
const configMenuCommand = {
name: configCommand,
description: "sweepnslash.commanddescription",
permissionLevel: 0,
cheatsRequired: false
};
init.customCommandRegistry.registerCommand(configMenuCommand, configFormOpener);
});
function configForm(player) {
//...
};
this is my take on custom commands
making the custom command to run codes directly rather than making it run a function kinda caused an issue where i couldnt reload to debug it
since registered stuff cant be reloaded mid game
so i just slapped functions here and there
ts -> this shit
how is the new swing event? its obviously more reliable than AC method, but how does it compare?
It is the same thing
what about the delay?
theres no delay
theres some issues with it though, such as, if you break a block, it'll trigger 20 times.
odd
i cant report it: #1407392112588230676 message
maybe you can, if its not reported already.
did u work it out?
That's not a bug
When you are breaking a block it run in an interval
what
I mean in creative
same
I dont understand.
creative is the same as survival
Minato
im asking what you mean by this
the swing animation run in an interval
that does not help

I dont see why this would be intended.
cause the swing is running in a loop
it spamming it 20 times when breaking a block is not a good thing.
would anyone know how to detect if an itemstack is a block?
check if the typeId is included within BlockTypes.
import BlockTypes from server
ah sweet ty
you'll have to do some manually since not all of the IDs are the same
e.g. the item is minecraft:sugar_cane and the block is minecraft:reeds
function isBlock(id) {
const types = BlockTypes.getAll().map(type => type.id)
if (types.includes(id)) {
return true
}
}
yeah.
true.
i'd move types outside of the function since they won't change
we love mojang :P
i quickly made this
mojang so cool
you can just try block.setType and see if it throw error
same issue would occur though
BlockTypes.get() left the chat
oops
đ
nothing wrong that logic
function isBlock(id) {
return BlockTypes.get(id) != undefined;
}
return list.includes(element);
useless condition
nothing wrong with that logic.
yes, it works correctly, but like, why?
because its the way I quickly wrote it.
Yeah, i just feel like it would be faster, you are dealing with a massive list there
it'll be faster with serty's correction I imagine.
ill do it after testing it
thanks
typescript is simply a 'language' that transpiles to js, when you write
function f(n:number):number {
return n * 2;
}
what it will convert to is:
function f(n){
return n * 2;
}
so anything available in js is available on ts, and anything available on ts is available on js, even though the code might not look beauty, such as decorators that are not implemented on most js engines
It would convert to:
"use strict"
function f(n){
return n * 2
}
i still dont get the usage of 'use strict'
what am i missing here
[Scripting][inform]-true std:mob_id
[Scripting][inform]-["mob_family"]
why is it showing in the log if the condition is true
...
nvm
tf is the var name đ
LMAO
hey did you get around to reporting what I was talking about?
oh i was planning to do it tomorrow
didnt update preview yet
Ah, alright
ah, i am surprised the spelling extension didn't flag that
"isMnoster"
i have the extension disabled
en
titties....
đ
Use WebStorm, it has those warnings out-of-box.
ok bro is fr obsessed with webstorm
fast typing, just dont care abt spelling but comprehension
would it kill my fans
vs code is slow as it is, no need for another bloated IDE
VS Code is pretty fast.
It has barely any impact on my MacBookâŚ
frfrfrfr
hardware differences
vscode is so slow with extensions and hardware differences, yeah
What's your hardware?
I have used VS Code twice after switching to macOS, JetBrains's IDEs are much better for me.
Oh, VS Code might be better for you.
i would use sublime text if i could
đ
and ye mine is a office pc
there is not really that much differences
-# which i brought home for free
yeah, that might be better, mine is a laptop
mine's just 1.8G
i usually work fine with my hardware.
but sometimes some projects require a lot of performance like my current project
opening the game + vs code + blockbench with a 1000 cube model and 1mb animation file
Jedbrains IDE's are peak but they somehow manage to hog up more resources then vscode. It is however faster when it comes to like auto completion suggestions and intellisense
Facts.
đđ
I have 4.4 GHz.
how do i fix this
by removing vanilla-data in your manifest.json
@minecraft/vanilla-data isn't an actual module included in the game, you have to include it yourself
how
i mean i did but if i dont add it to the manifest it tells me to do it
you can use a bundler
it says "if this is a native module, add it to manifest.json".
and if you haven't guessed it, vanilla-data isn't a native module!!!
oh right i didnt read that part
use a bundler or download it from here then add the js file to your project
https://jaylydev.github.io/scriptapi-docs/meta/cdn-links.html
How can I tag a player when they spawn an entity with an entity placer (spawn egg, armor stand, end crystal, custom placers, etc)?
does anyone have a latest typeId.js from herobrine chest UI? the one on his github seems to be outdated
how to keep entityDieAfterEvent from throwing errors when using command /kill?
does anyone know how do i give player spawn_egg 1 51 by do new ItemStack thrn add to player container?
new ItemStack(spawn_egg, 1)
are you trying to edit the entity after dying?
afaik spawn eggs have their own ids now, so you can just use id like zombie_spawn_egg
đď¸
okay iâll try
ik but im curious about itemid
cuz i do âminecraft:spawn_egg 1 51â so it throw me an error
but thanks for advice đđť
no just detecting
can you post the code here?
also what error is it throwing?
@hidden perch note that the method doesnt account for full inventory, so nothing will happen when the inventory cant store the item
you can do a workaround by using runCommand to give the item if you want it to drop from full inventory
this is fine
iâm helping that guy who trying to make admin panel
âHe knows đ¤â
Cannot read 'typeId'
const deadEntity = event.deadEntity;
const damager = event.damageSource.damagingEntity;
const damagingProjectile = event.damageSource.damagingProjectile;
const loot = deadEntity.typeId === "gg:scar_mag_loot" || deadEntity.typeId === "gg:scar_mag_empty_loot" || deadEntity.typeId === "gg:deagle_mag_loot" || deadEntity.typeId === "gg:deagle_mag_empty_loot";
if (deadEntity.typeId === "minecraft:player" && damager.typeId === "minecraft:player" && gotHit.hasTag("shot") && !loot ) {
player.addTag("dead");
return;
} else if (!loot && damager.typeId === "minecraft:player") {
player.setProperty("gg:is_hitting", 2);
player.runCommand(`/playsound random.orb @p ~ ~ ~ 1 2`);
return;
}
});```
of undefined?
this line throws the error else if (!loot && damager.typeId === "minecraft:player")
It doesn't really ruin the code but it's annoying
just add a check if the damager is valid
how?
@granite badger jayly bot not working again....... :<
the /docs info
.
is getBiome and getLightLevel still preview ?
Yes, still in preview.
can i get the 2.2.0-beta npm install comand
the bot is down
Contains many types related to manipulating a Minecraft world, including entities, blocks, dimensions, and more.. Latest version: 2.1.0, last published: 24 days ago. Start using @minecraft/server in your project by running npm i @minecraft/server. There are 77 other projects in the npm registry using @minecraft/server.
just booted up the bot again.
For the record, my site also has the npm install command for every module. Thatâs more reliable at times
Tip: In any event, use ?. after each property of the event to avoid errors.
Like:
const loot = deadEntity?.typeId === "gg:scar_mag_loot" || deadEntity?.typeId === "gg:scar_mag_empty_loot" || deadEntity?.typeId === "gg:deagle_mag_loot" || deadEntity?.typeId === "gg:deagle_mag_empty_loot";
Uh, don't use that everyware
import { Entity } from "@minecraft/server"
class EntityLootable {
private constructor() {}
private static readonly LOOTABLE_ENTITIES: Readonly<Set<string>> = new Set<string>([
"gg:scar_mag_loot",
"gg:scar_mag_empty_loot",
"gg:deagle_mag_loot",
"gg:deagle_mag_empty_loot",
])
public static isLootable(entity: string | Entity): boolean {
return this.LOOTABLE_ENTITIES.has(entity instanceof Entity ? entity.typeId : entity)
}
}
export { EntityLootable }
đż
Why ?
It is not a good practice, use it when it matters, and when it is better than the alternatives.
An early return well work better in such a case
yeah, cases like damagingEntity not existing and throwing error can be resolved by early return
Of course. But I mean if you want to use it in if and the code doesn't stop after that.
how would i get the block to an arbitrary direction of another block, without using a large if-else structure or switch statement? for example, i want to know if there is a function thet can do something like this:
block::getBlockFromDirection(Direction): Block
There's a method to get an another block by offset frmo another.
thx but i alr looked there
there doesnt seem to be a method for using a direction
You can use a hashmap to get a vector from a directory, then apply it to a method.
ok thx
Are you using JS or TS? Just asking if you need any code example, so I can write a simple one for you.
ts
Nice, I like using TS over JS.
import { Direction, type Vector3, Block } from "@minecraft/server"
const directoryOffset: Readonly<Map<Direction, Vector3>> = new Map<Direction, Vector3>([
[Direction.Down, { x: 0, y: -1, z: 0 }],
[Direction.East, { x: 1, y: 0, z: 0 }],
[Direction.North, { x: 0, y: 0, z: 1 }],
[Direction.South, { x: 0, y: 0, z: -1 }],
[Direction.Up, { x: 0, y: 1, z: 0 }],
[Direction.West, { x: -1, y: 0, z: 0 }],
])
const newBlock: Block | undefined = someOtherBlock.offset(directoryOffset.get(yourDirection)!)
thank you!
also yeah, TS is so much better
A life-saver in bigger projects.
umm, is it possible to extract a number from a string?
the text is from a custom item tag, it will look something like this customtag:4000 so i just want to see if it is possible to get that exact number or not.
+'wave4000'.match(/\d+/)[0]
Good to know! Thanks
text.split(":")[1]
umm, how can i use the tag string?
like i need to detect if the tag starts with customtag: for example and extract the number that will be after the tag.
const number = Number(entity.getTags().find(tag => tag.startsWith('customtag:'))?.split(':')[1]);
and i just have to put number in my codes? thanks!
Number returns unknown / not defined
then there is no such tag, idk
let numeric = 0;
if(tag.startsWith("customtag:")) numeric = Number(tag.slice(10)); //10 == length("customtag:")
ill deal with it later ig, gotta play some ||warThunder||
Use a Set instead.
Why getting a property mutliple times if you only need to do it once
const eTag = itemStack?.getTags()?.find(tag => {if (tag?.startsWith('xhydration:')) eHydValue = tag?.slice(11)});
console.warn(eTag)
```returns undefined
oh my bad
Beautiful
@thorn flicker apparently my preview is refusing to install so i might have to try it again after i get back to college dorm
Alr
thinking about it...
i wonder if the event triggering 20 times is the reason why v.attack_time has a delay
wait
i dont know if the event triggers 20 times at once
or on every tick
it only triggers 20 times when you break a block.
umm, player?.setDynamicProperty('xHydration:hydrationValue', hydValue + eHydValue); will set the hydrationValue to 206 for some reason, like it just looks like this: hydValueeHydValue
(you dont have to add namespace btw)
hydValue = 20
eHydValue = 6
instead of 26, it returns 206
thats probably because the number is actually string and not number
string + string results in stringstring
it is a string, then how can i turn it from sting to number?
maybe try converting it to number first
Number(string)
why is it a string though in the first place
oh, I see.
oh, i see.
so they just, burst out 20 times at once, in a tick?
yes
only issue with it, far as I know
other than that HELL YEAH, SWING AFTER EVENT WOOOO
FINALLY
and there's no delay, I think
my addon is one step closer to be player.json free
why do you need it for?
long range weapon swing?
nope
why do you need that for damage mechanics?
alr
right so you know that entities have minecraft:attack component, right?
yeag ill still explain it
I dont know whats popular if it is
that entirely disables damaging entities
okay so, no damage
and you use applyDamage?
you should add a config
the stats are data driven
that allows people to setup damage models
yeah thats what i added
my bad
its ok
