#Script API General
1 messages Ā· Page 45 of 1
well I just assumed it'd run the code before the world closed
since it's before you leave
It's before, but your code is in system run, so it's basically equivalent to after
Hey. Is there a way to script so you shoot up fireworks everywhere on a server? Say to not have as much lag that it shoots up based on where a player is?
Yo if anyone has the patience & ability to guide me throughout the process of making an adjustable particle, please check out my post.... https://discord.com/channels/523663022053392405/1320811741109555270
?
If you mean like summon fireworks
At new Years i want to shoot up loads of fireworks in my server. But summon the fireworks only gets you the rocket with the white particals. Not the explotion?
Do you know what he needs to fix?
for the poison I want him to attribute it to the affected player
the damage in void is if the score 53 is hit
for the nauseous I want him to attribute it to the affected player
for resistance it is the player who hits the other player who receives the effect
world.afterEvents.entityHitEntity.subscribe((data) => {
let {
damagingEntity,
hitEntity
} = data;
if (damagingEntity instanceof Player && hitEntity instanceof Player) {
const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
if (score === 50 && Math.random() < 0.10) {
damagingEntity.dimension.spawnEntity("lightning_bolt", hitEntity.location)
}
}});
world.afterEvents.entityHitEntity.subscribe((data) => {
let {
damagingEntity,
hitEntity,
player
} = data;
if (damagingEntity instanceof Player && hitEntity instanceof Player) {
const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
if (score === 49 && Math.random() < 0.10) {
player.addEffect('resistance', 100, {amplifier: 1, showParticles: false}); //200 => 20ticks x 10
}
}});
world.afterEvents.entityHitEntity.subscribe((data) => {
let {
damagingEntity,
hitEntity,
} = data;
if (damagingEntity instanceof Player && hitEntity instanceof Player) {
const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
if (score === 33 && Math.random() < 0.10) {
damagingEntity.addEffect('poison', 200, {amplifier: 1, showParticles: false}); //200 => 20ticks x 10
}
}});
world.afterEvents.entityHitEntity.subscribe((data) => {
let {
damagingEntity,
hitEntity
} = data;
if (damagingEntity instanceof Player && hitEntity instanceof Player) {
const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
if (score === 8 && Math.random() < 0.10) {
damagingEntity.addEffect('nausea', 200, {amplifier: 1, showParticles: false}); //200 => 20ticks x 10
}
}});
world.afterEvents.entityHitEntity.subscribe((data) => {
let {
damagingEntity,
hitEntity
} = data;
if (damagingEntity instanceof Player && hitEntity instanceof Player) {
const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
if (score === 53 && Math.random() < 0.10) {
Hurtplayer.applyDamage(1, { cause: "void",damagingEntity: entity})
}
}
});```
event listener inside a another one is a really bad practise
oh it's not, just weird indentation
can we set true/false condition to dynamic property? Like
.setDynamicProperty("test", true)
yeah you can set also boolean values
you can set strings, numbers, booleans (true/false) or even coordinates (Vector3 interface)
You can set: Vector3 or String or Number
Or undefined
Or null
Or just setting it like this:
.setDynamicProperty("bruh:bruh")
I fell for it too
(This will clear it & undefined too)
import { world, Player } from "@minecraft/server";
const kitObjective = world.scoreboard.getObjective("kit") || world.scoreboard.addObjective("kit");
world.afterEvents.entityHitEntity.subscribe(({ damagingEntity, hitEntity }) => {
if (hitEntity instanceof Player && damagingEntity instanceof Player) {
if (Math.random() >= 0.1) return;
const playerScore = kitObjective.getScore(damagingEntity) ?? 0;
switch (playerScore) {
case 8:
damagingEntity.addEffect("nausea", 200, { showParticles: false, amplifier: 1 });
return;
case 50:
damagingEntity.dimension.spawnEntity("lightning_bolt", hitEntity.location);
return;
case 53:
hitEntity.applyDamage(1, {
damagingEntity, cause: "void"
});
return;
};
};
});
You are gonna have to make your own explosion and particles...
Here read through this: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/dimension?view=minecraft-bedrock-stable#methods
It has some good examples.
you can add more cases for score
That is what i was afraid of. Thats a part i did not want to have to learn right now as im working on other stuff. Hehe. Thank you š
Oof that's sad, anyway, you're welcome!
this work but the thing with effect or damage doesn't work
Lol i have long passed that tier...
did you check that this won't always work due to your chance?
Haha. I will get there. One day. š Im just trying not to overload myself as is š
It has a such slime chance of not working lol. Math.random() returns around a number larger ~0.12843 (its not always that but yeah it almost always is larger than 0.1), ima test rq so im not just yappin
it's returning if it's larger than 0.1
Yes i know.
he should remove the Math.random if statement then test it again
like wrap it as a comment
It returns (~ .1)+
then on the end just add these chances
I replace the damagingentity with something so that the one with the score 49 gains 5 seconds of resistance with a 5% chance
no its ok i needed
Ayo.. (i dont mean to be annoying, sorry)
Not sure if this is the best place to ask but can anyone let me know the best way to set up a scripting environment?
Arenāt scripts made in JavaScript?
Not typescript
Typescript gets transpiled into Javascript.
And if I wanted to code fully in js?
My friend was streaming their work and had access to a bunch of autocomplete stuff
I think I might be missing some libraries
https://jaylydev.github.io/scriptapi-docs/latest/modules/_minecraft_server-1.html
Install typings if you're using vscode
@ocean escarp
Thereās an extension for this?
Iāve never used npm stuff
its basically the instruction for VsCode to have auto completions
Just open your command terminal, go to your project folder and copy the path then do: ```bash
cd /path/to/your/project
Then run:
```bash
npm i @minecraft/server
make sure you got node js installed
(And your vscode should be able to do the auto completions)
And this also:
So run ```bash
pkg install nodejs
or whatever the equivalent of pkg is for your system.
Do I have to install this all?
All I want is autocompletion. Any random math and stuff Iāll do manually
Yup, just delete the @node_modules folder in your project folder
Then you are gonna need to do all the commands i listed for you
Time for file bloat YAY!
There goes having a clean workspace
(I am forced to suffer because i am on mobile & i cannot use auto completions...)
for stable npm i @minecraft/[email protected]
for beta npm i @minecraft/[email protected]
NODE JS & NPM https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
thats the tutorial for the installation
https://youtu.be/-34dn_mKkMA?si=zOQGOPnVSjB8DgVA
^ another tutorial
i think its better to watch a video than reading text from microsoft learn
me who reads always...
And luvs reading
That's why I luv docs... Except maths but meh
if you want all of this without needing to install and do stuff to create your addon just use https://bridge-core.app/ it is 50 times faster to create a new addon
You mean Except? (I also love docs)
microsoft learn has the worst explanaitions ever
fr? why?
I hate it too lol
dap me up cuh
Idk it just seems clunky
I mean I prefer bridge v1
I hate it honestly, i never used it execpt for generating manifest files, now i use my own manifest generator.
Iāve never had to use the command prompt with coding before
command prompt?
I did use it before, but now I generate my own manifest in my own made manifest generator ( yes it supports scripts )
.
Well if you do start web dev, and make your own website & host it (a dynamic one i mean), then you are gonna interact with it alot.
So i guess its a good place to start. (This has nothing to do with the scripting api, dw)
Rahh, I need to do more maths to check if the shulkerbox is openable
š¤·
Iām 99% sure I have node.js
i ā¤ļø math
Fuck math
I mean I don't really need math in my cass but it's annoying
then check your npm version in the powershell
usually I just write stuff in lua and ask people to translateā¦
lua > js
Any day
json > lua
never used them but for assetto corsa scripts
json sucks except for data storage
json <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< all
NodeJS > all
java is better
Hater
How? :)
npm version? Lol idk dont actually do that
-# god Iām useless
Because json is not a whole language lmao
I hate being taught. I should just know the info automatically
And if it sucked then say that to Mojang... Because they still use it to this day
Nah. MySQL || MongoDB > JSON
npm pkg get version
Idk just do
pkg update nodejs
(Idk if its also a valid command lmao, btw it should update your nodejs version, not check it), for checking do:
npm -v
it isnt for looking if its valid its for checking if its isntalled
Idk if that means itās installed or if Iāve called something else random entirely
what
No you're NOT!
You just got feeded by new information
That you're Bain can't comprehend properly because if the speed of it
My goal is to install as little NPMs as possible
Scripting is the only way I can make my projects a reality
because json sucks ** COUGH COUGH**
I hate I can write out a perfect psuedo script for what I wanna do
but when it comes to actually making it I crumble
|| JSON is only good for storing dynamic properties ||
Speaking off Iām probably going to need hundreds of them
since my project basically redefines the whole concept of ādamageā
Nah, you just don't know how to use it properly
your message is sent using json
Anyways, does getBlock support float?
Nice....god, I need to check if there's 0.5 space above the shulker box
huh
I don't think you can do it like that
Shucks
Iām also going to need a UI developer but Iāll have to learn that myself too
it return a block... idk what are you trying to do
The health, armor and hunger bar are all going to be replaced
#1067869374410657962
Not really
Iām just gonna hide them and create a custom health system via scripts
alr
Let's get to the point. How can we help you?
I donāt think there is a way you can really. Iām bad at retaining info and refuse to use regolith
not all of us use regolith
Why is the regolith in this conversation now...
idk he seem to link it to his problem
i am saying we don't use it so he can ask whatever
Because my friend tried to teach me scripts and it was 1 of the first things that came up
I love regolith!!!
-# š
What the hell is regolith??
I'm on mobile so i have absolutely no idea wtf is most of the pc tools yall are using.
-# jk
A flexible and language-agnostic addon-compiler for the Bedrock Edition of Minecraft.
Nah why tf is the home page a copy of the bridge??
Almost like they used the same frontend.
lol
Yeah i absolutely can't use anything that asks for the com.mojang, why? Cuz my android loves to keep itself supposedly "secure" and not allowing me to do anything in that folder
-# "We have forbidden you to leave your home for your safety."
"Why, whats dangerous?"
addon development is
"But, they are only using my phone (the com.mojang folder), they aren't in my neighborhood?"
let stay on topic, lol
I want a inventoryChange event
Plz mojang... i neeed this.... (yes i do have an interval to check if your inventory changed but i hate intervals and they cause alot of lag!)
That's just javascript... Prototypes obviously save their properties and methods.
Serty! (In star wars sound) YOU DARE BETRAY US?
seem like a packet thing to me
I cant use bds
(I dont wanna use bds)*
|| It's just quite easy to implement without additional events ||
What are you trying to achieve
Yes i do have it but its not good as its interval
Kinda too much
Too much to explain plainly...
If when trying to install NPMs it says audited how to fix that?
Audited means edited/updated/fixed.... (i believe lol)
They clearly donāt exist
A lot of times the inventory transaction packet sends without the inventory even changing, and also doesn't give much helpful info on what changed
Are you sure you ran that command AFTER you typed cd /path/to/your/project?
npm audit fix
Iām working inside the BP folder itself
Ah alright
Then just do that:
yeah
i didn't mean it is implemented in the current api
if it was it will probably using packets
Maybe add a --force if it exists... i think I'm mixing up cloudflare commands with normal npm but maybe it exists
Just type it?
Ima need a item Cooldown end event for real š
Mc server for 1.16.0
uh check the item cooldown?
weird never seen that installing mc packages
He installed stable mc server version i think
What I'm currently doing on a loop but it has to assume you know the item cooldown, so if you want it for several it's gonna need one if statement for each
Like stable stable...
itemStack.getComponent('cooldown').getCooldownTicksRemaining(source)
my bad didn't see your response
world.beforeEvents.chatSend.subscribe(ev => {
if (ev.message.startsWith('!testForm')) {
ev.cancel = true;
const args = ev.message.split(' ');
const characters = args[1] ? parseInt(args[1], 10) : 10;
if (characters && !isNaN(characters)) {
system.run(async () => await testForm(ev.sender, characters));
}
}
});
async function testForm(player, characters = 10) {
let bodyContent = '';
for (let i = 0; i < characters; i++) bodyContent += String.fromCharCode(32 + (i % 95));
let form = new ActionFormData().title('Test Form').body(bodyContent).button('Back');
await forceShow(player, form);
}
async function forceShow(player, form, timeout = Infinity) {
const startTick = system.currentTick;
while ((system.currentTick - startTick) < timeout) {
const response = await form.show(player);
if (response.cancelationReason !== "UserBusy") {
return response;
}
}
throw new Error(`Timed out after ${timeout} ticks`);
}```
I made this stupid script to check how many characters my phone can handle in the server form
And it can handle below 80k characters, but higher than that closes my world
Scrolling is fine but opening and closing the form is the worst part it lags so bad lmao
Ah so i can just open a 300k character form to force crash any player?
Is there any way to grab entity components with scripts?
What's the error?
Error
[Scripting][error]-TypeError: not a function at durabilityDamage (main.js:128)
at <anonymous> (main.js:123)
Code:
mc.world.beforeEvents.playerBreakBlock.subscribe((ev) => {
const block = ev.block
const player = ev.player
const hand = player.getComponent("minecraft:inventory")?.container.getItem(player.selectedSlotIndex)
if (pickaxeBlocks.includes(block.typeId) && pickaxes.includes(hand.typeId)) {
const damageValue = pickaxeBlocks.includes(block.typeId) ? 1: 2
`LINE 123 -->` durabilityDamage(player, pickaxes.includes, damageValue)
}
})
function durabilityDamage(player, item, damageValue) {
`LINE 128 -->` const durability = item.getComponent('durability');
const enchantable = item.getComponent('enchantable');
const unbreaking = enchantable?.getEnchantment('unbreaking')?.level ?? 0;
if (Math.random() * 100 <= (100 / (unbreaking + 1))) durability.damage += damage;
}
Pretty sure it might be cause youāre calling it before itās initialised
Just like I didn't understand
Pretty much just move the function above where youāre calling it
so the code reads the function first
Custom functions usually work best at the top of a file
Oh, I understood
Thnks
Lemme know if it works
Okay
Like this?
mc.world.beforeEvents.playerBreakBlock.subscribe((ev) => {
const block = ev.block
const player = ev.player
const hand = player.getComponent("minecraft:inventory")?.container.getItem(player.selectedSlotIndex)
if (pickaxeBlocks.includes(block.typeId) && pickaxes.includes(hand.typeId)) {
const damageValue = pickaxeBlocks.includes(block.typeId) ? 1: 2
durabilityDamage(player, pickaxes.includes, damageValue)
}
function durabilityDamage(player, item, damageValue) {
const durability = item.getComponent('durability');
const enchantable = item.getComponent('enchantable');
const unbreaking = enchantable?.getEnchantment('unbreaking')?.level ?? 0;
if (Math.random() * 100 <= (100 / (unbreaking + 1))) durability.damage += damage;
}
})
you probably could but it still depends on the device's capability for example gaming PCs with a very high CPU, man...
-# and why bother doing that when you can just use the fastest one... while (true) {}
Because it didn't work that way
const pickaxeBlocks = ["minecraft:stone", "minecraft:iron_ore"];
const pickaxes = ["minecraft:iron_pickaxe", "minecraft:diamond_pickaxe"];
world.beforeEvents.playerBreakBlock.subscribe(({ block, player, itemStack }) => {
if (pickaxeBlocks.includes(block.typeId) && pickaxes.includes(itemStack?.typeId)) {
const damage = pickaxeBlocks.includes(block.typeId) ? 1 : 2;
system.run(() => durability(player, itemStack, damage));
}
});
function durability(player, itemStack, damage) {
const durab = itemStack.getComponent("durability");
const enchant = itemStack.getComponent("enchantable");
const unbreaking = enchant?.getEnchantment("unbreaking")?.level ?? 0;
const equippable = player.getComponent("equippable");
if (Math.random() * 100 <= (100 / (unbreaking + 1))) {
durab.damage += damage;
equippable.setEquipment("Mainhand", itemStack);
}
}
Anyone know how to solve this?: [Scripting] ReferenceError: Native property setter [HttpRequest::body] does not have required privileges. at <anonymous> (main.js:67)
Try wrapping that part with system.run
thanks, I'll try that
That's not true btw, you can call the function wherever it's placed on top it on bottom as long as you're calling the function in the same file and when it's not inside of an event listener
It worked, thanks
Really? Maybe Iām just used to other langs that use order of execution
JSON.
-# jk
but it still applies to most things... the function is the exempted one
Drag and drop doesn't exist for script api right?
Not even using complicate stuff like, yk cursor thing?
PlayerCursorInventoryComponent Class
You can grab ItemStack but not set ItemStack
Oh
Then it's not possible to do it?
No I guess? You can wait for someone with better idea
Someone did tell me, but he's not sure about if setting item is needed
Hmm, k... Tho we can't open a container with just scripts you need to interact with it.
So, what do u think? Worth a try?
Probably but you try because I don't know the drag and drop you mean
Maybe send a gif or a video of it?
Hmm, that's possible tbh
-# sorry late response
Yeah but this isn't possible with android devices
How to turn a player name as string (for example āAsquilorc ā) to an actual player object in my code?
I know how to turn a player object to a string
But how to do it the other way
name is already a string why convert it?
Anyone have any ideas on how to fix this?
I answered you in your post
const target = world.getPlayer().find(p => p.name === "theChosenOne");
That's what he meant wadahell...
It really depends on how horrible someone's explaintion is
Basically i just guess what they want...
Idk what to say lol.... my eyes are paining me
I just woke up
(For context, i slept when it was 5am and now is 9am)
4 hours ehh?
I hope thats enough but at least i got some commands to work and i fixed a bit more bugs on my website..
world.getPlayers({ name: 'theChosenOne' })[0];
No difference at all tbh...
I'm just showing another way
Also the [0] is unneeded since only one player can have the same name
Unless it's entities
Lemme test it rn
Nvm, I don't need to test it...
It's not bugged it's normal since getPlayers() is an array no matter what even if you added the name option
it still needs to check every player within that array with that name
Yea so [0] is right?
Hmm
you didn't use the method(there is no getPlayers())
What
Oh I understand
He not add ()
These things are always forgotten by me too lmao
I forgor š
whatā¦
Spam random lines of code: ACTIVATED+++
Don't worry man I will change that, I'm kinda busy and lazy rn
Is it possible to show a specific player's skin to other players? I know it's possible to see your own skin in a panel. But I'd like to know if it's possible to do that.
not with the script api.
and im not sure if you can do that in general.
-# probably not
Hmm, how is it with pc players though?
Like the person told?
it's very possible as long as it supports mouse and keyboard Android devices can't use it unless they use a external mouse
Like how still? Where do I start
I'll do something for Android players later
use runtInterval
Do you know how to do the person who told you how to do it??
Never used playercursorinventorycomponent class, would have to study it
more performant
if you say so...
Why study? You're just grabbing the ItemStack in the cursor that its
Idk man... I've been using it for quite a while and it doesn't lag me down...
Seems like a micro optimization to me..
I'm not saying it's gonna cause a ton of lag, but it is more performant
.
if you're doing this a lot, then not really
I mean a LOT
Yes
Like to the point that you're touching the 50ms line each tick
I do it like ~200 calls per 30 seconds
Nah my script doesn't lag
it's faster cause all the iteration is done natively instead of in the JS runtime
anyway even if it is a micro-optimisation, it's nicer to look at, and why not take the optimisation if you can
(Depending on the actions ofc but when there are gonna be players playing, its gonna be ~200, currently its around ~30 calls and test with multiple bots to like see my addon in action)
I hate the sight of world.getPlayers({name: "/"})
Really hate it
And also i do multiple extra parameters... i filter out some op permissions and their id and their gem... i dont think the query params would help with that would it?
I dont actually get the player name execpt a few times, all of the script is based on id, but i think there is an id param anyway
if you're using the id then world.getEntity(id) is even better
just typecast as player
I know there are native functions, i just hate the sight of them
I get an urge to break my phone
When i see them
Idk why, but it is what it is
I genuinely tried to use a good'ol world.getEntity() and i just... i got mad... idk i need help ig...
It was a week ago so yeah i might attempt to do that again...
I also love making my variable names as short as one or two characters at max
Why you may ask? The answer is... I GET A F-ing URGEEEE, im sorry but i just just.... i need help..
Should I just make a chestgui for it? Cuz android not able to do is just like losing main playerbase
any example to make a custom dimension using end and a mcstructure.
#1067869232395735130
I was going to ask on that channel but I realized that literally the entire system to go to the other dimension is with scripts
And there's also a method Cursor.clear() it clears the item
For Android just detect if the item is swapped that's it
if(r.selection === 0) {
if(player.hasTag("Staff"))
player.runCommand(`execute if entity @s[scores={md1=1}] run dialogue open @e[tag=memory_disc_all] @s memory_disc_all_1`);
else
player.sendMessage({ rawtext: [{ translate: 'memory_disc.menu.locked', "with": ["\n"] }] })
}
Heyy, how I can get rid of player.hasTag, but leave player.sendMessage when the score is not reached?
function getScore(ent, sb) {
let scoreboard = world.scoreboard.getObjective(sb) ?? world.scoreboard.addObjective(sb);
return scoreboard.hasParticipant(ent) ? scoreboard.getScore(ent) : 0;
}
if (r.selection === 0) {
if (getScore(player, "md1") === 1) player.runCommand(`dialogue open @e[tag=memory_disc_all] @s memory_disc_all_1`);
else player.sendMessage({ rawtext: [{ translate: 'memory_disc.menu.locked', "with": ["\n"] }] })
}
Use that @meager cargo
There was minor change in hasParticipate to hasParticipant - but it worked fine overall! Thank you very much!
You're welcome.
hmm
Hello scriptin' guys, and Merry Christmas!!! š
Just use multiple spawnItems
Yes, from 1 to 64. But if you need more, you will have to use multiple spawnItem
can i toggle sprint for a player?
Give them the blindness effect
To stop them from sprinting...
i mean to make them sprint
You wanna make them sprint?
yep
What the fk do you mean by "sprint". They can sprint by default...
Elaborate
Explain further
... you wanna keep their velocity?
yes
Do ```js
player.teleport({x: 0, y: 0, z: 0}, {keepVelocity: true});
???
How is it wrong @warm mason
let velocity = player.getVelocity()
player.teleport(location)
player.applyKnockback(velocity.x, velocity.z, 1, velocity.y)
keepVelocity doesn't work for players
but that they still lose sprint
This is the best you can do
thanks
Why are you teleporting a player, maybe there is a better way than teleportation
It clearly can be set to false in players
So i assume it would be able to be set to true
nope
K...
Tell me what you need. Why are you using teleportation?
//fence part
if (scoreboard.getObjective("fence").getScore(player) == 1 && player.isFalling == false && player.isJumping) {
player.runCommand("playanimation @s animation.humanoid.fence_vault.1 move 0")
player.runCommandAsync("execute anchored feet as @s at @s rotated ~ 0 run tp @s ^^^0.5")
applyKnockback(player.getViewDirection().x, player.getViewDirection().z, 0.1, 0.1)
}
.....
What is the essence of your code, why are you teleporting a player
a fence vault thing
Why was a teleport needed there at all?
?????
So they need teleport to tp the player above the fence
tp player in to the fence and push player out by knockback
But they still want the player to be able to run
yes
just edit the movement speed when not sprinting after that action
How do I import effect functions?
Whenever I try I only get the stuff Iāve used before
You want to give an entity effect?
Honestly for me itās js syntax I think
I donāt know when to use each type of bracket or an array
Watch training videos
Time to spend the next 3 years rotting
Or read the JS documentation
cause thatās how long itāll take me to understand step 1
It's better to try than to say that you will spend 3 years on it
entity.addEffect(āinfiniteā,āminecraft:health_boostā, true)
Laugh at me
I know Iām 8 miles off
Because you didn't read the documentation
addEffect(effectType: EffectType | string, duration: number, options?: EntityEffectOptions): Effect | undefined
Yeah I just saw that
This is literally my first time scripting in js
I thought at least some of my knowledge from lua would translate over
Iāve never done oop
we are just reading the docs and applying it, it is not that complicated for the most part
anyone know how to disable the player's left and right rotation animation?
They can still rotate but the animation of rotation doesn't play? That's more like a #1067869590400544869
Well figuring that you can edit the player's rotation i figured someone knew a way via script
disable camera controls
this disable the pitch rotation too
Bruh, I thought it was just an animation because he said rotation animation š
more context needed
What does the "checkforblocks" in the entity teleport options do?
I figure it would have canceled the teleportation if the destination would teleport the entity into nonpassable blocks, but that doesn't seem to be the case after testing.
probably only loaded blocks
Any way to check if block/entity is in unloaded chunk?
block/entity,isValid()
I have a problem: script engine runs my code slow and the game interrupts.
I'm making custom explosions with 'ray' mechanic. If I switch dim.createExplosion(coords, pwr, { allowUnderwater: true }); to // rayBlock.setType('minecraft:bedrock');, it works quite fast.
Anything I can do to increase the speed of explosion spread (without decreasing their amount)?
Here is a piece of my code:
const processedBlocks = [];
const onRadiusBlocks = getOnRadiusBlocks(explosionLocation, explosionMaxRadius);
for (const blockLocation of onRadiusBlocks) { // for each on radius block
const block = dim.getBlock(blockLocation);
if (!block.isValid()) { continue; }
const rayArray = createRay(explosionLocation, blockLocation);
for (const coords of rayArray) { // for each block in ray
let index = processedBlocks.indexOf(coords);
if (index > -1) {
continue; // do not create secondary explosion there again
}
processedBlocks.push(coords);
const rayBlock = dim.getBlock(coords);
if (!rayBlock.isValid()) { continue; }
// skip if doesn't fit in range
const dist = calculateIntDistance(rayBlock.center(), explosionLocation);
if ((explosionMaxRadius * secondaryExplosionsStartCoefficient > dist) || (dist > explosionMaxRadius * secondaryExplosionsStopCoefficient)) {
continue;
}
if (passBlocks.indexOf(rayBlock.typeId) < 0) { // break 'ray' if there's an obstacle
break;
}
// create secondary explosion
const pwr = calculateExplosionRadiusByDistance(dist, secondaryExplosionsMaxPower, explosionMaxRadius, 0);
// rayBlock.setType('minecraft:bedrock');
dim.createExplosion(coords, pwr, { allowUnderwater: true });
}
}
|| If I load the world after watchdog stopped it, I see such lovely crater ||
Maybe some async functions? But idk how to deal with them plus I need to wait to check if previous explosion removed an obstacle.
Is it the same thing? Can I use either one?
player.getComponent('equippable').setEquipment("Head", null);
player.getComponent('equippable').setEquipment(EquipmentSlot.Head, null);
First one a direct string second one you need to import the EquipmentSlot in the server
first thing to do would honestly be to find a better way to do what you want. Right now you're doing a double for loop, which will have exponential sclaing, and the createExplosion also has to internally do even for iteration to nearly blocks, so at the lowest it's probably around an n^3 complexity function right now
I would make a post detailing what it's actually supposed to do
How do you disable the pitch?
Is there any way to remove the push when an entity attacks you?
Any other suggestions for my simulated player menu addon?
Set a higher value on the knockback_resistance component in player.json
No U cant
I've tried it before when I wanted to make a custom kb
That's because knockback resistance is not supported on player
My suggestion is use negative values with applyknockback
This is a bad setting bc if it can work on player the custom kB addon will better
Yeah, they're the same case of knockback_roar you can't use that component directly on the player
The best but troubled way to create a custom kB is using plugin but only work on server
Unrelated but, I bug the game with my script so bad I have a culling block/ghost block š
const date = new Date();
player.onScreenDisplay.setActionBar(`${date.toLocaleString()}`);```
Thanks
How about toLocaleString()?
Just search in the link serty gave
.
When and where? I'm free anytime
-# jk
can you use world.beforeEvents in 2 different scripts?
Absolutely
ok
const getScore = (objective, target, useZero = true) => {
try {
const obj = world.scoreboard.getObjective(objective);
if (typeof target == 'string') {
return obj.getScore(obj.getParticipants().find(v => v.displayName == target));
}
return obj.getScore(target.scoreboard);
} catch {
return useZero ? 0 : NaN;
}
}
function enchants(player) {
new ActionFormData()
.title(title)
.button("§cPurchase:\n§sSharpness")
.button("§cPurchase:\n§sSoul Steal")
.button("§cPurchase:\n§s???")
.button("§cPurchase:\n§s???")
.button("§cPurchase:\n§s???")
.button(`§l§0Back`)
.show(player).then(r => {
if (r.selection == 0) {
player.runCommandAsync("execute @s ~~~ say");
}
if (r.selection == 1) {
player.runCommandAsync("execute @s ~~~ say");
}
if (r.selection == 2) {
player.runCommandAsync("execute @s ~~~ say");
}
if (r.selection == 3) {
player.runCommandAsync("execute @s ~~~ say");
}
if (r.selection == 4) {
player.runCommandAsync("execute @s ~~~ say");
}
if (r.selection == 5) main(player)
})
}
})```
as soon as i remove ```js
.textField(§u(${getScore('Money', player.nameTag)}))
it's pretty old getScore function
you can directly obtain non-player's participants
import { world } from "@minecraft/server";
const getScore = (participant, objective) => {
try {
return world.scoreboard.getObjective(objective).getScore(participant) ?? 0;
} catch {};
return 0;
};
and that should make it work?
so i was just using a outdated system
probably
textField isn't available on ActionFormData, only ModalFormData
that's a fact too
How would I go about creating a world border using blocks? I've got a border block with no collision already. Now I just need to figure out how to actually create the border itself without replacing blocks
Best approach in my book:
system.runInterval(() => {
system.runJob(function* () {
let plrs = world.getPlayers();
for (let i = 0; i < plrs.length; i++) {
let player = plrs[i];
isInBorder(player) ? saveLoc(player) : player.teleport(savedLocs.get(player.id) ?? {x: Math.min(player.location.x, world.getBorder(player).x-20), y: Math.min(player.location.y, world.getBorder(player).y-20), z: Math.min(player.location.z, world.getBorder(player).z-20)});
}
}());
}, 20);
There is more, wait
function saveLoc(player) {
savedLocs.set(player.id, player.location);
}
function isInBorder(player) {
return Object.keys(world.getBorder(player)).every(k => Math.abs(player.location[k]) < world.getBorder(player)[k]);
}
Done? Nah.
let savedLocs = new Map();
World.prototype.getBorder = function(player) {
return generalDB.get('worldBorder') !== undefined ? generalDB.get('worldBorder')[player.dimension.id] : addon.worldBorder[player.dimension.id];
}
Now edit the world prototype function however you want, but make sure it returns a vector3 with the border values
Like it returns a good'ol:
{x: 0, y: 1, z: 2}
What s new with script api ?
is there way to basically give infinite amount of blocks?
i treid to give 255 blocks but whenever they place a block, it just becomes 64
I mean...every 20 ticks just add a stack of blocks?
Oh, then, no.
oh alr
I think I have worded the question incorrectly
I have these border blocks
Basically, I want to do something similar to the world border in Java edition
If there's any other way to do it other than just using blocks, that would be cool to know
Also, you can go past the border
Hence why the block has no collision box
Ehem
The way i told ya
And visualize the border using a giant particle or a certain amount of vanilla particles when a player gets close to the border
Doesn't that teleport the player back if they go past the border?
I need the border to be visible at all times, so that won't really work
Yeah, just remove the teleport and add damage mechanism
I did add a damage mechanism (and another cool effect :3)
https://t2bot.io/_matrix/media/v3/download/matrix.org/OXhmUzDvyIaXdDZFKRWocPSC
Alright then just spam a giant particle so it appears at all times and doesn't cause lag
import { world, system, ItemStack } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";```
Ah so you wanna visualize only?
The damage mechanism isn't working because I'm in creative mode
Yeah, I want players to see an actual border thing. I don't know how servers like Hive do it, but it seems to work
Like i said either spam a giant particle (it can adjust) or just make a calculation system to show a border (it is is not good, use the first approach)
They do it using particles or blocks
If I did this I would use blocks
Block needs tickingarea for setting the block
In SkyWars, it's most likely an entity overlapped to a wall of barrier blocks
Particles also cannot be created outside loading area
(Possible but not as great as a gigantic particle)
Particle you'd need one ticking area at the middle and offset the the place it shows & change the size using MolangVariableMap from script api
I might not go with the blocks approach since that would require all chunks to be ticking (not really possible in Bedrock)
You can actually make ticking areas and do operations then delete these ticking areas but i dont think doing all of this and setting border blocks is very performant, so yeah
Yeah
100 players on a single server
I would help you make a giant particle but, i myself am in need of that, here is my post incase herobrine responds to me or i somehow resolve it.
https://discord.com/channels/523663022053392405/1320811741109555270
Does this not cause lag for clients?
I do not know, but i believe not, as it is one particle, not many redstone particles.
Oh, nice
I need this fast
how so?
.button("Text\n" + world.scoreboard.getObjective('money').getScore(player))
oooh thank you! I was putting in the wrong thing š
`(${getScore('Money', player.nameTag)})````
thats what i had before
How to change the direction of a player
I answered you in your post
.button(`${getScore('Money', player.nameTag)}`)
i got it thank you guys š
btw are you sure that you should use player.nameTag instead just player?
i mean really it cant break that much
i usually just make projects for myself and maybe some friends to play
it does not break when player has space in their name?
no I do
I experienced smth like this a long time ago when I was using scoreboard as a db
probably a old bug or something
maybe
What's the standard bundler people use here for ScriptAPI?
what happened?
I changed this
js .button("§sSharpness\n§a$" + world.scoreboard.getObjective('SharpnessPrice').getScore(player))
to this
js .button("", "§sSharpness \n§a$" + world.scoreboard.getObjective('SharpnessPrice').getScore(player))
can I add a image onto these?
.button("§sSharpness\n§a$" + world.scoreboard.getObjective('SharpnessPrice').getScore(player), "textures/...")
ooo thank you!
I dont wanna use applyImpulse, because is very very fast

And applyKnockback dont work on entities
What entity do you want to push?
Show the json code
Ok
{
"format_version": "1.13.0",
"minecraft:entity": {
"description": {
"identifier": "hyentity:shooting_star",
"is_spawnable": false,
"is_summonable": true,
"is_experimental": false,
"runtime_identifier": "minecraft:thrown_trident"
},
"component_groups": {
"despawn": {
"minecraft:instant_despawn": {}
}
},
"components": {
"minecraft:type_family": {
"family": ["shooting_star", "from_space"]
},
"minecraft:collision_box": {
"width": 0,
"height": 0
},
"minecraft:projectile": {
"power": 3,
"gravity": 0,
"uncertainty_base": 16,
"uncertainty_multiplier": 4,
"anchor": 1,
"should_bounce": false,
"offset": [0, 0, 0]
},
"minecraft:damage_sensor": {
"triggers": [
{
"cause": "all",
"deals_damage": false
}
]
},
"minecraft:physics": {},
"minecraft:pushable": {
"is_pushable": false,
"is_pushable_by_piston": true
},
"minecraft:conditional_bandwidth_optimization": {
"default_values": {
"max_optimized_distance": 80.0,
"max_dropped_ticks": 7,
"use_motion_prediction_hints": true
}
}
},
"events": {
"despawn": {
"sequence": [
{
"add": {
"component_groups": ["despawn"]
}
}
]
}
}
}
}
Do you need to throw it at some angle or just straight down?
Just increase the gravity value
I know, but I want to do it with an angle
Like real shooting stars
Using applyImpulse, is really fast
Im not english native speaker, sorry
will the player leave before event work for everyone except the host?
if so I can use it
Wait
if (player.id != -4294967295)
Use this
-4294967295 is host id
No lol
function throwStar(entity) {
let comp = entity.getComponent('projectile')
comp.shoot({
x: Math.random() - 0.5,
y: 1, // Indicate the downward flight force here
z: Math.random() - 0.5
})
}
Np
is it the same on realms?
Oh, thanks
because technically the realm owner isn't the host
I dont know, maybe...
I'll test it when I get home since I have a realm
Is there something like force hit?
i've got a reach check system that works but people has to click for it to work
Animation controllers are your best bet
how would i tell if the player strips a log?
Use a tool to "diff" the two. Figure out the difference between them. Decide which one you want to keep and which behavior pack it came from. Then strategically move the differentiated code from the other file over to it.
Once completed, and done successfully, you will delete the other file. It's no longer needed and the behavior pack it came from will no longer require it.
Your newly merged file can go back into the behavior pack where that file originated from.
From this point the behavior pack now lacking the file will be dependent on the behavior pack with the file containing the merged code.
Install both in your world and profit.
|| Takes practice. You will probably mess it up a couple of times. Even Veterans who are familiar with doing this can slip up and make mistakes so don't assume you are incapable. Practice it. ||
Is there a way to pass information from a resource pack to the script api?
No.
Is the easiest way to get progress of an item use event to store it in a hashmap when u start / finish or is there some way to get progress on it
before events of item use and after events of complete use, release use but it depends on the item
Then store in a WeakMap a time then compare the after events
I ended up just using a runInterval inside the start event, storing it in a map, and then clearing when finished. Ty tho
PlayerInteractWithBlockBeforeEvent
How can I detect when it is raining and the player is not taking cover?
you can't really detect if it's raining
but if it's raining, you can get top most block and check if player's Y is under if
Dimension.getWeather()??
const { x, y, z ] = player.location;
const isUnder = (player.dimension.getTopmostBlock({ x: Math.floor(x), z: Math.floor(z) })?.y ?? -64) - 1 > y;
const { x, y, z ] = player.location;
const isUnder = (player.dimension.getTopmostBlock({ x: Math.floor(x), z: Math.floor(z) })?.y ?? -64) - 1 > y;
if (isUnder && player.dimension.getWeather() === "Rain") {
// ur code
};
most useless functions are always in beta xd
Doesn't really matter but you can use Dimension.heightRange.min
yeah that's a fact too
iirc chatSend is the first event added and it's still beta to this freaking day...
I think they're keeping it in beta due to slash commands tbh
but that's only my opinion, I might be wrong
some example
Block.setPermuration is in stable
Which they will add for like at least 3000 years and more ;)
it would be pretty nice to see slash commands in add-ons
I am not making entire proxy or using software written on-top BDS just to have slash commands
Definitely but I also kinda understand why it's not really implemented yet
they have a bit more important things to add
that's why we don't have ender chest component, so we have to use hasitem selector
They added 3 good things but others too but this is my favorite... Custom categories and the getMovementVector(), more inputpermission options
or they're waiting for christmas to make it their gift to developers
Or things to disable
yeah, I really like it
but tbh slash commands are really nice to have
why I would type !entire-command-name when I can just /entir and then enter tab
Kinda late gift since the next preview will be in 2 weeks of January
in Russia, they're celebreating christmas on 7 January
MOTEHR RUSSIA
Russia moment
I just realized you spelled it as dinmension
fixed
technically I should be writing update to my API right now instead hanging out on this Discord xD
Ohh yeah, getBlockFromRay() and getBlockFromViewDirection() kind have difference
in the getBlockFromViewDirection has limits when you look at the certain angle of the block it passes through the block you're looking at compared to the getBlockFromRay but y'know what's funny they almost have the same functionality we just specified the direction like wtf
I have not used them yet tbh
cosnt blockFromView = player.getBlockFromViewDirection({ maxDistance: 20 })?.block;
const head = player.getHeadLocation();
const blockFromRay = player.dimension.getBlockFromRay({ x: head.x, y: head.y + 0.1, z: head.z }, player.getViewDirection(), { maxDistance: 20 })?.block;```
They don't have a difference, on paper but in game? They do
Really... Impossible
it is even mentioned in docs that they're a bit different from each other?
I keep seeing people say "add slash commands." However, slashes are just another form of a prefix before the actual command. We're able to create commands using various prefixes, so I don't quite understand what some of you mean when I come in here and read "add slash commands." Lol.
What does this do
guys, is there a way i could split this id, in such way, that i only have 'araucaria'? 'v360:araucaria_log'
basically, i have the same custom component for several logs, and i need to get just that first part of the id, so like, split v360 and log, and only have araucaria, so i could later use it in my script as for example v360:decay_${logType}_leaves, and that {logType} is the, welp, log type
i hope i didnt confuse
proper parameter definitions, closing chat, etc.
also just better UX
relying on chatSend also introduces performance problems
??? Please show code to demonstrate.
Already possible to include proper parameter definitions so long as you wrote your code with these things in mind, minus the ability to close chat, but I'm pretty confident they could extend to include that capability. The question is when and will they.
I think what you and others may be really implying here is not so much the ability to introduce "slash commands" since I believe that is not the proper term being sought out in this context, but instead "Command Auto Completion". That terminology makes a lot more sense here.
For example, showing a form, it requires a player to close the chat in-order to open the form meaning we have to loop everytime. Another way is to just create a expiration time or some sort but i don't really think it's that better of an option in terms of UX, we should have a way to send command and then quickly close the chat.
Also on auto-completions as said earlier. If i were to say it, i wouldn't consider sendChat as a viable option in terms of custom commands, it's just some clever way people made to create "custom commands". There should be another event that focuses on slash commands only.
That doesn't answer the question regarding poor performance. You mentioned looping to close chat but your statement is more generic than that so it's particularly not on subject with my statement, but the impact on performance while listening to close chat is minimal at best, unless the logic being implemented is trash (which I have seen some rather rough logic being used for it).
You still haven't provided any code to demonstrate general use case of chatSend being a problem with performance.
If you don't display the form for 300 players at the same time, there won't be any performance problems. (There will be problems only because of 300 players)
But what i said is some potential issues with using chatSend(in some larger quantities), you can use the generic forceShow in this server, even the best ones but it still falls in the same rabbit hole.
Give an example on how you would do it so it can be seen if performant or not.
No i won't, you can search them yourself in this server. It's all the same method anyways, check user busy then run a loop..
Can scripts grab the āminecraft:attack_damageā attribute
It's not the same method. Seen it many of time. I want you to validate your claim. If you can't then that is fine.
You made up a problem, didn't give us the code for that problem, and are telling us to look for a problem that doesn't exist.
No directly
You can create the entity you need, make it hit another entity, find out the damage through the entityHurt event and save it. But itās better to just duplicate the damage values āāin the scripts
What? You want me to create a code that is that is by far the simplest? I don't get the problem of searching it here theres literally hundreds if not thousands.
I can but i won't, it's something that is not worth of my time. And BTW if it's not the same then what kind of new technology do you use? You quite literally can't check if user exits the chat screen without running a loop which again falls on the problem i was talking about.
The logic is everything. Which is why I wanted you to demonstrate your usage, because not every logic is efficient. If you don't wish to show how you would do it so we can exercise the difference then there isn't any need to carry on the conversation.
The purpose of demonstrating it isnāt to engage in a competition, but to provide evidence and validate the data. More importantly, it ensures that others who are unfamiliar and come here seeking information can access reliable feedback.
Logic? If-statement and a loop in a function, how further would you able to simplify that?
If sending out information is what we are doing here then what is your first premise even about? You engaged at something controversial and we tried proving you wrong by giving out simple concepts but you just said they might implement those capabilities later on. You quite literally prove the first's guy by showing what are the holes with sendChat.
Here is an example of a regular force show function -> https://discord.com/channels/523663022053392405/1310685424402042910 and for it to start lagging you must call this function more than 1000 times
And there is no loop used here
There is and you haven't even noticed it
And where? A function within a function is not a loop.
Userbusy -> recursion -> userbusy -> recursion -> userbusy -> recursion, do you not see this idea?
In this case, there is a gap between code execution, unlike a loop, and this will not cause a server crash
Therefore, you need to run hundreds of such loops to cause lag.
Anyways read up to the top of the message, it still falls. We've said the problem on relying on it, you've quite literally proven my point on how ridiculous it is and not comparable to a fully supported slash command implementation
It's easy to make the number of function calls unlimited, you just have to add 2-3 lines of code
And I didn't say anything about "custom commands"
I personally think dismissing the proper support for slash commands isnt good. The equivalent is saying "Why did we need waterlog component when we can already nbt edit to make custom blocks waterloggable" or other ridiculous workarounds.
No not really. Best you could do I guess is detect entityHitEntity and grab the damage. Of course this doesn't factor in equipement.
the current way of adding slash commands do also add incompatibility
And, remind me, does chatSend detect command blocks and othwr means of executing commands?
nope
So then it isn't as versatile as proper commands therefore we do need support for it.
we need a way of knowing if event is canceled
the before event should still reach other packs with the cancel property set to false
yeah
i don't think the chat event is what they are going to use for that
if they do anyway
guys, y does it throw me error of unsupported out of bounds value?
block.dimension.spawnItem(new ItemStack('v360:blueberries', Math.random(2, 3)), block.center())
for Math.random()
argument 1 is invalid, and argument bounds in [1, 255]
Math.floor(Math.random() * 2) + 2)
ah, right...
i'll try it, thank u
works perfectly, thank u!
Is there a way stop when players click a item and then drop it but the item doesn't clear?
no problem
I'm not dismissing it. I'm saying the terminology being used to represent the idea is misleading.
Is it really though?
The main purpose anybody here wants out of it is solely for auto completion. So let's call it what it is.
Ok, now address my other issues.
And I don't believe that. There is also the issue that using / is the defacto command. Using other prefixes treats it as not a command rather a hack.
People aren't asking support to use the string /. They are asking for support for the sake of auto completion. Because when you use the native method built in the application for slash commands you get auto completion in return which makes for a convenient and logical experience to be had. Anyone saying they want support to use the string / in and of itself is either lying or arrogant and not being honest with themselves.
Unless someone contributes code to guide the discussion meaningfully, thereās no need to continue the conversation. Without evidence to weigh and steer the discussion in a constructive direction, a conversation based solely on disagreements offers no opportunity for learning or growth.
it's about highlight and easier validation
So you're calling me a liar and arrogant for wanting my custom commands to actually be treated like commands than can be ran from anywhere and not just the chat?
That sums up what I already spoke on and I don't disgree.
so do you prefer to type entire command name?
Right so you won't address the other benefits people want from slash commands.
they have more features than regular ones (just chat message)
Are you actually arguing that the main purpose is not for auto completion or are you just stirring the pot on something basely to prove your point because of an ego.
I'm stepping away since this is fruitless.
You are arguing like its the only purpose why people want it which I disagree.
It's the majority and I believe even someone like you recognizes to be factual.
When you go back and read the conversations previously had in here about wanting support for slash commands, majority of the time it is not based on support for a specific string but primarily for support having auto completion because of the benefits and convenience it offers.
it offers to make easier to get to know some commands
Agreed
you have information about arguments while typing it
Indeed and that brings a level of convenience that many would appreciate.
Sure, whatever. You spend more time in here than me. I do rarely see the convos that pop up beyond the "how do I make custom commands" questions. But from my experience and use case, autocomplete is one of the last things I worry about. I rather my commands be able to be used in command blocks and entities.
it's easier to implement
And I don't disagree with this statement either. I'm personally ok not having auto completion. My only point when bringing it up was the terminology being used by the majority when they wanted to express such support. Slash commands and auto completions are really different concepts when you look at it more in depth and that is all I was trying to point out before I got flanked lol.
but if you just want to implement smth, don't care about scale just use /scriptevent
Yes thats what I use.
But would you rather
/scriptevent dev:debug blocks
Or
/dev:debug blocks
I already said that
.
yup
As a buge HCF user and having to suffer from the previous management of HCF, having to rely on workarounds for 4 bloody years is a terrible UX. I do not wish the same for ScriptAPI nor future ApIs.
I don't like the term custom "slash" commands since there is only one type of command that exists. The / is used to specify that something is a command where it might not be (ACs where it could be an event name, chat where it could be a message). Commands themselves do not include a slash. If it doesn't start with a slash, it's not being treated as a command, so there is no reason for it to have autocompletions.
I don't know really why they're skipping this feature that much tbh
this would probably make chatSend a stable event
sending chat and running commands are two different actions
yup, and slash commands are there to sepreate them from regular messages
why would I have to handle them inside ChatSendBeforeEvent
Do you mean "Why would I"?
oh yeah
tbh I'm forgetting to swipe it when I'm not adding question marks to the end of my questions xD
world.afterEvents.itemUse.subscribe(ev => {
if (ev.itemStack.typeId !== 'minecraft:diamond') return; player.nameTag = 'Test'
** Does this work? **
There is no })
And it won't work, since you specify the name after return.
Ah, I understand why this is
world.afterEvents.itemUse.subscribe(ev => {
if (ev.itemStack.typeId !== 'minecraft:diamond') return;
ev.source.nameTag = 'Test'
})
it will
there is a semicolon
#1067535608660107284 message
can item stack be compared with other item stacks
Yessir (not natively and not using "===" nor "==", but rather with a function of your own)
Here is my function:
if the item is stackable you can compare them natively
isStackableWith
function isEqualArr(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
function compareItems(item1, item2) { // TODO: make component comparing, finish the world border first tho.
let props = ['typeId', 'amount', 'nameTag', 'keepOnDeath', 'maxAmount', 'lockMode', 'isStackable'];
for (let i = 0; i < props.length; i++) {
if (item1[props[i]] !== item2[props[i]]) return false;
}
if (item1.getDynamicPropertyTotalByteCount() !== getDynamicPropertyTotalByteCount()) return false;
if (!isEqualArr(item1.getTags(), item2.getTags())) return false;
if (!isEqualArr(item1.getLore(), item2.getLore())) return false;
if (!isEqualArr(item1.getCanPlaceOn(), item2.getCanPlaceOn())) return false;
if (!isEqualArr(item1.getCanDestroy(), item2.getCanDestroy())) return false;
if (!isEqualArr(item1.getDynamicPropertyIds(), item2.getDynamicPropertyIds())) return false;
return true;
}
Man i am missing so many basic aspects of the api and everything.. i really need to get back on track....
Is it possible to have a player1.json and a player2.json?
okay
but what doesnt work on this ?
#1067869022273667152
I get no errors when I have that file in my game 
but it work ?
huh?
.
Thanks, unfrotunately doesn't work so well for me when people can have the same full stacks of items
I'm trying to make my own inventoryChange event with server-net but I don't have a way to find out which item stack changed
If only item stacks had a unique id 
Use this, store the previous rows of items in a variable and compare with the current row in a loop. For example ```js
if (stringifyItem(oldItem) != stringifyItem(item)) {
// The item has changed
}
in a loop š
Do you have better ideas?
Unfortunately not
Well, that's all. You can check the inventory of one player every tick and there will be no lags
Do dynamic properties work on stackable items now?
No
Why do you need dynamic properties? You will still need to check this in a loop
Could probably make items have their own unique ids but that would be a lot of memory for dynamic properties
in unicode, 1 character is encoded in 2 bytes, let's say you use 32 characters. You will need quite a lot of such items so that the weight of dynamic properties exceeds the weight of at least one chunk
just cache the previous inv items and compare them
I already suggested this to him 
yeah
he seem to not want to do it that way
but it is better than any alternative
Why not set lore with a unique id?
Set each char with a § before it to hide it
I can imagine a person who walks around with a full inventory of 1 stone in each slot
Items will not stack due to different lore
newly picked items...
it will be a mess
Nah, not a good idea....
doesnt seem like a good idea imo
You are gonna have to setup multiple events and parsing. But hey, the result is great i guess..
I personally do this and it aint laggy
But yall do you
Ima do me.
thats alreadt what im doing but comparing them isnt so easy when they can have multiple of the same item
My method also doesnāt slow down and allows lore items to be customized
I know, its great, yours is a much better approch, but i am suggesting something as per their request.
They asked if they could have unique ids for the items. And i suggested the exact request they wanted. But, optimally, id use serty's approach if i am checking for invs and stuff, but in my case, i am literally making my own block pick up from java. So yes i need the items not to stack.
There's no 100% accurate way to detect drop and pick up even if you find a way there's definitely a limit or bug
if that's what you are guys talking about ( I'm out of topic )
You probably can with some obscure packet logging
I'm talking about script only
or using other entity inventory as cache
It's better to use a regular variable
Or using structure blocks (saving in memory or disk, disk is storage and memory is memory)
that's why I left them first...
There are so many options
I'm too lazy to find a solution for that, I would like to rest first...
but can't be accurate.
I wonder what is stopping you from using any of them?
yeah
i guess inv component cost performance
Nah many of the suggested approaches by all of us are accurate. (Execpt my unique id suggestion)
No.. never will
Elaborate.
server-net
i don't see why not
Now that you mention it..
It's not needed for this at all
I already am logging when player has item stack change to reduce the loops I do
I just dont know how to compare the player inventory item stacks to deduce what changed š
If you wanna go completely bazooka, use an sql db lmao (don't do this)
beforeEvents.packetReceive.subscribe((packet) => {
const { packetSize, sender: player } = packet;
const inventory = player.getComponent("minecraft:inventory").container;
const equipment = player.getComponent("minecraft:equippable");
// Scan the inventory for all item stacks and save them to an array
const playerItemStacks = [ player.getComponent("minecraft:cursor_inventory").item ];
for (const slot of ["Head", "Chest", "Legs", "Feet", "Offhand"])
playerItemStacks.push(equipment.getEquipment(slot));
for (let i = 0; i < inventory.size; i++)
playerItemStacks.push(inventory.getItem(i));
const playerInventory = playerItemStacks.filter(item => item);
// Save the item stacks into memory on the player if not undefined
player.inventory ??= playerInventory;
// Find which item stacks were removed or added and log them into the webhook
for (const itemStack of playerInventory)
if (!player.inventory.includes(itemStack)) inventoryTransactions.push(
`(+) ${player.name} ${itemStack.amount}x ${itemStack.typeId} [${stringifyLocation(player.location)}]`);
for (const itemStack of player.inventory)
if (!playerInventory.includes(itemStack)) inventoryTransactions.push(
`(-) ${player.name} ${itemStack.amount}x ${itemStack.typeId} [${stringifyLocation(player.location)}]`);
// Save the new inventory for future logs
player.inventory = playerInventory;
}, { monitoredPacketIds: [ "ItemStackRequestPacket" ] });
function stringifyLocation(location) {
const { x, y, z } = location;
return `${Math.round(x)}, ${Math.round(y)}, ${Math.round(z)}`;
}
const inventoryTransactions = [];
system.runInterval(() => {
if (inventoryTransactions.length === 0) return;
postWebhook("INVENTORY", inventoryTransactions.join("\n"));
inventoryTransactions.length = 0;
}, 50);
The include statements don't work for obvious reasons
I'm not doing anything much besides trying to log them for now
So what is stopping you from checking if the item is like the one cached?
You're storing the ItemStack in a variable?
!player.inventory.includes(itemStack) and !playerInventory.includes(itemStack) always are going to return true
Their amount, typeId, lore, enchants, componets, canPlaceOn, canDestroyOn, lockMode, keepOnDeath
you can't just compare ItemStack directly you need to grab it's data specifically...
That's why this returns true always
(You can limit this by checking if the new item has these things and the old one doesnt)
not unstakable ones at least
-# Just a reminder :)
https://discord.com/channels/523663022053392405/1292465092541026385
I already know that I was just showing the code to what I was doing with packets
The ItemStack... you still support what i and unknown said you need to grab the data ids, name etc.
So, WHAT IS STOPPING YOU? (Sorry for caps, but really, what is the problem?)
Ohh btw, dyeable component doesn't work on vanilla items iirc.. only in custom ones
Unless they fixed it? I dunno
The food component doesn't work with vanilla either.
That too
Correct since only custom ones expose dyable.
Lets say I do that. First of all im going have to iterate through the current inventory and the inventory cache, and compare if each items are the same. Thats a nested for loop and thus a big O^n operation. Slow as fuck. But lets ignore that. If I compare the item stacks with all the data, its going to return true most the time anyways because my items don't have much defining features from one another, the only thign that is different would be their typeIds and amounts. every other property is always going to be the same. So its going to be super slow and going to return true for items in the cache it shouldnt be.
but do you have another choice?
Or I guess I could map out the item datas into an array and see if its included in there so its not O^n, but still my second problem is still an issue.
If you got a better approach, please go ahead, tell me. I am willing to listen.
Its not really important for me I'm just trying to log what items someone is adding or removing into their inventory for the sake of it
Then limit the checks.
-# I would write the code for you, but I'm lazy, I went to eatš
Dont do lore checks, dont do component checks, it will be much faster.
If there are no enchants on an item, check if the cached has enchants, if yes, return early. (They are different)
dap me cuh
This is by Checking the length of the enchants, all a process of elimination to be faster.
I mean, unknown is correct tho... If checking is slow asf for you then limit check only checks typeid amount and name tag...
As if you have other choices since js is limited to mc rn...
Is it possible to run two things at once for example:
A block with two properties:
- hitbox1
- hitbox2
And both are in different positions is it possible to use something that makes them both enabled at once?
For example I was thinking switching between both on the same tick but idk if it will work prolly not idk
I've used this tactic in multiple game engines and they work but I'm not sure about Minecraft
Elaborate
Just running 2 same things at once basically and making it not override the other one
dude trying to hack the system and male stair like block
Yeah it'd work (without context, i can't provide much help nor details).
Thing is I want it to appear as running at the same time because normally they would both override but the idea is to run them both almost immediately right after the other making an interactive illusion that they're both activated at once
Wait hol up. You want two blocks in the same place?
The concept is to switch between both fast enough to create an interactive illusion that it's one hitbox
I've used It for years in most game engines like Roblox and unity
Just so we are on the same page, by hitbox, what exactly do you mean?
An area a player can hit?
An outline?
What exactly do you mean?
Collision
Ah so you can do this.
So you are gonna need two of the same block with different collision values and then do this:
import { world, BlockPermutation } from "@minecraft/server";
function switchCollision(loc) {
let oldBlock = world.getDimension.getBlock(loc);
oldBlock.setType("namespace:cool_block2");
oldBlock.setPermutation(BlockPermutation.resolve("namespace:cool_block2"));
}
switchCollision({x: 0, y: 0, z: 0});
So you can edit the function and all, its just an example
I'm just really tired so thats why i was typing slow, sorry.
Ah well, everyone has been there, good luck on your journey and i should probably get some sleep... i haven't slept more than (24) hours in the past 5 days... (if you are wondering it is somewhere around 4 & 5 hours per day)
Yo im just posting this here but I'll go sleep rn, if there are any molang & math nerds plz feel free to roast the absolute shit out of me. https://discord.com/channels/523663022053392405/1320811741109555270
Do you even know what's this notation or just trying to act smartass?
just do what they say, having two loops won't crash ur server, the lag would be just small.
And if you don't like that just wait for better packet reading Apis.
yes I know a bit about big o notation
for (loop) {
for (loop) {
}
}
is big O^n
š±
it's not O(n^2) though
you're only looping through the inventory once, checking another inventory at the same time. You don't check each slot for each item
You... Don't need that, that's what you are arguing with unknown it's slow asf?
Ohh my god.
yeah i notcied that after i sent the message here
i was just overthinking it
that's why unknown was confused why it will slow down the game you ain't gonna check it every tick right? Just once soo
no I guess? We still need to use a runtime identifier of snowball, arrow or whatever
so just use a runtime identifier it's just one line
Why?
ask smokey, I think he's experienced using throwable components on items...
HUUUUH?! is this a marketplace contents or some sort?
should not mention him lol
Oh no. :) take my place again void
im assuming it will be
We could have always done that. Your issue is just projectiles trajectory/velocity in general. As for that, no not really. Custom Projectiles still heavily rely on runtime identifiers and unfortunately, it does not seem that Mojang is putting any effort into removing them as it isnt their focus currently.
export let Jutsus = {
"fire_ball": {
damage: 30,
range: 1,
knock: true
},
"phoenix_flower": {
damage: 7,
range: 1,
knock: false
}
export function projetil(entity, player) {
if (entity.typeId != "wesl3y:jutsu_projetil") return;
const jutsuName = entity.getProperty("wesl3y:jutsu");
const teste = jutsuName ? Jutsus[jutsuName] : null;
console.warn(`Propriedade: ${jutsuName}, Damage: ${teste.damage}, Range: ${teste.range}`);
}
what's wrong?
the object is invalid too
You missed one }
export let Jutsus = {
"fire_ball": {
damage: 30,
range: 1,
knock: true
},
"phoenix_flower": {
damage: 7,
range: 1,
knock: false
}
};
How much better memory wise do you think it would be to use item components for onUse events as opposed to a normal item Use event
So with Script API Custom Item Components how do I make an item clickable? With blocks there's a custom component option that enables clicking how do I do the same with an item?
You need the use modifiers component in your item to enable right click.
I do but it still doesn't work
What are you trying to do?