#Script API General
1 messages · Page 32 of 1
dimension.getEntities
what gega means is
const target = [...world.getDimension('overworld').getEntites()].find(e => e.hasTag(`stand`))```
or
```js
for (const dimension of ['overworld', 'nether', 'the_end']) {
const target = [...world.getDimension(dimension).getEntites()].find(e => e.hasTag(`stand`))
}```
const target = world.getDimension('overworld').getEntities({tags: ["stand"]})[0]
world.getEntities = function (option=null) {
return [
...world.getDimension("overworld").getEntities(option),
...world.getDimension("nether").getEntities(option),
...world.getDimension("the_end").getEntities(option)
]
}
What do these dots mean?
Conveniently merge two array into one single array
if u didnt use the dot it'll become a nested array (array in array)
combining them into one array,
-# oof gega answered already
[...[1,2,3], ...[4,5,6]] = [1,2,3,4,5,6]
``` ?
yes
Deleted cus I'm not sure either :P
hmm dw
Does the name matter? Just know what it does should be enough
Just wanted to know - can be useful for own objects
How to make mobs to not attack players without changing difficulty?
Use entity.json and edit the target condition or player's family
well but how to get the new entity.json file? Cuz in vanilla behavior pack it’s 1.18.20 format version
will it work if I replace “tags” with “name”?
trigger the event that adds their baby component group
to find that, look in their files.
is it like possible to "clone" a mob, with all their components
for sheep, there's an event called spawn_baby
ok, thank you
you can clone mobs with structures
there's no official method to clone mobs yet
and to "copy" components to another mob?
no
ok
i want to make a wand that turns every mob in a range into a baby, but the problem is, that the mobs have different baby events. Is there a solution to this
```language
//code
```
for example
```js
//code
```
//code
ty
make object that map every event name to it mob type
for example
const eventName = {
"mineccraft:bee":"mob:event",
//...
}
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
@dull shell
Thank you!
Hey anyone know how I can save the player inv even when player disconnect?
const inventory = player.getComponent('minecraft:inventory').container;
With this method once the player disconnects the variable gets erased
let cache = {}
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
let items = []
for (let i = 0; i < 36; i++) {
const item = player.getComponent("inventory").container.getItem(i)
if (item) { items.push(item) }
}
for (const equipment of ["Offhand", "Head", "Chest", "Legs", "Feet"]) {
const item = player.getComponent("equippable").getEquipment(equipment)
if (item) { items.push(item) }
}
cache[player.name] = items
if (!item) return cache[player.name] === undefined;
}
});
world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
if (!initialSpawn) return;
for (const item of cache[name]) {
dimension.spawnItem(item, location)
}
});
idk how to check if player got disconnected
Yeah i have sumthing like this
But the problem is the saving in the world
world.sendMessage(`§4${attacker.nameTag , "killed The Ender Dragon"}`);
whats the proper formatting for a sendMessage command like this?
Okay thanks, do you have an example of how to save this const inventory in setdynamicproperty for example?
Alright sure, thanks!
itemstacks aren't entirely serializable so you'll lose nbt data if you do it this way
you could copy all the items to a storage entity and then save it in a structure though
🧐
is there anything that cannot be serialized?
wdym?
What data in an Itemstack cannot be serialized
a lot of it
technically none of the itemstack can be serialized in place
you gotta first get the typeid, enchants, lore, nametag etc
and then serialize those
and then make a new itemstack and set those
Rough draft @thorn spindle
import { world } from '@minecraft/server';
world.beforeEvents.playerLeave.subscribe((event) => {
const player = event.player;
let inventoryData = {};
const inventoryContainer = player.getComponent('inventory').container;
const inventorySize = inventoryContainer.size;
for (let index = 0; index < inventorySize; index++) {
const item = inventoryContainer.getItem(index);
if (!item) continue;
let itemData = {
typeId: item.typeId,
count: item.amount,
lore: [],
enchantments: []
};
// Get item lore (if any)
const lore = item.getLore();
if (lore.length > 0) {
itemData.lore = lore;
}
// Get enchantments (if any)
const enchantmentsComponent = item.getComponent('enchantments');
if (enchantmentsComponent) {
const enchantments = enchantmentsComponent.getEnchantments();
if (enchantments.length > 0) {
itemData.enchantments = enchantments.map((enchantment) => ({
id: enchantment.type.id,
level: enchantment.level
}));
}
}
// Get custom name tag (if any)
const nameTag = item.nameTag;
if (nameTag) {
itemData.customName = nameTag;
}
// Store the item data in the inventoryData object
inventoryData[`item_${index}`] = itemData;
}
// Serialize and save the inventory data
let serializedInventory = JSON.stringify(inventoryData);
world.setDynamicProperty(`savedInventory_${player.id}`, serializedInventory);
console.log(`Saved inventory data for ${player.name} (ID: ${player.id}) to the world.`);
});
Does anyone know how to set armor from a chest into your equipment slot(armor slot)
witht the component eqquipable
player.getComponent('equippable').setEquipment('Chest', <yourItem>);
that is a typescript error
you can just ignore it if you are not working with ts
Wdym
Its not a Error?
debugger is wrong
FINALLY!
Wow, and I was just starting to use it in my addon too. What are the chances
we no longer need laggy 3D nested loops to search for blocks
thanks bro, it worked
is there a stable way to remove tags from a player that is disconnecting from the world?
How do I execute a command when I break a stone block?
let commandList = ["say test", "say test2"]
world.beforeEvents.playerBreakBlock.subscribe(data => {
let player = data.player
let block = data.block
if (block.typeId == "minecraft:stone") system.run(() => {
commandList.forEach(cmd => player.runCommand(cmd))
})
})
ok
How do I store player data as world? So I can edit/retrive it offline?
In dynamic propertys opfc
ofc*
How do i run an command when an player named "ID" joins the server?
Also how do i check if an player kicks an other player?
player spawn event for the first one
Second one- player leave, although you can’t find if they were kicked or just left on their own
Ahh ok, thx
Hmm🤔 but there must be smth different in player stats or so when hes kicked
There sure ain't
Why the tag don't assing?
export function showForm(player) {
let filiationForm = new MessageFormData();
filiationForm.title("§l§0Choose Your Filiation");
filiationForm.body("Wich side you gonna get in? there are two options, the marine(honor) and the pirate(bounty), you can change it");
filiationForm.button1("§l§9Marine");
filiationForm.button2("§l§cPirate");
filiationForm.show(player).then(r => {
if (r.canceled) {
system.runTimeout((() => showForm(player)), 10)
} else {
world.sendMessage("Welcome to §lBlock Fruits server§r, you selected " + (["§l§9Marine", "§l§cPirate"][r.selection]));
if (r.selection === 0) {
world.getEntity(playerId).addTag("marine")
} else {
world.getEntity(playerId).addTag("pirate")
}
}
})
}
world.afterEvents.playerSpawn.subscribe(eventData => {
if (eventData.initialSpawn) showForm(eventData.player)
})
The error:
[Scripting][error]-Unhandled promise rejection: InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: string
What is playerId
And you can just do player.addTag(), you don't have to do world.getEntity()
Hummm
Sorry the ping
No worries
world.beforeEvents.playerBreakBlock.subscribe(data => {
let player = data.player;
let block = data.block;
if (block.typeId == "minecraft:oak_log" && isHoldingAxe(player, "minecraft:axe")) {
breakTree(block);
player.runCommand("say 1");
}
if (block.typeId == "oak_log" && isHoldingAxe(player, "minecraft:axe")) {
breakTree(block);
player.runCommand("say 2");
}
if (block.typeId == "minecraft:oak_log" && isHoldingAxe(player, "axe")) {
breakTree(block);
player.runCommand("say 3");
}
if (block.typeId == "oak_log" && isHoldingAxe(player, "axe")) {
breakTree(block);
player.runCommand("say 4");
}
if (block.typeId == "minecraft:oak_log" && test(player, "Mainhand", "netherite_axe")) {
breakTree(block);
player.runCommand("say 5");
}
if (block.typeId == "oak_log" && test(player, "Mainhand", "minecraft:netherite_axe")) {
breakTree(block);
player.runCommand("say 6");
}
if (block.typeId == "oak_log" && test(player, "Mainhand", "minecraft:netherite_axe")) {
breakTree(block);
player.runCommand("say 7");
}
if (block.typeId == "minecraft:oak_log" && test(player, "Mainhand", "netherite_axe")) {
breakTree(block);
player.runCommand("say 8");
}
});
export function isHoldingAxe(entity,tag){
const inventory = entity.getComponent("minecraft:equippable");
if(inventory.getEquipment("Mainhand") != null){
const mainhandItemTag = inventory.getEquipment("Mainhand").hasTag(tag);
return mainhandItemTag;
}
}
export function test(player,equipmentSlot,itemName){
const equippableComponent = player.getComponent("minecraft:equippable");
if(equippableComponent.getEquipment(equipmentSlot)!=undefined){
return equippableComponent.getEquipment(equipmentSlot).typeId == itemName;
}else{
return false;
}
}
I tested it like this and it wasn't any
:/
Same error
[Scripting][error]-Unhandled promise rejection: InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: string
Would recommend adding a .catch(error => console.warn(error, error.stack)) at the end of your form .show() so you can get the line the error is on
like: form.show(…).catch(…
it is not completely random, it is only pseudo-random.
if you want proper color space conversion, I recommend https://www.npmjs.com/package/color-core
color-core is a comprehensive, type-safe color manipulation library for TypeScript and JavaScript applications. It provides a powerful toolkit for working with colors across multiple color spaces, making it an essential tool for developers working on pr. Latest version: 1.4.0, last published: 3 months ago. Start using color-core in your projec...
why does this not work?
world.afterEvents.entitySpawn.subscribe((e) => {
console.log(`Entity spawned: ${e.entity.typeId}, NameTag: ${e.entity.nameTag}`);
if (e.entity.typeId !== "minecraft:item") return;
if (e.entity.nameTag === "§d§lStarter") e.entity.kill();
});
if you don't want to use a js bundler like ESBuild then here is an already bundled one from one of my add-ons:
meant to kill entitys with "§d§lStarter" name
I recommend using event as the variable name, as e is usually used for errors
i did still nothing happens
is it giving you any errors
none
are you getting the console log
i have it all turned on
and do you have your content log level set to "info" in settings
no errors at all
yes
so it did log it in the console?
still nothing
check if the entitySpawn event is firing at the first place
ohh
yes
oh then are you sure the formatting codes are in the EXACT same order on both
yes
wait so is the
console.log(`Entity spawned: ${e.entity.typeId}, NameTag: ${e.entity.nameTag}`);
function working at least
world.afterEvents.entitySpawn.subscribe((ev) =>{
console.log(`Entity spawned ${ev.entity.typeId}, NameTag: ${ev.entity.nameTag}`);
})
this doesn't work like how
wait its warn lol
now i get a warning but i dont get the "NameTag"
entitySpawn already returns the entity
Your asking for a double undefined
ev.nameTag```
oh
this works but doesnt kill the entity
world.afterEvents.entitySpawn.subscribe((ev) =>{
const entity = ev.entity
console.warn(`Entity spawned ${ev.entity.typeId}, NameTag: ${ev.entity.nameTag}`);
if (entity.typeId != "minecraft:item") return;
if (entity.nameTag === "§d§lStarter") e.entity.kill();
})
e is not defined
still nothing
I already told you why your code does not work
Quick question, how am I getting large watchdog spikes? All I have in my scripts is a system interval that says test.
It happens whenever I join the game.
gametest moment
...
Gametest(Js engine) is dependent on your system if its on a local world. Your computer is probably allocating more resources in loading the world then actually running gametest, leading to a watchdog notification
Ah okay, thanks.
this depends on how you set the runInterval
Guys, is there a way to place a block from an item with it's DATA? We know you could turn blocks in the world into item stack...
Dispenser
Dispenser do place block?
Tbh idk how to use it... But can you make that the player who placed it not visible?
Either use the invisibility potion effect or use the scale component in player.json
Any dev resources have a sample related to simulated players?
structure
Yeah I did that... Still thanks, the simulated players is kinda complex just for that
Lol
I have this code: ```javascript:
let dynamicUI = new ActionFormData()
.title("Select Destination");
for (let i = 0; i < anarray.length; i++) {
dynamicUI.button(anarray[i].name);
}``` but it doesn't work. How do I do this, dynamically add buttons to a server-ui ActionFormData form?
Grr. Why won't it syntax highlight?
Ahh opps. my bad 🙂
What does it supposed to do?
And what's inside of anarray
I mean it should work
you can do that
Depends your device but mostly when it reaches 200+ I think it would lag when you try to scroll
ahh you can scroll. awesome
Nope it doesn't have built-in pages but there's an addon who did that afaik jayly have than in his GitHub page
Hmm. I;ve decided I don't want to customise the ui json files because it is a potential source of incompatibility with other addons
He didn't modify the json ui iirc he just added extra button for next and previous
Are the dynamic properties on world loaded when beforeinitialise event is called?
Okay, seems not to me
oh wait.. doh
For proper syntax highlighting on discord use this formatting with JavaScript.
```js
Block of code here
```
Guys is the equippable component works on entities now?
Not sure, I remember them disabling that a long while ago, with the intentions of bringing it back. Not sure if they have yet. A quick test would confirm it.
That sucks
thx
How do I set item on the main hand if the entity not player... Shii I sound rookie here.
Need to get back on js now
how do i detect if a arrow hit a mob..
world.afterEvents.entityHitEntity.subscribe((data) => {
let he = data.hitEntity
let de = data.damagingEntity
let det = de.typeId
let dp = data.damageSource?.damagingProjectile;
//let owner = dp.getComponent("minecraft:projectile")?.owner;
if (!de) {
world.sendMessage(`working`)
}
})
Try de.getComponent('projectile') or de.typeId === 'minecraft:arrow'
No it isn't.
💀
Why do you wanna see who kicked someone? I thought only the host can do that
For those who are confused or who questioned mark jaylys message the context is this.
Whoops
Anyways, I wanna share something
If you know a solution just tell me, so the entityHitBlock function returns the block and source who broke it. When you're in creative it still triggers it but when you want to put the block in a structure the structure is empty because you broke the block so fast it didn't have time to load lmao.,
function health(Player) {
const health = new ActionFormData();
health.body({ "rawtext": [{ "text": "§l\n§r" }, { "text": "§lLevel:§r" }, { "score": { "name": "@s", "objective": "Speed" } }, { "text": "§l\n\n\n\n\n\n\n\n\n\n\n§r" }] })```
Scoreboard not appearing in menu
You don't even call the menu via .show()
ik this is just a part of it
when opening the menu I want the score speed to show next to level:
Make sure the name is correct and try * instead of @s
ok
if it is called speed, then the menu also needs speed, not Speed
no its Speed mb
{ "rawtext": [{ "text": "§l\n§r" }, { "text": "§lLevel:§r" }, { "score": { "name": "*", "objective": "Speed" } }, { "text": "§l\n\n\n\n\n\n\n\n\n\n\n§r" }] }```
like this?
yes
ok gonna try it
I suggest then not to bother with rawtext and just write js "Level: " + (world.scoreboard.getObjective("Speed")?.getScore(player) || 0)
ok ty
didnt think of that
it works now
but how do I add space?
is it the same as in rawtext?
"Level: " + (world.scoreboard.getObjective("Speed")?.getScore(player) || 0) + "\n\nText"```
hmm
this is why I wanted to use rawtext lol
@round bone
didn't read
I think the name part can change to ${player.name}
ty but dont need help anymore
and thats a very good info
Okey
I'm trying to rename a spawned item with myItemStack.nameTag = { translate: "translation.key" }. However, the item is just called object. Is it not possible to rename items using translation keys?
same when typing it as rawText
ah, what a shame. I'm making more bucketable mobs and have it so the mobs name is retained. I was hoping to have the words "Bucket of" be a translation key followed by the mobs name
I have exactly the same problem, it happens with normal forms and with customs that have a collection
https://discord.com/channels/523663022053392405/1302037164627853322
There are a lot of bugs with ghosts in Minecraft
Sometimes my entities stop being valid for no reason...
yeah i found out that it was json ui related
Did PeterGriffin_num1fan just got banned?
Due his latest messages?
Yeah but he also spams stupid bullshit and random shit on other channels without context or reasons
Hmm seems like he got what he harvest
He also wanted to touch a y'know?
you mean oojimayuuki01 ?
Who's that?
Someone he mentioned before
Anyways let's change the topic admins will delete this
Bad, I tell down the stairs I missed 3 ateps
Now my ankles are twisted like crazy
hah, tell
that's shit
my day was pretty okay
Anyways - if anyone needs help with scripts im open (for less than 5kb)
Good for you.
Lol, my script is 40kb 👀
I wana add an funny feature
Heyas.. I'm looking at Container.addItem... What does it return exactly? Does it return the untransferred item or something else?
Yes
ItemStack | undefined
That doesn't tell me what the return values mean. I'm assuming undefined when the item was transferred just like transferItem
It returns the untransferred/excess/remains, otherwise undefined/none
yep
How can I destroy items having only the itemstack?
In the PlayerInteractWithEntity afterevent, I'm trying to manipulate the beforeItemStack and itemStack members of the event. It tells me that itemStack is read only. How can I trick it into transferring the items and reducing the counts etc?
Dang even in survival mode, its duplicating the items
Oh man, even trying to get the equipment slot doesn't give me what I need to do a transferitem
system.run
nonsense.. what do I actually do?
?
private constructor();
/**
* @remarks
* The ItemStack before the interaction succeeded, or undefined
* if hand is empty.
*
*/
readonly beforeItemStack?: ItemStack;
/**
* @remarks
* The ItemStack after the interaction succeeded, or undefined
* if hand is empty.
*
*/
readonly itemStack?: ItemStack;
/**
* @remarks
* Source Player for this event.
*
*/
readonly player: Player;
/**
* @remarks
* The entity that will be interacted with.
*
*/
readonly target: Entity;```
The event returns readonly
And?
If you want to modify it you have to elevate its permissions
I need to delete the itemstack entirely
You can set it as a empty item stack by setting the amount to 0
setItem(slot, null)```
/**
* @remarks
* Sets an item stack within a particular slot.
*
* This function can't be called in read-only mode.
*
* @param slot
* Zero-based index of the slot to set an item at.
* @param itemStack
* Stack of items to place within the specified slot. Setting
* `itemStack` to undefined will clear the slot.
* @throws
* Throws if the container is invalid or if the `slot` index is
* out of bounds.
*/```
``` * `itemStack` to undefined will clear the slot.```
yeah but I couldn't find the slot. I eventually got it from the equippable component's getEquipmentSlot("Mainhand")
I mean he's not wrong, you can't modify anything in before events so you need to use system.run and it's not nonsense genius
no you wouldn't need system.run I don't think to get the equipment slot for the item and change that
The only reason I'm using system.run myself in this event handler is because I'm presenting forms
I said... He's not wrong that you can't modify anything in before events without system.run
That's all... Nothing else
ugh it has nothing to do with anything I'm actually trying to achieve
const destcontainer = djinn[formData.selection].getComponent("inventory")?.container;
const remainder = destcontainer.addItem(itemStack);
const equip = player.getComponent("equippable");
const equipslot = equip.getEquipmentSlot("Mainhand");
equipslot.setItem(remainder);``` would be able to be done without system.run I highly suspect
why doesn't it syntax highlight??
lol what
You're just getting not setting so you don't need system.run
setItem
Didn't notice the last one
const remainder = destcontainer.addItem(itemStack);
what is up with this?
addItem``` does not return anything
I have been trying various transfer methods and that's some remanent code
Thank you.
No! addItem does return an ItemStack
Returns the itemStack of the itemStack you just set it to?
No, less any items that were transferred
What?
yeah, if they can't be added, they are returned
Huh? Equippable use setEquipment not add item tho
Bro why you always sound angry 😆
This code does none of that?
huh? Sure it does
const destcontainer = djinn[formData.selection].getComponent("inventory")?.container;
const remainder = destcontainer.addItem(itemStack);
const equip = player.getComponent("equippable");
const equipslot = equip.getEquipmentSlot("Mainhand");
equipslot.setItem(remainder);```
This?
yeah?
use camel casing, its very hard to read
const destContainer = djinn[formData.selection].getComponent("inventory")?.container;
const remainder = destContainer.addItem(itemStack);
const equip = player.getComponent("equippable");
const equipSlot = equip.getEquipmentSlot("Mainhand");
equipSlot.setItem(remainder);```
Who is player defined as?
Who is equip defined as?
From the event
What event?
PlayerInteractWithEntity before
Show me how your setting that up
const inventory = player.getComponent('inventory').container;
inventory.addItem(new ItemStack('minecraft:stick', 1));
const equip = player.getComponent('equippable');
equip.setEquipment('Mainhand', new ItemStack('minecraft:stick', 1));```
addItem is slot then itemStack
I can't send the whole event handler
so I can present forms instead of showing the entity inventory
Add item don't have a slot tho.
dont know why anyone would use addItem when you can just scan the inventory for a empty slot and then use setSlot
No, it finds one and returns the remainder if it can't find a slot
Because I'm "giving" an item to an entity who is then transferring it to another entity
Sorry if I sound less than cordial, I'm very busy trying to write code and just prefer getting to the point
Sure it is
It does what I want now
I dont even think you understand this... You should be using js player.getComponent('minecraft:inventory').container See if they have a open slot, and if not just cancel anything more from happening
I'm not giving the item to the player - its going to an entity
the items is coming from the player via the interact entity to yet a third party
stack
I was trying singular items instead of whole stacks but got over it as it wasn't working
if the entity has something in their mainhand, then you want the item to be given back?
This part confuses me a lot.
const equip = player.getComponent("equippable");
const equipslot = equip.getEquipmentSlot("Mainhand");
equipslot.setItem(remainder);```
No, I want it to go to a third party
Niether of yourself nor the person you're talking to
😭
Try drawing out what your trying to do, I dont understand what your saying
Each player gets a djinn assigned to them and then you can post items to other players via them
let djinn = player.dimension.getEntities({ type: "mewp:maildjinn" });
for (let i = 0; i < djinn.length; i++) {
const ownerId = djinn[i].getDynamicProperty("mewp:ownerId");
if (ownerId == player.id) {
djinn.splice(i, 1);
break;
}
}
for (let i = 0; i < djinn.length; i++) {
let ownerName = djinn[i].getDynamicProperty("mewp:ownerName");
if (ownerName == undefined) {
ownerName = "<error>";
}
playersUI.button(ownerName);
}``` so from here?
Ok, so they click on a other player?
And then they get this menu
and in this menu they click on a animal to send somthing to?
They interact with their djinn and can send the item they are holding to another player's djinn
Or, interact with no item and see the items you've been sent
So what part of the code is not working?
It is working now....
ok
I'm quite happy... Hopefully I can also make memo items
Let’s hope
I think its quite clever.. I see it all the time, people wanting a mail system in their worlds... Now I have one
Although, you can't send items inter-dimensionally since it can't find the destination djinn if they aren't in the same dimension as you
I could maybe fix it...
Is there an actual approach to detecting what a player changes their mainhand item to, or do we just have to use system.intervals for that?
You need to use runtInterval
What a shame 😔
can i find entity using location?
depends how you want to find it - Dimension.getEntitiesAtBlockLocation?
Umm.. With System.runInterval, is there an issue passing data to the callback? How do I tell it about things? I can just take data from consts declared outside the call???
do the jobs persist between server restarts?
Is there semaphores or blocking in javascript?
Do I need to use them?
It feels really strange running this job without them
huh?
js is single threaded if I'm understanding your question correctly
so no semaphores
really have no idea wtf those even are so I hope wikipedia's definition is right
what are you doing in the runJob?
yeah you can just access variables in the scope above the callback
no, the entire javascript engine restarts so if you want to save any variables etc you gotta serialize them to a dynamic property or some other storage medium
got it
How can I replace a block with nothing? I am trying Block.setType("minecraft:air") but this doesn't seem to be working? It might be another issue though...
that should work tho.
idk whats your problem
send your code or any error you are facing
system.runInterval(() => {
for (const player of world.getPlayers()) {
const block = player.getBlockFromViewDirection({maxDistance: 6})?.block
block.setType('minecraft:air')
}
});```
yeah i just use this to test if it worked lmfao
oh dear
The block location was being changed by a reference
Then send your code... Ane make sure to get the block first before setting
Oh, I've moved on from that simple test.. But I'll show you the code now just 'cause you asked... ```js
function tickerTick() {
for (let i = 0; i < mewp_tickerdata.length; i++) {
const dimension = world.getDimension(mewp_tickerdata[i].dimension);
const block = dimension.getBlock(mewp_tickerdata[i].location);
world.sendMessage(`Testing ticker ${i}`);
if (block != undefined) {
const power = block.getRedstonePower();
if (power != undefined && power > 0) {
for (let j = 0; j < 5; j++) {
const y = mewp_tickerdata[i].location.y + (5 - j);
for (let k = 0; k < 11; k++) {
const loc = { x: mewp_tickerdata[i].location.x + k, y: y, z: mewp_tickerdata[i].location.z };
const plot = dimension.getBlock(loc);
if ((k + mewp_tickerpos) >= 20 || mewp_tickerstrs[j].charAt(k + mewp_tickerpos) == ' ') {
plot.setType("minecraft:black_concrete");
}
else {
plot.setType("minecraft:sea_lantern");
}
}
}
mewp_tickerpos += 1;
if (mewp_tickerpos >= 20) {
mewp_tickerpos = 0;
}
}
}
}
}```
The next steps are to try to implement a directional input control and then.. then... snake challenge duo!
What part you need to set it into air?
I stopped doing it. I was using redstone lanterns and redstone blocks to make the glowing "pixels" but there was lag in them turning on and off which caused display glitches I couldnt' live with so I changed it to sea lanterns and black concrete
I was only doing it the way I did initially because that's how I was having to do it with pistons and command blocks but now I have script.. wee hee
I have a small (1.6MB) video showing the result if anyone wants to see and I'm allowed to post it
Kindly create a ppst for it for further discussion
Oh whoops. I thought I had done, sorry
https://discord.com/channels/523663022053392405/1304769691247706184
Ig this is the post...
Guys, I am trying to lock a player in place while reading the input via getVelocity... In order to do that, I'm teleporting them in place all the time (runInterval) because using the inputPermissions prevents any reading of the user input. However, I need to provide the TeleportOptions because I want the view to be freely movable and I cannot calculate a facingLocation. How do I calculate something that teleport will be happy with to keep them in place and looking at relatively what they were. Here is the code I have now: ```js
const viewdir = mewp_inputplayer.getViewDirection();
const headloc = mewp_inputplayer.getHeadLocation();
const facedir = { x: headloc.x + viewdir.x, y: headloc.y + viewdir.y, z: headloc.z + viewdir.z }
mewp_inputplayer.teleport(mewp_inputlocation, { facingLocation: facedir, rotation: mewp_inputplayer.getRotation() });
does anyone know how to list the specfic scoreboard of the player in MessageFormData buttons?
Maybe set the movement value to 0.001?
Never tried that so idk if it would work
You could use the new input APIs.
values() {
if (!this.#validNamespace) return this.#MESSAGE.ERROR_INVALID_NAME(this.#settings.namespace);
const allIds = world.getDynamicPropertyIds()
const values = []
const get = (key) => this.get(key)
const filtered = allIds.filter(id => id.startsWith(this.#settings.namespace + ":"))
system.runJob((function* ids() {
for (let i = 0; i < filtered.length; i++) {
values.push(get(filtered[i]));
yield
}
})())
return values;
}
does runjob work without async (ignore the other code)
if its into a function in a class
const topEntityLocation = {
x: block.location.x + 0.5,
y: block.location.y + 1,
z: block.location.z + 0.5
};
const rotation1 = { x: 45, y: 0 };
const topEntity = world.getDimension("overworld").spawnEntity("swmc:door_entity", topEntityLocation);
topEntity.setRotation(rotation1);
why does setRotation wont work with alr inputed rotations?
it works with cardinal_directions of blocks
but not with const
Thats not the problem i think
try Y
rip me, i just read that x rotation doesnt rotate
it tilts the head
Yeah
Y
There's only two rot... Up, down and left, right
That's kinda easy.
i figured it out
and all of those on the y?
X and y
Is it possible to create a new command? Like /(command)
When i try 45 degrees for my x distance it doesnt do anything?
Anyway to fix?
Or to do ?
hey, how can i set armor durability ?
const equipInv = hitEntity.getComponent("equippable").getEquipment("Chest").damage
console.error("test :", `${equipInv}`)
const rot = player.getRotation();
console.error(`x: ${rot.x}, y: ${rot.y}`)```
Check it using this
You need to get the durability component first
const equipInv = hitEntity.getComponent('equippable').getEquipment('Chest');
const durab = equipvInv.getComponent('durability').damage;```
how do i check if an entity is alive?
neither isValid() or entity !== undefined worked for me :/
How do i get players around a particular entity?
get the entity's health component and the currentValue property and check if its greater than 0
world.getPlayers({maxDistance: 5, location: entity.location})
ty 👍
np
Is it possible to make a script to change the models and texture of the leaves before entering the Minecraft world?
Like making a bushy leaves
how would i set a light block with the light level of 2? preferably using setBlockType?
it was flattened and doesnt use states anymore, so just do setType('minecraft:light_block_2')
ah i see, thanks
guys is it possible to set the bouhding box of the structure block you placed??
it says failed to get property
export function summonPower(player, powerId, eventId, name, offset, test) {
const location = offsetPower2(player.location, player.getRotation().y, offset);
common(location);
function common(location) {
const rotation = setRotation({x: 0, y: player.getRotation().y});
const power = player.dimension.spawnEntity(powerId,(location, rotation));
if (power && name != null) {
power.nameTag = `${name}`;
} else power.nameTag = `entidade`;
if (power && eventId != null) {
power.triggerEvent(eventId);
}
}
}
export function offsetPower2(location, rotation, offset) {
function round100000(number) {
return Math.round(100000 * number) / 100000;
}
const yaw = (rotation + 90) * (Math.PI / 180);
const offsetX = round100000(Math.cos(yaw)) * offset[2];
const offsetZ = round100000(Math.sin(yaw)) * offset[2];
return {
x: location.x + offsetX,
y: location.y,
z: location.z + offsetZ
};
}
help
help with what
setRotation is giving an error
Inf:summon a mob with location selected, and with player's setRotation Y
Anyone knows how to get ingame time
Tried this but doesn't work: const time = world.getDimension('overworld').runCommand('time query daytime').data;
how's going everyone
doing great, how about you?
not active that much anymore
world.getTimeOfDay() is a thing
yeh, been doing other stuff
what ppl creating now
Any ideas what I could try to code for #1067535712372654091
getLightLevel() using A* Algo
code that make me don't sad.
function makeCoddyHappy(){
return dad
}
still sad
well, no
Would this cause lag?
import { world, system } from "@minecraft/server";
const targetCoords = { x: 27.53, y: 90.00, z: 27.51 };
const radius = 5;
function calculateDistance(pos1, pos2) {
return Math.sqrt(
Math.pow(pos1.x - pos2.x, 2) +
Math.pow(pos1.y - pos2.y, 2) +
Math.pow(pos1.z - pos2.z, 2)
);
}
function checkPlayersInRange() {
for (const player of world.getPlayers()) {
const playerPos = player.location;
const distance = calculateDistance(playerPos, targetCoords);
if (distance <= radius) {
if (player.hasTag("pvp")) player.removeTag("pvp");
if (player.hasTag("bs")) player.removeTag("bs");
if (player.hasTag("cpvp")) player.removeTag("cpvp");
}
}
}
system.runInterval(() => {
checkPlayersInRange();
}, 20);
i dont think for because of the amount of checks that is happening on the player, however ik this runs for every player on the world.
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
probably not
I was asking for ik there is a easy way to do this with commands but i wanna move away from them lol
oh yeah definitely not with commands
export function summonPower(player, powerId, eventId, name, offset, test) {
const location = offsetPower2(player.location, player.getRotation().y, offset);
common(location);
function common(location) {
const power = player.dimension.spawnEntity(powerId, location).setRotation({x: 0, y: player.getRotation().y});
if (power && name != null) {
power.nameTag = `${name}`;
} else power.nameTag = `entidade`;
if (power && eventId != null) {
power.triggerEvent(eventId);
}
}
}
const power is as if it didn't exist
Bc setRotation returns nothing, try doing power.setRotation() after creating the variable
I did this, but it summons and has a 1 second delay to set the rotation, I want the rotation to be activated as soon as it is summoned
beta-API !!!
dimension.spawnEntity("zombie", location, {
initialRotation: rotation // Int
})
?
hmmm
Well then you can spawn the entity with the command
There are no other options
as?
I don’t remember exactly how this is spelled in the command, but it seems something like this.
dimension.runCommandAsync("summon pig [loc: x] [loc: y] [loc: z] [rot: x] [rot: y]")
the question is that I want to make a mob be summoned in front of the player but the rotation doesn't matter, another thing is that it has to be only in the y rotation, since if I look up, will not spawn above, only in front
I don't think it's possible with a command
Didn't understand. Explain again
he just wants the mob to spawn infront of him.
but ignore vertical
summon an entity in front of me, regardless of the x rotation, but ignoring the y coordinate
dimension.runCommandAsync("summon pig [loc: x] 0 [loc: z] [rot: x] [rot: y]")
I still don't understand what it should look like. The mob should spawn in front of him but at his height?
I understand.
but like this, it wouldn't spawn in front of me, if I put 4 in z
yes
at my height, not at the height of my vision
Now I understand.
so you need to get the player's view direction and do some math.
also dont use commands, use the native method
dimension.spawnEntity('minecraft:pig', vector3)
ok
let view = player.getViewDirection()
let entity = player.dimension.spawnEntity("pig", {
x: player.location.x + view.x*5, // 5 - distance
y: player.location.y,
z: player.location.z + view.z*5
})
It would be possible to use a function to get the distance so that even if the player looks almost perfectly upward, the pig spawns at a distance of 5 blocks
ok, But the issue is that it is born in the same direction that I am looking, what do I do?
isnt that what you wanted
So that's what you need, no? Where should it appear?
dimension.runCommandAsync(`summon pig ${player.location.x + view.x*5} 0 ${player.location.z + view.z*5} [rot: x] [rot: y]`);
...
:)
.
also you are not inserting the values in the strings
Why in the command to set the rotation
Why do you set the height to 0?
to use template literals correctly you need to use backticks to form your string, not double quotes or single quotes
use this
✌️
rotation of the entity or where will it appear?
Once again, describe in detail and in simple text what you need.
When it is spawned, it has to be facing the same direction as the player who summoned it is facing.
let view = player.getViewDirection()
let entity = player.dimension.spawnEntity("pig", {
x: player.location.x + view.x*5, // 5 - distance
y: player.location.y,
z: player.location.z + view.z*5
});
entity.setRotation({x: 0, y: player.getRotation().y});
If I do it like this, it has a 1 second delay to be rotated
I don't want delay
dimension.runCommandAsync(`summon armor_stand ${player.location.x + view.x*5} ${player.location.y} ${player.location.z + view.z*5} ${player.getRotation().x} ${player.getRotation().y}`);
VoidVcell said not to use command lol
Because we didn't understand you
in preview
there's a way to set the initial rotation when spawning a mob with the native method
.
lol
Lots of "lol"
You English speakers are funny
lol
Did you mean to say: "You, half speaking through a translator"?))
we sure are
If you don't speak through a translator, then you know English clearly better than me
I know little, sometimes I use a translator
There are words I don't know
and sentences that I don't know how to put together
English is also a confusing language
However, it is quite easy to learn
yes yes
How do I detect fatal damage to my entity?
I want to execute a command if my entity receives fatal damage
world.afterEvents.entityDie.subscribe(data => {
let entity = data.deadEntity
entity.runCommandAsync("say I died")
})
Thnk
did microsoft say something about custom keybinds?
or if there will even be the ability to add them?
there's input apis in preview but its only for sneaking and jumping rn
oh, f
no?
there is almost all the inputs
show me where you are finding this information
because this is all we have rn
Documentation for @minecraft/server
how do you use oreUI?
this is not what I was talking about, or what he wanted
you cannot, its not released.
i see some ppl using it tho
ask them then
yeah, i wanted to register custom inputs
you cannot set custom keybinds yet
yeah, that's what i tought
like what?
keybinds?
im assuming he means like, press K and it does something
you cannot
i wanted to use custom inputs to control my plane lol
i'll need to be creative then
can you prevent the player from leaving the seat when he presses shift?
yeah
Yeah
how?
.
give me a sec
player.inputPermissions.setPermissionCategory(8,false)
@clear pendant
thx
Fuck, I want it now
I want to do cctv camera for so long that you can control now you can do it... Is sick asf
I know it's preview but bruh
yeah
lets hope it get released soon
how would I go about having my block run a function when interacted? unless you still can via json?
a script to get matching blocks in a certain area?
hm?
I just want a command to run when I interact with my block
but the on_interact doesnt work anymore
check out this.
https://wiki.bedrock.dev/blocks/block-events.html
thank you
did i set this up void?
why is there a random true in there
what is area_0?
and the 3 if statements above, you could simplify that.
those are for different outcomes
area 1 is simplified as i used to do if (block.dimension.getBlock({ x: 0, y: -60, z: 0 }).typeId === "glowstone" && block.dimension.getBlock({ x: 0, y: -60, z: 0 }).typeId === "glowstone"
thats just an example
the true is there because i thought it wouldnt cause it to run even thought the blocks arent there
will anybody help me with this issue with my code. please I can't find the solution to it.
Dude can you give the scripts you used? I wanna try in mine...
system.runInterval(() => {
world.getPlayers().forEach((player) => {
const vel = player.inputInfo.getMovementVector()
const armorStand = player.dimension.getEntities({type:"minecraft:armor_stand"})[0]
armorStand.applyImpulse({x:vel.x/4,y:0,z:vel.y/4})
})
})
What is MV Vec
Guys, is there a way to change a written book title?
Why you dividing the value by 4?
impulse of 1 is too fast
you are referring to getMovementVector?
no
Ok. What about using some NBT editor?
yes
normalized xy vector for the player input for example
forward: {x:1,y:0}
backward {x:-1,y:0}
right {x:0,y:1}
left {x:0,y:-1}
and so on
it is in preview
probably?
found a uuidv4 generator for javascript in internet after finding out uuidgenerator.net is horribly slow 
I have a book inside a saved structure. Do you know where can I find those files?
hmm, better than checking the velocity
yeah
the best thing is you can read that while player input permission is disabled
crypto.randomUUID() best
no idea sorry
didn't play with nbt for a long time
meeeh i cant do npm cuz i use standalone code editor
don't worry
What, wow that's cool
Can't you make a function?
Ohh it returns 1 and 0
Bro it's so freaking easy 😭😭
is this documented on mslearn
0 to 1
i said normalized
moving forward and left for example
no idea
i just tested that out
Ohh that's what you mean... Kk I got it
mind if i add this info to docs
Easy to understand...
let fu = () => '00000000-0000-0000-0000-000000000000'.replaceAll( '0', v => Math.floor(Math.random()*16).toString(16) );
sure
nah pseudo
Yooo.... Can't wait to see Minato's name into the docs
o
uuid do have a pattern if i am not wrong?
just a pseudo
game doesnt check that so its fine
yeah
it doesnt?
nah

Lemme check my scripts files if I have my old uuid generator
that for the best tbh
i used to use the same uuid and change it just a bit
Found it.
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
Logically it doesn't make any sense to validate if the pack uses the actual uuid4 or not, from the game's pov
I have done it since 1.20
All they need is an id system
hey
we are using the same one
why the pattern is needed anyway
it just limit the possibility
ye
it never said abt it anywehre in the app wtf
They use ext lib for js runtime, and if you see their doc, it has ut
For God sake guys, I don't do commissions.. my DMS are full of that
Ohh my god
Guys how do I disable my DMS or some shii
lucky you
How is that lucky 😭😭
mine is full for help questions or free work lol
wait where is the doc
Free work nah? Paid work nah? But I will help you but not 100% of it
Learn to do it 😄
you can search 'Eruda' on google
i ignore most of of them
i can help in a server where i can be corrected if i am wrong about something, DM just limit the help you are getting to one guy
You fr²
Which version includes this?
i have 50.26
Its 1.20.50 which is 1.17 in scripts
If im correct lmao
50.25+ i thing
Thanks
ur wlc
That behaviour is intended? where it works even in the disabled state
yeah it was not that way before
Yo is there a way to get item rarity in scripts?
Like an ender dragon egg would be epic rarity as you can see it having the colorcode "§d", and something that's common would be of no rarity so white, yellow for uncommon, and blue for rare, and magenta for epic. You can see this in-game by grabbing a trident from the creative menu it's rare, then you add a Enchantment to it, it becomes epic.
I don't think there is anyway, so basically I'll have to map everything. But I just wanna know if there is a component or something
Good to know.
Sad but it's at least good to make you focus on what you are doing.
Guys how do I get the center of two points?
function getCenter(loc1, loc2) {
return {
x: (loc1.x + loc2.x)/2,
y: (loc1.y + loc2.y)/2,
z: (loc1.z + loc2.z)/2
}
}
I did that but it doesn't work properly
So you messed something up somewhere
Nahh I don't think soo.. look
The armor stand should be in the middle but nah
code
in any case, the entered values are 100% incorrect
And here you don’t even need the center function.
why not use get entity options?
It's just a test that's not a permanent thing lmao
dose the entity get teleported?
You chose the wrong points
huh?
yeah
Well, according to the code everything is correct
can you log the tow pos and the tp location?
thn what? why the hell you said you chose the wrong points?
Because you chose points 1 and 2 as the same, or changed them somewhere
If you stood exactly in the middle of two blocks, then everything would be correct
bruh i ai'nt getting what you are saying no matter what how many times you change the loc of those two points it should properly say the center of it
huh?
Well, you chose the points wrong. That's it. When you clicked on "set pos" you selected them so that the center is not in the center of the blocks, but in the center of 1 of the blocks
thank you. can't you just say it in the first place.
I tried to tell you this 3 times
you're confusing ash :(
i already show the lcoation in the actionbar
hmm
get the armor stand position and check if it is the same
yeah, i tried to tp myself too and it's on there.
as what serty said, it's getting the center of 1 block only
it should be right
lol
the 0.5 did matter lmfao
i have no idea what are you talking about lol
const xCenter = (pos1[player.id].x + pos2[player.id].x) / 2 + 0.5;
const yCenter = (pos1[player.id].y + pos2[player.id].y) / 2 + 0.5;
const zCenter = (pos1[player.id].z + pos2[player.id].z) / 2 + 0.5;```
here. it gets the center of the two location
No, it's an offset center
yeah
mb, i am shit in explaining things, that's why my english is my lowest grade lmao
hmm, i get it
get the tow blocks center first then get the center
just add 0.5 to both before the / 2
yeah i have smol brain that i forgot that 0.5 can be a center
same in doing execute as @p at @s align xyz run tp @s ~0.5 ~0.5 ~0.5
Here you go.
function generateRandomUUID(): string {
const lut: string[] = [];
for (let i = 0; i < 256; i++) {
lut[i] = (i < 16 ? "0" : "") + i.toString(16);
}
const d0 = (Math.random() * 0x100000000) >>> 0;
const d1 = (Math.random() * 0x100000000) >>> 0;
const d2 = (Math.random() * 0x100000000) >>> 0;
const d3 = (Math.random() * 0x100000000) >>> 0;
return (
lut[d0 & 0xff] +
lut[(d0 >> 8) & 0xff] +
lut[(d0 >> 16) & 0xff] +
lut[(d0 >> 24) & 0xff] +
"-" +
lut[d1 & 0xff] +
lut[(d1 >> 8) & 0xff] +
"-" +
lut[((d1 >> 16) & 0x0f) | 0x40] +
lut[(d1 >> 24) & 0xff] +
"-" +
lut[(d2 & 0x3f) | 0x80] +
lut[(d2 >> 8) & 0xff] +
"-" +
lut[(d2 >> 16) & 0xff] +
lut[(d2 >> 24) & 0xff] +
lut[d3 & 0xff] +
lut[(d3 >> 8) & 0xff] +
lut[(d3 >> 16) & 0xff] +
lut[(d3 >> 24) & 0xff]
);
}
function isValidUUID(uuid: string): boolean {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
}
It's v4.
yo that's sick.
stealing it
Have at it.
Is there a way for a system.runInterval (() =>{})to reference it's own job ref (in order to cancel/stop itself?)
without
const runId = system.runInterval(()=>{})
```?
Well, you can make your own runInterval
I will be starting a job for each player upon spawn, but don't want to make a job keeper... I need it to stop running when the player leaves.
if player is not valid, cancel
For example this:
runInterval(func, delay) {
let interval = new class {
constructor() {
this.loop = 0
}
stop() {
system.clearRun(this.id)
}
}
interval.id = system.runInterval(() => {
func(interval)
interval.loop++
}, delay)
}
I feel like I stepped into advanced JS.. I am not sure how to turn ```JS
/**
*
- @param {Player} player
*/
export function playerCounterJob (player) {
system.runInterval(() => {
//add stopping mechanism here
DynamicPropertyLib.add(player, dynamicVars.aliveTicks, TicksPerSecond);
}, TicksPerSecond);
}``` into that. What am I passing to runInterval?
Didn't understand the question
I do not know how to use these parts..
Curious, why dont you want to use const blah to store the jobID?
uhh, shouldn't that be
DynamicPropertyLib.add(
player,
dynamicVars.aliveTicks,
TicksPerSecond,
system.runInterval(()=>{
player.isValid()
})
)
If you use my code. Then you need to write something like this:
runInterval((interval => {
if (bla bla bla) interval.stop()
}),1)
I personally would store the jobID in a dynamic property and before player leave grab the property and stop the job.
Each player would have a job running.. so all staggered based on when they spawned in, instead of one job running all players every 1s. But it needs to cancel itself if they are not valid anymore
And there is also a loop property. So you can write something like this so that it runs 10 times:
runInterval((interval => {
if (interval.loop >= 10) interval.stop()
}), 1)
If a player Alt-F4 quits.. job never cancels
which is better to store a temporary data in a player? player.test = true or dynamicProperties?
thats while world is running "temporary"
what? 😭
That is not a parameter in that class method... JS /** * * @param {Entity} entity * @param {string} propertyName * @param {number} [qty=0] */ static add (entity, propertyName, qty = 0) { if (entity.isValid()) { const currentQty = DynamicPropertyLib.getNumber(entity, propertyName); entity.setDynamicProperty(propertyName, currentQty + qty); } }
i see, alrighty
Imma see if this works....JS export function playerCounterJob (player) { const thisJob = system.runInterval(() => { if (player.isValid()) DynamicPropertyLib.add(player, dynamicVars.aliveTicks, TicksPerSecond); else { //cancel this job system.clearRun(thisJob); } }, TicksPerSecond); }
How to understand this?
Just pinging you with a made up logic to demonstrate runInterval() assignments. In case it helps.
import { world, system } from '@minecraft/server';
let playerIntervals = {};
// Function to create and assign an interval to a player
function createIntervalForPlayer(playerId) {
// Only create a new interval if it doesn't already exist for this player
if (playerIntervals[playerId]) return;
let runId = system.runInterval(() => {
let player = world.getEntity(playerId);
if (player) {
// Perform player-specific actions, e.g., logging every second
console.log(`Interval running for player with ID: ${playerId}`);
} else {
// If the player is no longer in the world, clear the interval
system.clearRun(runId);
delete playerIntervals[playerId];
}
}, 20); // 20 ticks = 1 second
// Store the player's interval run ID
playerIntervals[playerId] = runId;
console.log(`Interval assigned to player ${playerId}`);
}
// Player join event handling
world.afterEvents.playerJoin.subscribe((eventData) => {
let playerId = eventData.playerId; // Retrieve player ID from the event data
// Assign an interval to the player only if it's not already assigned
createIntervalForPlayer(playerId);
});
// Player leave event handling (before the player leaves)
world.afterEvents.playerLeave.subscribe((eventData) => {
let playerId = eventData.playerId; // Retrieve player ID from the event data
// If the player has an interval running, we stop it and remove it from the list
if (playerIntervals[playerId]) {
system.clearRun(playerIntervals[playerId]);
delete playerIntervals[playerId];
console.log(`Interval stopped for player ${playerId}`);
}
});
That is helpful, thank you. I figured I may have to have something on the outside tracking the jobs. Also, may need a 1-5 min cleanup. Not sure if events for leaving run if a hard-exit is done on the game.
LOL, gonna be a bitch to test... single player on PC....
Haha
Maybe the console log can still show
You could create a simulated player.
If a hard exit occurs, you probably won't need to care about it since the game's state may not have saved
that is when on single player, but this will be for a realm.... and if a player hard exits, game is still running until last player leaves
True. Might get finicky if the player fails to send a Disconnect packet then
is the player sending the packet, or is the world handling it?
I'm pretty confident when a player leaves the event is triggered. At least, I see the results on BDS when looking at the console lol.
Hard exit that is.
Technically the client does. When the user disconnects from a server normally the client is supposed to tell the server its intentions. If the game crashes and that packet isn't sent, then the only way the server knows if the client is gone is by waiting for its requests to time out
Whether data is saved, corrupted, or lost is another topic 🧐
That's my assumption anyway. Bedrock could be operating on a different communication model though
Seems like the player leave after event, is just playerId and name also... I am thinking this is on world level, and not player
where as before event is player object
Correct, because they still exist.
like with join
hence entity.isValid() eh...
yes, but that is on the player object... but if the leave after event, does not have the object ( because player is gone-gone), then maybe it is the world object handling that event
I see all events as being handled by the "world," or the scripting engine. It then polls whatever data is relevant to act upon in that event
world.afterEvents.playerSpawn.subscribe(data => {
if (!data.initialSpawn) return
let player = data.player
let interval = system.runInterval(() => {
if (!player.isValid()) return system.clearRun(interval)
})
})
I figured one could directly use the handler in the clearRun method, yeah. Might behave weirdly if the interval is 0, but I assume the engine would at least finish the assignment before executing the next loop
And also beforeEvents.playerJoin, and its afterEvents version returns only the player’s name
and id
Explain
@remote oyster
not that
Hii can someone help me? Want create a duel system 😭
All I see is he used the player object in the before join... so changed to eventData.playerId.. gonna test it out as is with that one change.
playerSpawn is a preference not a requirement in this instance.
world.beforeEvents.playerJoin does not exist
Is it more convenient to get the player's name and search for it?
we don't help with general questions like that.
start making it and post any question that you have
Ah crap lol, my bad. I mixed myself up with the other event.
Okay thx i alr did it
so? what is the problem
bruh
the after event will work.. to me, it is like the before event for player-spawn( which does not exist either) - but only for initial spawn
I will alter accordingly to test
that actually reminds of this thing i used to play with
What is this
some kind of player initializer, dunno can't remember
I edited it to use afterEvents for player join and player leave. Either way, it's just an example on the logic. How it's coded doesn't really matter to me. It's understanding how it works which is the point in this discussion 😁
was tryna make a custom getPlayers
Large code that does not clear what
Won't work
the playerJoin event fires
before the player spawns.
So getEntity(playerId) will return undefined and the interval will end immediately
How so? It returns the object.
Use playerSpawn
since block.setDynamicProperty isnt a thing, anyone know another way?
Making it bold doesn't explain it. If the event returns the object then the object is retrievable, so how would world.getEntity() return undefined?
@serty.name
playerJoin runs BEFORE the player spawns.
use the block's location as property key
as well as dimension.id
Making it bold doesn't explain it. If the event returns the object then the object is retrievable, so how would
world.getEntity()return undefined?
Because playerJoin and playerSpawn are different things. playerJoin - the player is connected to the server playerSpawn - the player has spawned. Until the player spawns, he is not on the list, so you are trying to get the player, too early
Here's an example. EDIT: more generalized.
function objectToString(obj) {
return `${obj.dimension}_${obj.location.x}_${obj.location.y}_${obj.location.z}`;
}
If the player hasn't spawned then explain the object?
alr thanks
Spawn or not, the object is there.
Fun fact, you don't have to call .location since block has a xyz property as well.
I know.
Do you see what I highlighted? You understand how documentation works. it returns entity or undefined
meanwhile me abt to test
undefined it returns when the entity is in the world.
What is the argument right now?
If the object didn't exist, as you claim, then how would the object be retrievable in the playerJoin event "because they haven't spawned yet"?
Let me explain in detail
As far as I know, playerJoin retrieves the player object.
Exactly
it does retrieve the player in playerJoin
There is not
using the id
because it shouldn't be
because that's what playerSpawn is for
maybe mojang made changes on it
it wasnt possible to get the player in that event before
All I know is that if you do world.getPlayers in playerJoin, the player that joined will be included.
No. As I said, playerJoin and playerSpawn are different events. join - the player has joined the SERVER. spawn - the player has appeared in the world. There is a difference. So you can't immediately get the player object in playerJoin because it doesn't exist yet.
I'm gonna write code to test and verify.
And yet, world.getPlayers gets me?
alr did ;-;
No
Results?
how to detect if player interacted with block on specific coordinates?
i used world.getEntity(playerId) and its possible
I say it again. join - before the player appeared in the world. that is, the player is not yet on the list of players. it's not valid
This was a code I used for a project
world.afterEvents.playerJoin.subscribe((eventData) => {
const player: Player = world.getEntity(eventData.playerId) as Player;
player.setDynamicProperty('namespace:property', false);
console.log('player initialized');
});
And it works.
are you testing it in a single world?
You can use either custom components(for custom blocks) or the playerInteract world event.
okay.. so what is available in the event for player join is only strings whereas the world.getEntity has access to all players, even pre-spawn... is that what we are saying?
I used this on a server. When you enter the world yourself, playerSpawn and playerJoin are triggered immediately. Because you are the host and you don't need to connect to the server
we are arguing about the functionality of playerJoin, but why do it at all if playerSpawn immediately returns an object
@wary edge
Basically
@subtle cove
The player exists when they join. I suppose the logical way to view it as one instance the object is valid and the other instance the object is not valid, but the object still exists either way.
ye
And it seems it's valid either way based on that image lol
I think Serty is saying this his experience of this on a server (not realm) is different.
I remember that it doesn't work like that on servers
same, but it was long ago
The functionality may vary between local, realm, and server. I honestly could believe that behavior to be factual. Would not surprise me at all honestly lol.
is there anything special you have to do to run scripts on a server.. I have one I can test with, just not tried any scripting add-ons
just a pack that uses scripts...
i would use playerSpawn because there is no need to get the player via getEntity and based on my experience it is better
that i agree
Unfortunately, you would need to track an additional data because if a player dies? Unless I misread the use case.
Why?
hence entity.isValid() ;-;
as long as the player is valid then the interval is there
I love how you press on this lol
player is still valid tho
My interpretation is that they want to do an action if a player joins a world. Wouldn't playerSpawn trigger this event numerous times?
dose that leave any use case for player join?
i guess it dose trigger before that, so idk
If in a single player world you wouldn't need to check for initial spawn. And makes the code readable imo.
I don't think that 1 line will interfere much. Moreover, it is completely understandable
the player don't exist yet when that trigger from what i remember
Agree to disagree.
In short... use whatever you want. I'm leaving
lol
guess I need to player to exist as I am altering his dynamic vars
yo what happened to WorldBeforeEvents.playerPlaceBlock??
why it now only has an after version
in the last beta
1.16.0-beta
I was literally using this event in 1.14.0-beta
Did you update your types? What version are you using?
1.16.0-beta
