#Script API General
1 messages · Page 11 of 1
It seems like too many people use this library at the same time.:
is onStepOn / onStepOff only in preview currently?
Nope, stable beta-apis
I'd wait 1-2 more weeks if it isn't urgent as it will be stable stable in 1.21.20
oh. i added it to a custom block and it just like doesnt work no error no nothing 💀
setDynamicProperty still not working for me
what's happening?
the game simply forgets about the property after the second interaction
the first time u set the property youre not inputting a value
what is the item stack referring to? the block or the item in your hand... I think you are not setting it on the item in your hand
only the key
to the item
it's not that.
dm me the whole thing or open a post with the whole file. and display the typeId of that itemstack
You can be sure, what I'm reading is "ready"
oh yeah, you dont need to do undefined, you can just leave it blank
the code is "small"
import { system, world, ItemStack, Block } from "@minecraft/server";
world.beforeEvents.playerInteractWithBlock.subscribe(e => {
if(e.itemStack?.typeId === "ewds:resource_counter") {
e.cancel = true;
const ready = e.itemStack.getDynamicProperty("isready");
world.sendMessage(`before setting to "true": ${e.itemStack.getDynamicProperty("isready")}`);
if(ready) {
e.itemStack.setDynamicProperty("isready", false);
const target = e.block.location;
const source = e.itemStack.getDynamicProperty("source");
e.itemStack.setDynamicProperty("source");
const minX = Math.min(target.x, source.x), minY = Math.min(target.y, source.y), minZ = Math.min(target.z, source.z);
const maxX = Math.max(target.x, source.x), maxY = Math.max(target.y, source.y), maxZ = Math.max(target.z, source.z);
const storage = new Map();
for(let i = minX; i <= maxX; i++) {
for(let j = minY; j <= maxY; j++) {
for(let k = minZ; k <= maxZ; k++) {
const block = e.block.dimension.getBlock({ x: i, y: j, z: k });
if(block && !block.isAir) {
storage.set(block.typeId, (storage.get(block.typeId) ?? 0) + 1);
}
}
}
}
const list = [];
for(const [block, quantity] of storage) {
list.push(`${block} (${quantity}x)`);
}
system.run(() => e.player.onScreenDisplay.setActionBar(list.join(" §7-§r ")));
} else {
e.itemStack.setDynamicProperty("isready", true);
world.sendMessage(`after setting to "true": ${e.itemStack.getDynamicProperty("isready")}`);
const target = e.block.location;
e.itemStack.setDynamicProperty("source", target);
system.run(() => e.player.onScreenDisplay.setActionBar(`§7source position set to §s${target.x} ${target.y} ${target.z}§r`));
}
}
});
what exactly is the issue?
I t may return the itemStack of what is in your hand, not not what is in your hand... I think you need to do it on the slot.
it you can....
You need to set the item back into the hand
try puttingit on yourself
I could say this is bad 👁️
ItemStack is but an abstract reference to an item, it does not have to actually exist in the world.
ContainerSlot exists, and is a tangible thing the player can interact with in the world.
When you getItem, it's like you're pulling a copy of the item out of the inventory and into the code
and.... what is this ```js
const source = e.itemStack.getDynamicProperty("source");
e.itemStack.setDynamicProperty("source");```
value = null
I'm deleting the property
Did what Hero said make sense to you Elias?
Yes :D
Guys.. how do you get what is in the hand... is it this... js const inventory = player.getComponent("inventory"); const selectedItem = inventory.container.getItem(player.selectedSlotIndex);copied from the API example
that works
new territory for me... but you are probably on your way to your solution now
can also ```js
const equipment = player.getComponent("equippable");
const selectedItem = equipment.getEquipment(EquipmentSlot.Mainhand);
and then he can put his dynamic property on it?
yes
player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand)``` returns an itemstack
don't forget to set it back! 
like this
LOL
then add like player.getComponent("equippable").setEquipment(mainhand)
i just realized
AND gates are just multiplication operators and OR gates are just addition operators
1x1 = 1 , true and true returns true
1x0 = 0, true and false returns false
1+1 = 2 (positive), true or true, return true
1+0 = 1 (positive), true or false, return true
0+0 = 0, false or false, return false
🤓
i shouldve specified that it only works when the event fires and the player sprints at the same time
but not when the event fires during the sprint
now it's working, thanks
How do I get the name string of a block?
you can't
you can only get the typeID at least, but not the itemStack properties before it was placed
how do i detect if a command wasn't successful in scripting?
successcount seems to do nothing with what im trying to do
.then()
how do i pass the damage value from entityHurt to entityHitEntity using async
i kinda never tried using async so i wanted to know if async works for those or not
i've tried all that. i figured out a workaround with what im doing but im still curious
random question but does player.sendMessage just send to the player or to everyone
yes
ye every entity
yeah i thought so xd
nvm my command just wasnt running no matter what, given that the successcount was always 0
thanks
Is dynamic properties better than Map?
It depends if you want to store data to world permanently or temperatorily
Thats not a good comparison. Dynamic properties is for storing data to the world persistently.
Comparing maps to objects or arrays is a better conversatiob
are maps better than objects
Well what would be better if you're trying to check stuff. Also to help reset things once the player leaves the world
What exactly are you trying to achieve
apparently it doesnt work

