#Script API General
1 messages · Page 4 of 1
wait wtf that sounds better
nuh uh
yeaj
which cant be done with nametags
I could show you mine rn

is the scale done via property
no, it just uses the query.health molang by scaling it horizontally. which has its own drawbacks
Song is fire
oh hmm
with models i can lerp the hp bar
which means less strain(in my brain) getting heal and damage
ok im putting that into my todo list
good to know
ty
yw
i wrote a guide (https://discord.com/channels/523663022053392405/1263468963694903336) to get PC like auto completions on android, can someof you try to see of it works for others or not
How can I detect the player equipment when I step on a specific block?
I tried this but it's not working
content log?
TypeError: cannot read property 'getComponent' of undefined at onEntityFallOn (onStep.js:30) and cannot read property 'getEquipment' of undefined at onStepOn (onStep.js:9)
check the docs again and see if youre using the right properties
is it made with stable api?
@short cliff #debug-playground message
Hilp
mood
sorry i was doing smth
dw
Now i know why they hate programming
Ok so it is working but it's not running when the slot is empty
[Scripting][error]-InvalidContainerSlotError: The container slot is either empty or is no longer loaded. at onStepOn (onStep.js:17)
This is my new code
change this:
const equipment = player.getComponent(EntityComponentTypes.Equippable);
to:
const equipment = player.getComponent('equippable');
Both should work
why slot though, just get the itemStack
Check for boots being valid another way. I believe boots is still an object, so it will not be undefined. But boots.typeId can be undefined. b Maybe use isValid()
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_11_0.EntityEquippableComponent.html#getEquipmentSlot
Common isValid() W
and how do i get the id of the item then
I'm pretty dumb at scripting
.typeId ?
like this?
Just use getEquipment() not getEquipmetSlot()
yeah but i'm using 1.12.0-beta
so it stills throws me an error saying that Feet is not valid
isValid is a function.. so && boots.isValid() && boots.typeId.....
as soon as something fails in the && line, it stops, so it will not evaluate the next thing
^
|| and && are very useful for order evaluation
If you really want, you can replace if statements with &&
if (condition) executable -> condition && executable

This does not error```js
function listEquippablesBygetEquipment(player){
const armor = player.getComponent(EntityComponentTypes.Equippable)
if (!armor || !armor.isValid()) return
for (const key in EquipmentSlot) {
if (armor.getEquipment(key))
player.sendMessage(`ItemStack ${key} = ${armor.getEquipment(key).typeId}`)
else player.sendMessage(`ItemStack Nothing -> ${key}`)
}
}I cannot find a way to test the validity of a ContainerSlot. I suggest using getEquipment for that, then is that if valid, can use the slot, like this JS
function listEquippablesBygetEquipmentSlot(player){
const armor = player.getComponent(EntityComponentTypes.Equippable)
if (!armor || !armor.isValid()) return
for (const key in EquipmentSlot) {
if (armor.getEquipment(key)) {
player.sendMessage(`ContainerSlot ${key} = ${armor.getEquipmentSlot(key).typeId}`)
}
else player.sendMessage(`ContainerSlot Nothing -> ${key}`)
}
}```
If you just want to test the typeId and do not need anything from the ContainerSlot, then just use getEqipment() and not getEquipmentSlot
Does ContainerSlot class avoids the item hold animation when setting item?
When I do a sendMessage(%); then % doesnt show up in chat. I'm trying to display a percentage does anyone know the proper way to do this lol
oh! it's just %% lmao and it only displays one
is % minecraft's escape character?
Good math
I want to see warden's
wdym?
the health bar only widens for a little if the mob has over 30hp
so its only slightly larger than iron golem
its for langs
the wielding animation
For translations yeh
Detect if the player has moved by seeing if their positions have changed or by velocity, and if they have moved, cancel system.runTimeout
how can i make it in this script
world.beforeEvents.chatSend.subscribe((data) => {
const player = data.sender;
switch (data.message) {
case '-rtp':
data.cancel = true;
player.sendMessage(`§l§a${player.name}, §o§fwait 5s for the random tp`)
system.runTimeout(() => {
player.runCommand('spreadplayers 0 100 10 10000 @s');
player.runCommand('effect @s feather falling 30 1')
}, 100);
break;
}
});
any suggestion?
Animation controller which triggers a script event
If you are wanting to cancel the timeout, you would necessarily need access to the handler, right?
Need help
I suppose that could be stored as a property on the player
I want to create an object within an object like this :
let object = {}
object.object = {}
object.object.key = "something like that"
But after i write that the the second object only has one proprety!
Someone knows why ?
Isn't that what you told it to have? That is functionally the same as this:
let object = {
object: {
key: "something like that"
}
};
Yeah but there are another keys
Get added in it
But only the last one appears
Ok , wait...
My bad i didn't declare the second object in the right please
Yeah, seeing the full order of things should make this clearer
Thank u for ur help
If you aren't aware of it already, check out Object.assign. This would be right up your alley
Thx
getDynamicPropertyIds().length
Do you mean not having any dynamic properties? Or not having a specific one?
Write its id
If u get undefined
This proprety dosen't exist
In
getDynamicPr...("id")
That doesn't have a specific
Then try kiro's solution
It didn't work
Can you share what you wrote?
Yeah
system.runInterval(() => {
world.getAllPlayers().forEach(player => {
const getTime = getDynamicPr...("Time");
if (!getTime) {
player.setDynamicProperty("Time", 7)
}
})
}, 20);
Ah, getDynamicPr... should be written in full, getDynamicProperty
how do you push an entity around a circle?
It worked
Thanksss
Thanksss
world.afterEvents.entityHitEntity.subscribe(data => {
let health = data.hitEntity.getComponent("minecraft:health");
let tags = data.hitEntity.getTags();
let SlapperCommand = [];
for(const tag of tags) {
if(tag.startsWith('SlapperCOMMAND:')) {
SlapperCommand.push(tag.replace('SlapperCOMMAND:', ''));
}
}
if(data.hitEntity.hasTag("Im Slapper")) {
health.resetToMaxValue();
for(let player of world.getPlayers())
world.getDimension('overworld').runCommandAsync(`execute as "${player.name}" run ${SlapperCommand}`);
}
});```
When a player hits an entity, all players can run world.getDimension('overworld').runCommandAsync(execute as "${player.name}" run ${SlapperCommand}); is there any way to fix it? ?
Remove the for loop at the end
world.afterEvents.entityHitEntity.subscribe(data => {
let health = data.hitEntity.getComponent("minecraft:health");
let tags = data.hitEntity.getTags();
let SlapperCommand = [];
for(const tag of tags) {
if(tag.startsWith('SlapperCOMMAND:')) {
SlapperCommand.push(tag.replace('SlapperCOMMAND:', ''));
}
}
if(data.hitEntity.hasTag("Im Slapper")) {
health.resetToMaxValue();
world.getDimension('overworld').runCommandAsync(`execute as "${player.name}" run ${SlapperCommand}`);
}
});```
like this?
Sure, but make sure to update the player object in the command to be hitEntity, as player does not exist in that event
Alternatively, you can do hitEntity.runCommandAsync(SlapperCommand)
yo guys, can anyone help me with listing all the features / explaining them (of a utility adddon) as a "reward" i will give the pack : dm me if ur intersted guys !
its a pretty big pack tho so be prepared !
data.hitEntity
#1263861834478260274 someone can help?
oh, I assumed SlapperCommand was a string to begin with
What is the purpose of it being an array? As the command will not run due to it being in an array, even if you convert it to a string
i rwaly need helppppp
realy*
Really*
Don't we all
.-.
For example: I give the villager the tag "Im Slapper" and the tag "SlapperCOMMAND: give @s diamond" and when I hit the villager, all players can run the command "give @s diamond", I just want The person who hit that villager runs the command "give @s diamond"
But why an array? Wouldn't you just want the first SlapperCOMMAND tag? Or do you want it do multiple commands are ran if multiple tags exist on the entity?
entity has only 1 tag slapperCOMMAND, for example "slapper COMMAND: give @s diamod"
someone have a site for thr list of all texture/ui/ like textures/ui/icon_deals
then you could do something like:
world.afterEvents.entityHitEntity.subscribe(data => {
let health = data.hitEntity.getComponent("minecraft:health");
let tags = data.hitEntity.getTags();
let SlapperCommand = data.hitEntity.getTags().find(tag => tag.startsWith('SlapperCOMMAND:'))?.replace('SlapperCOMMAND:', '');
if(data.hitEntity.hasTag("Im Slapper")) {
health.resetToMaxValue();
if (SlapperCommand) data.damagingEntity.runCommandAsync(SlapperCommand);
}
});```
The vanilla resource pack has all available textures
thx
thsk
Use this format... js ...sendMessage(` Percentage of Stuff ${pct}%`)that way you do not have to worry about what else the % may do or be.
when i interact with my block it opens multiple forms on desktop
world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
const player = data.player;
const block = data.block;
if (!player.isSneaking && block.typeId == "example:my_block") {
data.cancel = true
system.run(() => {
openForm(player)
})
}
})```
well technically desktop, i connected my mouse and keyboard to my phone lmao
Yeah, the interact event runs many, many times.
One way to prevent it would be to use a temporary cooldown-
if ((player.__tempCooldown ?? 0) > Date.now()) return;
player.__tempCooldown = Date.now() + 500; //Half a second of delay
or
if (player.lastTick == undefined) player.lastTick = 0
if (system.currentTick - player.lastTick > 5) {
system.run(() => {
openForm(player);
})
player.lastTick = system.currentTick;
}```
humans are slower than ticks... you can test this out by doing a sendMessage in the interact and see how many ticks it is interacting within one quick click on the right mouse button.
ah i see, when i click i technically hold it longer than a tick
i see the problem, thx guys 
also, where is the lastTick? i dont see it in the docs
well some one suggested me to use this and lastTick does not exist
interesting, does it get the tick that the player last did the event?
with first if statement it put lastTick as 0 then when we run our code next to it it put system.currentTick as lastTick so it will check if its not higher than 5
kinda
lastTick is a variable that does not exist in the docs, because you as the coder are defining it.
thx for info
world.afterEvents.entityHitEntity.subscribe(data => {
for (const player of data.damagingEntity) {
const equip of player.getComponent('equippable'))
const item = equip.getEquipment('Mainhand');
if (!item) continue;
const lore = item.getLore();
if (lore.includes('lightning')) {
if (getRandom(20)) {
data.hitEntity.runCommand(`summon lightning_bolt`)
} else {
return;
}
}
}
})```
@valid ice Is such a for loop correct?
i dont think you need loop
if i don't use loop it gives error
What did you have before adding the loop
And just because it does not give an error does not mean it is correct
I used for(const player of world.getPlayers()) before, but if I did that, whoever was holding an item with lightning lore would cause all entities to summon lightning after being hit.
Yes, because you are looping over all players in the world
So is there any way to fix it?
Delete the loop entirely
world.afterEvents.entityHitEntity.subscribe(data => {
const player = data.damagingEntity;
if (player.typeId !== 'minecraft:player') return;
const equip of player.getComponent('equippable'))
const item = equip.getEquipment('Mainhand');
if (!item) return;
const lore = item.getLore();
if (lore.includes('lightning')) {
if (getRandom(20)) {
data.hitEntity.runCommand(`summon lightning_bolt`)
}
}
})
Any suggestions for my crate menu? also, is it possible to make a loading animation/screen within the crate menu? For example: I open up the crate and the pattern blocks changes 3 times with some sort of sound effect within minecraft files.
Well, thank you very much
does the Player.addExperience(...) goes to the equipped tool / weapon the player is holding with mending? I tried with Player.Dimension.spawnEntity(MinecraftEntityTypes.XpOrb.id, Player.location); it works, but with this Player.addExperience(...) , it doesn't.
please add colorful format 😔
are you able to just take off a row from that inventory and adjust the panes so the chest fits in the center?
yep, you can just do [] for it
ok
tnx
Quick question, custom components work with js or only ts?
What's the best way to adjust scoreboard values through scripting
.getObjective().setScore()?
Thank you quazchick
yes
How do I escape read-only mode
wrap the code in system.run() or use the after event instead
It's running in an afterEvents.scriptEventReceive listener, would that work okay?
it also depends on what you're trying to edit. I assumed you were using before events and attempting to write to the world. What are you trying to do?
kinda off topic but whats the unkown texture path? (the black and purple one)
After receiving a script event, it runs a switch statement to a case and eventually reaches a point where the message from the script event is used to modify a scoreboard value
what's the part that you are running into read-only at?
Best to ask in #add-ons
not very active lol
I checked the wiki and it said that .addScore and .setScore can't be used in read-only. I knew from previous work that it might not allow these methods so I was wondering how to escape read-only to write new scores
So?
Ah- read-only in that case is when using before events. You are using after events, so no issues will occur
Ok appreciated
oh
Dynamic properties
Yes
No
Yes- third party editors can access the saved data
Yes ?
I thought that impossible
I’ve accessed them from MCCtoolchest & UME before
Thanks, do you know good documentation about Dynamic properties?
didn't find
is it comperhansive enough?
world.setDynamicProprety("id" , data )
Probably the best you’ll get
world.getDynamicProprety("id")
You cannot, no
No
I mean, maybe creating custom command that will send me back the data no?
But u can make a command
idk, but have you tried creating a minecraft:book and adding enchantments to it?
It creates a enchanted book not the enchanted_book. I am currently at 1.20.51 im fixing my slightly large old scripts, but have you guys tried in the latest?
i think it's a bug
Here's a normal enchanted_book using the give command without enchantments.
Enchanted enchanted_book
I think u need nbt
Pretty sure it’s intentional. They are two different items.
For that
Enchanted book
oh okay, i was confused earlier
give book then giving it enchantment with command gives you enchanted_book with specific enchantment, but using script with addEnchantment(...) to a book gives you an Enchanted book, which doesn't work with anvils
oh okay
That s good
;_;
It s something like glitch but it s not
Because the script api is not dealing with items the same way as the vanilla
How do i subtract from a stack?
yo @valid ice
u got time for like probably a quic kfix ?
its like an update thingy but i cant figure it out
getPlayersFaction(player) {
const factionTag = player.getTags().find(tag => tag.startsWith(factionPrefix));
const factionName = factionTag?.replace(factionPrefix, '');
return factionName;
}``` not a function at line 2
i think thats like the get tags function
That looks fine
please help, what does this mean?
[2024-07-19 14:02:44:513 ERROR] [Scripting] Plugin [Main - 1.0.0] - [index.js] ran with error: [ReferenceError: Module [@minecraft/server] not found. Native module error or file not found.] i've tested it on a different server and it worked, but on my main server it gives an error
nvm, figured it out
weird
import { system, world, Player } from '@minecraft/server';
import { ChestFormData } from './extensions/forms.js';
function ChestTest(player) {
const chestui = new ChestFormData('27')
.title('§l§d Pickaxe shop V2')
.button(10, '§l§3Tier 6', ['$50,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/netherite_pickaxe')
.button(11, '§l§bTier 7', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
.button(12, '§l§9Tier 8', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
.button(13, '§l§5Tier 9', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
.button(14, '§l§5Tier 10', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
.button(15, '§l§dTier 11', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
.button(16, '§l§dTier 12', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
.show(player).then(response => {
if (response.canceled) return;
switch(response.selection) {
case 10:
for(const player of world.getAllPlayers())
player.sendMessage("heyy")
const Money = world.scoreboard.getObjective("Money")
if (Money.getScore >= "50000"){
for(const player of world.getAllPlayers())
player.runCommand("give @s netherite_pickaxe")
for(const player of world.getAllPlayers())
player.runCommand(`scoreboard players remove @s Money 50000`)
}
if (Money.getScore < "50000"){
for(const player of world.getAllPlayers())
player.sendMessage("§l§d HCV KitPvP >> §l§4You do not have enough for a Tier 6 pickaxe")
}
break;
case 11:
break;
case 12:
player.sendMessage("hey 2")
break;
case 14:
player
break;
case 15:
player
break;
}
})
}
world.afterEvents.playerInteractWithEntity.subscribe((event) => {
let entity = event.target;
let player = event.player;
if (entity.hasTag("pickui")) ChestTest(player)
});
Herobraine64 could you help me with your chestui system, am trying to remove score from a player but for some reason i cant
but nvm imma get that off my pack
i am using runJob to achieve this but my game tps drop a lot
way is that?
Are you looping through every item in the game?
lol
yeah
I would recommend using a shorter array of common items, so the game does not take as long then
that a good idea
is there a way to make the function more like async functions?
can i dm you the code?
Shore
W echest viwer
lag machine 2.0
does anyone know what the replacement for "q.block_neighbor_has_any_tag" is in scripting?
what q.block_neighbor refer to?
it is to detect the position of a certain block, practically to detect a block on the sides using "0,0,0"
and what i want to do is be able to know how to use something similar to that but in scripts since I am trying to make a block connect to another with only 2 sides, either north and south or west and east
a picture of what i want to try to do (i did this with HCF events)
If I recall correctly, that molang took a relative direction and a list of tags, correct. So
- if you have your block object, you have it's location,
- then can do the vector3 math to any of the surrounding blocks,
- then get that block object and use the hasTags method.
Turn this into a function with similar parameters.
Also, Kaioga in his gitHub (see resourses), may have code that did connected blocks in scripts, so he would have something that is similar, if he used tags, but he would have to check neighboring blocks.
Is anyone else having an issue with the Equippable and Inventory components from the player?
Sometimes when I do /reload the components become undefined for every player
And it fixes itself by doing /reload again
can I use script to make the glass borders disappear when they are connected https://cdn.discordapp.com/attachments/1260721197876908125/1263999039918309387/Screenshot_2024-07-20_12.19.43_AM.png?ex=669c4657&is=669af4d7&hm=086c14875bbfd9e43230176b5d97b0a60713a94cce0aad4c6358de41f8cd5dc4&
You gotta make your own texture for each possible connection
what a long hp bar
ikr
does aynyone have setTickTimeOut code?
system.runTimeout()
import { system } from "@minecraft/server";
system.runTimeout(() => {
// Code
}, 20);
no
so then
it only requires a valid manifest to use the api and import system
basicly the code RedTnT provided
trying to make a util and I found that they export like this why is there a variable that contains the same thing?
gotta use customComponents and check every tick on its N, S, E, W
hmm idk, thats weird
do I need the constant?
shuld I just remove it?
Nope, iguess he wanted to like classify the thing
Valid
putting there the vanilla server?
if you need it you can add the module for it
Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
and which version should i use
uhmm wait
alr
insert that into your terminal:
npm i @minecraft/[email protected]
it will install the like ressources what vanilla-data contains to your code engine
and then you can use it
you dont need to add a module to your manifest
you can, when he didnt exported the constant, maybe he added it to like classify the functions
but any player that doesnt have installed that cant run the addon like me?
classify?
thats just autocompletions for your IDE
vanilla-data is not used
vanilla-data is only for types and autocompletions
Mainly useful for typescript
I believe you don't need it if you're in javascript?
Correct me if im wrong since I always use typescript
javascript and typescript are the same thing
so, i just learned i little bit more about javascript, what are the differences between typescript and javascript
not the topic, but TS is js but, better support for Types
just use js
alr
oh wait we can use typescript as main script? like main.ts instead of main.js?
they dont need to install it, because the code runs on your device not on theirs
Kinda, Typescript a more extended version of javascript* or more like Java
not really
i find it haves some differences, but wich programming langues dont haves it
the distance between js and java is huge ☠️
i meant TypeScript
Yeah mb, i correct my sentence: the only difference is, the typification
for a "better" usage
(it broked me)
thats true
i couldnt use TypeScript sadly.. i needed to install many shit for it so i gave up
system.runInterval(() =>{
while (switch1) {
statement....
}
},20)
what's the correct way to do this?
do what?
the one above
this would trigger the code in the box every 20ticks
yeah
so depends on your plans, it would work
What are you trying to do? Those are two different things
a switch
system.run(() => {
<your code>
}, <tick Delay>);
while (true) {} 
let switch1 = false;
world.afterEvents.chatSend.subscribe((event) => {
const { sender, message } = event;
if (message == "test1") {
switch (switch1) {
case true:
switch1 = false
world.sendMessage("Off")
break;
case false:
switch1 = true
world.sendMessage("On")
break;
}
}
});
best way to shutdown the world
and why a runInterval?
Not my fault that quickJS ain't a microcontroller 
and why do you even use switch for a boolean?
im connecting it to this switch so when true the runInterval would start and stop if false
wait
the while loop doesnt work when it'ts true
let switch1 = false;
world.afterEvents.chatSend.subscribe((event) => {
const { sender, message } = event;
if (message == "test1") {
sender.sendMessage(switch1 ? 'On' : 'Off');
switch1 = !switch1;
};
});
this is better
yeah that's a lot mor better but that is not the problem though, the while loop doesn't start when it's true
can someone send the most recent manifest.json and package versions
it needs to get triggered
ive not scripted in months lol
you only need the versions right?
how do I trigger it?
Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Latest NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
Preview Beta APIs NPM Types
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
with a function?
(Chat flood but those are latest versions)
np
how dare you-
i got it
so just use the basic manifest like before it should work
I don't know how.....
what do you want to do?
All you need to do to manifest is update version, if using beta APIs. Pretty easy.
yep
while (switch1) {
system.runInterval(() =>{
world.sendMessage("looping")
},20)
}
Do you know what a while loop is? It doesn't make any sense to use one here
// add this somewhere in the code, like on the top
system.runInterval(() => {
world.sendMessage('looping');
}, 20);
@valid ice have you time for a short question?
@halcyon phoenix if you dont know, a while loops runs the code in his block till statement is false
system.runInterval(() => {
if(switch1) {
world.sendMessage('looping');
}
}, 20);
I think this is what you're looking for.
A while usage @halcyon phoenix
let counter = 0;
while (counter <= 10) {
console.log(++counter);
};
Is it possible to like overclock the minecraft TPS, just curious
what
the script was for @halcyon phoenix
oh lol this is what I just needed to do
wait then make it like that:
yeah I reviewd the MDN page thanks for the help
let me send a perfomant version okay?
I don'w even know why I got the idea to use a while loop
let switchState_1 = false, runId = undefined;
const intervallCallback = () => {
// code of the interval
};
world.beforeEvents.chatSend.subscribe((evd) => {
const { sender, message } = evd;
if (message.startsWith('test1')) {
evd.cancel = true;
// switch state
switchState_1 = !switchState_1;
sender.sendMessage(switchState_1 ? 'Loop: on' : 'Loop: off');
// "cancel" or "add" interval
if (switchState_1) {
runId = system.runInterval(intervallCallback, 20);
} else {
if (runId) {
system.clearRun(runId);
runId = undefined;
};
};
};
});
np, everyone begins tiny ( idk how to say it )
While loops are good in moderation- be careful to keep them in check.
This code wont call uselessy the interval when its not true
actually i never used them
so my question from before were, Is it possible to like overclock the minecraft TPS, just curious
Like make higher than 20 TPS?
Yes
Nop
how to know if itemstack is block? (isBlock(ItemStack))
sooo
wait a sec
/**
* returns true, if the provided itemSTack is a block
* @param {ItemStack} itemStack
* @returns {boolean}
*/
function isBlock (itemStack) {
return BlockTypes.get(itemStack.typeId) !== undefined;
};
i used this
import { BlockTypes, ItemStack } from '@minecraft/server';
nice thank you, good person
Np, yw
thanks alot for the help
Does <Entity>.clearVelocity() freeze projectiles?
Im trying to set its velocity, although using .clearVelocity() made my arrow freeze, reloading the world deletes it as well for unknown reason
New thing I found, after waiting for a bit, it disappears but retrying it works
Nevermind, that's the arrow's despawn interval, although reloading it makes it disappears instantly
Is that some sort of bug or?
mind showing how
is there an official documentation for the syntax of minecraft script
it’s just JavaScript (es module)
In generell I had really bad exeperiences with clearVelocity(), and idk why. It just doesn't do what you want it to do sometimes
if you got some external tools you can overclock it pretty easily actually
welp guess that solves it lol
Arrows can't also set its velocity again after hitting a block for some reason so that also solves why apply impulse doesn't work
You have to apply it after spawning
so there no actual document listing the different syntax and what they do
As the Script API is a framework built on JavaScript code, having an understanding of JavaScript is key.
If you are being shown this, then you most likely are a beginner with JS and could use a little guidance.
Videos on Learning JavaScript
Javascript in 1 hour
Javascript Classes in 1 hour
Web Guide:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
Reference Sites:
https://www.w3schools.com/jsref/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://javascript.info
real
Does anyone know how I can set a money score for a player in the first time event entering the map without using player.runCommand?
you can use Scoreboard APIs
first get scoreboard objective
then set value or add value with that entity
I tried but it says that the setScore was not defined
may you share your code here
k
world.afterEvents.playerSpawn.subscribe((eventData) => {
const initialSpawn = eventData.initialSpawn
const player = eventData.player
if (!initialSpawn)
return;
if (!player.hasTag("Member")) {
player.runCommand("scoreboard objectives add deathTime dummy");
const scoreboard = world.scoreboard.getObjective('Money');
scoreboard.setScore(player, 10);
player.addTag("Member");
}
})
well are you share that "Money" objective exists?
Yeah
than there should be no error, do you think you can copy your error here?
not defined is not really specific tho
Ok
Wait a moment
Oh
Now it worked
I changed the order and it worked
Thanks
you still need help?
DM me or open a thread
I'll help
okay I dmed you
What event is click block? Like if a person clicks on a stone block at x y z, it will teleport that person to a certain location
what.
there's a event for that?
either entityHitBlock or playerInteractWithBlock
thask
entity is unloaded
does anyone know how to detect a player phasing though a block?
i think it has been removed in 1.21
why should it be, also it works fine in my other addon
i don't know but that also happens with my Databse addon
damn
that error usually occurs when an entity not in loaded chunk or entity is gone
"Failed to ..."
oh , but how does this happen
r u using runInterval?
no
code...
world.afterEvents.playerInteractWithBlock.subscribe(data => {
if(data.block.typeId == "minecraft:ender_chest" && data.block.x === -13 && data.block.x === -38 && data.block.x === -12) {
data.damagingEntity.runCommandAsync(`tp 200 -60 200`)
}
});```
damagingEntity?
world.afterEvents.projectileHitEntity.subscribe((data) => {
const {projectile, source} = data
if (projectile.typeId.endsWith('_projectile')) {
let hitEntity = data.getEntityHit().entity;
if (!hitEntity.typeId.startsWith('sw_')) {
let value = (0.1 * projectile.getProperty("projectile:damage"));
let sourcePlayer = damageSourceEntity.get(projectile);
hitEntity.applyDamage(value , { cause: `overwrite`, damagingEntity: sourcePlayer });
}
};
})
When I click the ender chest, what happens? What's the problem?
it should be data.player
world.afterEvents.projectileHitEntity.subscribe((data) => {
const {projectile, source} = data
if (projectile.typeId.endsWith('_projectile')) {
let hitEntity = data.getEntityHit().entity;
let sourceEntity = sources.get(projectile);
if (hitEntity.typeId.startsWith('sw_') && (hitEntity.id != sourceEntity)) {
let shield = 0
if (hitEntity.getProperty("fighter:shield")==undefined) {
shield = 0
} else {
shield = hitEntity.getProperty("fighter:shield")
}
let value = shield - (0.1 * projectile.getProperty("projectile:damage"));
if (hitEntity.getProperty("fighter:shield")!=undefined) {
hitEntity.setProperty("fighter:shield", ( 0 >= value )? 0 : value);
console.warn("PROPERTY:"+hitEntity.getProperty("fighter:shield"));
};
if (value <= 0) {
let health = hitEntity.getComponent("minecraft:health");
health.setCurrentValue(health.currentValue+value);
};
console.warn("shield1"+shield);
console.warn("value:"+value);
console.warn(hitEntity.getComponent("minecraft:health").currentValue);
console.warn("shield:"+hitEntity.getProperty("fighter:shield"));
}
};
})
this was the working code in my different addon
@subtle cove
world.afterEvents.playerInteractWithBlock.subscribe(data => {
if(data.block.typeId == "minecraft:ender_chest" && data.block.x === -13 && data.block.x === -38 && data.block.x === -12) {
data.player.runCommandAsync(`tp 200 -60 200`)
}
});```
nothing happened
hmmm
you're doin if statement wrong, you did block.x three times
and there is native way for tp too
So how do I make it teleport me when I click on the ender chest at position -13 -38 -12?
block.x == -13 && block.y == -38 && block.z == -12
how
property issue is fixed , you were right it wasnt loading that time
thsk
now this is the issue :
hitEntity.applyDamage(value , { cause: `overwrite`, damagingEntity: sourcePlayer });
its override
clearVelocity or teleport
can we clear velocity right at the beginning? also doesnt clear velocity not work on players?
use teleport for player
Use enums.
but it will freeze the player
Is @minecraft/server-net still maintained?
exactly
is there any way to just remove the knockback ?
"counterweight" it
hm
Hasn’t been added to for a while, but it still works yes
Great, because it works perfectly
I can't tell if you're being sarcastic or not
No, I'm being real. It works!!
anyone can help me on the post https://discord.com/channels/523663022053392405/1263548447676698697
Its bad for the performance of the game having a script running constantly?
(2 ticks per code run)
Depends on what is being ran- runIntervals are not inherently lag-causing.
`import { system, world } from "@minecraft/server"
system.runInterval(() => {
let players = world.getAllPlayers();
let online = players.length;
for(let i = 0;i<online;i++){
players[i].runCommandAsync("enchant @s efficiency 2")
players[i].runCommandAsync("enchant @s unbreaking 2")
}
},2)`
Its for enchant items as soon as they get it on their hand
humans are slower than ticks... why you need to run less than 10. 30 ticks probably register before they realize it is in their hands
That should be relatively safe to run
However, native enchant methods would be preferred, albeit the code would be more complicated.
Well if this works i aint changing it
lmao the phantom
Also should check if holding something enchantable.. commands do not return errors, but you are still registering one in a way, like if on the command line
im aplying unbreaking also
so all items can get unbreaking
mmm
i think so
well i found the first problem
it enchants books
so ill have to change it
Imagine if dynamic properties could save ItemStacks
Recursive storage in minecraft? Yes please.
bra
i wanted to make recently a script that can storage the items of a dead player in a chest, and i think its not possibly to save the enchantment of the items
Best you can to is transfer the item between containers, which would preserve all data on the item
getComponent('equippable').getEquipment('Mainhand')
uhhh
`for(let i = 0;i<online;i++){
let item = players[i].getComponent('equippable').getEquipment('Mainhand')
if(item==!"minecraft:book"){
players[i].runCommandAsync("enchant @s efficiency 2")
players[i].runCommandAsync("enchant @s unbreaking 2")
}
}
},2)`
this is not working for me then
item is an ItemStack instance in that case- you have to check the .typeId property to see the item ID.
if(item?.typeId !== "minecraft:book"){
ok let me check
it works!
thanks
holdon
it throws me that error when i select the book
i can save the error to dont show it or sumn?
or maybe it was the hand
im || undefined
import { world, system, EnchantmentType } from '@minecraft/server';
system.runInterval(() => {
world.getPlayers().forEach(player => {
const heldItem = player.getComponent('equippable').getEquipment('Mainhand');
if (!heldItem || heldItem.typeId === 'minecraft:book' || heldItem.typeId === 'minecraft:enchanted_book') return;
const enchants = heldItem.getComponent('enchantable');
if (!enchants) return;
const efficiency = { type: new EnchantmentType('efficiency'), level: 3 };
const unbreaking = { type: new EnchantmentType('unbreaking'), level: 3 };
const existingUnbreaking = enchants.getEnchantment('unbreaking')?.level ?? 0;
const existingEfficiency = enchants.getEnchantment('efficiency')?.level ?? 0;
if (existingUnbreaking < 3 && enchants.canAddEnchantment(unbreaking)) enchants.addEnchantment(unbreaking);
if (existingEfficiency < 3 && enchants.canAddEnchantment(efficiency)) enchants.addEnchantment(efficiency);
player.getComponent('equippable').setEquipment('Mainhand', heldItem);
})
}, 2);```
ty it works perfectly tho
how do i kill an entity with scripts
entity.kill()
thanks
why my player tellraw is [object Object] [object Object] ?
tpmenu.show(player).then((r) => {
const buttonNames = []
for(let i = 0; i < privatetp.length; i++) {
buttonNames.push({id: i, name: privatetp[i]})
if(buttonNames[privatetp.length - 1]) {
for(let i = 0; i < publictp.length; i++) {
buttonNames.push({id: i + privatetp.length, publictpname: publictp[i]})
}
}
}
if(r.canceled) return;
const selection = [r.selection]
if(selection[0] === 0) player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"${buttonNames.forEach(element => JSON.stringify(element.name))}"}]}`)
})```
@valid ice how do i get the slot.armor.head in container?
player.getComponent('equippable').getEquipment('slot.armor.head')
?
getEquipment('Head')
and to get it as itemStack? for example player wears a diamond helmet,
const helmetItem = source.getComponent('equippable').getEquipment('head') its not just like this?
Head, not head. Case is very important.
and getEquipment returns an itemstack
is there anyone who can do a anti-phase?
Anti phase
You mean cheat
Anti cheat
U mean like go through a wall
And those types of cheating
yeah pretty much, i wanna stop players from going though blocks/walls
yes
yes
beta
Yeah i can do it
Did u check first if there free ones
Or open sourced ones
Or idk
Check first
i did but none of them have anti-phase or noclip
Ok
DM me
- more infos like :
Wanna kick the player , prevent him from that etc... @glacial widget
prevent him from
Any other infos
I made a gametest but when I try to run it, it says that it can't find it even though I'm running /gametest run {classname}:{testname} or in my case, /gametest run pvptest:test1. Any idea on what the issue could be? I just need to know where to begin debbuging because rn, I have no clue.
why my player tellraw is [object Object] [object Object] ?
tpmenu.show(player).then((r) => {
const buttonNames = []
for(let i = 0; i < privatetp.length; i++) {
buttonNames.push({id: i, name: privatetp[i]})
if(buttonNames[privatetp.length - 1]) {
for(let i = 0; i < publictp.length; i++) {
buttonNames.push({id: i + privatetp.length, publictpname: publictp[i]})
}
}
}
if(r.canceled) return;
const selection = [r.selection]
if(selection[0] === 0) player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"${buttonNames.forEach(element => JSON.stringify(element.name))}"}]}`)
})```
@valid ice can you help me pls ?
Are you including the file that contains the game test?
I think so, it's in the behavior pack inside the scripts folder
did someone found out what this does?
There’s a closeAllForms() which closes all modal/message/action forms from a player https://jaylydev.github.io/scriptapi-docs/preview/classes/_minecraft_server_ui_1_3_0_beta.UIManager.html#closeAllForms
how can that be helpful?
some of you all asked for it months ago shrug
what about an ender chest component? that's more imported I think
How can I execute something when the player gets hit by a projectile?
I know that I should use projectileHitEntity but it's just now working
Send your code
Sup
Ah so
I need the block before player rotation in x
Stupid math : P
I just want to know if player 0 rotation degree
Starts with north block face
Or not
#1264379514377732108
Is there any way to make a Is there any way to make a piece of code run exactly at 8 o'clock? run exactly at 8 o'clock?
Use Date() object
Yes
Can you give me an example code?
I really get bad time with rotation
Does
getRotation({x , y })
Get me the rotation on game's X and Y
Or
They get swapped
It doenst receives any arguments
At 180> it starts to -x
Maybe someone else can help 
You just want the block from behind the player right? Acording to the body rotation
Yep
I found that
So
The function
Return
vec2
That mean x and y
But x and y in regular Minecraft cordination are the yaws
And Y is the pitch
But this is something else
So
X = pitch
And
Y : yaw
And that hurting my brain
Pitch?
Yeah
It like rotation on Y axis
And yaw is rotation on x , z axis
And they are vec2
X : Y
how to get when player is in diff dimension
You need to use just X component
o yeah there is
Yeah
Not sure if you found a solution but try blockComponentRegistry instead of blockTypeRegistry, had that fix an error for me today
Debug result for [code](#1067535608660107284 message)
Compiler found 2 errors:
[36m<REPL0>.ts[0m:[33m4[0m:[33m13[0m - [31merror[0m[30m TS2552: [0mCannot find name 'dimension'. Did you mean 'Dimension'?
[7m4[0m dimension.runCommand("/say tick OR random tick NOT working (tried both)")
[7m [0m [31m ~~~~~~~~~[0m
[36m@minecraft/server.d.ts[0m:[33m3987[0m:[33m15[0m
[7m3987[0m class Dimension {
[7m [0m [36m ~~~~~~~~~[0m
'Dimension' is declared here.
``````ansi
[36m<REPL0>.ts[0m:[33m7[0m:[33m13[0m - [31merror[0m[30m TS2552: [0mCannot find name 'dimension'. Did you mean 'Dimension'?
[7m7[0m dimension.runCommand("/say works")
[7m [0m [31m ~~~~~~~~~[0m
[36m@minecraft/server.d.ts[0m:[33m3987[0m:[33m15[0m
[7m3987[0m class Dimension {
[7m [0m [36m ~~~~~~~~~[0m
'Dimension' is declared here.
ESLint results:
<REPL0>.ts
3:23 error 'e' is defined but never used @typescript-eslint/no-unused-vars
4:13 warning The /say command can be fully replaced with the World.sendMessage api in the @minecraft/server module. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/world#sendmessage for more information. minecraft-linting/avoid-unnecessary-command
6:19 error 'e' is defined but never used @typescript-eslint/no-unused-vars
7:13 warning The /say command can be fully replaced with the World.sendMessage api in the @minecraft/server module. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/world#sendmessage for more information. minecraft-linting/avoid-unnecessary-command
how did this code even work
you tried using getViewDirection()? and decrementing the player coord
x = viewDirection.x * r - player.x
oh nice!
What's 💀
huh?
The distance between the player and the block you want
Oh
Those drops in the video are because of the laptop I have :c
can we detect if entities teleport?
Could you tell me what you mean? Is it about the mob stack, right?
im using an entity inside a block
If I use entities in the blocks??
On your system.runInterval detect when the distance between the old position and the new position of the entity is higher than a "x" blocks, save the old position of the entity as a propoperty of it
there's no other way?
i just want my entity to stop teleporting with teleport command
Wdym
i do /tp @e most of the times, and accidentally not putting target selectors because i have like 10+ entities that needs to be stationary
Nope, just be careful
keep clicking on the wrong server 😔
can you detect what way a block is facing?
I see it well
What the mob stacker does is check if there are entities of the same type in a certain range, where it starts to join them like item staxks, I don't know if he understood me correctly, and every time you kill one, another appears until the amount they collected runs out.
simplest way would be
addTags to the entities that you don't want to get teleported
check for those tagged entities location
if location is changed then it will teleport it back to the location where you added the tag
BEHOLD!
the power of math
"Yo momma so fat that cows orbit her" or something
LOL
Guys can i make item lore with translate instead of using string ?
I tried using rawMessage but it didn't work
can you spawn structures with scriptAPI?
Well i am not sure if thats possible but try using % before the translation key maybe it works like that
Like what?
for example
setLore(["%translation.key"]);
Okey thanks
is there a way to run a function in another js file or do they have to be in the same file?
I separated my scriptevent js in a different file, but I was wondering if there was an alternative way to execute scriptevents without using runCommand.
onPlayerInteract's faceLocation still seems to be relative to the world origin rather than the bottom north west corner of the block, is there a bug report?
how do i get the player's direction? like north, south, east, and west
can i set a block's rotation using script
you can detect where the player is facing, then setPermutation, for getting the direction part idk
so i tried per = block.permutation and then otherBlock.setPermutation(per)
but the otherBlock just get deleted
use something like this either directly inside the setPermutation or in a variable
block.permutation.withState("example:state", 1)```
this should work
const directions = [Direction.South, Direction.West, Direction.North, Direction.East];
function getDirection(player) {
let yRotation = player.getRotation().y;
if (yRotation < 0) yRotation += 360; // Convert to positive if negative
let cardinalRotation = Math.round(yRotation / 90);
if (cardinalRotation === 4) cardinalRotation = 0; // 0 and 360 are the same rotation
return directions[cardinalRotation];
}
const direction = getDirection(player);
oh, thanks
ok thanks
how to check if blocktype is solid (when block is not yet placed on world)?
how do i apply knockback/impulse without doing damage?
also make the knockback/impulse stronger the longer the attack lasts
i want my entity to pull in mobs
the longer the attack lasts, the stronger the pull is
basically starts from 0 to 1
wdym?
are you trying to check that on a permuation
or what
what i want is to place a random block relative to player location
if the random block is solid the block is placed below
else, the random block is placed at the player's location (at the feet)
How do i get the block in playerbreakblock event?
Get the destroyedpermutation
anyone got a snippet of code to detect if player has an armor set when damaged?
Entityhurt -> get equippable component
I have tried doing that, but for some reason it didn't inflict the wither effect to the attacker
could have been my error on that part
what triggers an itemUseOn?
Any item that can be right clicked
if I remember it was something like :
const necroArmor = [
/*Armors Goes Here*/
'wh:necro_helmet',
'wh:necro_chestplate',
'wh:necro_leggings',
'wh:necro_boots'
]
world.entityHurt.afterEvents.subscribe(event => {
const source = event.attackingEntity;
const playerEquippableComp = event.source.getComponent('equippable');
const equippedHelmet = playerEquippableComp.getEquipment(equipmentSlot.head);
const equippedChest = playerEquippableComp.getEquipment(equipmentSlot.chest);
const equippedLegs = playerEquippableComp.getEquipment(equipmentSlot.legs);
const equippedBoots = playerEquippableComp.getEquipment(equipmentSlot.feet);
if(necroArmor.includes(equippedHelmet.typeId,0) && necroArmor.includes(equippedChest.typeId,1) && necroArmor.includes(equippedLegs.typeId,2) && necroArmor.includes(equippedBoots.typeId,3)){
//Add Wither Effect Here
}
})```
world.afterEvents.entityHurt
so if i were to use the place block component on the item it would trigger?
Yes
and its damagingEntity
this one isn't the code snippet itself, but its similiar to it
i see thanks
what does initialPersistence do?
yeah I forgot it was called that, but it is proper in the actual code
I'll guess I have to either test more stuff out or just search for other methods
Not sure why you're doing .includes when you can directly just compare?
...
alright to be fair I might have used some existing scripts from my previous help channels that was for items
bruh
and I thought it was the only way for stable
if it does work on stable then I could've used that instead the entire time
you are just using logical operators
which is just in javascript, and any other language
did notice that when messing around with scripts
Personally I would do:
const validEquipment: Set<string> = new Set(["sword", "shield", "armor", "boots"]);
// Example equipped items
const equippedHelmet: string = "sword";
const equippedChest: string = "armor";
const equippedLegs: string = "leggings";
const equippedBoots: string = "boots";
// Check if each equipped item is in the valid set
if (validEquipment.has(equippedHelmet)) {
console.log("Helmet is valid equipment.");
} else {
console.log("Helmet is not valid equipment.");
}
// Repeat for other equipped items...
``` Could also do this instead of an array
Or just do
equippedHelmet.typeId == "blah"
I'll take notes about these, thank you very much 🙏
typescript
?
💪
so his example will not be the best for you unless you want to learn ts
It's called an example dude
I don't give out actual snippets, just examples so people will actually learn
erm, can you please give me a script that does the griddy?
I was talking about it being typescript, not it being a full script
player.playEmote('griddy')
TS transpiles to JS 🤷
Again, it's an example of what I would do, not directly it being, "Hey, copy/paste this"
forgot lore doesn't work with lang keys 😔
is that applyImpulse?
XD
Is it possible to get all the possible enchantments of not enchanted sword or tool e.g. fishing rod can have mending, unbreaking, lure, and luck of the sea. Like that? Without hardcoding the enchantmentSlot and mapping each enchantment
is it possible to read an sqlite file via js when mc loads a world?
you cannot read files
you can export data from this file manually to js/ts file
you should use dynamic properties to have the fastest speed
if you use bds you could make a request to an endpoint of yours that would perform the db reads/writes
k
he can use connect command too, no?
well yeh but you have to manually connect web sockets
there is no automatic way of doing that
ah
yeah
question, in the block permutation class, how does getState and withState work
withState takes 2 parameters and return a boolean depending on if the value of the first parameter is equal to the second parameter
And getState only takes 1 parameter and return the value of that state
withState returns a new permutation object with a state set to a value
permutation.withState("my:state", "value")
so could i detect if a block has a specific cardinal direction with one of those?
You can use get state
permutation.getState("minecraft:cardinal_direction") === "north"
autocompletion doesn't work for me in functions, does anyone have a solution? I even tried to use @param but got no result
How are you doing it?
function itemActions(index, itemStack) {
/**
* @param {Number} index
* @param {ItemStack} itemStack
*/
if (index === 0) {
}
}```
Still saying "any"
The comments are supposed to be above the function definitio
🤷 if you were using TS you can easily define the param type
aah, not inside
I will try thx
I'm too lazy to always define everything
I mean you dont have to always define everythinf
Can anyone tell me if this works?
const domainAround = player.dimension.getEntities({location: player.location, excludeFamilies: ["domain"], maxDistance: 50})
const domainRay = domainAround[0]
if (domainRay === true) {
player.runCommandAsync("tag @s add domain_around")
} else {
player.runCommandAsync("tag @s remove domain_around")
}
}
I could try
Try it and see
Cant really help you if you dont try it yourself
Same could be said: Instead of asking if this will work, why dont you try it first?
Can you tell me if using (domainRay === true) will identify if there is the const entity around me?
Because even if it works, I won't know why it's working
I need someone to help me understand... Saying that kind of thing sounds really rude.
domainRay seems to be getting the first index of an array of entities so no, it will not work. You need to check if it isnt null. Alternatively, you could just check the array length
I dont see how its rude
"Try and see" sounds like "Are you stupid?"
Especially for those who translate this
Hmmmmm
I dont see it like that but sure. Everyone interprets things differently
Like this?
I wanted to make sure that tag was added if it identified the specific entity within a radius of 50 blocks
Are you telling me to just use the "domainAround" const?
getEntities is like
const domainAround = [Entity, Entity, Entity]
```so doing an if statement like
```js
if (domainAround.length) {}
```will be true when the array have at least 1 entity in the array, and false if 0 [].length
I didn't understand
So you're telling me to use the const "domainAround" and in the If to use "domainAround length'?
For checking if at least an entity is within that radius, Yes
So here you explained to me how "getEntities" worked?
I thought I was supposed to create this const as an array 😅
That's what it looks like
It's already an array of entities depending on the query
Perhaps
player[domainAround.length ? "addTag" : "removeTag"]("domain_around")
@subtle cove
I did this, but even without having any entity from the "Domain" family around, the commands are executed
function domainAround(player) {
const domainAround = player.dimension.getEntities({location: player.location, families: ["domain"], maxDistance: 50})
if (domainAround.length) {
player.runCommandAsync("tag @s add domain_around")
player.runCommandAsync("say domain_around")
}
}
Hmmmm
Wait a moment, I think I got something
the creeper says hello
I Didn't know Mace didn't have Enchantable Slot 🤔
Scanning Items stuff
-# I ain't mapping this sh*t man
works with other addon ig
damn, i'm learning from other people's problem
maybe mace enchantable slot is not applicable yet
yet another hardcoded value xd
The values must've not been updated yet for the API
Bedrock doesnt have spawn chunks
how can I create a new Block like "new ItemStack(identifier)"?
You cant
EnchantmentTypes.getAll()```
why this throw the error is not a function?
oh, there is no getAll...
so how do I get all enchantments?
Does DataEntityTriggerAfterEvent fire even if the event doesn't exist?
Is onBeforeDurabilityDamage from ItemCustomComponents can cancel attack damage?
damn i thought it was a thing back then? i remember doing my command blocks on spawn chunks
anyone have an example of getBlock and it checking if a specific block is there
unless you can confirm
block.dimension.getBlock(blockInLeftLocationNorth = "minecraft:dirt")
works
if (block.north().typeId == "minecraft:dirt")
console.warn("test")
so is north just 1 block next to the origin block, from the north side of course. cause i was using blockInLeftLocationNorth as my location, which was const blockInLeftLocationNorth = { x: x - 1, y: y, z: z };
and then i can use .permutation.getState at the end to get the cardinal direction?
block.north().typeId == "minecraft:dirt".permutation.getState("minecraft:cardinal_direction") === "north"
well
const testblock = block.west().typeId == "minecraft:dirt"
testblock.permutation.getState("minecraft:cardinal_direction") === "west"
doesnt seem to be working, the error keeps saying cant getState, undefined when im literally defining it up there
Anyone?
nope
Then is there any way to detect an interaction to an entity with stable api?
you can make the entity interactable and make it run a scriptevent when interacted with
const westblock = block.west()
//check if its dirt
if (westblock.typeId == "minecraft:dirt") {
//run as dirt
}
//check its states
if (westblock.permutation.getState("minecraft:cardinal_direction") == "west") {
//run if facing west
}
The thing is that I want to get the player who interacted with the entity
The closest player is not always accurate
I just found a way
ah, i see
how to get an item with name tag and lore = script?
so i cant combine them into one if statement
You can, but it will result in a really long if statement
If you don't mind then do it
You want to detect it or set the lore and nametag?
😂😂 currently this is my if statement
if (itemInFirstSlot?.typeId === blockBehindN?.typeId && block.permutation.getState("minecraft:cardinal_direction") === "north" && westblock.typeId == "minecraft:dirt" && westblock.permutation.getState("minecraft:cardinal_direction") == "west")
so i dont really mind
&& is my favorite apparently
Try like this so its more readable```js
if (itemInFirstSlot?.typeId === blockBehindN?.typeId &&
block.permutation.getState("minecraft:cardinal_direction") === "north" &&
westblock.typeId == "minecraft:dirt" &&
westblock.permutation.getState("minecraft:cardinal_direction") == "west"
)
I want to set an item with lore and a name tag in an empty inventory slot
const item = new ItemStack('minecraft:stick');
item.nameTag = 'Epic stick';
item.setLore(['Power: 100', 'Durability: Infinite']);
can name tag break line
I guess
yes
Same string value, just placed differently
Wdym attack damage?
Documentation for @minecraft/server
its for detecting and getting item's durability before being used
world.afterEvents.playerJoin.subscribe((join) => {
for(const player of world.getAllPlayers()) {
const id = join.playerId
const name = join.playerName
if (player.hasTag == `"rank:§a§lVIP"`){
world.sendMessage(`A VIP member ${name} has joined`)
}
}
})
can this work guys cuz tag the has this in them " "
no it wont
player.hasTag("rank:§a§lVIP")
@glacial widget
also why are you iterating all players lol
use playerSpawn event, i dont think you can get player data with playerJoin
Can someone tell me the difference between = and == and === cause I thought I knew but apparently not
= is for assignment.
== checks for value equality
=== checks for both value and type equality
Anyone using Android 13 for Minecraft bedrock scripting? How do you copy your whole BP folder to the "com.mojang" directory located in Android/data?
The (join) will have the player that joined, not need to cycle thru them all, which if you do, all VIP are going to be announced, not just the one that just logged in.
PlayerJoinAfterEvent only has playerId and playerName. Tag is not available, so if you use the playerSpawn event instead, you can check the tag of the player that joined and spawned in. Be sure to check the initialSpawn property to determine if just logged in or not, so that it is not activated from a respawn after death.
https://stirante.com/script/server/1.14.0-beta.1.21.20-preview.22/classes/PlayerSpawnAfterEvent.html.
can't you archive to .mcpack and import?
but if you need access to android/data, without root, use ZArchiver + Shizuku, search how
Ok, thanks. I'll try it later
Hello everyone, how to decrease an item durability every ticks when it's equipped in the chest slot ?
system.runInterval(() => {
for (const player of world.getPlayers()) {
const slotChest = player.getComponent("equippable").getEquipment("Chest");
const slotMainhand = player
.getComponent("equippable")
.getEquipment("Mainhand");
let durabilityMax = slotChest.getComponent("durability").maxDurability;
let durabilityDamage = slotChest.getComponent("durability").damage;
let durability = durabilityMax - durabilityDamage;
if (getEquipmentVoid(slotChest) === "minecraft:netherite_chestplate") {
player.applyKnockback(0, 0, 0, 0.35);
durabilityDamage = durabilityDamage + 1
player.sendMessage(`${durability}`);
}
}
}, 3);``` I tried this but it doesn't work
how to use .teleport?
@stiff ginkgo
entity.teleport({x:100, y:256, z:300}, ...) // ... is teleportOptions (see second link)```
https://stirante.com/script/server/1.11.0/classes/Entity.html#teleport
https://stirante.com/script/server/1.11.0/interfaces/TeleportOptions.html
Documentation for @minecraft/server
Documentation for @minecraft/server
How to know you're making a progress on JS:
Able to fully understand documentations are beautiful thing to ever exist
TS is like having a senior at your back reading your code
TS is JS with types
You can't, without root. You can thank Google for that. They call it "Scoped Storage". The idea is to add additional security and privacy protection by limiting how other apps can interact with one another. They implemented it back in Android 11 but it wasn't being enforced. By Android 12 that changed.
Edit: You can do it if you plug your device to a computer. Root is not required.
How? I tried using adb, such as push and shell, and still can't operate to create a directory or touch a file. I mean I can adb push 1 file at a time, but that's tedious. Can't push a whole directory from my computer to android
Don't need to use adb. Just mount the device and open your file manager on the PC. Go to the mounted drive and make changes to the file/folder from there.
The point of typescript is that you always know what the type of every variable is. If you set things up right, typescript will always give you auto complete for every part of your code automatically and you never have to worry about getting undefined errors in the game because typescript can identify 99% of bugs before you even start Minecraft.
Jayly's script debugger is just a combination of typescript checking and eslint. You can easily set up VSCode to always give you that information and more.
Oh, okay. I was trying to copy a BP directory from my computer to "com.mojang" in Android/data using the mounted drive, and didn't work idk.
There should be no restrictions when connected to the PC. The restrictions are limited to the framework of Android only.
When you plug your device in to your computer it should recognize the connection. By default it's charging only. On your device you select to change it from charging to file transfer. This will have your computer mount the storage drive.
Open the file manager, double click on the mounted drive related to your device, then go to Android/data/com.mojang and you should have no issues modifying that directory. When done, just make sure you properly unmount the drive or use your phone to change back to charge only to prevent file corruption/damages.
you can use shizuku and zarchiver
someone already suggested this
Oh okay. Thank you for your responses. Going to try rn (2nd time), i think i was just hungry earlier that's why I am confused of what am I doing
I am using zarchiver and shizuku in android 13, and can't create a file or folder inside android/data
You have to grant those permission to access the directory but even still, it will be limited on what it can do.
enable this settings
Yup already did
kinda weird cuz ima able to make files and folder in android/data
Which Android version are you on?
13
Does it let you copy files over to Android/data? Can you show a video?
I do know that Root can open the door to make it possible to bypass Scope Storage but every device is slightly different on how you approach it due to OEM's making their frameworks unique by their own standards.
world.afterEvents.playerSpawn.subscribe((v) =>{
let joined = v.initialSpawn
let player = v.player
if (player.hasTag("rank:§a§lVIP" && joined)){
world.sendMessage(`VIP member ${player.name} has joined`)
}
})
smth like this right
Weird
Yeah, thanks for the responses, really appreciate it.
ah, its beta api, thank you
Yes, like that. Have you tried it out?
what will beta-1.140 change from beta-1.13.0?
Who made this website, he is a genius
@charred dune

That s cool man , u really make knowing changes between api versions easier than before


