#Script API General
1 messages · Page 22 of 1
- if u gonna dive into programming
Yeah it was just a tip
30% is a lot
also you can't tell that
js have a lot of stuff
Yeah
30% of the course
But ☠️ if u learn it
They have a progress bar
I can told u that u can learn any other programming language in less than month
alr
Or month
Nah js is my year goal
It doesn't take year to learn it tho
I want to be a decent coder in js by next year
Ik
☠️ i mean if u give a good time
Not just one hour a day or idk
But yeah it still worth it
No programing language takes more than 6 month except that one that like directly programs the CPUs circuit
Not binary
Idk what it's called
What was your best project so far?
Ah ، i can't tell but
I have decent knowledge in js
I need to sleep lol
☠️
how to make invisible model?
let _topBlock = firstBlock.above();
while(true) {
if (!_topBlock?.isValid() || !isLogIncluded(_topBlock?.typeId)) break;
if (_topBlock?.typeId !== blockTypeId) break;
yOffsets.set(_topBlock.location.y, false);
_topBlock = _topBlock.above();
}
are there better way to do this? i tried getBlockFromRaycast but it doesn't really get to the top of the oak log, it just stops to the first one, and getTopMostBlock can be tricked if the above block is solid block.
dont do while (true)
can you tell what youre trying first
i still don't know how to proper way to use getBlockFromRaycast i think. I just think of this as a raycast from the name itself that can be used with vector maths for directions
i'm interacting (onUseOn) with a log block like from the bottom, and i want to get the height of a tree starting from bottom. I mean this works fine, but i think there's proper way to do it, instead of manually getting the block above from one another.
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_13_0.Block.html#above
well you could try for loop
Block.above() returns Block, and you can specify the steps too
like Block.above(3) returns the block thats 3 blocks above
hmmm, i think its the same as the current one😅 or i'm wrong
well
while(true) can be a bit painful to manage in the future
one wrong oopsie and youll face Out of Memory crash
i thought getBlockFromRaycast stops when it detects there's a block that is not included in its options or excluded
let me check
true
i just checked and block raycast returns when the filter is passed
not sure if the raycast excludes the caster
but considering its from dimension class, its highly likely that it doesnt exclude the caster
const topMostBlockRay = player.dimension.getBlockFromRay(blockInteracted.location, {x: 0, y: 1, z: 0}, {
excludeTypes: [
MinecraftBlockTypes.JungleLog.id,
]
}) ?? undefined;
if(!topMostBlockRay) return;
const topMostBlock = topMostBlockRay.block;
console.warn("Height: ", (topMostBlock.location.y - blockInteracted.location.y) + 1, "\nID: ", topMostBlock.typeId);
i mean this works, but it still including the air block to not stop the raycast
well this does the same anyway
but isn't getBlockFromRay more efficient to call instead of just calling getBlock or above(), and traverse to whatever direction you want?
honestly i cant tell
but Block.above() is called directly from the block
while raycast is called from dimension
hmm true, i think i'll just stick with Block.above(). As long as it gets the job done 
someone help #1284420155870416926
rays is the most inefficient way of doing it
When a player places an armor stand does it count as a player spawn?
Mb
Entity
Entity spawn
yeah...
Ok
nvm,
U didn't even talk
yo guys, sliders (modal form) support decimal values? like 0.1, 0.5 etc
yuh...
alr ty
mhm lmao
ty anyways
it does, but it doesnt show the decimals in the form
system.runInterval(() => {
const dimension = ['overworld', 'nether', 'the_end'].mab(dim => {
for (const entity of world.getDimension(dim).getEntities()) {
const inv = entity.getComponent('inventory')
const item = inv.container.getItem
if (!item(0)) entity.setDynamicProperty('0', false)
if (item(0)) {
const itemType = entity.setDynamicProperty('lastItemType', item(0).typeId)
if (item(0).typeId === 'minecraft:stick') {
entity.setDynamicProperty('0', true)
if (item(0).typeId != itemType) entity.setDynamicProperty('0', false)
}
}
}
})
})```this should save the last item typeId, if the item has been changed it will be detected and set the dynamic property false, hmm
wait.
[0] not (0) when wanting to grab the first element of an array, but your use case here is not correct either way.
getItem is a method not a property and it returns a single Itemstack and not an array. It also expects a slot value to know which ItemStack to return if the slot is defined.
i had to make the script set the dynamic property value to false when the item is changed,
like u put a stick in that slot, then u change the stick into a cobblestone, the script will detect the item has been changed and turn off that value
Your code is wrong.
i know
alr tysm
so the problem is another one in my code lol, ill try to solve it
the entity has 3 slots, 0 and 1 and 2,
should i use getSlot(0)?
Are you wanting to check a specific slot or all of them?
Map
specific slot,
Which one?
0, 1 and 2
each one will have its own system
Because u are going to use standalone function
If u didn't bind it to its object"this"
like if (item(0)) {,,,} // if (item(1)) {,,,} ,,,
getItem(0) or getItem(1) or getItem(2)
all of these 3 slots have their own section
0 will work differently than 1 and 2, ext
if (item(0)) { entity.setDynamicProperty('0', true); codes/// }
if (item(1)) { entity.setDynamicProperty('1', true); codes/// }
if (item(2)) { entity.setDynamicProperty('2', true); codes/// }
☠️
Here, just use this and modify it to handle whatever condition you need it to handle:
system.runInterval(() => {
const dimensions = ['overworld', 'nether', 'the_end'];
dimensions.forEach(dimName => {
const dimension = world.getDimension(dimName);
for (const entity of dimension.getEntities()) {
const inv = entity.getComponent('inventory');
if (inv) {
const container = inv.container;
const slot0 = container.getItem(0);
const slot1 = container.getItem(1);
const slot2 = container.getItem(2);
// Handle slot 0
if (!slot0) {
entity.setDynamicProperty('slot0', false);
} else {
const itemTypeSlot0 = slot0.typeId;
entity.setDynamicProperty('lastItemTypeSlot0', itemTypeSlot0);
if (itemTypeSlot0 === 'minecraft:stick') {
entity.setDynamicProperty('slot0', true);
} else {
entity.setDynamicProperty('slot0', false);
}
}
// Handle slot 1
if (slot1) {
// Logic for slot 1
const itemTypeSlot1 = slot1.typeId;
entity.setDynamicProperty('lastItemTypeSlot1', itemTypeSlot1);
if (itemTypeSlot1 === 'minecraft:stone') {
entity.setDynamicProperty('slot1', true); // Example condition for slot 1
} else {
entity.setDynamicProperty('slot1', false);
}
}
// Handle slot 2
if (slot2) {
// Logic for slot 2
const itemTypeSlot2 = slot2.typeId;
entity.setDynamicProperty('lastItemTypeSlot2', itemTypeSlot2);
if (itemTypeSlot2 === 'minecraft:diamond') {
entity.setDynamicProperty('slot2', true); // Example condition for slot 2
} else {
entity.setDynamicProperty('slot2', false);
}
}
}
}
});
});
That s extra code ☠️
They said they wanted to handle each slot (0, 1, and 2) differently. That is a baseline to do that.
I just see it s a simple code dosen't need all that complications
Bro the problem with him , is that even if u wrote him 1000 lines of code he won't use them
use switch
Don't want him to use it. I want him to understand the logic because the code isn't written for him to actually use out of the box. They will be required to make changes to it. It's to help them learn.
hm,
if the item doesn't stick, it will turn off that dynamic property slot, but the second item ( cobblestone ) will turn that on
stick will turn it off bec the slot doesn't have a stick, the cobblestone will turn it on bec it has a cobblestone
am i wrong?
how
He didn't
Imagine expecting someone to learn in 5 minutes.
No i mean ._. i wrote him simple code yesterday
He didn't understand it s purpose
It was simple and direct
The logic for what each slot does will be up to you. The code I shared simply shows one way of handling conditions per slot.
how about using switch just like that dude saying? does anyone know how switch actually work?
🗿
A switch statement is nothing more than an if/else statement.
take a value and compare it to multiple cases
allow em to be curious of other methods
switch (x ) {
case 6 /* as example u can put strings too and other things /* : console.log("6");
break ;
}
switch(defined_variable) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// You can add more cases as needed
default:
// Code to execute if none of the cases match
}
once they realize the code gets too wordy, they start to get stressed and find other way to shorten it, then ask/try
expression?
no
Chat gpt..
system.runInterval(() => {
const dimensions = ['overworld', 'nether', 'the_end'];
dimensions.forEach(dimName => {
const dimension = world.getDimension(dimName);
for (const entity of dimension.getEntities()) {
const inv = entity.getComponent('inventory');
if (!inv) continue; // Skip if no inventory component
const container = inv.container;
for (let i = 0; i < 3; i++) { // Check slots 0, 1, and 2
const itemStack = container.getItem(i);
const itemType = itemStack ? itemStack.typeId : null;
entity.setDynamicProperty(`lastItemTypeSlot${i}`, itemType);
switch (i) {
case 0:
entity.setDynamicProperty('slot0', itemType === 'minecraft:stick');
break;
case 1:
entity.setDynamicProperty('slot1', itemType === 'minecraft:stone'); // Example logic for slot 1
break;
case 2:
entity.setDynamicProperty('slot2', itemType === 'minecraft:diamond'); // Example logic for slot 2
break;
}
}
}
});
});
switch (key) {
case value:
break;
default:
break;
}
it take a value
not particularly a expression
dose using switch check the type? (like ===)
It uses loose equality (==).
make sense
@distant tulip what did u say?
huh?
?
why the error?
should i use that system? i mean u know scripts more than me so,
Up to you. You just need to add the logic for how you want to handle each slot.
actually, all slots will work the same but, each one will have its own property
☠️
u forgor break
all 3 slots work the same
slot0 has s0 property
slot1 has s1 property
//
its like a leak in cases
once it went through the line, it tries to continue the following lines
i did it on purpose to test for multiple cases
uh,
with tsconfig.json
That's not what you said earlier.....
Still, the switch statement will be fine.
yah im dumbas²
It uses strict equality. I was mistaken.
it is not @remote oyster lol
it does ===
My tests messed me up
the only difference between them is
if slot0 has an item, the item will start smelting, but when u add another item to the second slot, it will start smelting from 0 not with the first slot
lets say first slot almost smelted, and u put another item inside the second slot, it will start smelting the second item from 0 not instantly smelted with the first slot u know what i mean
Not based on that screenshot from Minato. If that were the case 1 and "1" would not return "1 as a string", and so forth. So it's attempting to change the type from a number to a string where the types match.
It still has to match types
if there's no break
Yes, but the cases still have to match or it can't execute the code.
1 does not equal "1" unless you change the type.
that because you stooped the code
it depend of the order
case is just like a door, and all cases are connected, regardless of the case, cuse one of it was entered already
that's the reason why I'm making different properties for each slot,
thats the downside of switch/case
it is useful
true
That seems like a flaw in my brain.
you can test for multiple cases (none strict ==) and unique ones (strict ===)
switch (1) {
case "1":
console.log("hello from string '1'");
case 1:
console.log("hello from number 1");
}
This just returns the second case for me. Same results when I add breaks.
So now I'm wondering if this is something specific to the js engine.
Which is why I'm thinking it's a flaw lol.
I'm so confused now 😭
wtf did i do the first time
LOL
🤨
Is it the variable causing the symptom?
(e => {
switch (["bleed", "speed"].map(s => e.hasTag(s)).toString()) {
case 'true,false':
break
case 'true,true':
break
case 'false,false':
break
}
})
brrk
But why does it execute each case in that switch statement but the other switch statement only executes the exact type match.
its le switch leak
The behavior should be identical
Lol
I think the switch statement has a serious bug.
is it the order or something
Swap the order in the other one and see.
me when case (()=> false )():
That's cool :v. Cool version of if/else
it is
i am never using switch without break lol
this is confusing
Yea bro I'm convinced that's a bug and not intended behavior.
well, the break is allowed there, so thats it's purpose... idk anymo
i once used that 'bug' when constructing a string
Living dangerously I see. A man of culture.
well, it sure is interesting
Random Number Generator.
I'm definitely convinced it's a bug lol. I wonder if it's one of those situations where they shipped it as a "feature" 🤪😂🤣
Try creating variable with the same name in each cases without break
Did u know how to make it?
I've done it before. It's pretty simple. Just need to create a list of messages that you want to randomly select from.
No , u go to check this #1284086788989648928 message
I want do it at world sender
I don't understand this thing
Bc I'm just a beginners
I did some research.
The behavior you're observing has to do with how switch statements handle break statements. Without a break, the switch statement exhibits fall-through behavior—meaning that once a matching case is found, the code will continue to execute all the subsequent cases, regardless of whether they match or not, until a break is encountered or the switch block ends.
So it does use strict equality unless you experience fall-through behavior. Then equality goes right out the window unless you use breaks lol.
EntityQueryOptions
oh ye
i miss this brain cell burning
RPG vibes
when you don't use breaks, switch behavior breaks
got it. lol
good to know
unless it's intentional behaviour
switch (typeof _subject) {
case 'boolean': case 'number': case 'undefined': return _subject;
case 'string': return _subject; case 'bigint': return _subject?.toString?.();
case 'symbol': return Symbol.keyFor(_subject) ? `Symbol.for(${_subject.description})` : _subject.toString();
case 'function': return _subject.toString()
};
//object type gets cooked here
how to create a border in 10k 10k and in -10k and -10k please help me
if (inborder) saveLocDim(player)
else player.teleport(...getLocDim(player))
in runInterval
for the visual
high:10000px;
width:10000px;
border: 2px dotted red;
🤡
how to create a border in 10k 10k and in -10k and -10k please help me
And for the sound:
<audio src='err404.m4a'>
I believe 🤡
already answered
xD
If you're comparing exact values it's generally more intuitive and performant to use a Map or plain JavaScript Object. Switch statements fall into the same category as == does of "I'm definitely going to cause a very hard to troubleshoot bug if I use this" lol
replies 'nuh uh'
Yea it wasn't for me. It was for someone else, but when I do use switch statements I typically isolate each case under its own functions for maintainability. Keeping the lines between the breaks and cases at a minimum. Makes it manageable and you don't have that issue you mentioned.
Im making a freeze effect and I want to set a freeze texture to any entity, any idea to do this? idk if this is possible with scripting
playerpermission movement
texture, texture
not the movement xd
I want to set a freeze texture to any entity
meanwhile
You cant dynamically change a texture via scripting
I recommend #1067869022273667152 or #1067869590400544869 if you wanna learn about texture variations
k
is there a way to fix the mismatch between server-ui and server for all files cuz i dont feel like adding @ts-ignore everywhere https://i.imgur.com/TVdDEji.png
#1279063742994317404 message
Replace the version with your actual version
thanks
How do you fix this error?
[Scripting][error]-Plugin [Witchery Expansion - 1.0.0] - [main.js] ran with error: [SyntaxError: expecting ':' at blocks.js:5
]
[Scripting][warning]-Script reload did not re-register 'fm:block_interact' custom block component
world.beforeEvents.worldInitialize.subscribe(initEvent => {
initEvent.blockComponentRegistry.registerCustomComponent("fm:block_interact", {
const player = itemEvent.source;
const block = eventData.block;
if (block.typeId === "fm:mana_generator") {
if (itemEvent.itemStack.typeId === 'fm:evil_amulet') {
system.run(() => {
player.dimension.runCommandAsync('summon zombie');
}
}
}
});
});```
is there a way to get the direction the player is moving
for instance; if the player is facing north and moving south, is there a way to get it
is there a way to create a block placing system where a block can be stackable? first it would start off as a vine tip then when another vine tip is placed under the original vine tip it would change to a vine base and so on
my script dont work help plz
your script doesnt work because is made with chatgpt hehhe
chatgpt is never that good prolly a specilized ai
how do i use the addItem for potions
no do u think it looks good bru
cuz it dont work
get potion item component
const item = new ItemStack("minecraft:potion{Potion:swiftness}", 1)
item.getComponent("minecraft:potion").typeId
inventory.addItem(item)
idk how to asign the effects
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_14_0_beta.ItemStack.html#createPotion code examples attached there
import {
MinecraftPotionEffectTypes,
MinecraftPotionLiquidTypes,
MinecraftPotionModifierTypes,
} from "@minecraft/vanilla-data";
is not working anymore or do i have to import it into my manifest
ohh
Well technically you can use it via a single file or bundle it... https://jaylydev.github.io/scriptapi-docs/latest/modules/_minecraft_vanilla_data.html#md:external-minecraft-library
what is the javascript type?
it's not a native module, but it is a module
since it isn't built into Minecraft you have to include it in your scripts folder manually and either import it by file path or use a bundler
ohh alright
hmm, how about making it simpler,
each item will have it own dynamic property so when u put a stick, the dynamic property of it will be saved, when u replace it with something else like cobblestone, it will start a new dynamic property, when u put back the stick it will complete the srick dynamic property
yah that looks stupid, but i like it its so much simpler than making switch or saving last item id
how do you create an explosion with scripts?
system.runInterval(() => {
const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
for (const entity of world.getDimension(dim).getEntities()) {
if (entity.typeId === 'exe:grinder') {
const inv = entity.getComponent('inventory').container;
const item0 = inv.getItem(0);
const stick = entity.getDynamicProperty('stick')
const slot0 = entity.getDynamicProperty('slot0')
entity.setDynamicProperty('stick', 0)
entity.setDynamicProperty('cobblestone', 0)
if (!item0) entity.setDynamicProperty('slot0', false)
if (item0) {
entity.setDynamicProperty('slot0', true)
if (item0.typeId === 'minecraft:stick') {
entity.setDynamicProperty('stick', 1)
console.log('slot0HasStick')
} else entity.setDynamicProperty('stick', 0)
if (item0.typeId === 'minecraft:cobblestone') {
entity.setDynamicProperty('cobblestone', 1)
console.log('slot0HasCobblestone')
}
if (stick === 1) world.sendMessage('Stick')
if (slot0 === true) world.sendMessage('Item!')
}
}
}
})
})```so messy, ik
but it should work like how i want
console.log isn't sending a log for some reason, i think its console.warn right?
YESS
is there a way to get the direction the player is moving
for instance; if the player is facing north and moving south, is there a way to get it
Facing direction can be acquired through the player's y-rotation (use getRotation). Movement direction is a matter of plugging the player's velocity into an atan2 function, then multiplying by 180/π if you want degrees. I can never recall the correct order of arguments though.
@scarlet sable ?
just wanted to dm
If you're unsure what atan2 is, I recommend looking it up! Fascinating function that is
For more context: You would pass in the player's z-velocity and x-velocity into it, acquired from the getVelocity method (I neglected to mention this earlier, whoops)
JavaScript has a native atan2 through Math.atan2(), though it does return an angle in radians IIRC
U know that default case exist right ?
Well, radians are superior, so it only makes sense 
export function projetil(entity) {
const
family = entity.getComponent("type_family").hasTypeFamily("projetil"),
family_range = entity.getComponent("type_family").id.split("range:")[1];
switch (family_range) {
case "1"
entity.runCommand("say range1");
break
}
}
help me
I don't know how to do it in const family_range
Is const and family = on different lines?
yes, but there is no problem
is there a way to summon fireballs via script
export function projetil(entity) {
const
family = entity.getComponent("type_family"),
family_range = entity.getComponent("type_family").id.split("range:")[1];
if (!family?.hasTypeFamily("projectile")) return;
switch (family_range) {
case "1":
entity.runCommand("say range1");
break
}
guys
how can i use lockMode or ItemLockMode to lockup a specific item?
item id:
exe:place_holder
anyone just show me an example how to lock that item, after the item is locked, it cannot be moved or dropped and kept on death
and the most important thing is,
putting that locked item inside of entity inventory
Does this returns info about addon of items loaded in the world ort just vanilla stuff?
It includes custom items and blocks
Does anyone know how to do this, when you mine any block (like stone), it will create a small explosion, like breaking the surrounding blocks
I was too focused on details xD, thx btw
you can use the player break block event, filtering for stone blocks, i.e.
world.afterEvents.playerBreakBlock.subscribe((e) => {
// code
}, { blockTypes: ["minecraft:stone"] });
Does anyone have a way to have a player break a block through the api and not physically ingame?
#1284806985426014239
help #1284802627153956904
#1284815845889015869 ^
cross posting 📈
sorry my bad
minato
i need you
if (player.typeId !== 'minecraft:player' || !player.hasTag('vip')) return;
how can i make that if a player don't have the tag vip
it return
why not just do if statement for hasTag only
uh
i want make a script that active keep inventory for only the tag "vip"
world.afterEvents.entityDie.subscribe(({ damageSource: killa, deadEntity: player }) => {
if (player.typeId !== 'minecraft:player' || !player.hasTag('vip')) return;
const inv = player.getComponent('inventory').container;
const location = player.location;
for (let i = 0; i < inv.size; i++) {
const item = inv.getItem(i);
if (item) player.dimension.spawnItem(item, location);
}
const equippable = player.getComponent("minecraft:equippable");
["Head", "Chest", "Legs", "Feet", "Offhand"].forEach((e) => {
const item = equippable.getEquipment(e);
if (item) player.dimension.spawnItem(item, location);
});
player.runCommandAsync('clear @s')
})
though idk the issue of this if statement
is it not working

Can you help me
import { world, EquipmentSlot, EffectTypes } from "@minecraft/server";
world.afterEvents.entityHitEntity.subscribe((data) => {
const hitEntity = data.hitEntity;
const damager = data.damagingEntity;
if (damager && damager.typeId === "minecraft:player") {
if (damager.hasTag("user")) {
const inventory = damager.getComponent("minecraft:inventory");
const mainHandItem = inventory.container.getItem(EquipmentSlot.mainhand);
if (mainHandItem && mainHandItem.typeId === "minecraft:netherite_sword") {
applyEffectToEntity(hitEntity);
}
}
}
});
function applyEffectToEntity(entity) {
if (entity && entity.hasComponent("minecraft:effect")) {
const slownessEffect = EffectTypes.get("minecraft:slowness");
entity.addEffect(slownessEffect, 100, 1, false);
}```
What is the error why effect is not applying to entity on hit?
turn content logs on
theres no such thing as effect component
umm, d u know how to lock a specific item?
did you really ghost ping me
ItemLockMode or itemStack.lockMode
container.getSlot(0).lockMode = 'inventory'
help me
is that typescript
no js
How is that line not working tho...
yeah it should work??
IT WORKS
moyai
BUT
UwU
🗿
I want to take those who don't have that tag, not those who have it
ghost ping
eheheheheheh
if (player.typeId !== 'minecraft:player' || !player.hasTag('vip')) return;
pls
I redo the script
if (player.typeId !== 'minecraft:player') return;
if (player.hasTag('vip')) return
resolved
slot0.setItem('minecraft:stick'); returns undefined
slot0.setItem(new ItemStack('minecraft:stick'))?
import { ItemStack, system, world } from "@minecraft/server";
world.afterEvents.playerSpawn.subscribe((data) => {
let player = data.player
let inventory = player.getComponent("inventory");
let slot = 8;
let item = new ItemStack("minecraft:stick", 1);
item.lockMode = "slot";
inventory.container.setItem(slot, item);
});
@untold magnet use this, tell me if it works
the item is locked but, u still able to take them out using hoppers
i should make it not shipped by hoppers
idk
is that an entity?
use lock to inventory and stop he hopper thing
i better use another way, making a custom UI with 3 slots only
Is there a module to import from
For the ```js
world.events.blockPlace.subscribe(handleBlockPlacement);
world.events.blockBreak.subscribe(handleBlockDestruction);
world.events.explosion.subscribe(handleExplosion);```
i have an idea,
i dont have to put every single script inside of one huge script and get infinite input lag,
block and break are already in the @minecraft/server module?
explosion you can do aswell
world.afterEvents.playerInteractWithBlock
world.afterEvents.playerBreakBlock
oh
yep
Does it need .subscribe?
yh it does. I just did a example for you
is explosion changing to afterEvents?
nvm
ty anyway
Thx
Where can i see modules of “@minecraft/server”?
Is there a replacement for
‘BlockLocation’ module ? Cuz it outdated
cant use it in minecraft scripting api
many javascript functions are locked out
This is bad
though you can use Date.now()
its one of the stuff that minecraft didnt lock out afaik
there could be other stuff though
you can use millisecond precise timing with that instead of using ticks (as long as youre not running it in tick-based runs)
Btw Write here @distant gulch
oh yh i remember that happending to me lol
he used a unsafe system.runIntervel
with a while loop inside am guessing
If it is a realms I think you can only use it once
and if it is a normal world, verify that the cheats are activated
are you op?
Yo guys to get the amount of damage that was applied to my entity is it
world.afterEvents.entityHurtEntity.subscribe((event) => {
const getvalue = event.damage.valueOf
});
or
world.afterEvents.entityHurtEntity.subscribe((event) => {
const getvalue = event.damage
});
how to make particles? Using JS?
Not like how I mean by having this tag makes this particle show up or summons this particle
dimension.spawnParticle("kimetsunoyaiba:test")
Like that?
player.getComponent("health");
Thx
bra why does mc have to crash for every minor error like unknown variable or syntax
the entire mc app crash or js crash
i hate it when i make an error, and all of my custom components stop working
i get like 10 error messages for a single comma i missed
try typescript / @gaunt salmon
how do i set item durability
How do i set a item in a players main hand
mc app
player.getComponant("equippable").setEquipment("Mainhand", item)
const inventory = player.getComponent("inventory").container;
const heldItem = player.getComponent('equippable').getEquipmentSlot("Mainhand")
const itemInHand = inventory.getItem(heldItem);
inventory.setItem(heldItem, itemInHand);
inventory.getItem takes a slot number
for some reason i get a error for this
ohh
the same with inventory.setItem the first parameter is a slot number
does getSlot do the same thing?
it has to be?
yes
then how can i set a item that am holding in my main hand?
am guessing this is "item"
player.getComponent('equippable').getEquipmentSlot("Mainhand")
Do you guys know how I can enchant both main hand and offhand items? at the same time?
what do you mean you're holding? isn't it already in your main hand?
Using command or via script
im tryna rename the item that is in your mainhand
Documentation for ScriptAPI - v1.21.0
okay but is it possible via command as well?
only the main hand with commands
Bummer 😕
const equipment = player.getComponant("equippable")
const item = equipment.getItem("Mainhand")
item.nameTag = "whatever"
equipment.setItem("Mainhand", item)
.
yeah it works, thank you
entity custom components when...
Real
I don't think it's necessary
having a onTick and onRandomTick for entitys just like blocks would be nice
instead of doing hacky shit'
Entity on tick? Thats just a timer
yeah im using that right now
Im not seeing the "hacky"
file too long maybe?
import { system } from "@minecraft/server";
system.beforeEvents.watchdogTerminate.subscribe((event) => {
event.cancel = true;
console.warn(`[Watchdog] canceled server crash`);
});```
world.afterEvents.entityHurtEntity.subscribe((event) => {
const getDamageValue = event.damage;
world.sendMessage(`the amount of damage applied to the entity is ${getDamageValue}`);
});```
Nah, I just shared it for cursed stuffs, i think it's just a not-big-of-a-deal responsiveness for minecraft window's screen size
Has anyone done a lock on target system? Like the player's third person camera locks on a entity within a certain range of the player? If you're familiar with elden ring or dark souls type of locking
what is the most efficient way to get the entire player's inventory and set lore for each items
I just learned that itemStack doesn't have ID or even hash for each itemStack... How do I compare if one another is the same? I mean i have an idea, but i think someone could have made it simpler
iirc theres a "compare itemstack" in #1067535712372654091
Oh that's a bunch of checking
Thanks anyways!! I'll try to create one that is short, if my brein go boom, I'll just stick with that
where does the structure manager class store the structures
Is it possible to add paramaters to the vibration:listener component of the Warden because I want to add distance to it vibration detection range it seems the default is 16 blocks radius
Through scripting API of course
If you use the world StructureSaveMode then In the world's leveldb database along with all the other world data. Just like the /structure command
Structures are very useful. There's the world building of course, but it also allows you to actually store ItemStacks and Entities, with all their data, as dynamic properties
how to test how far above the ground player is?
you can use the getBlockBelow() function and get the differences between the location of the block the function returns with the current block location the player is on
once we can read and write nbt, structures will become obsolete
Well we're never going to get raw NBT access, but as the API develops I'm sure we'll get most capabilities eventually.
They'll still be plenty useful, we just won't need to use them as a workaround for so many things.
Can you disable a spawnrule through scripting API
I want to prevent an entity from spawning ones a condition is fullfilled
maybe just detect entitySpawn then kill it afterwards
NBT data in Java for their add-on equivalent stuff is gone now
You could use runCommandAsync and run /gamerule domobspawning false
that's not what he meant
But I want a specific mob
you can use entitySpawn event and Entity.remove()
its not perfect but it will work
Thanks again
@glacial widget Hello mate check your dm
When you ask a question via DM, you are restricting the total number of people who can help you from all potential server members to just one. Asking in the public channels is the best way to get a good, community-sourced answer to your question, allowing other observers to give their input.
While you are certainly welcome to DM with each other, please be aware it is against our rules to send unsolicited DMs requesting help.
i was out my bad
it's gone for just items, but got replaced with a much more powerful components system
there is a oninteract for mobs?
We have events for player interact with entity, if that's what you mean
but afaik it's still in beta api
I meant this
like a normal npc
@unreal cove can you make me an example
pls