what are you doing?
I'm just trying to learn, there's not achievement yet
me? well uh
Ok, what are you trying to learn
trying to bypass iframes
override, nah
The difference between the map and dynamic properties, or if there're better alternatives to both
Do you know what they are in the first place?
im trying to get the damage from entityHurt but would health changed event work here?
Again, what are you trying to do
Somewhat
What are you trying to store?
Both are very different things and should be used in appropriate places
maybe?
Could you give me some examples
im really not sure cuz entityHitEntity fires before entityHurt so entityHitEntity can only get the damage that was done before the event
What's best for dynamic properties/map
and idk if health changed event is any different
To put it bluntly, maps are reset when world closes, dynamic properties are not.
Ahh
They are not the same, however. A map can be a dynamic property if converted & set, a map is a native javscript object and unrelated to script API, a dynamic property exists solely within the minecraft environment, and a lot more.
You would be better off comparing an object to a map.. although I am sure that many threads for that subject exist online, and you can research that on your own time.
As previously stated
Okay so let's say I want to store items from an entity would I use a dynamic property or map?
Do you need the data saved
You can use whatever you fancy. Array, object, map, global variables- heck, if you want use a string.
Yes
Then you would need to hse dynamic properties since maps cannot do that
Ok ok 👌 thanks
You can't put ItemStack in DynamicProperty
Seriously...
but you can put dynamic property in itemStack
string, boolean, number, or vec3 types only
Make a custom entity with the sole purpose of being a itemStack database 🤓
Imagine if itemstacks in dynamic property- recursive properties, yippee!
Does someone else has the same problem? it appears like 2 minecrafts are open
Well I'm currently using map for the video above
and consumes so much resources
At that point, why not make all stackable items have dynamicProperty
Then just stringify the map and store it
Would that store the quantity?
You can store the itemStack in dynamicProperty by first getting all its Components (Enchantment, Name, TypeId, Quantity, Durability, etc) and then converting them into JSON stringified objects.
But it has its own downside
no data 
What data do yoi need?
Sounds like a few extra steps
Ahhh, aux val
Just wait for 1.22
You gotta put a ticking area or teleport them somewhere where the player exists. (Chunk loaded)
/kill isn't an issue after the minimum health is set to 1
You build your re-usable code to handle it for you... that is the great thing about programs...
tick world entity component
What will keep things optimized? Map or dynamic properties
Map will always be faster, as it's a native JS method, whereas dynamic props are a script API exclusive.
However, speed at that level should not really be a huge concern.
Well what if the player leaves the world and I need to transfer their items back.
What bout it?
What's the best option between the two
Why not this
Would work for your needs, it looks like
I highly suggest you take the time to learn and read the docs
I believe they answered you. You said you want to keep the data between sessions. Within a dynamic property you can store only, number or string or boolean or vector3 interface. So within the string you can get creative by taking data and converting it to a JSON obect, then stringifying it, then you can store it as a string. You can retrieve it and revert it back to JSON and so stuff with it.
Look in resources for example code to understand more.
I may go with this method instead
Thank you for being helpful 🙂
If anybody wants to give feedback on the in Interact API share it here!
#1268601041063247955 message
so it appears that onStepOn/onStepOff only works if the block is at least 4 cubes tall in collision
A slab then?
oh, then a trapdoor tall?
guys, how do i use /scriptevent command and what do i need to make in script file itself for it to work?
Yes, just like the old step on component from hcf as well
system afterEvent scriptEventReceive
or smt like that
okey, i'll look into it
oh i didnt know that
Any way to make the compass point to a player without using the world spawn point?
What's a good code editor for android?
I was thinking of showing some text in the subtitle that looks like a compass, but I don't know how to do that
Is it possible to give the player a book and quill with specific text inside via scripting?
can we force enchant an armor? let's say i want to enchant an armor with protection and fire protection at the same time
i know its not possible with script api, but is there a way to do this?
I think you can in creative and save it in a structure to spawn but I haven't tested anything like that
You would have to use an NBT editor and save the item in a structure, but it does work.
I'm not sure if both effects are actually applied though.
wow @amber granite
thanks, would it be changed if I converted it into itemStack in scriptAPI?
If anyone know how to make a durability system that shows the armo durability of the armor that you have on can you let me know 🙂
Hmm ?
No other way man lol ,
Unless u don't know how to use it
Pay someome
Get inventory equipment then get the rusbility and damage and use json ui to display it
I told him
i will
Yeah?
the block id itself is "minecraft:monster_egg"
infested deepslate is the only one withe the right id "minecraft:infested_deepslate"
Its flattenned in .20 or .10
No sound is being played using this:
entity.dimension.playSound("fall.amethyst_block", entity.location, { volume: entity.getDynamicProperty("scan_volume") * 0.01, pitch: 3 });
The scan_volume property is set via UI slider:
sProperty("scan_volume", r.formValues[8] * 0.01);
How come this isn't working?
The slider goes from 0-100
It was working perfectly and suddenly it started showing these errors
i have no idea what happened
Just a question because I haven't seen this yet, but why do you have the two green variables like that
It’s just comments. It has no impact on the functionality of the code
they are in comment
How do I test by block id and state?
I've been racking my brain over this for half an hour
This thing was working perfectly
Oh 😳 I don't use notes in my code, should probably start doing that
Like "minecraft:dirt" ["dirt_type" = "normal"] ?
(🇧🇷) Se eu soubesse alguma coisa de blocos eu ajudava, mas tú deve achar na lib
Eu dei uma olhada mas n entendi bem como funciona ;P
block.typeId
block.permutation.getState('name', value)
Esse negócio de teste é condições né?
Tks
Ss
O mano aí explicou
De qualquer forma, valeu 🫡
Can anyone help me with MolangVariableMap? For particles
Yes
send your particle file
are you going to help them
i will see what i can do
show script side
So it would be something like this?
if (block.typeId = "minecraft:dirt" && block.permutation.getState("dirt_type","normal"))
this is the script?
no
The particle json
Ok
you are not assigning values, you are checking them.
use 3 equal operators " === "
I didn't realize I only put one
Tks
and im pretty sure that state name and value is wrong
im not sure what it is called, but you could use commands and see the auto completions to figure out.
oh you are right, it is dirt_type
...and normal
lol, okay, everything is right sorry
seems like that was your only mistake, this should be all set 👍
@noble lagoon
the script side should look like this
let mvm = new MolangVariableMap(); mvm.setSpeedAndDirection(`v.entityDirection`, 20, vector3 ) //vector3 is direction
entity.dimension.spawnParticle("arc:dash", vector3, mvm) // vector3 is position
20 is the speed
speed and direction will not work anymore, iirc
Thanks, I'll look into this better
use setVector3 instead
let me take a look at the docs
that was an old script i used
Someone told me this, and setSpeed wasnt working for me
But that's literally what I did
I separated it into vector3 and a float
In different variables
you're good, everything looks fine
v.variableName not variableName
-# i think?
uhhh
test it and see
.
that is not what you are doing?
molangVarMap.setVector3("variable.test", vector3)
@thorn flicker
It is instructed that the variable.variableName be only in the particle
I'm going to test putting this in the name but I don't think it will change anything
well thats how I have in my projects
and it's working.
Did not work
I don't see any error in the codes, I don't eliminate the possibility of error, but...
It literally just broke out of nowhere
Maybe the snowstorm broke something, which is usual.
then I have no clue.
The problem was simply capital letters
I write variableName in the particle
But Minecraft reads variablename
A rather stupid problem, I noticed it by seeing that the errors only wrote the name of the particle with everything in lowercase
"canopy:customFuse": {
"minecraft:explode": {
"fuse_length": 4, // change this from ScriptAPI
"fuse_lit": true,
"power": 4,
"causes_fire": false
}
},
}
Is this possible? Current solution is just to make lots of different component groups with different fuse times and select the appropriate one, but I'd rather just be able to set the value smoothly.
DataDrivenEntityTriggerBeforeEvent
Sth like that
U can control an event what comp_group to add/remove
yes you can trigger events, but I want to modify some event settings, and then trigger it
oh so getModifiers() on this might work
https://stirante.com/script/server/1.15.0-beta.1.21.30-preview.21/classes/DataDrivenEntityTriggerAfterEvent.html
Documentation for @minecraft/server
since those are writable
Yeah
How do I modify the block state?
@subtle cove The data driven entity trigger event can modify which components are used, but not the arguments of those components. Is there a way to edit the arguments?
system.run() maybe?
Nah that's different this is already an afterevent. It only gives you the strings of the component id.
Oh
it was possible in old beta, sadly
does anyone have a template for detecting player selecting slot
actually nvm i can make one
player.selectedSlotIndex?
yeah but it returns the number only
i was looking for smth like detecting the change
should be simple to make
Yep-- I've done it. A runInterval that updates the lastSelectedSlot, then you can just check if the player has scrolled since the last tick with this:
function hasScrolled(player) {
return player.selectedSlotIndex !== lastSelectedSlots[player.id];
}```
yw
so again, anyone know if you can do this without just creating a ton of customFuse events?
Is there any alternative for isOp() for realms?
Yea, a custom security check. A lot of different methods and ideas to roll with that. Just have to hit the drawing board and be creative on how you wish to manage it.
how would I add custom classes to a preexisitng class like Player?
Not sure if you can completely, but I dont see why not. I think you'd use 'extends' to extend from the Player class.Doc for extends
yeah I'm not sure if that would really work unfortunately as I want to kinda create a manager system per player, and the best I have at the moment is a map storing the playerId and manager
specifically for the player since you can't create a new instance of a player so I would somehow need to convert the parent to the extended class
Object.defineProperties(Player.prototype, {
getter: {
get() {
return true;
}
},
setter: {
set(value) {
this.setDynamicProperty('test', value);
}
},
function: {
value(param1, param2) {
return param1 + param2;
}
}
})```
would setting an entity's health value in entityHitEntity event apply the health before the entity gets 'hurt'?
how can i get the entity, that i have hit , in projectileHItEvent ?
Have you read the docs
i am messing for 1 hour
with docs
location returns even if i shoot the projectile even at a block
but i cant detect if i have hit entity
there is only projectileHit
oh
how can i use it? :))
I'm sure you can figure that out
i cannt
this my full code
import { Player, system, world } from '@minecraft/server';
world.afterEvents.projectileHit.subscribe(( { location: hitLocation, source } ) => {
// i have to figure out now that the code will run after hitting a entity
// these code run even if i shoot the arrow on a block
if (source instanceof Player) {
const hitDistance = Math.trunc(calculateDistance(source.location, hitLocation));
const interval =
system.runInterval(() => {
world.getAllPlayers().forEach(source => {
source.onScreenDisplay.setActionBar(`Player has hit an entity ${hitDistance} blocks away`)
});
});
interval;
system.runTimeout(() => {
system.clearRun(interval);
}, secondsToTicks(1));
};
});
/**
* Calculates the distance between a Vec3 and another Vec3
* @param {Vector3} vecA - First Vec3
* @param {Vector3} vecB - Second Vec3
* @returns {number} The distance between the Vec3 and the other Vec3
*/
function calculateDistance(vecA, vecB) {
const dx = vecA.x - vecB.x;
const dy = vecA.y - vecB.y;
const dz = vecA.z - vecB.z;
const distance = Math.hypot(dx, dy, dz);
return distance;
}
/**
* converts seconds to ticks
* @param {number} second
* @returns {number} tick
*/
function secondsToTicks(second) {
const tick = second * 20;
return tick;
}```
help me fix pls
i have to figure out now that the code will run after hitting a entity
these code run even if i shoot the arrow on a block
thats the problem
Sorry would this need to be applied in a specific file to be applied globally?
I have mine in a file which is imported into each file I use. I don't think it really matters as long as your manifest file can access it..?
Ah right ok
Try to use entityHurt event instead of projectileHit
why are you still calling for interval variable?
why not use projectileHitEntity?
world.afterEvents.projectileHit.subscribe((event) => {
let {location: hitLocation, source} = event
let entityHit = event.getEntityHit()
if (!(source instanceof Player) || !entityHit) return;
const hitDistance = Math.trunc(calculateDistance(source.location, hitLocation));
const interval =
system.runInterval(() => {
world.getAllPlayers().forEach(source => {
source.onScreenDisplay.setActionBar(`Player has hit an entity ${hitDistance} blocks away`)
});
});
system.runTimeout(() => {
system.clearRun(interval);
}, secondsToTicks(1));
});
@prisma shard
wait a damn minute
is onBeforeDurabilityDamage technically entityHitEntity but focused on item?
i should test smth with this
its detecting when the tool gets damaged, not when the tool damages an entity
but theres a property hitEntity
for some reason
because durability damage isn't just mining
I think that's why
E.g. swords take durability damage when it hits an entity
oh hmmm
yeah
oh there is onHitEntity too as mentioned
ye
I would've expected a "cause" property or something for the durability.
is the durabilityDamage property able to be edited?
the other event listeners pretty does that, that durability fires when it’s like "when everything happens", also yes you can edit damage
meaning we can use this instead of getting the durability component, and making methods out of that
custom item only*
well yeah
ik
well this doesnt trigger the damage, this just edits the damage obviously
i have a game theory, normal mods that are common on java have it so you can make chairs and sit in them, theoretically for bedrock, could you make a chair block and when you interact with it, it teleports you inside the block and plays the animation for when you are inside a minecart so it looks like you are sitting, and when you move the player, the animation stops?
cause using an entity is so boring and unoriginal
How do I getComponent a players armor slots?
Custom items only take damage when hitting an entity. However, since the game cant tell if your item is a weapon/proper tool or not, it will damage 2. This custom component allows you to fix it by making it get damaged 1
oh thats actually neat
hi there, I noticed that sometime ago mojang/microsoft have changed the way they handle player.name ingame for consoles (at least for PS)
before ingame our player.name was the same as gamertag set on microsoft profile account.
now it uses the PSN name as player.name... which is causing some issues of correlation to my ban system.
is there a way I can get ingame the xbox gamertag instead of the PSN name? I know player.id would be unique, but I need to correlate it with the right gamertag
would setting an entity's health to 0 kill them?
Yes / Why not .kill() method?
Yes then
aight ty
have you tested that?
I'm just piggybacking off what Herobrine64 showed you to give more clarity:
import { Player } from '@minecraft/server';
export function initializePlayerPrototype() {
Object.defineProperties(Player.prototype, {
isSpecialPlayer: {
get() {
return true;
}
},
setTestProperty: {
set(value) {
this.setDynamicProperty('test', value);
return this;
}
},
addTwoNumbers: {
value(param1, param2) {
return param1 + param2;
}
}
});
}
import { world } from '@minecraft/server';
import { initializePlayerPrototype } from './playerPrototypeModifications';
// Handle the worldInitialize event
world.afterEvents.worldInitialize.subscribe(() => {
// Initialize the Player prototype
initializePlayerPrototype();
// Additional initialization code
});
Some may disagree with you using Prototypes. If you know what you are doing then ignore the hate you may get.
How do I add text from a language file to a text box in an ActionFormData(); UI?
Read the documentation, use a Rawtext instead of string
.body({ translate: 'my.body' })
system.runTimeout, system.runInterval, system.run
What is the difference between them and what are they for?
Run - once
RunInterval - Run every X ticks
RunTimeout - Run once after x ticks
can I import whole js files into my entry file or can it only be constants and functions that can be exported
you can import the whole file yes
tell me how please
import "./file.js"
Oh ok I got it
Thks
I did that but my files still didn’t run
can you show a screenshot of your scripts folder?
and the script you have done the import in and the one you imported?
content logs?
nothing
are you sure the js files are in the same directory the main script file is in?
you can set the path if you didnt know
(though the content log should say something if the file wasnt there)
just to be sure, this file is linked to the manifest right?
yes
it should work then
What does the other files look like...
uh
const interval = system.runInterval(() => {
});
// the question is- do i need to put the variable here?
// because the interval is stored in a variable
// then how the code run, if its stored in a variable?
// i tried removing this "interval;", but it still work...
// does clearRun runs the variable, then stops it?
interval;
system.runTimeout(() => {
// stop the runInterval after 1 second
system.clearRun(interval);
},20);
```^
help me solve this confusion @valid ice
?
🗿 learn js
you keep coming with stuff like this
but i am not asking for code
this channel is for solving anyone's confusion isnt it
interval is a number which is the ID of the runInterval loop
the code is not stored in the variable the code run and return a number that we store in the variable
that number refer to that interval
look at it like this "hey i am ruining an interval with the id xxxx"
then when we want to clear it we can do that easily sense we have it "address"
When you clearRun that variable, it stops the runInterval
oh
understoood
you can also put the clearRun inside of the first interval if you add a timer```JS
let ctr=0
const runId = system.runInterval(() => {
if (ctr++ == 20) system.clearRun(runId);
<go do stuff here>
),1}```
can i use for loop to clearRun a interval after 20 ticks
Well this one is if the interval is every tick... if not, then outside.. like if you had an interval for every 1.5 minutes and you wanted it to stop at 10 minutes, then it would need to be outside the loop for ease of reading, or inside with the correct math
i was to keep my interval keep running ever tick, then after 20 ticks, the interval will stopped by clearRun
yes
i wanna use for loop
to do this
No, for loop goes fast
use system.runTimeOut
okie
try it... see how many iterations of a for loop you get in a tick
It is best to test out your theories, that is how you learn... from experience
this is doing more work than a runTimeout
const interval = system.runInterval(() => { });
system.runTimeout(() => {
system.clearRun(interval);
}, secondsToTicks(1.5));```
i was just testing how things work, but this is my final code
Yes it may, but if you wanted to do something with the counter, then it is there. Either way works, just showing alternatives... there is even a 3rd way with a for loop and and just system.runTimout.
yeah
he is looking for something like a for loop, so i can see why is that better
But for readability and maintainability by others, then the 1st way is best, no one has to guess what you are trying to do and make sure your math is correct.
be sure to add the interval number to the first system.....
even if it is one
doesnt really need to
system.currentTick could also be used
onTestFailed: wasdhc:simulatedplayer - Failed to spawn test structure with path 'structures/wasdhc/simulatedplayer.mcstructure pops up whenever i run a gametest. I want to test something out using simulatedPlayer but for some reason it wants ot place a tst structure, can i avoid it?
code :
import { register } from "@minecraft/server-gametest";
register("wasdhc", "simulatedplayer", ((gameTestData) => { console.warn("ASd"); }));
I know it does not need it, but best practice is to be clear in your intent. I try to w rite my code like someone else has to maintain it.... like the intern who does not know the details of the method
same problem, idk how to start simulated players too
Simulated Player is a gametest thing which requires structures
gametest is weird. do i need something or can thge structure be filled with air / empty. by this i mean do i need anything to make it run
Prob a special .mcstructure
i used that last week and idk why it doesn't work, it always says failed to run
i want to use simulated players for testing systems where i need multiple players to run something
Bc gametest is used for unit testing lol
Gametest isnt meant for normal addons
it did for me
but as smokey said use it only for testing
yeah i just need it to test some things that required some players
im thinking its a problem on my manifest file, can you tell me what gametest module did you use?
Isn't there only one available version?
can anyone give me a delay function
system.runTimeout bro
function delay (ticks) {
new Promise(resolve => system.runTimeout(resolve, ticks));
} ```
you literally used it in here
i made one but it dont work
This is not exactly where to ask it but do u guy remember the hidden setting in BDS that allow certain command?
@valid ice why does it not work??
idk
Like the privilege level 4 setting
yeah use this, this returns a promise @prisma shard
@warm drum
well i created one and put into my world
but still shows this message
sorry for hte ping, forgot to turn off
sadly i am on 1.4.0-beta, and waitTicks doesn't exist there
so i gotta make a function myself
like waitTicks
that returns a promise
Why?
Are you on edu or smthng?
-# not this talk again lol
i wonder why you can't update your minecraft loll
Why can't you update from 1.20.10???
can we read the container of a chest in a saved structure without placing it? i assume the answer is no, because we can get the permutation, and not the block itself.
Can't you not reassign the movement component value of any entity? Like if i want this entity to not move? Since it's only read-only.
If we can't then sadge
i can just say..
I, don't, have, microsoft store.
is it possible to grab the items of a players inventory and see what item they are holding?
It is possible, yes
how would i go about doing it
const item = player.getComponent('equippable')?.getEquipment('Mainhand') will return an ItemStack
ah ok thanks
/**
* Getting the item that player is holding
*/
const item = player.getComponent("inventory").container.getItem(player.selectedSlotIndex);```
or also you can do it this way
how would i go about returning all the items as json and if you have like a list of the possible functions with that
like every inventory item
and like the amount, enchantments, etc
loop though the container
You need to player.getComponent("inventory").container.getItem() for each slot
ah ok
const container = player.getComponent("inventory").container;
for (let i = 0; i < container.size; i++) {
container.getItem(i);
//Other stuff
}```
const invContainer = player.getComponent("inventory").container;
for (let i = 0; i < invContainer.size; i++) {
const item = playerContainer.getItem(i);```
BRO I SWEA-
alr
i swear i sent this before herobrine, but just bcoz of my internet, it was sent some seconds later 😭
😭
lol\
sadge
?
the this?
yeah,
waitTicks don't exist in my version
so i have to make waitTicks function myslef
world.getAllPlayers().forEach(async player => {
const container = player.getComponent("inventory").container;
const size = container.size
for (let i = 0; i < size; i++) {
const item = container.getItem(i);
if (!item) return;
world.sendMessage(JSON.stringify({ typeId: item.typeId, amount: i, enchants: item.enchants }))
}
})```
when running this it doesnt seem to grab weapons ex: diamond sword or a bow
and i wanted to test enchants with it
You're going to have a hard time being stuck in an old version. Just update it. It's going to annoy a lot of people especially since you never specify the version you're using
.enchants is not a thing in item
ok it still doesnt work with weapons
Should work for everything
(and you won't want to print i for amount, that's your iterating variable)
i just saw that 😭
fixed the amount
but still no bow showing up
world.getAllPlayers().forEach(async player => {
const container = player.getComponent("inventory").container;
const size = container.size;
for (let i = 0; i < size; i++) {
const item = container.getItem(i);
if (!item) return;
world.sendMessage(JSON.stringify({ typeId: item.typeId, amount: item.amount }))
}
})```
aside from the .enchants property, I do not see a problem there
damn
ah wiat
Is it the .size
Ah
You want to use continue
the return is triggering on the first empty slot- essentially saying, "if this slot is empty, then stop this forEach iteration"
#1271187723486625833 i plan on making a inventory gatherer like this for easier use
We didn't see it at first either. It's an easy mistake
did i just make the same thing, as the thing you sent me 😭
seems so
💀
Does not exist
flip
womp womp fr
Everyone and their grandmother wants it
So the ender chest is outright not accessible?
Only with commands
Ah, fair. /replaceitem and such
it probably is thru replaceitem
script devs are pretty generous with features- if it exists, they would release it.
it's definitely possible- it's accessible via commands, so it has to exist on some level.
mhm
Priorities for script API at the moment is getting HCF & custom components out
hcf?
Which is over now
DEATH TO HCF RAHHHHHHHHH
Holiday Creator Features
what do those even do 😭
Item & block components & events
Some components were made stable, others were tweaked and made stable, and events were completely removed in favour of custom components in script API
they need to make the getComponent a class so i can actually see what im doing instead of guessing if it exists 😭
it autocompletes for me/
Does ItemStack.prototype.setLore need system.run?
shouldnt
It does
why 😭
(The answer is up to me, right?)
setLore modifies the world, so if it's being used in a before event, it needs to be pushed to the next tick
If you are not using a before event, it does not need system run
btw if your getting itemStack from inventory component, then you need to set the lore into the slot, not the item.
is it possible to get an items enchants
Does setDynamicProperty need it?
Get the enchantable component
I see- it completes for me.
You can also use jsdocs to type cast the container variable.
idk how to do that, how would i grab a certain items enchants
i had some class, wait let me search my folders, if i still have t
/** @type {Container} */ above the variable declaration
i have an old inventory see somewhere but i cant find it
Documentation for @minecraft/server
1.15.0-beta 😱
@grave nebula
i have a whole class,
which has methods like getEnchant, addEnchant, removeEnchant
import {EnchantmentTypes, ItemEnchantableComponent} from '@minecraft/server';
export class Enchantments {
//returns an Array of Enchantments the itemStack has
static getEnchants(itemStack){
let enchantmentsArray = [];
if(!itemStack.hasComponent(ItemEnchantableComponent.componentId)) return []
const eCompo = itemStack.getComponent(ItemEnchantableComponent.componentId);
enchantmentsArray = eCompo.getEnchantments();
return enchantmentsArray;
}
}
@grave nebula
thx
it returns an array of enchantments, the itemStack has. :))
Back in my day enchant component sucked to use
whats the time in ur area
?
just curous
1:22 pm
i am staring at my pc at midnight as always 🙂
What happens if the length of the string I put in setLore() is greater than 50 characters?
won't work
The game yells at you and it doesn't set
funni
Would be nice if it auto-truncated it
Doesn't it still suck to use? I saw it was so weirdly structured
I guess I'm asking if we still need to pass an EnchantmentType instance to the type property
How so? Aside from the slots missing a few things
Better than before- you had to do some weird stuff with setting & getting the component for it to work
Mm
world.getAllPlayers().forEach(async player => {
const container = player.getComponent("inventory").container;
const size = container.size;
let inventory = []
for (let i = 0; i < size; i++) {
const item = container.getItem(i);
if (!item) continue;
const enchants = Enchantments.getEnchants(item) || [];
inventory.push({typeId: item.typeId, name: item.name, lore: item.getLore(), amount: item.amount, placement: i, enchants: enchants})
}
world.sendMessage(JSON.stringify({ playerId: player.id, inventory: inventory}))
})```
how would i get the items name?
ive tried item.name and item.getName()
neither work
const enchantment = item.getComponent('enchantments');
const enchantmentList = enchantment.enchantments;
for (const enchantType in enchants) {
enchantmentList.addEnchantment(new Enchantment(enchantType, enchants[enchantType] || undefined));
}
enchantment.enchantments = enchantmentList;
``` from an old script of mine
its nameTag isnt it
You can't get the lang file definition for the name, if that's what you're after
oh
e.g. "Blackstone Bricks"
Gotta format the typeId
are there any resources for that
Or manually map all typeIds to their respective names
typeId.replace(/.*(?<=:)/, '').replace(/_/g, ' ').replace(/(^\w|\s\w)/g, m => m.toUpperCase());
Removes the namespace, replaces underscores with spaces, and capitalizes the start of each word
real
Regex helped me do custom enchants from item lore back in the day
fun (& laggy) times
ok slight issue
when i have items with data ex: red sand what would i grad
grab*
item.data?
can't
bru
Wait for the flatenning
No way to get that, unfortunately
help? the lore doesn't appear on my item, what gamerule do I have to enable to show the lore of my item?
system.run(() => {
const result = `§7source position set to §s${target.x} ${target.y} ${target.z}§r`.replace(/(?![^\n]{1,49}$)([^\n]{1,49})\s/g, "$1\n");
e.itemStack.setLore(typeof result === "array" ? result : [result]);
inventory.setItem(e.player.selectedSlotIndex, e.itemStack);
});
I'm setting :(
Maybe try defining the itemstack & the player as a variable outside of the system run
hm, ok
do you mean that?
system.run(() => {
const result = `§7source position set to §s${target.x} ${target.y} ${target.z}§r`.replace(/(?![^\n]{1,49}$)([^\n]{1,49})\s/g, "$1\n");
e.itemStack.setLore(typeof result === "array" ? result : [result]);
});
inventory.setItem(e.player.selectedSlotIndex, e.itemStack);
I don't understand
const itemStack = e.itemStack;
const player = e.player;
And work with those instead of the event variables
hm, I'll do that, if it works I'll let you know
@valid ice it didn't work, and I had to change all variables that had the name "block" to avoid conflicts.
ah lol
I guess there's nothing I can do. ⚔️
Do translation keys not work for slider labels on modal UI forms? Every other aspect works like toggles and buttons, but slider just display the key and not the key's value
Slider key is config_UI_1.slider_1 both in my script and the en_US language file
Also noticed the key doesn't work for the textbox on action form UI
sup guys
well, I'm trying to do something a little bit complicated
making the new custom blocks always has the regular statements, but when the player starts looking at the block, the statement will be changed in a specific case, but when the player looks around the block it will automatically change into the regular statement
without using "minecraft:ticks" or custom block components
i might not be doing that for now, cuz maybe mojang will introduce it later i mean who knows :/
at <anonymous> (bundle.min.js)
at forEach (native)
at createSystems (bundle.min.js:1)
at init (bundle.min.js:1)
at <anonymous> (bundle.min.js:1)
Hey! @wary edge any idea why im getting an undefined error here!
Im sure its the second event im subscribing to, because i get no error when it is commented out
You're binding an after event to a before event
so just remove the 'bind' ?
Notice how the commented line says beforeEvents where as the bind is AfterEvent
But its commented? I was cosuing on the third line
Is the comment still somehow throwing that error
playerInteract is beta
What should i use in the meantime? for player interacting with an entity
switch to beta in the manifest json
Any other currently active events i can sub too?
maybe try item use and get entity from view
Yea but entity hit entity is left click interaction. Im looking for right click
so the onInteract
thanks for the further clarification
that doesn't work i believe, but i am not sure, i tested it on blocks and it didn't work
not with an empty hand
how did your test go exactly? i used afterEvents.itemUse to detect when i use an item on a block that isn't normally interactable and it didn't detect it.
the item also doesn't have interactions
the after event only fires when i am looking away from a block
itemUse always fire on use
i used that and getBlockFromViewDirection
are you sure about that?
Why doesn't it work?
mc.world.afterEvents.playerSpawn.subscribe(eventData => {
const player = eventData.player
if (eventData.initialSpawn) {
worldInitialized(player)
}
})
yeah?
let retest that
Item right click triggers ItemUse on block or air
entities?
Getblockview is just 2nd approach
whatcha trying
Might not
i would retest as well when i can
what doesWorldInitialized function look like
Open an ActionForm when the player enters the world
try opening the form with other event
world.beforeEvents.playerPlaceBlock.subscribe(data => {
const loc = data.block.location
console.warn(!isLocInPlayerIsland(loc, data.player))
if (isInMapRegion(loc) && data.player.getGameMode() == GameMode.survival) {
if (!isLocInPlayerIsland(loc, data.player)) {
data.cancel = true
}
}
})
all the functions work properly as in they return true and false at the right moments
put it in a run interval
clear the run if the form opened
oh, because the player screen didn't load yet
if it works, then you didnt make the form to check for cancel
you can just make the form to check if the form was canceled unintentionally
itll open the form by their own, since the form was already told to do that
was going to say that
function worldInitialized(player) {
const form = new ui.ActionFormData()
.title("title")
.body("body")
.button("button")
form.show(player).then(r => {
r.selection == 0 ? "" : null
})
}
function dcConfig(player) {
let form = new ModalFormData()
.title("Dungeons Combat Settings")
.toggle("Toggle Mod\n(You can use compass to open this menu.)", player.getDynamicProperty("dc_state"))
.slider("Camera Distance", 15, 30, 1, player.getDynamicProperty("dc_camdist"))
.slider("Camera Position", 1, 4, 1, player.getDynamicProperty("dc_campos"))
.slider("Camera Lerp", 10, 50, 5, player.getDynamicProperty("dc_camlerp"));
form.show(player).then((response) => {
const { canceled, formValues, cancelationReason } = response;
if (response && canceled && cancelationReason === "UserBusy") {
dcConfig(player);
return;
}
if (canceled) return;
player.setDynamicProperty("dc_state",formValues[0])
player.setDynamicProperty("dc_camdist",formValues[1])
player.setDynamicProperty("dc_campos",formValues[2])
player.setDynamicProperty("dc_camlerp",formValues[3])
if (player.getDynamicProperty("dc_state") == true) {
setcamera(player)
} else {
clearcamera(player)
}
})
}
this is my modal form
I wanted to open it when I entered the world, it doesn't need to be playerSpawn, but I don't know any other way
No way
just keep loading it until r.canceled returns false
Put the form in a function. Call it in a spawn event. Verify if it's their initial spawn. Then call the function for the form. Verify if the user is busy. If they are, then recall the function. It will loop without creating a memory leak. When they are no longer busy the form will pop up on their screen.
It may be too soon, either push it out a few secs in ticks ... or do a sendMessage to see if stuff can be seen at that time yet. I did something where I let them know where they last died when they re-log back on in case they did not choose to respawn at that time. I had to push the message 40 ticks.
Like this?
I'm not reading essays, am i...
form.show(player).then((response) => {
const { canceled, formValues, cancelationReason } = response;
if (response && canceled && cancelationReason === "UserBusy") {
dcConfig(player);
return;
}
if (canceled) return;
player.setDynamicProperty("dc_state",formValues[0])
player.setDynamicProperty("dc_camdist",formValues[1])
player.setDynamicProperty("dc_campos",formValues[2])
player.setDynamicProperty("dc_camlerp",formValues[3])
if (player.getDynamicProperty("dc_state") == true) {
setcamera(player)
} else {
clearcamera(player)
}
});```
just use this as an example
world.beforeEvents.playerPlaceBlock.subscribe(data => {
const loc = data.block.location
const player = data.player
if (player.getGameMode() == GameMode.survival) {
if (!isLocInPlayerIsland(loc, player) || isInMapRegion(loc)) data.cancel = true
}
})
i doubt anyone will ever search for anything like this ever but i feel like sending the solution anyways (dont do conditions at 2am it doesnt end well)
canceling block placement when outside plot and spawn
@buoyant canopy
world.afterEvents.itemUse.subscribe(e=>{
const b = e.source.getBlockFromViewDirection()?.block??e.source.getEntitiesFromViewDirection()[0]?.entity
console.warn(b?.typeId);
})
WHAT? what version of Minecraft is this?
latest stable
i did my test in a 1.21.10 preview
how do i motivate myself to organize this
jesus
Just do step by step
ok suggestion
i know how i just lack motivation 😭
it doesn't work when the interaction do something
like armor sand pose or trapdoor open
if you dont organize itll grow bigger
you must stop it before it becomes unstoppable
my test was with a Trial key on a used Vault.
What are trying to do ?
clear my confusion about the itemUse after event lol
probably count as interaction
or itemUseOn
maybe, although there was no hand swinging animation
But
i did saw a forum post about that
Hmm did u try itemUseOn ?
iirc you need to use beforeEvents.worldInitialize for item's custom components
itemStartUseOn
this thing doesn't fire if there wasn't a successful interaction between the item and the block
yeah that still the same
active vault do work tho
me and my one file habit
that clears things, so does the itemUseOn fires when using a trial key on a used Vault?
this is even worse
i did it once for a box pvp server
never again
I literally organized my project structure with guilt in my heart just because I saw a large project that is organized xp
me who had export function habit before i realized class exists
camelCase filenames
Decoupling files into another files from other folders = ☠️
iLoveCamelCase
And yet, your name is PascalCase, intriguing
all my projects are one file scripts
even 1000+ line ones
it wouldnt look good in camelCase it can be an exception ok
haha i have a database with nearly two thousand lines
switch(x){
case🐫 : console.log("camelCase")
break;
}
Hey someone can tell me what's the problem of my shark because it despawn and respawn a little time after
I mean I use index.ts/js (for each directory to just easily import it, but still need to exclude some coupled files, so it doesn't blow up) so it's really hard and time consuming for me
The problem apparear at ~30s
i keep each feature in its dedicated file
it dose fire tow times
what did you use to despawn the shark
lol, even though there is no hand animation
"minecraft:despawn": {
"despawn_from_chance": false,
"despawn_from_distance": {
"min_distance": 10000,
"max_distance": 999999
},
"despawn_from_inactivity": false,
"despawn_from_simulation_edge": false,
"min_range_inactivity_timer": 30,
"min_range_random_chance": 800,
"remove_child_entities": false
},
oh i thought it was scripts
I don't get it , what u want to do with hand animation
ah i meant for not used vault
it doesn't work with used one
isn't there like persistent component so it will never despawn?
oh nvm, it's just a 10k block away from Despawn
so used vaults are basically undetectable?
I don't know anything like that
in stable
kinda wired
its probably similar to mobs not despawning if tamed or was fed at least once
you could use that
and then use scripts to despawn sharks instead
the single case i tried, is the one that can't be detected 😂
I found mine from this repo (First large project I found that is organized): https://github.com/nox7/mc-bedrock-villager-system
I don't want despawn the shark, that's my problem
oh just entirely?
that would be funny if all the other blocks work
Yes I would like it to go around the island but it has a radius of 200 blocks
"minecraft:persistent": {},
put that inside entity json
Yippee my discord following to dev and script resources post now works
it does'nt working, but i think it's because the entity don't moving because the shark just have an animation who move it but he stay at the same place
maybe add some navigation behavior components
like : minecraft:behavior.random_swim
ok but if i do that the shark doesn't go around the island ? it just swim randomly
From what I see in the video, it's likely the resource pack fault.
The entity didn't despawn and respawn. The model just disappeared when in certain angle and distance.
Probably because the entity's hitbox was out of the camera visible range. Making the game to unload the entity model?
The entity don't moving because the shark just have an animation who move it but he stay at the same place
That's the issue
The actual entity was out of the player camera, so Minecraft unloaded the model for performance
So I can't make the shark go around the island without making random movements? I must move the entity randomly ?
try increasing the entity's collision box or hitbox
Is it possible to make an item unable to be picked up?
or... make the model rotate based on the entity's head rotation. Then teleport it repeatedly in a predetermined path. (not animation)
i heard you can edit the time of item pick up time by editing NBT data?
Cleared, yes, but answer is no
nvm then
damm it
You can't apply animations to an item using playanimation either, right? I tried but I didn't get any results
you can filter out items and play animations on player
but you cant apply animations on item
I need it in the item entity
I guess it's over
then no
like this? #1267939250503028817 message
Yes, I look for it to be compatible with any item
mines compatible with any item lol including custom ones from other addons
I still need help :)
What did you do to achieve that?
just create an entity with mainhand
then display the item in it
And in this case there are several entities? one for each item?
no, lol, you just need one
do they have many hands then? xd
but in your clip there are more than 2 items
yep, it consists of 4 entities
is on random tick before or after event?
this lists the afterevents ordering
theres also beforeevents orders so you could check that
would this work or is it stupid
string, not array
This is not even runCommands ☠️
I got lazy
[{families:["infantry"]}, {type:"ata:vehicle"}, {type:"ata:aircraft"}]
.forEach(q => {
if (target.matches(q)) target.applyDamage(125, {cause:"override"})
}) ```
yeah this looks pretty interesting, thanks
Those {} are just EntityQueryOptions
where uh would I fit these
Just at the target.runCommand
Replace it there
if (target....) {
[{}].forEach...
} ```
okay 👍
real quick question
what if I want to damage each families with different amounts of damage?
[{families: ["infantry"]}, {families: ["mob"]}, ...othrstuff]
``````js
const dmgs = {
infantry: 100,
mob: 50
}
``````js
const dmg = dmgs[q.families?.[0]] ?? 125
target.applyDamage(dmg, {cause: "override"})
Why isn't this displaying the message? It only displays the translation keys + whatever is within the ${}
entity.sendMessage({ translate: `seeker_wand.scan_message_1`.concat(` `, `seeker_wand.scan_1`, ` `, `${i}`, ` `, `seeker_wand.scan_message_2`, ` `, `${bSide}!`) });
Doesn't work removing .concat and adding + between the keys
ya saying it doesnt show
` `
that?
In game it's displayed as "seeker_wand.scan_message_1 seeker_wand.scan_1 999 seeker_wand.scan_message_2 East"
When someone teleports far away and they're just in 'limbo' for a couple of seconds, is this just a realm thing or a general thing? Made a script for my realm and it takes a while before people can move after teleporting
its because the chunk isn't loaded yet
whatcha trying though
Anyway to make the chunk load faster?
your device
So the translation keys should be wrapped in " " and not ` `?
im honestly not sure
and on top of that, i dunno what concat is
can you tell me about it
.concat() is just a simpler was of adding strings without using +
So msgVar.concat("string1", "string2") would add the string in the msgVar variable, string1 and string2 together
translate each seeker wand
uhm.. i think you can't concat on a translate string without the string being translated yet
sounds like a big fat line is coming right up
idk if % templates still works for translate strings
{rawtext:[{translate:'wand.e'},{translate:'wand.g'}]}
add "text" in between for spaces
Would ${} still be able to be inserted?
Between each translate key brackets
let rawmessage = {
rawtext:[
{translate:'seeker_wand.scan_message_1'},
{text: ' '},
{translate:'seeker_wand.scan_1'},
{text: ' ${i} '},
{translate:'seeker_wand.scan_message_2'},
{text: ' ${bSide}!'},
]
}
entity.sendMessage(rawmessage);
@grave thistle
I'll give that a go and let you know if it works
Is there a way to give a custom model to the Agent in EE?
or make a custom agent? (as in like a new entity)
Will see it in the morning, but having trouble writing a promise that waits for a player to load in and return them.
Thats not a scripting questiom. Seems like a #1067869590400544869 question
That's common and to be expected.
This code is untested and based on the assumption that teleporting a player triggers the playerSpawn event. If this assumption holds true, you can listen to the playerSpawn event before teleporting the player. After teleportation, you can verify in the event handler whether the spawned player matches the one being teleported. If they are a match, you can resolve the promise and proceed with other actions.
import { world, Player, Dimension, Vector3, PlayerSpawnAfterEvent } from "@minecraft/server";
/**
* Teleports a player and returns a promise that resolves when the player has fully loaded.
* @param player - The player to teleport.
* @param location - The destination coordinates.
* @param dimension - The dimension to teleport the player to (optional).
* @returns A promise that resolves when the player has fully loaded.
*/
function teleportPlayer(player: Player, location: Vector3, dimension?: Dimension): Promise<void> {
return new Promise((resolve, reject) => {
try {
// Subscribe to the playerSpawn event before teleporting
const playerSpawnSubscription = world.afterEvents.playerSpawn.subscribe((event: PlayerSpawnAfterEvent) => {
if (event.player.name === player.name) {
// Unsubscribe from the event after the player has spawned
world.afterEvents.playerSpawn.unsubscribe(playerSpawnSubscription);
resolve();
}
});
// Teleport the player
player.teleport(location, dimension);
} catch (error) {
reject(error);
}
});
}
// Usage
const player = world.getPlayers()[0];
const location = { x: 100, y: 20, z: 100 };
teleportPlayer(player, location)
.then(() => {
console.log("Player has fully loaded after teleporting.");
// Proceed with further actions
})
.catch((error) => {
console.error("Failed to teleport player:", error);
});
This is only a theory to experiment with. If it works then you have a potential solution. If not, then it's back to the drawing board.
I may also add, you can check player.isValid(), and if it returns false, call your function to loop back until it returns true. Once true, you know you should be safe to execute code off the player as needed.
import { EntityType } from 'net/minecraft/entity/EntityType';
import { AttributeModifierMap } from 'net/minecraft/entity/ai/attributes/AttributeModifierMap';
import { EntityAttributeCreationEvent } from 'net/minecraftforge/event/entity/EntityAttributeCreationEvent';
import { SubscribeEvent } from 'net/minecraftforge/eventbus/api/SubscribeEvent';
import { Attributes } from 'net/minecraft/entity/ai/attributes/Attributes';
class AkazaEntity {
static EntityAttributesRegisterHandler = class {
@SubscribeEvent
onEntityAttributeCreation(event) {
const attributes = new AttributeModifierMap.MutableAttribute();
attributes.createMutableAttribute(Attributes.field_233821_d_, 0); // Example attribute
// Add more attributes as needed
event.put(EntityType.AKAZA, attributes);
}
}
}
Does this work?
how can we even tell
is that for java?
thats for bedrock?
Ye
Some features of js are unavailable
Bruh for 1.21.1?
Any version
Also I'm going to try do scripting since my demons slayer mod will break in 1.21.20 which is very sad
I will crash out
This is not how you import, and i have never seen code like this in bedrock script api
Fr?
tell me
Chatgpt
where did you get that
i was almost going to tell that
please don't use chatGPT for bedrock script api
I made that 100% why?
hmmmm
Have you checked the script api documentation?
minecraftforge? 
Those routes looks like java modding
What's that 💀🙏

Oh bibble
Oh..
like
i dunno what youre trying to do either
you never mentioned that except "does this work"
Please see the docs if you want to learn the script api
Is the load from spawning in from a join or from a portal?
if from a spawn in, use world.afterEvents.playerSpawn.subscribe and put the thing you want to do in a system.runTimeout after 40 ticks.
It worked, thanks 👍
unless he decoupled all the modules into separate files to make it like you're in java 
you are still alive
// Define the rotation angles for the swinging animation
const swingAngles = [0, 30, 60, 90, 60, 30, 0];
// Function to perform the swinging animation
function performSwingAnimation(entity) {
let swingIndex = 0;
const swingInterval = setInterval(() => {
// Rotate the entity's arm or any other part based on the swingAngles array
// In this example, we are rotating the entity's yaw (horizontal rotation)
entity.yaw = swingAngles[swingIndex];
// Increase the swing index for the next angle in the array
swingIndex++;
// If the end of the swingAngles array is reached, clear the interval to stop the animation
if (swingIndex >= swingAngles.length) {
clearInterval(swingInterval);
}
}, 100); // Adjust the interval duration to control the speed of the animation
}
// Call the performSwingAnimation function when you want to trigger the swinging animation
// For example, when a player swings a sword or attacks
performSwingAnimation(playerEntity); // Pass the entity object that you want to animate
I made something that makes the player constantly swing 😔🙏
i think you couldve
used for loop


