#Script API General
1 messages Β· Page 26 of 1
getItem(9).amount -= 1 isn't working
i tried inv.getSlot(9).amount -= 1 and it works
should i do it like this inv.getSlot(9).nameTag = 'f'?
const item9 = inv.getSlot(9)
if (item9.hasItem() && item9.typeId === "minecraft:stick") item9.nameTag = "f"
does the BlockComponentStepOnEvent work for non-collision blocks that you walk through? I not, how can you detect if a players walks through a non-collision block?
usingonTick to detect player entity inside the block...
if i move the structures into a subfolder of the structures folder, do i need to change something in the structure manager code?
filename is allu need
great
bruh
just deleted a week worth of work
fml
the built product is still here
that's good
should have made a GitHub repo
it took the git folder with it π
fuck you neotree
welp take it as a opportunity to refactor
What were you working on?
How do I give a wolf armor through scripts? Wolves seem to not have an Equippable component, so I can't use setEquipment like I can with players?
Like, if I get the "equippable" component of a wolf, it's just undefined
Wolves do equip armor to a "slot.armor.chest" though, so this is very bizzare
Ok, so you can just tag the wolf when you spawn it with scripts, and then give the wolf armor based on the tag with the replaceitem command, but it feels wrong lol
just use the command directly from the script?
yeah that's what I did, sorry, I just like to avoid using commands in scripts if I can
alr
Im trying to make a leveling system for a tame, i wanted to know what would be the best way to get kill xp with .applyDamage()? Basically the player will ride this tame and level it up by doing certain tasks, killing a mob is one of them.
Hey guys. Just wanted to let you know that today is my last day at Mojang. It was a blast engaging with this community and working together to build the new scripting system and APIs. Can't wait to see all the awesome things you make in the future. 
Thank you memcpy!
I wish you good luck with whatever you pursue next!
Thank you memcpy!
Yeh good luck and thank you also from my side!
How do I detect if an entity is moving forward or backward, without using Velocity?
get the head rotation and compare it to the direction the entity went
but I've already done that, but there's a problem with the acceleration system whether I do it via coordinates or via body/head rotation
btw which entity other than the player can walk backwards?
rideable entity
if I press w the condition always occurs because applyKnockback always increases the velocity, but if I do clear it does not work applyKnockback always there is no method only through tp, but through tp there is a problem A and D does not work only through mouse movement you can move with the vehicle
Try comparing motion across ticks. You already know which direction the scooter moved in on the last tick, as well as the impulse you applied to it (theoretically), so you can subtract that vector from the movement direction in the current tick.
That will not be easy though
Hope you're having a good trip as time moves on and thank you for all the amazing things you brought to this community :)
for (let i = 1; i <= 4; i++) { ,,, } this should detect numbers from 1 to 4?
Is Herobrine's Chest UI just for shops?
no?
How do I make it work like a regular container?
I'm a bit confused with it
you can't
it is just a form
Good luck, memcpy!! And thank you so much for everything you have done for this community!
yes
is there a way to control mob spawn rates using script or control the spawn rates within a certain area
jeez
i found the problem in my system
it was this: entity.setDynamicProperty('sk', sk + 1)
the sk + 1 is broken and super slow
whats the difference between system.runTimeOut and system.waitTicks?
Good bye you were the only mojangster who actually replied to my dms π
how long has the getBlocks function from the Dimension class been in beta?
not that long
its kinda new method
can I somehow connect to WebSocket on Realm?
ey, i need a little help
how can i use inv.setItem(5, ???) to increase the item in that slot?
.amount++
if (slot5) slot5.amount++;```?
if (!slot5) inv.setItem(5, new ItemStack('minecraft:stick', 1));
if (slot5) {
slot5.amount++;
inv.setItem(5, slot5)
}
inv.getSlot(5).amount++ will do it
hmm
if (!output) inv.setItem(5, new ItemStack(itemType));
if (output.amount < 32 && output.amount > 1) inv.getSlot(5).amount++;```those have a log
output = inv.getItem(5);
ugh
if (!output?.hasItem) console.warn('empty')
const output = inv.getSlot(5);
||const @subtle cove = help(t17x);||
i just want to detect if that slot is empty
thats where u use isValid()
I wish you could force the player to interact with an entity
Hi, how can i fix the code, the console says: native function does not have the required privilege
world.beforeEvents.itemUse.subscribe(ev =>{
ev.source.sendMessage("HII")
ev.source.dimension.createExplosion({x:-40,y:1,z:3}, 10);
})
if (!output?.isValid()) ???
use system.run to delay it, you can't modify state in the before events
how do i use system.run?
system.run(() => {
ev.source.sendMessage("HII")
ev.source.dimension.createExplosion({x:-40,y:1,z:3}, 10);
});
nothing happens
Are you using an item?
@subtle cove same log
i know why
the explosion is happening at that location, not nearby the player
const { x, y, z } = player.location;
//({ x: x, y: y + 5, z: z}) will generate an explosion above the player by 5 blocks
just any javascript tutorial
learn JS, then learn basic of npm and start reading some examples + docs
or you can read these
anyone who know the error about of not a contain main file
idk how to fix it
PLZ help
send your Bp folder
no need i solved it thx
hi there! how can get the item type id from the entity item?
get the item component
damn
beat me to it
like this? javascript const entityItem = player.dimension.getEntities({ type: "minecraft:item", location: player.location, maxDistance: 10 }) const item = entityItem.getComponent(EntityComponentTypes.Item);
yep, that works, thx!
Probably put a condition there to check if entityItem is defined before trying to access a component on something that doesn't exist.
Since it's possible that you may not get any items returned.
entityItem will return an array as well. So if you have more than one object (item) then you will need to loop through entityItem, and then access its component.
can I somehow connect to WebSocket on Realm?
is there a way to get the inputs by the player, like if the player presses the jump key?
you can detect movement, but not certain moment of input
ok, thanks
How can I add lore to items on the ground?
you can grab the item, then modify it, remove entity and place a new one
EntityItemComponent
yeah
you dont need to remove the entity
health is 2 decimal
I'm having trouble doing this.
you do
that sucks
fr
is there anyway to detect player input?
Define input?
Assuming this behavior:
#1290336475803680809 message
movement input
Not sure about "movement input" other than to monitor position, velocity, etc.
Can someone help on what to import inorder to get the onplayerinteract_block function in Minecraft
Good evening, a question, how do I get the enchantments of an item and show them in the console?
It's still there
where did mmine go π
Place your pack in development_behavior
Is possible to make my own custom crafting table through scripts combining UI server module and Minecraft server module.
The idea is I will register a custom component with onPlayerinteract on it then it loads the UI however I don't have any idea what happens next
no
there is already a custom crafting table block component
Are there any alternatives I don't want the custom crafting table component because it has this auto craft system I want to remove that
no
I really makes my addon so easy to beat if I use that
trades(?
Remove admin commands from yourself in the pause menu crown and readd it
happens when you download a world from a realm
thank you
applyImpulse just adds to the current entity velocity correct?
uh
Essentially, yes. There's also acceleration and drag to consider, but that's not usually necessary.
(https://minecraft.fandom.com/wiki/Entity#Motion_of_entities)
how to know which id item has?
For example
netherite sword id = 632
im switching from minecraft:food to item custom component but the animation using q.is_using_item doesn't work
Anyone know how to fix it
#1290968640597790760
minecraft:use_modifiers
How do you get the entity to be summoned with a tag?
system.run(() => {
block.dimension.spawnEntity('occultismus_arcanus:funace_entity',block.center());```
if (block.typeId === 'occultismus_arcanus:oven') {
system.run(() => {
let entity = block.dimension.spawnEntity('occultismus_arcanus:funace_entity',block.center());
entity.addTag("test_tag")
Sorry, it's actually a name tag
entity.nameTag = "nametag"
Thanks
can someone explain to me how faceLocation works?
It shows always 0, 1, 0 or 0, 0, 0 as Vec3 (with decimals)
even tho i interacted elsewhere
you can add the block location to it to get world related location
makes sense, i thought it was the "world related location"
do y'all think its useful to create a class that uses timers without using ingame ticks like you can set the timeout at 1ms?
Well you can't actually set a timeout of 1ms, so it might be confusing for the people who would use it.
Also, has anyone already done the work to get the biome at a particular block location? I could have sworn I saw something a few months ago but I don't see it in search.
Well you can, but i would only do that with Date and as a cooldown, timeouts in seconds are not a good practice in Minecraft Script API
yeah that i was thinking abt using date, i wanted to create a timer class that uses ms instead of ticks
i did
wasn't that precise
@fiery solar
import { BiomeTypes, Player, world, system } from "@minecraft/server";
Player.prototype.findClosestBiomeAsync = async function () {
const biomes = BiomeTypes.getAll();
let closestBiome = null;
let closestDistance = Infinity;
for (const biome of biomes) {
const loc = this.dimension.findClosestBiome(this.location, biome.id);
if (loc) {
const distance = vector3distance(this.location, loc);
if (distance < closestDistance) {
closestDistance = distance;
closestBiome = biome;
}
}
await new Promise(resolve => system.runTimeout(resolve, 0));
}
return closestBiome;
};
function vector3distance(a, b) {
return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z)
}
//example
world.getPlayers().forEach(player => {
player.findClosestBiomeAsync().then(biome => {
console.warn(JSON.stringify(biome));
})
})
Thanks, I was playing around with something like that, but it's a little too slow. I might go the entity route
didn't they deprecated that query?
or are you planing to use filter
Yeah, filter seems like the best option
Wow, this is way faster than I thought it would be. Got the exact biome of every block in 25 chunks in 3.5 seconds.
nice
are those blocks?
try to test without any visual
They were particles, just to help visualize the biome boundaries. Surprisingly sending 6400 particles doesn't seem to add much time at all, I guess that's handled in another thread. Here's a screenshot of another test with no visuals
yeah make you wander why the biome thing was removed
also great job
Does anyone know why the scripts are not working on the Aternos server?
Alright. Waiting for new beta to drop. Im gonna try to see if I can implement my "creaking husk" idea.
Should be easy, as long as I keep it to listening to entity spawn and die events.
is it still possible to grab a double chest and do something like this:
const block = player.dimension.getBlock(tempBlock);
const container = block.getComponent(`inventory`).container;
const item = container.getItem(53);
if so how because i keep getting an error saying that slot provided is invalid. and the max is 26
is it possible to use playerInteractWithEntity on mobs that do not have the component minecraft:interact?
Is there a way to set a mobs agggresion to the player
or another entity
using script
what do you mean? I didn't understand
Im trying to make a block or entity whichever can do the job, make every mob passive within a certain radius
oh yes, sorry I thought you were answering me
It is
is there a way to check how much experience an experience orb will give you?
ugh
how can i make it work inside loaded chunks only?
this happens with entity?.isValid()
Maybe try getting the block on the entity location? It returns undefined if it's on the unloaded chunk (not an error)
if it is too complicated, I'll just leave it works inside unloaded chunks
does anyone know how to figure out whats causing a slowdown
for an item?
you mean cooldown
?
use the script debugger
vscode extension
i would appreciate help
https://discord.com/channels/523663022053392405/1291410733954760704
how do i run an event for an entity shooting an projectile?
const mainhand = player.getComponent("equippable").getEquipment("Mainhand");```
Inventory for item ig

are you trying to get entity component?
item entity
why do you need that
just like
/kill @e[type=item]
It's too obvious, i want to make those item entities disappear
Yes
i knew it
how do i run an event for an entity shooting an projectile?
Wdym, like forcely trigger minecraft:shooter?
no ,like run an event once the entity shot an projectile
before i used run command in the projectile lol
No events exist for that, there's just on entity/block hit for projectiles, but ig you could use the entitySpawn event, and just check if the spawned entity has minecraft:projectile component to further confirm it's a projectile, that component also has owner property which can be used to check for it's source
Now, when using the entity spawn event signal, can we even get the owner using script?
yeah you can
O:
How again? I couldnt seem to find it in the wiki
Dont tell me its simply getOwner..
(Idk if that exists)
if (reIy.includes(floorItem?.typeId)) floorItem.entity.remove; aren't working for some reason?
theres 30 different item type i want to remove, so i putted them all inside of that reIy
let projectileEntity1Component = projectileEntity1.getComponent('minecraft:projectile');
let ownerEntity = projectileEntity1Component.owner
What's floorItem? `
const floorItem = entity.getComponent('minecraft:item');
if (reIy.includes(floorItem?.itemStack.typeId))
Yes or no?
yes
still not removing those item entities
.remove; β> .remove();
ah, i see
if (reIy.includes(floorItem?.itemStack.typeId)) floorItem.entity.remove(); stills not removing them
why not try
killEntity?
Can u show full code?
const reIy = ['someCorrectIds']
const floorItem = entity.getComponent('minecraft:item');
if (reIy.includes(floorItem?.itemStack.typeId)) floorItem.entity.remove();```thats all
wait
for (const entity of world.getDimension(dim).getEntities()) { /// }
import { system, world } from "@minecraft/server";
system.runInterval(() => {
for (const entity of world.getDimension("overworld").getEntities()) {
const reIy = ['minecraft:apple']
const floorItem = entity.getComponent('minecraft:item');
if (reIy.includes(floorItem?.itemStack.typeId)) entity.remove();
}
}, 20);
works just fine for me
entity.remove,
floorItem.entity.remove will not work right?
my feeling tells me entity.remove will remove all entities not only those items
that too works
only the matched entities
then why its not working for me
entity is locally defined as the current iteration of .getEntities(), so it should only remove those that match the conditions
did it pass the conditions...
damn it...
console.warn(entity.getComponent('item')?.itemStack.typeId)
why do ownerEntity.setPropery("soldier:ammo", soldierAmmo-1); cause an error?
import { system, world, DimensionTypes } from "@minecraft/server";
const dims = DimensionTypes.getAll().map(d => world.getDimension(d.typeId))
system.runInterval(() => {
for (const entityItem of dims.flatMap(d => d.getEntities({ type: "item" }))) {
const reIy = ['minecraft:apple']
const floorItem = entityItem.getComponent('minecraft:item');
console.warn(floorItem.itemStack.typeId);
if (reIy.includes(floorItem.itemStack.typeId)) entityItem.remove();
}
}, 20);
what error...
not a function...
spelling
setProperty
setVelocity()
clearVelocity()
setRotation()
is there is any reason why all those not present in the player class?
is there a bug that preventing them from being added or what?
You could say that. Those would probably cause a client-server desync if used
The reason applyKnockback() works and applyImpulse() doesn't, I imagine, is that the former calls upon an existing code path in Minecraft (in this case, the knockback roar). Similarly for why teleport() works and setRotation() doesn'tβthe former, in essence, invokes the same logic as the /teleport command
So in theory, if Minecraft supports applying arbitrary velocity or rotation and can send those packets to the client, then scripting should support it too
I'd love setRotation() π
sound like client side scripting
Eh, not really. Only proper client-server communication
i can hear java player laughing π
I don't see setVelocity() in docs.
do we have anything like that currently?
i guess camera command?
Basically everything that works relies on communication in some form. The server tells the client what to do, and the client tells the server what its intentions are
applyImpulse π
Camera is a good example. Server tells the client "you should move your camera to this location with this rotation"
yeah i see your point
can someone send me entity event event signal code preset rq?
you mean DataDrivenEntityTriggerAfterEvent?
Ye
DataDrivenEntityTriggerEventAfter
should look like
world.afterEvents.dataDrivenEntityTrigger.subscribe()
is it possible to use item.nameTag and elr use the name chosen in the lang file?
i want to get the teamxyz family name, like get team1 and make it so the result is 1 and if the entity has an family with the name team2 the result should be 2
no
that is client side
This is sad
replace team with an empty string
const teamIndex = Number('teamxyz'.replace(''team',""))
but, how do we
1.get the family names of an entity
2.get every name starting with team
check the entity class
there probably a getFamilies() function
as for the second one just filter them out
hm
Does anyone know if system.runJob allows to return a value from a function?
my freaking bad,
i was writing the entity killer inside of the block entity
i mean if (entity.typeId === 'myBlock:entity') { /// item entity killer }
i put it outside that and it works fine now
actually
bec im too lazy
i will not make a system that will remove those items from the player or the entity inventory
well,
how can i make the script work only inside loaded chunks?
bec the block entity keeps working inside unloaded chunks
entity.isValid() will make it work inside unloaded chunks, how can i reverse it? like putting a ! or something?
Perhaps entity.isValid() == false?
not working
it should console.warn when it is inside the loaded chunks
it does not console.warn even inside the unloaded chunks
Hmm. You said you were testing a block right?
block entity
in fact it is an entity
Well, maybe you can get the entities location, use the location with the getBlock method. If the chunk is unloaded, the method should return undefined.
does anyone in here know term cmds for bds?
If you have an entity loaded then the surrounding chunks are loaded.
i just accidently pressed ctrl+z in a term while my bds was open and it stopped it and im lowkey scared i messed sum up
it also wont open again
wait, is it bec i have this:
entity?.isValid() && block?.isValid()?
You will be fine. I think I have only experienced corruption once and it was due to something far more complex.
it wont open the server again it says something about freeing up ports. and it says exiting program
thats for testing if the entity is inside the motherblock or not
You need to kill it. Is this in Windows or Linux?
In the terminal enter the following:
ps aux | grep bedrock_server
This will, or should, show a list of process ID's related to the application for the server still running in the background. Technically you should only see one. It will have a PID which is short for Process ID. Grab that and enter the following in the terminal:
kill -9 12345
12345 would be the PID for your case so make sure you replace that. -9 basically tells the command to forcefully kill the Process.
okay thank you so very much
Welcome. After that you should be able to run the server again
it shows 3
do i kill 2?
Kill all three of them.
Linux FTW π₯³
Well if you are using Block.isValid, then that area is still loaded then, cuz block?.isValid only works when the block is loaded and instantly fails when it is not.
^
it returns a log without block.isValid
should i remove block?.isValid() from the script?
That's because entity.isValid ignores unloaded chunks. It works as long as the entity exists.
so entity?.isValid{() === false will make it work only inside loaded chunks?
No I don't think so. Why don't you try just block?.isValid{() === true?
if it is true it should not keep loading the chunks around it?
sorry but my brain isn't braining on the isValid section
can u explain to me specifically what they are for?
entity?.isValid() && block?.isValid() β i have them like this
tell me what should i change
When an entity uses isValid(), that tests whether the entity exists, even if it is stuck in unloaded chunks. When a block uses isValid(), tests if the block exists and is not in an unloaded chunk. If you're trying to make sure it only works in unloaded areas, then try this:
entity?.isValid() && block?.isValid() == true
that should make it work inside loaded chunks only right?
It will not work inside loaded chunks just because you are checking for isValid. The purpose of that property is to tell you if the entity is loaded or not. If they are not loaded it will return false. If they are loaded it will return true. It does not matter how you try to manipulate the property. The results will be the same whether the entity is loaded (true) or not loaded (false).
i just want to make the script work only when the entity inside loaded chunks, like the spawn loaded chunks,
Any entity loaded will be inside loaded chunks. I'm not aware of any entity being loaded and there not being loaded chunks. It's the same principle on why some people will create fake players (entities) to remain logged in so certain farms will continue operating when everyone logs off.
Actually, I'm ahead of myself. Player entities will be in loaded chunks. I believe other entities are programmatically designed to despawn or freeze when a player steps away or logs off. Now I'm curious on how far that extends outward with entities π
Sometimes getEntities will return entities that are outside of loaded chunks that have a valid lifecycle (entity.isValid()). I only ran into this recently, it's pretty annoying. I think it happens when they were loaded, but not you move out of the area
It will tell you if the entity is dead or not
That's interesting behavior right there.
that means its useless for my script
out of curiosity, how do I send a form using the scripting api and get the result of which button/input or what every has been used?
let's say I have a custom form
an input, maybe even a slider and a toggle
finally
after 5 days of coding a script,
oh, wait
i forgot
j gotta make the slot 5 locked
i think
if (item5?.typeId !== 'minecraft:stick') inv.transferItem(5, playerInventory) will transfer any item from that slot into the player inventory
but wait
is it will transfer the item to a random player or for the nearest player?
where are you getting the inventory from?
Is there a way to save and edit multiple arrays per player, or are we just forced to keep track of dozens of dynamic properties?
Can use JSON.stringify() & JSON.parse() to save arrays/objects to a single property
Never tried a method like that before, I'll have to look into it
entity.getComponent('inventory').container
in fact this is possible
where are you getting the entity from?
world.getEntities()
im so tired
ok?
after a lot of research and testing I managed to do this
that not a thing
i know
how?
are you using any entity query options?
what are they?
newItem.nameTag = `%item.lampc.name\n%item.lampc.desc\n${mobName}`
uhm ...
that not from the lang file
Item.lampc.name and item.lampc.desc are descriptions used to name the lang file
in the game it looks like this
and how can i use that to make the player cannot place any item inside a specific slot?
I'm asking if you are using any of those options
i don't think so
do you want the item to be transfered to nearest player?
you are not really getting the name that way
that just using raw text
i kinda messed your point from the question early, sorry
no, just a locked slot, the player cannot place items inside it, only taking off items
I'll show u a video as an example
ok
oh yes, I don't speak English so sorry if you didn't understand, but earlier I was asking if it was possible to do this
oh
the slot is an "output slot" correct?
exactly
discord is glitching for me
i literally can spam messages
not exactly like this
hmm I can't think of a good way. this behavior is hardcoded for inventory uis
i mean the player cannot place items there, if the player did place the items they will be canceled or dropped
or something
btw i think doing most of those stuff from the entity json would have been so much better
rly?
how
timer and calling script when needed
just my thought so nvm
hmm,
transferItem β when a player place the item there, it will transfer the item back to the same player
or, just drop any items inside that slot
how will you prevent duplication exploit
transfer the item will not be a problem right?
maybe it will work
just transfer the item from the entity to the player who is placed that item there
hmm
i think dropping the item will be better
gosh, nvm wait
i found a good way
just make a slot for the result?
making it has a placeholder - locked
its an output slot
it shouldn't accept items
that what json ui is for...
i know i can lock the slot using UI
but when it has a output, how can i take it off?,
if the slot is locked
can't you prevent just adding items?
look at the furnace ui
furnace_output_panel?
you will need to look at that panel and see what that slot is using
also off-topic
"furnace_output_panel": {
"type": "panel",
"size": [ "50%", "100%" ],
"anchor_from": "top_right",
"anchor_to": "top_right",
"controls": [
{
"[email protected]_item": {
"anchor_from": "left_middle",
"anchor_to": "left_middle",
"size": [ 26, 26 ],
"$cell_image_size": [ 26, 26 ],
"offset": [ 20, 0 ],
"$item_collection_name": "furnace_output_items",
"$focus_id": "furnace_output_item",
"$focus_override_right_binding_type": "none",
"$focus_override_right": "FOCUS_OVERRIDE_STOP",
"$focus_override_left_binding_type": "none",
"$focus_override_left": "furnace_fuel_item"
}
}
]
},```ui stuff hurts
change the vars one by one and test and see π€·ββοΈ
anyway move to the json channel
maybe tomorrow
Does anyone know if system.runJob allows for returning values from a function?
runJob return the run id
so no?
you will need to pass the value other ways
yeah make it edit some sort of object or map or whatever you want and then you basically have return values
You can wrap your runJob in such a way that you can await its completion and have the promise resolve to any value you want.
How do I do that?
I've never understood how people are able to use the await keyword.
let itemList = ["minecraft:diamond_axe",
"minecraft:iron_axe",
"minecraft:netherite_axe"]
world.afterEvents.itemUseOn.subscribe((data) => {
const player = data.source
const item = data.itemStack
const block = data.block
const itemId = item.typeId
for (let ItemsID of itemList) {
if (itemId.includes(ItemsID) && block.typeId === "minecraft:grass_block") {
player.runCommand("/give @s diamond")
}
}
})```
Why does the script not work
Its meant to give the player a diamond if the player rightclicks on grass with an axe
can anyone help
const itemList = ["minecraft:diamond_axe", "minecraft:iron_axe", "minecraft:netherite_axe"];
world.afterEvents.itemUseOn.subscribe((data) => {
const player = data.source;
const item = data.itemStack;
const block = data.block;
for (const aitem of itemList) {
if (item?.typeId === aitem && block.typeId === "minecraft:grass_block") {
player.runCommand("/give @s diamond")
}
}
})
try that
Ok
you could also use the array includes method to make things short, but i chose not to add that to your script.
it was already in the one sent before
i saw
nope it doesnt work
any error
nope
const itemList = ["minecraft:diamond_axe", "minecraft:iron_axe", "minecraft:netherite_axe"];
world.afterEvents.itemUseOn.subscribe((data) => {
const player = data.source;
const item = data.itemStack;
const block = data.block;
for (const aitem of itemList) {
if (item?.typeId === aitem && block.typeId === "minecraft:grass_block") {
player.getComponent("inventory").container.addItem(new ItemStack("minecraft:diamond", 1))
}
}
})
try that instead
i think it was the command that wasnt working
It depends what you want to do, there's lots of ways to pass data around.
Here's a basic example of a function that gets all the Air blocks in a cube using runJob and returns a promise that resolves to those blocks.
function getAirBlocksInRadius(dimension: Dimension, origin: Vector3, radius: number): Promise<Block[]> {
return new Promise((resolve) => {
const generator: () => Generator<void, void, void> = function* () {
const airBlocks: Block[] = [];
for (let x = -radius; x <= radius; x++) {
for (let y = -radius; y <= radius; y++) {
for (let z = -radius; z <= radius; z++) {
const location = { x: origin.x + x, y: origin.y + y, z: origin.z + z };
const block = dimension.getBlock(location);
if (block?.isAir) airBlocks.push(block);
yield;
}
}
}
resolve(airBlocks);
};
system.runJob(generator());
});
}
Usage: const airBlocks = await getAirBlocksInRadius(player.dimension, player.location, 10);
doesnt work, idk why onUseOn is always like this
so annoying yo use π¦
keep in mind await need to be in a async function
const itemList = ["minecraft:diamond_axe", "minecraft:iron_axe", "minecraft:netherite_axe"];
world.beforeEvents.itemUseOn.subscribe((data) => {
const player = data.source;
const item = data.itemStack;
const block = data.block;
if (itemList.includes(item?.typeId) && block.typeId === "minecraft:grass_block") {
player.runCommandAsync("give @s diamond 1")
}
})
try that
i agree, itemUseOn can be pesky sometimes
doesnt work, guess ill just not use itemUseOn
it worked just fine for me
can you show
hmm, if i try it with the .includes part, it doesnt work
but without it, it works
that's odd
Is it possible to keep the Actionform open even after choosing an option?
no
re open the form

Okay, it works now, i was puting it in the wrong file, thanks for the help
ah
no problem
Is there a way to make a particle appear for only 1 exclusive player?
player.spawnParticle
its in beta
thank you
how long has it been in beta?
I dont know.
just note that no other player can see it
thats what he wants.
1 exclusive player
well he said for 1 player
as in, only 1 player can see it.
ok chill out
bye bye
Why this error?
import * as mc from "@minecraft/server"
import * as hash from "./hash.js"
mc.system.runInterval(() => {
for (const player of mc.world.getPlayers()) {
LINE 7 --> const hand = player.getComponent("minecraft:inventory").container.getItem(player.selectedSlot)
if (hand && hand.typeId === `minecraft:diamond`) {
player.onScreenDisplay.updateSubtitle(
`Test`
)
}
}
}, 5)
change selectedSlot to selectedSlotIndex
I put this to signal
Okay
why in the hell does it keep saying this?
the TickTime dynamic property could be undefined or wrong
thats why i have if (TickTime === undefined)
def not the issue, even with removing the TickTime stuff it still throws an error
i've never had this issue so i have no clue :(
like?
player.selectedSlotIndex
Thnk you
Yo
Just send the question directly or create a post in https://ptb.discord.com/channels/523663022053392405/1067535382285135923
I already did bro, but no one replies...
Either im too dumb or no one knows how to do that
Could you help me bro? π
Plz
How would i update a water block immediately after setting it?
i'm setting it like this: block.setPermutation(BlockPermutation.resolve("minecraft:water"))
why not set use .setType?
are you trying to make it flow everywhere?
Yeah
that's a thing?
yes...
does that update the block?
not sure
rip
minecraft:flowing_water works
I shall try that
just tested it
Is it not possible to use multiple addons which have scripts??
it is possiblle
Howw
just add more packs zo you world π
what kind of "scripts"
check the blocks around (the sides and down) for air block and set it to flowing water
or invis blocks and remove it
or just air?
Setting it to flowing water instead of just water did the trick
in the source block?
Ye
you can't pick that up
huh
When I set flowing_water it acted like a source block too
weird
#1291532531489046551 
Well the one that includes items and entity after events
Is it possible to recreate the behavior of fishing rod but instead of pulling the entities it pulls you and I also sticks in blocks
grappling hook?
yeah sure
https://cdn.discordapp.com/attachments/1164900377108422749/1283394520926523412/Minecraft_2024-09-11_12-49-22.mp4
just make a projectile and leash it
the movement is a knockback
hi there, on the playerLeave I cannot get the dimension and location the player was?
Use the beforeEvents variant, it provides the entire player class. Including dimension and location.
not sure what are you using that for but keep in mind that may not trigger if the game is force closed
I guess you can periodically save each data with system.runInterval with a bit cost of performance
Bro your my savior
LOL, just realized that now there is dyeable component for items, we need a method in scripting to manipulate such values.
Wait, nvm, there is a dyeable component in scripts lol.
Cool but you could add some delay before you start moving with player based on the distance of the hook has hit
yeah
i did that
that was an old video
the hook trigger the event when it land
Cool
thanks
technically there is no method to destroy blocks / get drop from blocks using script api (not including commands) right?
in theory there is Simulated Player that has breakBlock method where you cn specify the item to break block with as well
why in theory?
bc its not module for addon development
well at least not now
This is exactly what i am using for couple hours to create a map with every loot
well well well. . .
only one last thing is left for the forge block
adding custom sound effects
hmm should i say that this map has 38k lines and doesnt have fortune, silk touch and shears? π’
i spent like 10 hours
but i have it (partially)
now
sounds, particles, enchants and shears!
π
?
r u talking about custom ores?
Is it possible to detect when the player dies?
almost all vanilla blocks
so i can get a drop from a block
really?
i literally made a whole system for it
a couple months ago
when i was new at scripting
nice
but does it have all tools?
nah only which tool drops this item from this block
already have it
this is quite odd, but u can see how i make it look like vanilla 99%
fortune is applied too, u can use fortune and u will have different drop amounts
same with silk touch
if the ore required iron tier +
and u trying to break the block using a silk touch shears, it will not drop the block.
nice
mine looks like
the only downside that this map lags my IDE (vsc) alot
i will improve it and post it on github
u should make it not dropping anything if the player are in creative mode
i already done that ;>
for now i will not update it
I'll be focusing on making the addon functionality
ik i just made a quick script that retrieves the drop
world.afterEvents.playerBreakBlock.subscribe(({ itemStackBeforeBreak: itemStack, player, brokenBlockPermutation: { type: { id: typeId } }, dimension, block: { location: { x, y, z } } }) => {
const usedTool = tools.includes(itemStack?.typeId.replace("minecraft:", "")) ? itemStack.typeId : "fists";
const drops = lootTable.get(typeId).tools.get(usedTool.replace("minecraft:", ""));
for (const drop of drops)
dimension.spawnItem(new ItemStack(drop), { x: x + 0.5, y: y, z: z + 0.5 })
});```
i will implement an "API" for this in my https://github.com/syylaxx/RockWrap
jeez this is so different from what i did months ago
anyways
#1291848665052483614

Oh
yeah
entityDie i guess
import { Player, world } from "@minecraft/server";
world.afterEvents.entityDie.subscribe(({ entity }) => {
if (entity instanceof Player) world.sendMessage(entity.name + " died");
});```
effectAdd?
Say I want to make a particle persist until I want to remove it. Basically, I want a 2D graphic to persist until I'd like to remove it. Is the only way to attach it to a dummy entity/make it part of the entity's animation, and then remove the entity when I want to remove the particle?
just:
brokenBlockPermutation.dimension.spawnItem()
brokenBlockPermutation.dimension.spawnItem()
just put it twice
he wasnt asking how to do it
he was asking if there was a vanilla block that did that
lol

?
Ive gave you code about a dynamic property not that long ago
you had issues with it being slow or something
yes it is slow as hell
I dont see how
im using 3 different dynamic properties at the same time
i have to increase the dynamic property number at the same time for each one
which was sooo slow
in fact, im using 4 different dynamic properties
yah
whats the fix? im curious.
bruh
thats why i changed it
you are just retrieving the current value, and adding onto it...
everything is 200% right, but still slow and having issues with the timer
I use this same logic with a bunch of stuff in scripting all the time.
i removed the delay from the interval, it should spam it
i did some tests
console.warn outside the property thing
and console.warn inside the property thing
it should spam it fast, but it not
correct β
any ideas?
answer to your question: no
oh nice
different items, no.
nice
why?
aright gotta mine some ores using my looting 3 pickaxe
i am trying to make a map with every loot from every vanilla block with every fortune level and silktouch
already made one just with pure tools and not randomized drop rate of ores and other alike blocks*
Have you tried faking it with ScriptAPI
efficiently? isnt possible
unless you count setblock ~~~ air destroy
Try spawning items on break block?
the loot table command have the blocks drop?
wdym
loot table or dimension spawn item
I dont understand what you are trying to do really
imagine you need to destroy a block with a stone pickaxe fortune 2
how can you do it using scripts?
||you cant (using methods)||
Its possible to make when i click in a block if i have a tag the block switch?
playerBreakBlock beforeEvent + enchantable component of the held item
no destroyBlock method yet
unfortunatly
not what he means
Ah alright
look, I want to destroy a block using Script API
something like : new BlockManager(block: Block).destroy(): void
?...
using new Map<k, v>()
or just have a destroy method on the block class
thats it
nothing fancy
block.destroy()
yeah,
yes
it is possible to switch a block whenever you interact with a block with a specific tag
when you click it, just use the setType() method.
is that a thing
how?
fr
the funniest part is that my undone map is already at 38k lines π€£
i will join you on that
if (player.hasTag('whatever') {
block.setType('minecraft:dirt')
}
assuming the variable for player, is player, and for block, its block ofc.
I know that
...
empty
custom components or world events
if its a vanilla block, it needs to be a world event
playerInteractWithBlock
Api version?
for playerInteractWithBlock, you need beta apis.
should come out in stable 1.21.40
Thanks
if its a custom block, you could use custom components, which is in stable rn.
ugh
jump onboard
im getting more issues

It is sometimes fun to look at #1046947779118895114
How some people do amazing stuff using Json UI, or code custom blocks with their own mechanics or code helpful utils
yep
Is running commands inside scripts better than running commands through tick.js functions?
i dont think it really makes a difference. however, a lot of commands in a script can slow down it.
use the native methods
Its possible to open a container with playerInteractBlock?
no
Running the logic of the commands through scripts is always faster than running commands through tick.json since the game always has to evaluate every command with all the selectors every tick.
What are the use cases for scriptevent commands?
Better custom chat commands
Block, NPC, Entity, Server can use it
Is there a way to detect when a player right clicks an entity with an item? using scripts
playerInteractWithEntity event and player.getComponent('equippable').getEquipment('Mainhand') it will return itemstack then check for item and entity
i thought the player .interact with entity event is still experimental
nope
it is
it is
are you saying it is experimental or its not
[Scripting][error]-Unhandled promise rejection: TypeError: cannot read property 'subscribe' of undefined
[Scripting][error]-Plugin [Extractinator - 1.0.0] - [main.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined at <anonymous> (pulverized_copper.js:34)
world.afterEvents.playerInteractWithEntity.subscribe((data) => {
const player = data.player;
const item = data.itemStack
const entity = data.target
if (item.typeId === "splus:syringe" && entity.typeId === "minecraft:creeper") {
player.runCommand("/say I extracted your dna")
}
})
Why do i receive this error
right there
its still beta
crap
it will get stable in next update iirc
it is experimental
is there any way to replicate this
edit the creeper json or use getEntitiesFromViewDirection() with itemUse world event
β οΈ
why is it in the jayly docs on v1.13.0 not beta
im not jayly, so I dont know.
also 1.14.0 is the latest
its right there??
iirc s1 said that event signals are stable but event it self is still beta for some reason but not sure
same thing on stirante
or do this
so the game has been gaslighting me the whole time???
can someone give me code like when a player gets out of the cordinates
420 62 271 269 62 361
then i can do someting
const q = {
location: {x: 269,y:-60,z:271},
get volume() {
return {x: 420 - this.location.x, y:500, z:361,
- this.location.z}
}
}
if (!player.matches(q)) {
//is outside
}
ItemComponentUseOnEvent seems to never fire for custom items that have the minecraft:is_shovel tag...
is there a way to pass info from scriptAPI to attachable?
I want to use animation controllers to play different animations base on data from scriptAPI
So is there a way for scriptAPI pass data to molang then in RPAnim, use query to play animation base on the molang
is it possible to write/read files with script api?
what you mean
no
Oh, then you can't
but you cant write files with sceipt api
Oh, Then you can't
Using http method with @minecraft/server-net module in bds
is it possible to trigger uis in JS? like a simple regen bar
what are some stuff it can do?
just forms
is that better than just simply using jsonui?
I want to know the difference
no
you can't do anything using only json ui
it always need a base
action bar - title - forms - ....
found this: ```js
enchantments.addEnchantment({ type: new EnchantmentType(MinecraftEnchantmentTypes.FireAspect), level: 1 });
but doing this: ```js
enchantments.addEnchantment({ type: FireAspect), level: 1 });
is the same right?
will this work?
const armor = player.getComponent("equippable")?.getEquipment("Armor");```
I think you gotta say which part
Body, Head, Chest etc....
how to check the 4 parts at once?
make 4 variables
and check each
whatcha tryna do?
you can't check them all simultaneously because they are different
resolved
define an array with all the armor parts and map the items
hey minato the second one is fine right?
no
see what MinecraftEnchantmentTypes.FireAspect return
and it also need to be a string
so I need to do
MinecaftEnchantmentTypes?
I can just do "minecraft:sharpness" like that?
yeah, I saw that in getEnchantment it returns a string so I thought maybe I don't need to do the MinecraftEnchantmentTypes.*enchants*
asked you something in there
getEnchantment don't return a string
what are you trying to do
What s new ?
const armorSlots = ['head', 'chest', 'legs', 'feet'];
for (const slot of armorSlots) {
const armor = dEntity.getComponent('equippable')?.getEquipment(slot);
if (!armor) continue;
Error:
[Scripting][error]-TypeError: Native type conversion failed to argument [0] expected type: EquipmentSlot at <anonymous>
Head, Chest etc
12 freaking days of making only one block
day 1: model + texture
day 2: unfinished UI
day 3 ~ day 12: functionality + UI
im tryna make disenchanter
grindstone...
grindstone just removes the enchantment and gives u some XPs
yeah never used it once π
but i'm tryna make a portable disenchanter that uses amethyst as fuel
/// USES CHATSEND AFTER
let mainhand = sender.getComponent("equippable").getEquipment("Mainhand")
let enchants = mainhand.getComponent(ItemEnchantableComponent.componentId)
enchants.addEnchantment({type: "minecraft:fire_aspect", level: 1})
sender.getComponent("equippable").setEquipment("mainhand", mainhand)
hilp π¦
Wrong!
One block has more than 1 different drop
one out of hundreds
is there something to know if a chest state is opened or closed?
heyhey how do you check if an inventory slot is empty?
const itemSlot = container.getSlot(13)
if (!itemSlot.hasItem()) {
//no item
}
leaves can drop all of them?
i was talking about netherreactor
lol
;-;
why?;
entity?.triggerEvent('exe:despawn')
this is the full line:
system.runTimeout(() => { if (block?.typeId !== 'my:block' && block?.isValid() === true) { entity?.triggerEvent('exe:despawn') } }, TicksPerSecond * 0.1);
if (item.typeId == "minecraft:book") {
const enchants = item.getComponent("enchantable")
enchants.addEnchantment({type: "minecraft:fire_aspect", level: 1})
}
is this the correct way to add enchants?
idk, i like triggerEvent more
search addEnchantment here
here?
yeah, to see other's code samples
dude what....
mhm
how does /enchant works?
why did the book not turn in enchanted
dang mending is now stackable
its likely abug that doesnt auto change the book into enchanted_book
Is there an event that updates every tick and can detect player moving?
made a workaround convert all book to enchanted ones and enchant them
latest
I should post this to PheonixSC subreddit
anyone
youd have to make a function to check movements every tick
ye
does getVelocity works with that?
never used it
velocity changes either when player moved or got-moved
does it output 0 when not moving?
then that could work i gues as a afk detector
Will an entity (especially a player) stop getting pushed by water flow if I set their underwater movement attribute to zero?
dunno, test it
Mmm, yes, let me test on Lava movement too
How to make player fall after his βmayflyβ ability disabled? Because when I disable it player still will be in fly mode and will not fall down until he disables fly
i will soon add this "event" to my wrapper, you can just use it as refrence if it releases ^_^
π ||almost every crop||
Anyone know how to crack the copyright key of word office 2016 please help me!
no
πΏ
Use the web version, it's free. or use windows 7
this is a minecraft add-on development server
or LibreOffice π€·ββοΈ
i use windows xp
Is it possible to detect empty entity slot?
.
Thanks
how to detect player jump?
player.isJumping
can script attack as a player? like when player jumping?
huh
You can cause damage to an entity through script and specify the source of the damage as the player
I need to simulate sword hit animation is it possible through scripts?
How do you save the mob inside?
Dynamicproperty?
Does anyone know how I can make a script that counts how many blocks an entity has walked?
import * as mc from "@minecraft/server";
mc.system.afterEvents.scriptEventReceive.subscribe(event => {
for (const player of mc.world.getPlayers()) {
//if(!event.id.startsWith("test:")) return;
const wg = event.id.split("wg:")[1];
const eventEntity = event.sourceEntity;
const player2 = event.sourceEntity;
switch (wg) {
case "clone":
clone(eventEntity);
break
}
}
});
export function clone(eventEntity) {
for (const player of mc.world.getPlayers()) {
const plr = player.nameTag == `${eventEntity.nameTag}`;
eventEntity.runCommand(`event entity @s wesl3y:hair.${plr.getProperty("wesl3y:hair")}`);
console.log(`plr`);
}
}
help
Are Maps or objects faster?
I'd imagine objects are faster
hi 
con i ask something in here ?
its about block.location....
π π
It depends what you're doing with them
retrieve data from 50 thousand other values?
just ask
It's hard to know for sure without more details, but Map is faster in almost all cases with that many values.
block.dimension.spawnParticle("minecraft:crop_growth_emitter", block.location);
how can i change the block.location?
const { x, y, z } = block.location;
Send the code
i want the particles appear above the block...