bc.world.afterEvents.playerInteractWithEntity.subscribe(e => {
const { itemStack, player, target } = e;
// your code here
})
bc.world.beforeEvents.playerInteractWithEntity.subscribe(e => {
const { itemStack, player, target } = e;
// your code here,
// PS: you can cancel this event
})
thx musashi
help
import * as mc from '@minecraft/server';
mc.system.runInterval(() => {
for (const entity of mc.world.getDimension("overworld").getEntities()) {
projetil(entity);
}
});
export function projetil(entity) {
const family = entity.getComponent("type_family");
if (family.hasTypeFamily("projectile") && family.hasTypeFamily("attack")) {
switch (family.hasTypeFamily()) {
case "ball":
console.warn("ball");
break
}
}
}
[Scripting][error]-TypeError: cannot read property 'hasTypeFamily' of undefined at projetil (wg/commands.js:11)
at <anonymous> (main.js:43)
player.runCommand(`/tellraw @s {"rawtext":[{"text":"Not enough mana"}]}`)```
hmm, i dont know why the command inside wont run, am i missing something or....
The syntax is correct. If it's not running then it's most likely not getting called.
PS: Instead of the tellraw command, use player.sendMessage. It's a native method for sending messages.
player.sendMessage("Not enough mana");
try const family = entity.getComponent("minecraft:type_family");, sometimes it doesn't work without the minecraft:
k thanks
For those using ES Lint we publish some rules that can help catch these things 🙂
i think it could be the slash
i have a crazy theory, if we can replicate the method used by the game to place biomes with JavaScript, then we can create a dimension.getBiome(location) function
yeah
it is possible
same as how it was done with slime chunk
Same can be done with structures as well
oh, is there already a slime chunks behavior pack out there? i tried to make one but couldn't get the Mersenne Twister to work
i know it's possible, because chunk base does it, but is it possible with the script API?
there is
it would be interesting to make an addon that highlights the spawning spots of a fortress
it would require some serious code digging tho
i wonder if i can use that in my map?
not mine
yeah i know, i was reading the readme file, and it seems complicated
not really
i thinks the wiki have some infos
Web app to visualize slime chunks in MCPE. Contribute to depressed-pho/slime-finder-pe development by creating an account on GitHub.
yeah i read that page, it's what led me to attempt making my own slime chunk finder
the part that got me confused is the random number part
why do we need it i the chunks are constant across seeds
bedrock edition uses the mersenne twister which is a random number generator, it takes a seed which is a weird number to determine if a chunk should spawn slimes or not
i know but that should make it random across seeds. no?
i should look into MersenneTwister
the different between java and bedrock is that in java the twister seed depends on the world seed while im bedrock it's constant
the slime have its own seed?
this line explains everything
there is that weird function called mul32_lo which generates the seed for the twister and then it converts it into a true or false
but of course because the density of slime chunks is 10% of the world there this little modification
that seem to multiplies the two 32bit integers and returns the lower 16 bits of the result
i black boxed the the mul32_lo function and the mersenne twister to make it easier for me to understand
that explains the name lol
yeah
lo for lower (probably)
the general idea is clear but the details is what need to be looked at
the mersenne twister is the real boss here, there is no way i understand what it does
i read that nonsense twister
It was developed in 1997 by Makoto Matsumoto
us 27 years later
i did not know that there is a do statement in js ._.
maybe it's just a fancy way of writing a while statement
Do while?
Every language has that
i never use while, so it makes sense why i never encountered that
do..while is similar to while except that it always executes its loop body at least once. And is also harder to make sense of
For the condition being below the loop body hides it, you would need to reach the end of that block to understand when it should loop
So I've kinda been away from minecraft since early June (Busy building the house) but they went and updated Education Edition on me and now my Homeschool remote pack isn't working properly so I need to fix it. Educaiton is now in v1.21.05 so I assume I'm stuck working with 1.21.0 for everything. Previously I was using education edition v1.20.10 and I had enabled experiments for it (though in the update that has gotten trickier since that RP now seems to mess with other sections of the UI if I leave it enabled.) Anyway, v1.20.10 beta and I was using server 1.4.0 beta and server-ui 1.2.0 beta.
Now I need to figure out what I need to change for 1.21.05. So does that mean I should just try updating the manifest to server 1.11.0-beta? Looks like server-ui is still the same.
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]
WOW! Who is responsible for this, at a glance my jaw dropped Thank you for this.. Thank You for the link!
Education is just behind and they try to make it impossible to use experiments.
Which makes sense
rip
They have been getting better at keeping up lately though. Not like when we were still in 1.14 and everyone else was about to get 1.18
so i have broken it down, these are the bits needed for sime chunks
nice
time to test it and see if it works
you can test outside the game
dude! it works perfectly!
i used madHatter's technical resource pack to see where the slime chunks are
but those chat messages use the script that i modified
now this is some black magic shit
Bedrock's slime chunk positioning is the same for every world according to the wiki
It is correct
Camera command should be added rotation parameter
And FOV too for dolly zoom 🤪
is this java or bedrock?
look at the top left corner of discord lmao
java
was almost about to say, as if mojang would not add some pointless, creativity limiting, stupid limit to the rotation parameter so you can not go above a certain value
i mean you can already make stuff that breaks the limit
p sure this one is cuz of technical limit
no
its not
it was that way before, and it worked fine mojank decides to fuck it up just because they can an update later
sorry for my language. Im just expressing my frustration
the creativity limits are for vanilla stuff (vertical slabs for example) while the camera is for commands & scripting API
iirc the rotation value existed when it was beta but it got removed on release, correct me if im wrong
why would they limit creativity for commands and scripting api?
Probably to avoid unexpected behavior for other devices?
But yeah, some were unnecessarily restricted.
Does anybody know how to get the player block above the player all the way to height limit?
dimension.getTopmostBlock
import { world, system, Entity } from "@minecraft/server";
system.runInterval(() => {
for (const dimension of dimensions) {
const block= player.dimension.getTopmostBlock(player.location, player.location.y);
for (const block of dim.getEntities()) {
if (!block && player.hasTag("oni")) {
entity.runCommand("function burn_to_ash")
}
}
}
}, 1);
It doesn't work help
player is not defined
Either is dimensions
import { world, system, Entity } from "@minecraft/server";
const dimensions = ["overworld", "nether", "the end"];
system.runInterval(() => {
for (const dimension of dimensions) {
const dim = world.getDimension(dimension);
const block= entity.dimension.getTopmostBlock(entity.location, entity.location.y);
for (const block of dim.getEntities()) {
if (!block && entity.hasTag("oni")) {
entity.runCommand("function burn_to_ash")
}
}
}
}, 1);
How about now?
Now where are you defining entity?
Dimensions
?
I'm lagging
I'm not that advance yet Idk
Try with this ```js
import { system, world } from "@minecraft/server";
const dimensions = ["overworld", "nether", "the_end"].map(d => world.getDimension(d));
system.runInterval(() => {
for (const dimension of dimensions) {
for (const entity of dimension.getEntities({ tags: ['oni'] })) {
const top = dimension.getTopmostBlock(entity.location, entity.location.y);
if (!top) entity.runCommand('function burn_to_ash');
}
}
});
Ight but later I got important things to attend to
What s new with script api ?
structure.delete(structureName);
structure.createFromWorld(
structureName,
dimension,
{ x: entityX, y: 318, z: world.getDynamicProperty("storagelocation").z },
{ x: entityX, y: 319, z: world.getDynamicProperty("storagelocation").z },
{ saveMode: "World", includeEntities: true }
);
do someone know a better way to overwrite a structure?
that's already great for me
Custom components ig
UIManager, and some beta to stable
found any solution for this?
getEntitiesFromRay?
mhm
That's the way. You can try to get it first if you're not sure if it exists
If its a custom entity, you can try using minecraft:on_target_acquired, then trigger an event that uses queue_command with "target": "other" to run a scriptevent command
I just thought of this
Like this
This is the event
ohh, yeah! I've also thought of that. But do i have to create an event to the target entity's bp or the "target":"other" is enough to run the command as a target? sry, I'm not expert in entity jsons
no
If you try to trigger the event directly on the target, then yes. But queue_command doesn't required that
alr, thanks! appreciate the help
I used it to run a command as the player when interacting with an entity
thats for my item db, users will need to do it not me
#1285580941963825234 message
bro does not know it💀
I wrote him a script in the link above. It has a bug. Please debug it.
no?
Bro does not know it 💀
world.beforeEvents.chatSend.subscribe((data) => {
const { sender: player, message } = data;
data.cancel = true;
if (!coooldowns[player.name]) coooldowns[player.name] = 0;
if (coooldowns[player.name] > Date.now()) return player.sendMessage("§cНе флудите!");
coooldowns[player.name] = Date.now() + 1000 * config.cooldown;
if (message.startsWith(config.prefix)) {
world.sendMessage(`[§gG§f] ${getRank(player)} ${player.name} » ${message.replace(config.prefix, "")}`);
} else {
const { x, y, z } = player.location;
for (const target of world.getAllPlayers()) {
const { x: x1, y: y1, z: z1 } = target.location;
if (Math.sqrt(Math.pow(x1 - x, 2) + Math.pow(y1 - y, 2) + Math.pow(z1 - z, 2)) > config.distance) continue;
target.sendMessage(`[§bL§f] ${getRank(player)} ${player.name}§r » ${message}`);
local & global chat
💀
player.id for cooldown would be more efficient than the name of a player. I only say that because I know names can be manipulated by hackers.
I thought you said chat ranks were useless and interfered with other add-ons? A change of heart?
wym
where do you see change of heart
Some months ago you mentioned it.
yes?
You made a complaint about using chat ranks and that they were useless and interfered with other add-ons.
I see you use it in the code above.
send me an ss
of it
Its in paradox server
Yes
well i changed my mind long time ago
Doesn't work :v
is this for me ?
if yes then can u explain this a bit ?
so you wanted a local chat or smt? local chat is in radius of 100 blocks, global is to everyone, you can setup local chat in config
ohh ok
can u explain how ?
wait im busy rn
i just want proximity chat
Voice chat?
why arent my scripts working now, is there a new version I need to use? Ive been using v1.14.0 I tried switching it to 1.14.0-beta and 1.15.0-beta and even 1.13.0 yet my scripts continue to not work
Send your content log
1 sec
Theres a ton of like non important errors btw
So ur gona have to use the find/search thing
2 MB of errors 💀
💀
clear your log and perform what yo have problems with
Just take a picture
idrk what im looking for
dont think its a script issue its gota be the version or wouldnt it show the script 'index' in the logs
but ive tried every version
do u have BP/scripts/index.js?
yeah
17:34:25[Scripting][inform]-Plugin Discovered [§l§cJujutsu Awakening | Survival Update | Addon BP] PackId [c7ee8989-14cc-44aa-9fdd-1c039b64b3f6_0.1.0] ModuleId [52992277-36e3-4ac6-a329-b3cfc84a34ce]
17:34:25[Scripting][error]-Plugin [§l§cJujutsu Awakening | Survival Update | Addon BP - 0.1.0] - failed to create context.
17:34:25[Scripting][error]-Plugin [§l§cJujutsu Awakening | Survival Update | Addon BP] - module [§l§cJujutsu Awakening | Survival Update | Addon BP - 0.1.0] requesting invalid module version [@minecraft/server-ui - 1.3.0-beta].
Available versions:
@minecraft/server-ui - 0.1.0
@minecraft/server-ui - 1.0.0
@minecraft/server-ui - 1.1.0
@minecraft/server-ui - 1.2.0
@minecraft/server-ui - 1.3.0
@minecraft/server-ui - 1.4.0-beta
@minecraft/server-ui - 2.0.0-alpha
17:34:25[Scripting][error]-Plugin [§l§cJujutsu Awakening | Survival Update | Addon BP - 0.1.0] - run failed, no runtime or context available.
or whatever file entry thats in manifest
I saw that im not having issues with my UI script though
Its my other script I didnt think that was an issue
il try fixing that tho rq
those are all the script related errors
- The error already tells you what version you need to use
- fix your manifest entry file
ok nvm
im stupid af
that was the issue 😭
I was gona leave that for later cuz i wanted to focus on my main scripts before I fixed any ui based ones but I didnt think that was actually an issue
Sad
😭
ur wlc
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]
oops wrong channel
Ok, I have a pack that summons an owned entity (currently does it all without scripts since this is for education edition and from a few version back.) However, I would really like if there were some way to automatically give the entity a nametag. I currently give the students the materials to be able to apply a name tag to their entity manually, however, this doesn't make them do it, nor does it let me know what the entity gets named or who it belongs to.
Is there some way, perhaps with scripts, that I could handle this name tagging? Perhaps I need to remove the whole operation into script but I'm not even sure where to start. I would also like to somehow apply a sign or nametag to other things when the scrip automatically does something for one of the students (for instance, I would love to have name tags on the barrels for the inventory control room.) Is this something scripting can do? Perhaps I need a special "nametag" entity that gets summoned at the inventory control locations. I'm not sure that would work for the Original issue I want to fix since that entity gets moved/teleported when the students move their "home" location. If it is possible, let me know and I'll open a thread to explore how.
Any error?
I can't really find the error since I have a whole addon to work with it but I'd say I don't have a clue
But it just does not work
I have to many errors to fix and it's being overshadowed
im so confused
{
"format_version": 2,
"metadata": {
"authors": [
"HiveLanky"
]
},
"header": {
"name": "Bedrock Plus Practice 1.21.3x2",
"description": "",
"min_engine_version": [
1,
20,
80
],
"uuid": "19eb4bb0-43fd-445b-9f23-ff267b730e70",
"version": [
1,
0,
0
]
},
"modules": [
{
"type": "data",
"uuid": "f7ed625e-1236-470d-8bc8-b05faaf90241",
"version": [
1,
0,
0
]
},
{
"type": "script",
"language": "javascript",
"uuid": "7465518a-22c8-4f93-89ab-90fa3fc8c569",
"entry": "scripts/main.js",
"version": [
1,
0,
0
]
}
],
"dependencies": [
{
"uuid": "73f2a58c-d909-4bd7-8e8f-6636711cdb1d",
"version": [
1,
0,
0
]
},
{
"module_name": "@minecraft/server",
"version": "1.15.0-beta"
},
{
"module_name": "@minecraft/server-gametest",
"version": "1.0.0-beta"
},
{
"module_name": "@minecraft/server-ui",
"version": "1.4.0-beta"
}
]
}```
this for some reason isnt working
"minecraft:inventory" in blocks
?
Installation for @minecraft/server-net
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Module '@minecraft/server-net' not found in stable.
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]
Description
This script checks whether a player has the hack "Nuker" enabled through the use of block break event.
Credits
These scripts were written by iBlqzed
#debug-playground
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]
"type": "script",
"language": "javascript",
"uuid": "50aba025-a867-4be0-b40c-b4235c314f60",
"entry": "scripts/main.js",
"version": [1,0,8]
}
],
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.14.0"
},
{
"module_name": "@minecraft/server-ui",
"version": "1.2.0"
},
{
"uuid": "df89e8c6-1e59-4344-85ea-6721c50e9c74",
"version": [0, 2, 0]
}
]
}
What's the latest version of Minecraft/server and the script
Script is [0, 0, 1] to my knowledge. Not aware of any specific versioning beyond that. Would definitely like some links/resources that shows otherwise if I am mistaken.
You can follow up on the latest version for the server module here:
https://www.npmjs.com/package/@minecraft/server/
Contains many types related to manipulating a Minecraft world, including entities, blocks, dimensions, and more.. Latest version: 1.14.0, last published: 8 hours ago. Start using @minecraft/server in your project by running npm i @minecraft/server. There are 52 other projects in the npm registry using @minecraft/server.
What was beforeEvents.playerPlaceBlock replaced by?
import { world, system } from '@minecraft/server';
world.beforeEvents.playerPlaceBlock.subscribe((event) => {
const player = event.source;
if (event.permutationBeingPlaced.type.id === 'minecraft:diamond_block') {
const min = 1200;
const max = 1300;
const randDelay = Math.floor(Math.random() * (max - min + 1)) + min;
system.runTimeout(() => {
player.runCommandAsync('say detected diamond block placed after ' + randDelay + ' ticks');
});
};
})
Wiki says it's fine but compiler doesn't like it
It's still the same.
Alr, does @gaunt salmon need to be updated?
Or does it just gather info from GitHub/Microsoft
Most likely needs to be updated. 1.20.30 just released today so I'm not sure if Jayly got around to it yet.
Alr
So like is there any info on how to set up the particle to use this?
Do i just use start variables or something else
you set variables without defining it in variables & curves
if you set variables and then click on # icon, youll see "unused variables" that you can manually adjust
those variables are what you can set with molangvariablemap
Hello I need help on running a function or command in this script you see ones the queen dies I want a certain type of entity to stop spawning and I don't know how to use the entity.remove
Here is my script
import { world, system, EntitySpawnAfterEvent, Player } from '@minecraft/server';
let queenAlive = true;
world.afterEvents.entityDie.subscribe((event) => {
if (event.deadEntity.typeId == 'cm:death_angel_queen') {
let queenAlive = false;
world.sendMessage('hello');
}
});
world.afterEvents.entitySpawn.subscribe((event) => {
if (event.entity.typeId == 'cm:death_angel' && queenAlive == false) {
// function or command here plsss
}
});
i have a trouble with this script. it works but only teleports me, and i need that it teleport entities with specific family types and that the entities do not get stuck inside the walls when teleporting
Is a custom cooldown on pearls possible?
yes
Can i show different scoreboards for each individual?
Oh crap I’ve been trying for a while and my noggin isn’t working I didn’t think it was possible
you tried to do with item json?
So my brain doesn’t work tn no I didn’t :(.
how you tried to do then
I haven’t really I wanted to see if it was possible in the first place and item json didn’t come to mind
You cant change items typed “minecraft:” even through the item json
you can do cooldowns with script api
You can make it to the custom items through item json
Here’s an example how to make it
Config.js:
export default {
items: [
{
typeId: "minecraft:ender_pearl", // Item ID
time: 30, // Cooldown (Seconds)
instantUse: true // Item Instant using yes/no?
},
{
typeId: "minecraft:enchanted_golden_apple",
time: 120
},
{
typeId: "minecraft:golden_apple",
time: 30
},
{
typeId: "minecraft:chorus_fruit",
time: 30
}
],
combat: { // Cooldown only on pvp mode?
enable: false,
object: "combat" // Scoreboard objective
}
}```
An example of importing from config.js and applying cooldowns.
let cooldowns = {};
world.beforeEvents.itemUse.subscribe((data) => {
const { source: player, itemStack } = data;
if (player.typeId !== "minecraft:player") return;
if (config.combat.enabled && getScore(player, config.combat.object) < 1) return;
for (const item of config.items) {
if (item.typeId == itemStack.typeId) {
if (!cooldowns[player.name]) cooldowns[player.name] = {};
if (!cooldowns[player.name][item.typeId]) cooldowns[player.name][item.typeId] = 0;
if (cooldowns[player.name][item.typeId] > Date.now()) {
player.runCommandAsync("title @s actionbar Wait §e" + ((cooldowns[player.name][item.typeId] - Date.now()) / 1000).toFixed(1) + " seconds.");
data.cancel = true;
} else {
if (!item.instantUse) return;
cooldowns[player.name][item.typeId] = Date.now() + item.time * 1000;
}
return;
}
}
});```
like this
@untold copper
you should use js world.afterEvents.itemCompleteUse.subscribe
To apply cooldown to the food
ohhh oky
i had this at the moment
world.beforeEvents.itemUse.subscribe(data => {
let player = data.source
if (data.itemStack.typeId == "minecraft:ender_pearl") system.run(() => {
spawnConfetti(player);
const container = player.getComponent('inventory')?.container;
const itemselect = container.getItem(player.selectedSlot);
if (!itemselect) return
const coold = itemselect.getComponent("minecraft:cooldown")
const d = coold.startItemCooldown(itemselect,10)
})
});
else if (heldItem?.typeId == 'minecraft:shears') {
player.sendMessage(`§7%farming.trim`)
block.setPermutation(blockPermutation.withState("runecraft:is_diseased", false));
block.setPermutation(blockPermutation.withState("runecraft:growth_stage", 0));
return;
}``` So confused. I'm unable to set the block state "runecraft:is_diseased" to false
I'm able to set it to true
Cus it immediately gets overwritten by the old permutation where you set the growth stage
is_diseased is still true in your blockPermutation, so when it does .withState("growth_stage"), it creates a new permutation where is_diseased is still true
hi there, what have changed to the interaction scripts? all my npcs stopped working
Is there no easy way to set multiple states at once?
yea I m on beta, but I think they changed something on the way it trigger now
.withState().withState()
ah I was trying to remember how to od that, thanks
entityRemove beforeEvent fires before an entity is removed. But surprisingly, a hopper can suck an item entity first before the event runs, so it's not valid anymore (I can't get the itemStack). 💀
For those who don't know, you can now see inform (messages from console.log) in content log gui by setting log level to info
sense it is not a toggle
dose that disable other console functions?
I think it's the minimum level, so on warn, it'll display warn & error, error is only errors, and info is info, warn & error
I might be completely wrong though
yeah
seem logical
Cant give different scoreboard sidebar to each players?
Yeah, that's been known for a bit. I don't know what they plan on changing, but they do want to rework things.
Ya, you can use it if you are beta player
i mean its easier to use than beta bc it doesn't changes the version numbers so it will propably work better if you are doing some personal addons
i thought its just server ui that got 2.0 alpha, by the reboot they are just gonna change syntax like before they did world.events to world.afterEvents/beforeEvents? or we will see new cool stuff
both, syntax is still same as its JS, but API design like methods and properties may change as well but we can expect new features as well
hello, is it possible to get the display name of a block?
Block.getItemStack().nameTag just returns undefined.
name tag is not traslation key for that identifier, but its custoable string
there is no way at the moment
oh okay, sadge
is that for vanilla blocks?
nope, it's for everything (custom and vanilla)
hmmm
well then no there is no proper way
but you can try using tile.identifier.name
Can i give each player a different scoreboard sidebar? personal scoreboard sidebar
custom translations from other devs and vanilla isn't really consistent.
like for example:
tile.log.big_oak.name=Dark Oak Log for vanilla, and for custom ones it's just tile.identifier.name
this could be done only by title and modifier UI
Well other devs is problem bc vanilla is being falttered
this is not current anymore
true (like me xp)
i'll just use this, and hardcode the vanila ones xp, thank you!

oh wait
that might actually work
thank!
how do i get the head slot item of an entity?
equippable.getEquipmentSlot(EquipmentSlot.Head).typeId only works for players from my testing
equippable component don't work on entities
use testfor command with hasitem property
const entity = world.getDimension('overworld').spawnEntity("floating:text",{
x: Math.floor(block.x),
y: Math.floor(block.y) + 1,
z: Math.floor(block.z)
});
uh
why it dosent work
block.location.x
okay
assuming block is a block
so Math.floor(block.location.x),
?
is it about breaking block to get items
yes
same for y and z
nop
odd
???
i mean weird
sorry i dont speak english
oh okay
odd = weird
you want the file?
nah
the script is not mine i only want to fix it
i am lost what part of that is related to breaking a block
but can you show the code that handles spawnEntity
const entity = world.getDimension('overworld').spawnEntity("floating:text", {
x: Math.floor(block.location.x),
y: Math.floor(block.location.y) + 1,
z: Math.floor(block.location.z)
});
there is no part of breaking block?
world.afterEvents.playerInteractWithBlock.subscribe(data => {
const block = data.block;
const player = data.player;
if (player.hasTag('cratesAdd') && block.typeId === 'minecraft:chest') {
let tags = player.getTags();
let Crates = [];
for (const tag of tags) {
if (tag.startsWith('Crates:')) {
Crates.push(tag.replace('Crates:', ''));
}
}
const entity = world.getDimension('overworld').spawnEntity("floating:text", {
x: Math.floor(block.location.x),
y: Math.floor(block.location.y) + 1,
z: Math.floor(block.location.z)
});
const particles = [
"minecraft:basic_flame_particle",
"minecraft:falling_dust_dragon_egg_particle",
"minecraft:falling_dust_red_sand_particle"
];
const randomParticle = particles[Math.floor(Math.random() * particles.length)];
entity.addTag("system")
entity.addTag("Crates");
entity.addTag(`Crates:${Crates}`);
entity.addTag(`cratesLocation:${block.x} ${block.y + 1} ${block.z}`);
player.runCommand(`summon bat ${Crates} ~~~`)
player.runCommand(`tag @e[r=2,type=bat] add Particle:${randomParticle}`);
player.runCommand(`tag @e[r=2,type=bat] add system`);
player.runCommand(`tag @e[r=2,type=bat] add Crates:${Crates}`);
player.runCommand(`tag @e[r=2,type=bat] add "cratesLocation:${block.x} ${block.y + 101} ${block.z}"`);
player.runCommand(`tag @e[r=2,type=bat] add Crates`);
player.sendMessage(`[Crates] §aSuccessfully created §e${Crates}.\n\nhold/right click item to add item`);
CratesDB.set(Crates, `position: ${block.x} ${block.y} ${block.z}`);
KeyDB.set(Crates, `Crates:${Crates}|position: ${block.x} ${block.y} ${block.z}`)
player.runCommand(`tag @s remove cratesAdd`);
player.runCommand(`tag @s add cratesAddItem`);
}
});```
bruh
NOOOOOO
addTag function and commands in the same time 😅

it's not my script
yo @hazy nebula

/*
- addon by long9boy (long9tpmcr), please dont modify code!!!
- Discord: @hazy nebula
- youtube: @long9tpmcr
- Copyright by long9boy©
*/
so? how this spawnEntity dosent work
- the player might not be in the overworld
in that case you can use player.dimension.spawnEntity
I'm just fixing it
that throw another type of errors
also playerInteractWithBlock
idk?
your entity is not summonable
edit the json
okay
that could be the reason
{
"format_version": "1.8.0",
"minecraft:client_entity": {
"description": {
"identifier": "pao:floating_text",
"materials": {
"default": "entity"
},
"textures": {
"default": "empty"
},
"geometry": {
"default": "geometry.armor_stand"
},
"render_controllers": [
"controller.render.floating_text"
]
}
}
}
mh
behavior one
okay
{
"format_version": "1.8.0",
"minecraft:entity": {
"description": {
"identifier": "pao:floating_text",
"is_spawnable": false,
"is_summonable": true,
"is_experimental": false
},
"component_groups": {
"despawn": {
"minecraft:instant_despawn": {},
"minecraft:explode": {}
}
},
"components": {
"minecraft:damage_sensor": {
"triggers": {
"cause": "all",
"deals_damage": false
}
},
"minecraft:nameable": {
"alwaysShow": true,
"allowNameTagRenaming": false
},
"minecraft:health": {
"value": 1,
"max": 1,
"min": 1
},
"minecraft:collision_box": {
"width": 1.0,
"height": 1.0
},
"minecraft:push_through": {
"value": 1
},
"minecraft:scale": {
"value": 0.0
},
"minecraft:knockback_resistance": {
"value": 100,
"max": 100
},
"minecraft:physics": {
"has_gravity": false
}
},
"events": {
"minecraft:despawn": {
"add": {
"component_groups": ["despawn"]
}
}
}
}
}
"is_summonable": true,
yeah it should be pao:floating_text
try use a vanilla mob
not floating:text
oh
lol
I thought in the json I wasn't understanding
yeah
https://cdn.discordapp.com/attachments/1271961611237720126/1285944646404673577/avc_Minecraft_2024-09-18_13-39-46.mp4
is there a way to know when player stop breaking block
even if using animation controller
i heard you can use gametest
dosent work
and break everything depend on it lol
gametest is for testing
by making a simulated player to start breaking on the block and check if the player has broken the block before the simulated player
but this sounds horribly hacky
i think theres basicslly no way to check this at all
probably animation controller
or making the breaking depend on an item an check if it is released
sea I fixed the floating text by redoing it now could you help me with applyKnockback
pls
I want to do that pushes you to the opposite side that you are looking, but I don't know how
or like that the center from which it repels me is the position of a block
uhhhh
hmm
function applyKnockback(center,target,vector2 = { x: 0, y: 0 }) {
const { x, y } = vector2;
const dir = {
x: target.location.x-center.location.x,
z: target.location.z-center.location.z
}
try {
target.applyKnockback(dir.x,dir.z,x,y);
} catch {}
}```
```js
applyKnockback(player, entity, { x: -1, y: 0 })```
i have this chunk of code
im quite busy rn so i cant make it dependent on view direction rn
this is enough
I mean this
Does anyone know how I can save items from the hotbar and then reload the items?
hmm?
import { world } from "@minecraft/server";
function saveHotbar(player) {
let savedHotbar = [];
for (let i = 0; i < 9; i++) {
const item = player.getComponent("minecraft:inventory").container.getItem(i);
if (item) {
savedHotbar.push({
id: item.typeId, // Save the item type (e.g., "minecraft:diamond_sword")
amount: item.amount,
data: item.data
});
} else {
savedHotbar.push(null);
}
}
return savedHotbar;
}
function reloadHotbar(player, savedHotbar) {
for (let i = 0; i < savedHotbar.length; i++) {
const itemData = savedHotbar[i];
if (itemData) {
const itemStack = new ItemStack(itemData.id, itemData.amount);
player.getComponent("minecraft:inventory").container.setItem(i, itemStack);
} else {
player.getComponent("minecraft:inventory").container.setItem(i, null);
}
}
}
world.afterEvents.playerBreakBlock.subscribe((event) => {
const player = event.source;
const savedHotbar = saveHotbar(player);
// Simulate reloading items after 10 seconds (200 ticks)
system.runTimeout(() => {
reloadHotbar(player, savedHotbar);
}, 200);
});```
not related it seem
Can't you check if the player stopped hitting the block and the block is the same as it was when he first hit it?
HitBlock
we can't
there is no event for that
weirdly animation control also can't do that directly
you will need to combine it with script api to get some kinda of work around
entityHitBlock or playerHitBlock
entityHitBlock only trigger on the start
Really?
yep
yipee
where did you get the script from
Why is this happening?
Error:
[Scripting][error]-ReferenceError: Native function [Entity::setProperty] does not have required privileges. at <anonymous> (attributes.js:10)
Code:
mc.world.beforeEvents.chatSend.subscribe((eventData) => {
const player = eventData.sender;
switch (eventData.message) {
case '!test':
eventData.cancel = true;
LINE 10 -> player.setProperty("hash:skin", 1)
player.sendMessage(`Skin: ${player.getProperty("hash:skin")}\nHair: ${player.getProperty("hash:hair")}\nHair Color: ${player.getProperty("hash:hair_color")}`)
break;
default: break;
}
});
(why is the error log not in english??)
many stuff cant be used in read-only mode
beforeEvents put the code into read-only mode since it cannot directly modify the stuff that didnt fully happen
Sorry, I corrected it
youd need to wrap setProperty and sendMessage with system.run()
Okay, I'll test it.
It worked, thnk
Why sometimes scripts got slowdown?
mostly because of excessive amount of stuff
How are player.addEffect(), player.removeEffect() used?
player.addEffect(effectType, duration(ticks), { amplifier: number, showParticles: boolean})``` returns `Effect`
```js
player.removeEffect(effectType)``` returns boolean whether the effect has been removed
playerInteractWithEntity isn't working?
It's working, why?
my game is just ignoring this event for a reason
It's still beta, do you use beta module?
yes, 1.15.0-beta




