#Script API General
1 messages · Page 44 of 1
annoying... i thought i noticed you could get the feedback from the command at some point or was i mistaken
Btw is there any other good way to load just a single chunk before I go try stuff lol
only if the command is successful or not
I guess you could try to use that to tell how many ticking areas there are
maybe use a world dynamic property, and increment this property value everytime the command is successful?
Win + R, type %appdata%, goto mojang/path/to/minecraftpe/options.txt, search for "viewdistance", set value to 16
That's actually a fair idea for checking how many are available -- just create till it fails and then however many you created is how many are free
Someone could definitely make their own little wrapper for the tickingarea commands so you could access them more like an api
Nevermind the commandResult for a successful tickingarea placement is the same as an unsuccessful one
Item json minecraft:interact_button triggers itemUse event right?
If the ticking area placement is unsuccessful the successCount should be 0. If it is successful it will be 1.
this is what I'm using, though it still needs a tickingarea. In my case we're strictly not using any permanent tickingareas so should work most of the time.
await_chunks isn't super optimised since the game has to check all the blocks in the volume, but the others are fine afaik
hey guys im developing a framework to create addons at the speed of light, does anyone wanna try it out?
thats impossible, unless the framework has no mass
lol
How heavy are bytes
"around 1 attogram"
Petition to start forcing everyone to use typescript
they should replace QuickJS with deno
What if entity location chunk is not loaded and it keep spamming “Failed to get property location at <anonymous>”
const { x: ex, y: ey, z: ez } = entity?.location;
Cus entity is not valid
It's not loaded so ther is technically nothing there
It’s valid
Check again...
An entity is only valid if it's in a loaded chunk
Ive only seen "Failed to get property" errors when an object isn't valid, in script api
Well how to make it do not spam in console until chunk is loaded?
-# hence entity.isValid()
try { /** code */ } catch (e) {}
@warm mason lazy coding 🤷♂️
That's a solid solution -- it doesn't quite fit into my use case so I'll have a think about it. I think I need to go back to designing anyway before worrying about this.
jokes on you... I am using ts since then
I want to switch to ts but I do not have the motivation to rewrite 30 files that I’ve created over the span of a year
I have no idea what is going on in half of them because the code is so messy
Rewrite them one by one 🤷
Well exactly yes that’s what I’ll have to do but do I want to? no
Even opening them to make small edits is painful to my brain
no idea what all the variable names are supposed to mean unless I look for the definition and everything is hardcoded
the best time to clean up tech debt is right now. Don't let it compound, eventually you or someone else will have to do it, and it'll just get worse and worse
That is the point of rewriting it... You rewrite it to learn, but also remove junks and unneeded parts of your script plus for readability and reduce file size
how do i show action form when player first time spawns i have tried playerSpawn event with initialSpawn but when i load the world it doesn't show any form, should i use system.runTimeout?
Force show
if (response.canceled && response.cancelationReason === 'userBusy') return form(player)
Thnx
Quick question... It's not possible to get the file name inside the folder right?
Out of curiosity since I could do it on non mc js
Probably Not and no one should be able to do anything in FileSystem ever. Can you imagine the havoc?
Not outside the scripts folder... Just inside of it. Not the whole system
You can't read files inside or outside the scripts folder, you can import (and maybe even dynamic importing if they added it back) but you can only import js files, and I'm sure you know that by now like c'mon, you're coddy the G.
Is double checking bad 😃
My mind is mixed with non and mc js lmao
Looks like I'll be making a python that converts multiple json into an object or map
sigh
You won't be able to, you can't use require as mc doesn't use commonJS and you can't import json or other files because they don't "EXPORT" anything. And there is no file manager system in mc. Imagine being able to access the Player's world directly from your script lmao
The havoc
Hmm, why calling me coddy the G makes me giggle a bit
I like chaos, that's why my last name is chaos
So umm, idk if this is script related shii but is it normal that fishing hook doesn't have an owner?
Like when the player used a fishing rod to spawn the fishing hook it's normal that it doesn't have an owner instead of the player who spawned it?
why should it?
it doesn't give the thrower any credit directly
Idk it killed it's owner or ran away ig?
hit and run
Assault on minor and hit and run
And it is on the loose, if you find anything about that fishing rod please Head to the nearest fish police station to report it
As it also committed murder and murdered 3 fish cops so far
Damn, looks like I'll be using !player.isOnGround instead of player.isFalling
Anyway gtg
the isFalling isn't triggered when the player doesn't move an inch example I'm afk and I tp'd myself 20 blocks above, the isFalling isn't triggered ughh
Cya soon.
It's triggered when they jump and free fall into the gates of heaven
suspect is wearing a red and white hoodie and a black hair with some sort of string that connects
@Fish Police! Here is info!
bang splat
Why did you kill him, officer we need information on about his friends whereabouts
Hopefully it's not the weird guy
why is there conversation like that
I'm the weird guys 🙈
hi there, do someone know if there is a limit of characters for server form title field?
Wanna know how to test it?
I mean the limit (if there is any) on that formUI.title(titleMsg)
I m using this field as codes/instructions for my custom UI, so I want to know if there is any limit on that to avoid going over
No but it will lag
i used 800 character long body text here https://discord.com/channels/523663022053392405/1280301965271896124 and it didn't lag that much, unless hiding the text dose help
i do however remember it lagging in normal forms
well it is fine, is a on demand UI, it will not keep updating so the lag is not a problem, but still I maybe was too concerned about because my length is still under ~200 characters, so I have space to work yet, thx
hi, is it posible to apply knockback to a player if he is one block above an entity?
Why BlockComponentPlayerInteractEvent player argument either returns Player | undefined? Isn't it suppose to be only player since what other things may interact with this?
Hmmm?
Oh-
help
world.afterEvents.playerBreakBlock.subscribe(({ player }) => {
const blocksMinedObjective = world.scoreboard.getObjective("blocksMined");
const moneyObjective = world.scoreboard.getObjective("money");
if (!blocksMinedObjective || !moneyObjective) return;
// Get current blocks mined
let currentBlocks = 0;
try {
currentBlocks = blocksMinedObjective.getScore(player);
} catch {
currentBlocks = 0;
}
// Increment and update blocks mined
currentBlocks += 1;
blocksMinedObjective.setScore(player, currentBlocks);
// Update action bar
player.onScreenDisplay.setActionBar(`${currentBlocks} blocks mined`);
// Check for quest completion
miningQuests.forEach((quest) => {
if (currentBlocks === quest.blockTarget) {
let currentMoney = 0;
try {
currentMoney = moneyObjective.getScore(player);
} catch {
currentMoney = 0;
}
// Reward the player
const newMoney = currentMoney + quest.reward;
moneyObjective.setScore(player, newMoney);
player.sendMessage(
`§aQuest Completed! You mined ${quest.blockTarget} blocks and earned $${quest.reward}.`
);
}
});
});
Be specific and include relevant details about the question upfront.
- What are you trying to accomplish?
- If you have code, which part is not working? Any content logs?
- What have you already tried?
- Have you searched the Bedrock Wiki?
getscore is not working
Suggestion for @elfin rose
Description
Gets the score recorded for {displayName} on {objective}
Parameters
player: Player or entity on the scoreboard
objectiveId: String Objective Identifer to get from
rNull: Boolean If the return should be null if its not found or 0.
returns
Number - Score that Was recorded for {Player} on {Objective}
example
getScore(player, "objective"): number
Credits
These scripts were written by iBlqzed
Description
A wrapped function that set/add/remove entity score and fetch scoreboard objective display.
entity: EntityEntity's scoreboard to changeobjectiveId: stringObjective to apply the score to.score: numberScore valueaction: ScoreboardActionDecides whether to add, remove, or set score to entity (default = set)fetch: booleanFetch scoreboard objective display (default = true)
Usage
Add score:
import { setScore, ScoreboardAction } from "./index";
setSco
```...
ScoreboardM
A enhanced tool for managing scoreboards
Description
How to use?
This example will explain it.
import { ScoreboardM } from "index.js";
ScoreboardM.newObj("id","val") //This is for assigning new objective to the world.
ScoreboardM.setObj("id","val2") // this changes
ScoreboardM.getObj("id") //This returns the Objective with given identifier.
ScoreboardM.hasObj("id") // This Returns True Or False Telling whether the objective exist or not.
ScoreboardM.delObj("id
```...
oh ok
any help?
Open a post in or debug it in #debug-playground
And I wouldn't wanna judge but that code looks awfully like AI written code.
player?
Who murdered Mr villager?
Is it player?
Is he who did that?
It is for sure him because he ran away now.. we can't get his .id now...
-# def not the weird guy
GASP HE DID THAT? WHY?
Villagers with composters?
entity.location.y+1 === player.location.y ? player.applyKnockback() : null;
Yes the name of the event is weird, since it has "player" but idk ig they don't like an entityInteractWithBlock or smth
Or maybe the documents are just high on mc vodka potions
i am making the grand switch to ts today
34 files to be fixed
i wish you could use a combination of ts and js imported files in script api
But how do you implemented in Code?
i want to make flying jellyfish on which you get knocked If you are over it(Like a slime Block)
You say like a slimeblock are you trying to get the motion of the player when they fall on top of it and work off that?
Yes
I meant is there like an Event that only triggers If an entity ist near an entity. Or do i have ti Put it in a Loop which Runs every tick
entity.json component, yes
but not in script api
But how exactly? Im new in entity creation
I think environment sensor has a distance_to_nearest_player filter
then you can have an event ran if a player is within certain distance ("event:player_near") for example
this is more of an #1067869022273667152 thing
but you could then just test for the event in the script by using world.afterEvents.dataDrivenEntityTrigger and filter for the event by using something along the lines of event.eventId === "event:player_near"
Ok, i'll try it. Thank you
if it doesnt work lmk ill see if I was wrong about something
I will try it in Like 3h.
world.afterEvents.entityHurt.subscribe((eventData) => {
const hurtEntity = eventData.hurtEntity
const damagingEntity = eventData.damageSource.damagingEntity
const item = damagingEntity.getComponent("equipment").getEquipmentSlot("Mainhand")
const LIGHTNING_CHANCE = item.getDynamicProperty('[lightn]');
function shouldStrikeLightning() {
return Math.random() * 100 < LIGHTNING_CHANCE;
}
if (!hurtEntity || !damagingEntity) return;
if (damagingEntity.typeId === 'minecraft:zombie') {
if (shouldStrikeLightning()) {
const { x, y, z } = hurtEntity.location;
world.getDimension('overworld').runCommandAsync(`summon lightning_bolt ${x} ${y} ${z}`);
}
}
});```
any1 knows what im doing wrong
The equippable component is only available to players
oh
damager is player itself tho
then how can i fix it?
world.afterEvents.entityHurt.subscribe((eventData) => {
const hurtEntity = eventData.hurtEntity
const damagingEntity = eventData.damageSource.damagingEntity
const item = damagingEntity.getComponent("equipment").getEquipmentSlot("Mainhand")
const LIGHTNING_CHANCE = item.getDynamicProperty('[lightn]');
function shouldStrikeLightning() {
return Math.random() * 100 < LIGHTNING_CHANCE;
}
if (!hurtEntity || !damagingEntity) return;
if (damagingEntity.typeId === 'minecraft:player') {
if (shouldStrikeLightning()) {
const { x, y, z } = hurtEntity.location;
world.getDimension('overworld').runCommandAsync(`summon lightning_bolt ${x} ${y} ${z}`);
}
}
});```
like this?
thanks
oof now i need soemone to test tahnks
cannot read property of getEquipment slot
of undefined at anonymoyous
@warm mason
uh
world.afterEvents.entityHurt.subscribe((eventData) => {
const entity = eventData.hurtEntity
const player = eventData.damageSource.damagingEntity
if (!entity || player?.typeId != "minecraft:player") return
let item = player.getComponent('equippable').getEquipment('Mainhand')
if (Math.random() < item.getDynamicProperty('[lightn]')/100) {
entity.dimension.spawnEntity('lightning_bolt', entity.location)
}
});
Should work
no errors, and nothing happens now
Try temporarily removing the lightning spawn condition
entity.dimension.spawnEntity('lightning_bolt', entity.location)
This one?
Uh okay
works without it
This means your item does not have the "[lightn]" property or it is equal to zero
its set to 100 tho
it worked
works*
thanks, i edited ur script it works
God damnit... Why a lot of people asking if I do a commission
Does anyone know how to make a crafting table script using entity? Simple and compact, please help me
Scripts for a crafting table using an entity? What?
like it was a custom crafting table but using entity
Why would you use an entity and not a crafting table component in blocks?
because it will have more slots than normal
he is asking for a custom recipe system using entity inventory and json ui
Well, it definitely won’t work out compactly here.
Although the script itself..
he is not asking about the ui
just the detecting of the recipe
i guess you can just map the slots to an array and compare that to a recipe?
bro @distant tulip I sent you a message in private can you answer me
can't help you right now, sorry
Ok
Use EntityInevntoryComponent to find out what items are currently in a “crafting table” and compare them with the ones you need, if everything matches, then delete them and issue a new item
@pseudo marlin how many slots do you have
and what it the output slot index
are on an 81 slot base with the exit slot being 82
💀
sorry it's a lot right?
yeah
anyway is it a grid or what?
As I remember, you can’t have so many slots
the 81 slots are a grid while the output slot is a loose slot
you can, the way json ui displaying them is what limit them
9x9?
Yes @distant tulip
If someone is interested about a class for the new input info #1319734492478312498 message
It took me 25 mins to alphabetical order translated words lmao
-# it's 2am in the morning so pls be chill with me
what happen if you set item amount to 0?
is there any different method, like tracking block changes via a scoreboard or any subscribe?
Use dynamic property?
huh? get removed?
i am asking so i can deal with that case if it doesn't
Yeah, it gets removed...
Wait lemme try...

you will receive a prize in the form of an error
thought so
my favorite
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) =>{
if (itemStack.typeId === 'minecraft:diamond') {
const inventory = source.getComponent('inventory').container;
system.run(() => {
itemStack.amount = 0;
inventory.setItem(source.selectedSlotIndex, itemStack);
});
}
});```
So umm it throws an error saying not a valid amount and the amount should be 0 to ,255
From 0 to 255, but in fact from 1 to 64
My internet is so shit, that it just sends now
yeah
good to have that confirmed
Fr 😭
custom items...
I couldn't make the stack larger than 64
// Player join event
world.afterEvents.playerJoin.subscribe(({ player }) => {
const playerId = player.name;
const playerPlot = db.get(playerId);
if (playerPlot) {
loadPlot(player, playerPlot.index, playerPlot.coordinates);
}
});
// Player leave event
world.afterEvents.playerLeave.subscribe(({ player }) => {
const playerId = player.name;
const playerPlot = db.get(playerId);
if (playerPlot) {
unloadPlot(playerPlot.index);
}
});
```\
got a error at const playerId = player.name;
Debug result for [code](#1067535608660107284 message)
Compiler found 6 errors:
[36m<REPL0>.js[0m:[33m2[0m:[33m43[0m - [31merror[0m[30m TS2339: [0mProperty 'player' does not exist on type 'PlayerJoinAfterEvent'.
[7m2[0m world.afterEvents.playerJoin.subscribe(({ player }) => {
[7m [0m [31m ~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m4[0m:[33m24[0m - [31merror[0m[30m TS2304: [0mCannot find name 'db'.
[7m4[0m const playerPlot = db.get(playerId);
[7m [0m [31m ~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m7[0m:[33m9[0m - [31merror[0m[30m TS2304: [0mCannot find name 'loadPlot'.
[7m7[0m loadPlot(player, playerPlot.index, playerPlot.coordinates);
[7m [0m [31m ~~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m12[0m:[33m44[0m - [31merror[0m[30m TS2339: [0mProperty 'player' does not exist on type 'PlayerLeaveAfterEvent'.
[7m12[0m world.afterEvents.playerLeave.subscribe(({ player }) => {
[7m [0m [31m ~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m14[0m:[33m24[0m - [31merror[0m[30m TS2304: [0mCannot find name 'db'.
[7m14[0m const playerPlot = db.get(playerId);
[7m [0m [31m ~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m17[0m:[33m9[0m - [31merror[0m[30m TS2304: [0mCannot find name 'unloadPlot'.
[7m17[0m unloadPlot(playerPlot.index);
[7m [0m [31m ~~~~~~~~~~[0m
There are no errors from ESLint.
Read the documentation again
playerJoin does not have a player property
OK thanks
Just use playerSpawn
and initialSpawn
If you only need playerId (I prefer playerId over player.name cuz it doesn't change), get playerId from playerLeave event. (e.g. https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.WorldAfterEvents.html#example-leavemessagejs)
Same with playerJoin (https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.WorldAfterEvents.html#example-subscribejs-21)
world.afterEvents.playerSpawn.subscribe(({ player, initialSpawn }) => {
if (initialSpawn) {}
});```
in playerLeave just use before events not after events
If... You're settling something otherwise just use after events
yeah, i thought we can
Any suggestions for my simulated player menu?
Write an AI that will perform the actions it is told to do.
Like chatgpt? I give it's description and basically use the action that is in the class. Is that what you're talking about or just an AI mob for example can walk around the map.
Yes, like gpt.
Debug result for [code](#1067535608660107284 message)
Compiler found 3 errors:
[36m<REPL0>.js[0m:[33m1[0m:[33m1[0m - [31merror[0m[30m TS2552: [0mCannot find name 'block'. Did you mean 'Block'?
[7m1[0m block.dimension.setBlock(block.location, block.type)
[7m [0m [31m~~~~~[0m
[36m@minecraft/server.d.ts[0m:[33m3864[0m:[33m15[0m
[7m3864[0m class Block {
[7m [0m [36m ~~~~~[0m
'Block' is declared here.
``````ansi
[36m<REPL0>.js[0m:[33m1[0m:[33m26[0m - [31merror[0m[30m TS2552: [0mCannot find name 'block'. Did you mean 'Block'?
[7m1[0m block.dimension.setBlock(block.location, block.type)
[7m [0m [31m ~~~~~[0m
[36m@minecraft/server.d.ts[0m:[33m3864[0m:[33m15[0m
[7m3864[0m class Block {
[7m [0m [36m ~~~~~[0m
'Block' is declared here.
``````ansi
[36m<REPL0>.js[0m:[33m1[0m:[33m42[0m - [31merror[0m[30m TS2552: [0mCannot find name 'block'. Did you mean 'Block'?
[7m1[0m block.dimension.setBlock(block.location, block.type)
[7m [0m [31m ~~~~~[0m
[36m@minecraft/server.d.ts[0m:[33m3864[0m:[33m15[0m
[7m3864[0m class Block {
[7m [0m [36m ~~~~~[0m
'Block' is declared here.
There are no errors from ESLint.
Yes, you need to look at the documentation, and not invent your own methods
block.setType('dirt')
soo ```js
block.setType(block.location, block.type)
.
@pseudo marlin
replace
container.setItem(slot, new ItemStack(resultItem.split(" ")[0], Number(resultItem.split(" ")[1])));
with
container.setItem(81, new ItemStack(resultItem.split(" ")[0], Number(resultItem.split(" ")[1])));
Well if I'm going to be using gpt I have to use a bedrock dedicated server.. which idk how I can start making it and even setting it up.
Use The bot in the #debug-playground pls
ok
I thought I'd forward this here for those that are curious about V2's upcoming changes that (I don't think?) have been publicized.
Is it possible to programmatically apply an item to an item frame via script api?
no
i need helper for this library, this soo long project i can't handle alone🙃, i know this will be get a lot time to perfect this project, i rebuilt this 5times for feel easy to use and easy to learn,
https://github.com/nperma/Stool-API

is there a way to duplicate an entity?
oh wait
do scripts even work on falling snow?
how do I set the player's view direction? I know there's an accessor method I just wasn't sure if there was a mutator method I wasn't aware of
I want a breed component
C'mon guys don't be weird...
We have a tameable components accessible in scripts, how about breeding?
I like hamburgers
nope
Why 😞🥺
No. I'm gonna throw a tantrums here.
this is how I feel about not having biome-related apis.
The only thing we have is findBiome but it's also performance HeAVy
findClosestBiome
im aware
Oof I forgot the actual name because I don't use it.
I know just saying 🤷
Me when no setLore limit increase fr
That too... God
Guys what is target? I see it in entity class here example
world.afterEvents.playerSpawn.subscribe(player=>console.warn(player.target)) what is this do can you give example?
When a zombie comes towards you and wants to attack you, you are its target.
Awhhhh thx I understand now
Umm, just a confirmation... I want to sort something into alphabetical order, but the words are translated is it possible to do that?
you're using translation keys?
yeah
Guys is there anyway to export the world in minecraft pe with ORE UI? I'm stuck for it
just get the world from files
I need .mcaddon
zip it and change file type
must from the export method
there is no different
Alr
How many lines of strings do you guys think the body in the server form can handle before it lags your devices?
Can string char code sort em...
Also, if they're categorized in keys, it shouldn't be a problem
Can you create a poster with custom text using js?
I'll ask for more information tomorrow morning and I mean tomorrow probably 2-3 hours from now because I'm sleepy asf
const response = form.show(player);
system.runTimeout(() => {
if (time > 0 && !response.canceled) {
uiManager.closeAllForms(player);
waitUntilOpens(player);
} else if (time === 0) {
uiManager.closeAllForms(player);
}
}, 20);
Why form keeps opening even I’m closing it?
?
do u decrease time?
If yes, ```js
else if (time <= 0)
Also
const response = form.show(player);
system.runTimeout(() => {
if (time > 0 && response.cancelationReason === "UserBusy") {
uiManager.closeAllForms(player);
waitUntilOpens(player);
} else if (time <= 0) {
uiManager.closeAllForms(player);
}
}, 20);
Now it’s not counting
I need to make it keep updating until player closes the form
but it keeps opening when player closes form
Im trying json ui again, can anyone tell me why the ui form wont show?:
world.afterEvents.playerSpawn.subscribe(({
player, initialSpawn
}) => {
if (initialSpawn) {
console.warn("JOINNNNNNNN");
const players = world.getPlayers();
const modalForm = new ModalFormData().title("Example Modal Controls for §o§7ModalFormData§r");
modalForm.textField("Input w/o default", "type text here");
modalForm.textField("Input w/ default", "type text here", "this is default");
modalForm.show(players[0]).then((formData) => {
players[0].sendMessage(`Modal form results: ${JSON.stringify(formData.formValues, undefined, 2)}`);
})
}
});```
hey uh how do i fetch player's tag?
if (player.hasTag('tag'))
ah thanks
anyone?
Ohh thx
It won't look very good
function updateUntilClose(player) {
let menu = new ActionFormData()
/*
Form settings
*/
let close = false
menu.show(player).then(data => {
if (data.canceled) close = true
})
system.runTimeout(() => {
if (close) return
UIManager.closeAllForms(player);
updateUntilClose(player)
},3)
}
function myForm(player) {
let menu = new ModalFormData().title("Example form")
menu.textField("Input w/o default", "type text here");
menu.show(player).then(data => {
if (data.cancelationReason == "UserBusy") {
return system.runTimeout(() => {
myForm(player)
}, 10)
}
//Code if the form was shown
console.warn(formData.formValues);
})
}```
For some reason the form value is invalid
Does the debugger talk about any errors?
Just that its undefined
world.beforeEvents.playerBreakBlock.subscribe((event) => {
Object.entries(Enchantments).forEach(([key, value]) => {
if (value.onEvent === event.constructor) {
if (!(event.itemStack && ItemUtils.getItemType(event.itemStack).length > 0)) return;
const Enchant = EnchantmentUtils.getEnchantments(event.itemStack).find(enchantment => enchantment.name === key);
if (Enchant) {
value.Callback(event, Enchant);
}
}
})
})
can somebody explain to me why indexing anything on event after the if (value.onEvent === event.constructor) condition defines the type of event to be never ?
value.onEvent: typeof PlayerBreakBlockBeforeEvent | typeof ArmorIterationEvent | typeof CustomHitEvent
this condition worked just fine for me when i used jS
I understand that it's comparing an Event class to a function but ehh it's confusing me a bit, the condition works in terms of logic but it gives errors in ts
Are you intending to see if value is an instance of event? Because you can use if(value.onEvent instanceof event)
nvm
switched it to event.constructor and it works
thx
Player.prototype.nameTag
use lang files for that
Whats prototype?
Oh ok
player.nameTag = "hhagdfkugdfksdgfhdf"
a prototype object of class Player, i used it as an example
Ahh
if you get a player from an event it's an instance created from the Player class, these objects have a nameTag property
Would that also change appearance of the leave message?
no it wouldn't
Ah i see
no
from what I know only the player name displayed on the use of /w & 3d name tags in game
Sheet
the name property is what's used for kill messages and such but it's read-only
use lang files like i said
Oh rip
I just need to change the name tho
what do u wanna change in it
that's what you'd use it for
Or can we replace player name with nameTaf
no you cannot
the name and nameTag properties are two different things
multiplayer.player.joined=§8[§a+§8] §a%s # is for example what I used
%s represents the name of the player
but afaik you cant rlly update that
I want to make some box where you can set an player name so your xbox name stays hidden
ask in #1067869318383157430 or #1067869590400544869 i think
Rip
well what u could do is
create a fake leave/join msg using scripts
and make the vanilla message display as empty
it will create a new line in chat yes but it's just a visual issue
🤔alr
i can make a helper class for you
im assuming you want to make a nicking system?
so players can disguise themselves better
a fake name
O: thats be great ig, yea, like to stay anonymous
TypeScript:
class NickUtils {
getPlayerName (player: Player) {
return player.getDynamicProperty("nick") ?? player.name;
}
updateNick (player: Player, nick: string) {
player.setDynamicProperty("nick", nick);
}
resetNick (player: Player) {
player.setDynamicProperty("nick", undefined);
}
}
class NickUtils {
getPlayerName (player) {
return player.getDynamicProperty("nick") ?? player.name;
}
updateNick (player, nick) {
player.setDynamicProperty("nick", nick);
}
resetNick (player) {
player.setDynamicProperty("nick", undefined);
}
}
wait
lemme add 1 mroe
use NickUtils.getPlayerName(player) anywhere to get their name; it always prioritizes retrieving their nickname over their actual username, bc name is always defined, the nick property is not
if you want to remove their nickname use NickUtils.resetNick(player)
if you want to update their nickname use NickUtils.updateNick(player, nick)
const nickCommand = "!nick %s";
const resetNickParameter = "reset";
world.beforeEvents.chatSend.subscribe((event) => {
const { sender, message } = event;
if (message.startsWith(nickCommand.split(" ")[0])) {
const nick = message.replace(/@/g,'').match(/"[^"]+"|\S+/g)?.[1].replace(/"/g,'');
if (nick) {
nick !== resetNickParameter ? NickUtils.updateNick(sender, nick) : NickUtils.resetNick(sender)
}
}
})
example usage
wait
Ah, i used an map for storing it
world.afterEvents.playerSpawn.subscribe(({
player, initialSpawn
}) => {
if (initialSpawn) {
myForm(player);
}
});
let playerName = new Map();
function myForm(player) {
let menu = new ModalFormData().title("Example form")
menu.textField("Input w/o default",
"type text here");
menu.show(player).then(data => {
if (data.cancelationReason == "UserBusy") {
return system.runTimeout(() => {
myForm(player)
}, 10)
}
playerName.set(player, data.formValues);
player.nameTag = data.formValues;
})
}
world.beforeEvents.chatSend.subscribe(data => {
const senderEntity = data.sender;
let senderName = playerName.get(senderEntity);
const message = data.message;
world.sendMessage(` ${senderName} ➭ ${message}`);
data.cancel = true;
})```
yes as long as this works then it's fine
Works just for chat rn
My guys why yall over complicating the task?
Missing is:
Join/leave message
Death and kill messafe
Oh 😬😬
so that's why I recommend a dynamic property
Alr yea, property is better than
how
How else would you want to disguise the name in chat messages
that's not overcomplicating, it's preference
But sure, yall do whatever yall wanna do.. I am busy rn so I can't really show you want I mean.
*Sigh*
i was initially going to make only a function for getting the player name but i found that there was no harm in adding two more ..
Sure just you do you
?
i think it's a good practice to use classes or whatever
Ima be back in some hours prob
maybe this isn't a good scale to represent the benefits of it
Making A function or class for little actions and you aren't even gonna use them more than once or twice in the whole script isn't good practice
Yeah.
but it still does keep it easier to maintain
why
twice is already enough
to make a function for it
imo
once yeah maybe not
Bruh
and there might be other ways that he wants the players to be able to change their nickname
than just a chat command
I'm sorry for starting this argument just go on bruh, you do you.
no worries
I like to avoid arguing when I don't have time to prove my point so yeah ig your "right". (No offense)

-# hence where code...
static enchant (itemStack: ItemStack, enchantment: Enchantment): ItemStack {
const properties = {
enchantmentSlots: itemStack.getDynamicProperty("enchantmentSlots") as number,
usedEnchantmentSlots: itemStack.getDynamicProperty("usedEnchantmentSlots") as number,
enchantments: JSON.parse(itemStack.getDynamicProperty("enchantments") as string) as Enchantment[] | string,
whitescrolled: itemStack.getDynamicProperty("whitescrolled") as boolean,
nameTag: itemStack.getDynamicProperty("nameTag") as string
}
if (!(Array.isArray(properties.enchantments))) return itemStack;
if (properties.usedEnchantmentSlots >= properties.enchantmentSlots) return itemStack;
const enchantmentExists = properties.enchantments.find(_enchantment => _enchantment.name === enchantment.name)
if (enchantmentExists) {
enchantmentExists.level = Math.min(Math.max(enchantmentExists.level+(enchantment.level-(enchantmentExists.level-1)), enchantment.level),(this.getEnchantment(enchantment.name) as typeof Enchantments[keyof typeof Enchantments]).MaxLevel)
} else {
properties.enchantments.push({
name: enchantment.name,
level: enchantment.level
})
}
properties.usedEnchantmentSlots = (properties.enchantments).length
properties.enchantments = JSON.stringify(properties.enchantments) as string;
for (const [key, value] of Object.entries(properties)) {
itemStack.setDynamicProperty(key, value);
}
const updatedItem = ItemUtils.updateLore(itemStack)
if (updatedItem instanceof ItemStack) {
return updatedItem;
}
return itemStack;
}
i expected using as string statement when updating the value of properties.enchantments to force the type to now be string and not Enchantment[] | string, so now I get a type error here:
/* for (const [key, value] of Object.entries(properties)) { */
itemStack.setDynamicProperty(key, >> value <<);
/* } */
how do i fix this
i tried a typeof type guard for it before I update dynamic properties but it doesn't change anything
if i return function with using system.run it garant what function will be completed in no more than a tick?
If someone is interested #1320052540582264912 message
Hey I'm here now.
Wait @warm mason isn't there a
thing in github that uses gpt 💀 (idk felt like adding the skull)
For simulated players
?
Codex
????????????
Does anybody know how much system.runInterval impacts server lag?
Is it a high or low impact?
Depends on the function you made
And what is this?
Simulated Players using chatgpt look at the full codes, etc ...
🤖
All I want for Christmas is a breed component
Cool. I was just about to make my own navigation system because entity components hate me
this is kinda nice
you need a open ai api key tho
Yeah heard about hugging face tho?
the api is free?
🤖
Yes hugging face you just create an account and u get free API keys
Without paying a dime
U also have to find a model doe
Yes. 😞😞
coddy, its time to move on
No. I will never, I made a promise...
Just make your own breed component
you might be asking about it for years
Fak nah...
why not?
What? I never asked about the breed component to be added ever.... just today
And a dedicated server too
yesterday you did
Ohh, yeah but not years ...
also I didnt say you were doing it for years, I said you will be, because thats how long it'll take to come out
Ahh, I get it...
Anyways unrelated but it took me 10 minutes to set up a lang file because i didn't read the docs properly on how to use %s, %%s and %%1...
breed apis = 5 years
lore limit increase = 10 years
biome apis = 50 years
breed component, translation string sorting... what are you cooking?
Herobrine won't like this ...
Just let me cook brother...
I'll have to become immortal
OreUi 200 years
thats being too generous
Who said 200 years? You mean 1000 years?
thats more like it.
Equippable for all entities - 1/0 years
too generous
nahhh
Rotate players camera: not happened in any parallel universe
I got equippable to work on simulated players
what if the whole script api gets restarted
custom commands: ∞
(ノ`Д´)ノ彡┻━┻
Idk what pfp to use that's why I left it blank for now...
Did you notice just now?
no
I want something that is kinda describing me but somewhat cool...
In 2050 we will play Minecraft with ai friends 😭😭
a rat
But I don't know how to design that's why I left I blank
Why the fuck RATT!!
Developers don't play Minecraft
lmaooo
I do I play the shi7 I create
y'know what's funny, it's kinda reference in how I am kinda obsessed with the user that has a rat character....
what
Maybe you should have one as a pet
I'm talking about Ignis
Username sorry
oh.
God damnit, my auto correct is slipping
I understood the nonsense 👍
Dap me up cuh.. 🤝
I asked this and nobody responded... What do you guys think the limit of lines of strings that the body of the server form can handle before it starts to slow down the game
It will always slow down the game
Hmm...
long string in ui freeze the client for a bit
my multi-tab server form uses 800 character long string and it still work normal
Maybe you just got a good pc
800 is not much
it is a potato
Well some people define a 4060 as a potato
nah , i am not displaying it all at once
1000 do lag normal forms a bit
what
i5 6Gb ram laptop
no cart graphic
Long ago I asked in BuildAPc discord group and they said that a 3060 was trash, and they also recommended me a 400€ keyboard satin that it was the minumum
hm
you said 4060
Was an example becouse now it the latest, when I was buying my pc I asked for 3060
They're probably just from the future, where cookies cost $1000
I mean it won't since it's not really big strings, how about 2k
not my cookies 🍪
😔
that is a thing now btw
afslut 🗿
I just realized that Game is paused isn't translated
"markedsplads"
Is that flag from Czech Republic?
Are you talking about the flag in my username?
Ye
lol
I can't imagine how this reads
It's Philippine flag
Ohh
yours is russia right
No ukraine
ohhh
You can’t be serious
Ohh no void...
👍 👍
You re Russian
I know... I'm just shitibf around
What’s that alien language
👀
Russian spy... insert tf2 sound effects
bruh
serty is russian yeah
Oh no, I've been found out
t pose in 2024 is unexpected
Russian language letters look like ancient prehistoric symbols
upside down head is more unexpected
What about Chinese?
bruh
6000 symbols well well
How do you manage to undersand this
this is very script api related fellows
Yeah
Yes...
This is starting to be like #art-and-modeling
Well if you want to talk about script api why don’t you take a look at this #1320052540582264912 message
No...
-# just kidding
KEEP IT SCRIPT API GUYS FOR THE LOVE OF GOD
😭
sorry master 😔
hahaha
alr
-# bruh my joke got nuked
What joke
I saw the "Bean Chillin" and you deleted it
minato you are still here, so the joke is not gone.
lmao
they did
😭
Ohh my god... 😨
Mods deleted it? Crazyyy
Why you cryin?
not close lol
Anyways, I just want BREED COMPONENT to be accessible...
im aware
Yes I said it thrice already
I need that oreUi
-# The moderator is already choosing a target
And if I lose my mind here, I will literally redo the whole breed system in scripts
then do it
I need.... Love :(
Is it denial to refuse to learn json ui until oreui comes out?
I didn't lose my mind so, I ain't doing it yet
Nah, that's just being smart 😛
It'll pay off in 5 or so years
console.log("he hurt my feelings") //this is script related
JSON ui is just trash, hard to control, ancient, inefficient, complex, hard to read
are you sure
erm 🤓 based on my learnings of json ui for the past 3-4 years it's not hard to resd
Your just blind
"Your exist blind"
being able to read something ≠ it being easy to read
"Your hust blind "
used to hate it, now i kinda like it
3 years 😭😭 1 year ago I didn’t even know that I could make Minecraft addon by myself
FOR UFCK SAKE AUTO CORRECT 💯
lmaooo
Now I'm losing my mind not because of scripts but because of auto correct!!!
Rahhh
Yeah iOS 18 is a$$
#off-topic
Instead of a mob vote they should host a vote on adding features to the bedrock development community
Actually it's been four years...
This is becoming off topic
no really?
I thought iphones were related to minecraft
Or just MOVE THE CONVERSATION, not that hard
Aura is crazyyy
That caps lock felt like shouting
Let's move cause Herobrine will literally activate and one shot us all
Because he is...
is it off topic if you formatted every message
world.sendMessage("like this?")
Stop spamming gifs or images now
if only there was a channel that conversations with no topic could take place in 😔
Time to make herobrine64 mob
and he deletes your player data like a gif
where do you go to talk about jigsaw blocks
That’s script api related 👍👍👍🔥🔥🔥🔥🔥 #1320052540582264912 message
😐
Shameless plug
He's just a moneyman doing business
What does this mean
nah, he is trying to save the channel
I want feedback
The channel born 3 hours ago
🕳️
i meant this one (form off-topic topics)
-# so I can't give a good opinion
The 20k jam submissions having no topic ironically makes it harder for me to come up with something for it
Actually is a form that uses action bar as dysplay and input info as control
There are 3
"I undastand it now"
4*
nice idea
-# bruh
Thanks
Can jigsaws be scripted
minecraft 360 graphics
sometimes these things can overlap if you start using turns and stuff for the path
and I'm allergic to structures overlapping 😷
PS3 2015 ahh graphics
I used to play on that thing
That’s really cool (I hate structures)
Did you know 1981 was the year of raaaahhhhhhhhhh 👏👏
structures would be a game changer if we could exclude/include entities using entity filter
you should be a comedian
he can't if he is the joke
You can
uhm...no?
you can?
in structures?
Yes there is the options
yeah i am out of here
and they already do btw... who ever tf was that
Just use the command
That was carchi lol
! true (script api related)
!
don't java villages have some type of anti collision logic with their jigsaws when generating
the audit logs would reflect differently
-# If I get a good idea of what that is I could probably script it
i am talking about something like EntityQueryOptions
I hope jigsaw will be easy to set up
Where scripting?
System.out.println(“here”);
I thought it was easy
Why do you need jigsaw when there are scripts? :)
village generator worked up until I added turns on the path then they started going in on themselves
I mean..
It’s the most complex thing in the world, they don’t have auto completions they have old ui and code lines like command blocks that don’t have auto completions
testing it out was fun
"is the scripting in the room with us right now?" -smokeystack
scripting is the friend we made along the way
That is what a jigsaw looks like
Yes, I used it for that village screenshot
Please move elsewhere.
I'm here for a reason
what do you guys think would be the best way to add a custom effect/potion effect
I don't imagine there's any support for that so would giving the entity a tag and running something every tick be one way to go?
Yeah.
that's unfortunate
how do I make a simluated player?
Is there a player hit entity event?
There's entity hit entity, and you can check if it's a player
damn, isnt that stressful
cant we just have one for the player directly
Is a player not an entity?
They likely won't add a separate event solely for player, as the entity one does the job just fine and is a more general use case.
🫤
What's the problem with just writing one if
i have, im just asking if theres a direct method of doing it
There sure ain't
can the gravity of knockback to players be modified
...
an if statement is stressful?
don't think about it your brain will melt
theirs or mine?
✅ all of the above
What
has to be a troll.
is it bad for me to find other and easier ways to do something
😠
It doesn't get any easier than a single if statement 😭
if you think an if statement isn't easy...
the gravity?
yes
or like
inertia
more of
i feel like the player falls back down too fast, it's hard to hit anybody high up in the air
trying to make custom knockback
Im not sure how to go about that
maybe use entity hit entity event, wait a second or less, grab player velocity and multiply it and apply to knockback ?
you can also likely just get direction between you and hit entity, and apply a flat amount of knockback in a certain direction
U shouldn't player[0] just player
they need to first create a for of loop to do that (or use forEach)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
The for...of statement executes a loop that operates on a sequence of values sourced from an iterable object. Iterable objects include instances of built-ins such as Array, String, TypedArray, Map, Set, NodeList (and other DOM collections), as well as the arguments object, generators produced by generator functions, and user-defined iterables.
good game
Use toLocaleString() or custom function
Yee, its already changed
yeah i've done that but i want to modify the falling speed
the vanilla kb speed is too quick
but that also affects jumping and anything else that involves falling + it doesn't make a difference in the upwards velocity only downwards
.applyKnockback(); // test and find out the perfect knockback value for applying knockback from the bottom
Ar U making custom knockback
yes
the kb itself works but the values just are not good for actual pvp
Can U give me if U done it
maybe idk
Im alr looking for it for a long time
there's more to my pvp system than just the knockback itself
just code it urself
I can't make It perfectly
well neither can I and that's why I'm here asking for help with it
I just need a low knockback and high falling
high falling as in being able to combo people without them constantly being on the ground
I alr tried to do it
?
But the effect is not good
i have the same problem 
its not fun to pvp with its awful even vanilla kb is better
Yea I need it can do combo at player
with the double hits
.getVelocity();
// there is a post somewhere in this server that eventually leads to converting that value to kb
.applyKnockback();
// edit the kb to your liking :)
I said this
but this won't affect the speed ? i don't understand
This is what I do
Nope it won't
Can U give a example
that's what my original problem was
Unless you mean the attacking speed
noo i mean the speed that they fall and go up at
It literally dismantles them.
the speed that the knockback takes effect at
Making the player fall slower is likely going to require running a teleport every tick or giving them slow falling
He means get the speed and convert to knockback
but knockback is always done at a fixed speed no ?
Increasing the height they go up is very easy and is a parameter of knockback as is
i was wondering if there's a way to modify that
Sigh, let me find the post for ya rq
Who can help me make the code more good
I think I already have a nice value for applyknockback but the code is not perfect
it seems fine to me
U tested my code?
no i didn't test it
Ah, here it is:
https://discord.com/channels/523663022053392405/1286283295801348096
You are gonna need to read through tho. So yeah get some popcorn or your papers & pens or whatever you wanna get lol and read through.
Is there a way to change the entity's name shown on a bossbar? Using .nameTag = doesn't update it.
Component groups?
You can change it through component groups
I want to change it dynamically using scripts
Oh
Is it a custom entity? Did you try to do it on withers?
I just tried both and failed. It only updates the bossbar name only when using nametag (the item).
-# typical hardcoded stuff
I found a janky workaround using runCommand() and /summon
Can anyone help me make a anti combat log system ??
If anyone can then please ping me
are these bad stats
?
@minecraft/debug-utilities.collectRuntimeStats()
Why fetch them? Are they important?
Oh, never use this...
not really bad stats
but there's not really any really useful case that you can use them in practise
Felt like they wouldve been valuable to help me visualize if my scripts were efficient or needed work
they just show usage of resources
Use a TPS counter
or just benchmark it
They won't really help you check it..m
tps is 20 up until like 30 players and i cant even tell if its my scripts anymore cause of how much times ive refactored it always seem to lag just as much
it's good then
im only using 1% of my total ram and 2% of my total cpu
I'd love to be able to handle more players but doesn't seem like something I can do
Not sure whats the cause
if it'll be some public add-on I wouldn't care about performance on bigger numbers
pls i need help
as far as it's okay for 10-15 players it's good
I'm using my own addon for a network 😅
oh, then this might be a small issue if you have more than 30 players
Anyone know if its a good idea to run 10000+ world.structureManager.load() at once to replace setType() 💀 or fillBlocks()
you can't split it in time a bit?
Probably could just thinking about making a simple world edit and since setType doesn't work in unloaded chunks it'd be nice to work at a larger scale which structures provide
I could definitely split it up
if i do player.__leftClick = true
can i get that value in different event even if that event will be in different file?
Yes
Player seems to save its properties across events and what not, its pretty damn useful
How to I make a anti combat log system ?
Can anyone help me or hive me advice?
beforePlayerLeave event, save all the items into an array, and then in the next tick spawn the items
#1099050351140818954 message
Enough advise there to get you fairly 70% of the way there.
yep just saw tysm 🙂
You're welcome.
What's the best method of spawning something only certain players can see, is there any way to make a particle or something else that is only visible to certain players?
Thanks
block.setPermutation('perm','value')
whats the correct syntax???
import { BlockPermutation } from '@minecraft/server'
block.setPermutation(BlockPermutation.resolve('blockId', {
'property': 'value'
}))
if (itemStack?.typeId !== 'worldedit:debugstick') return;
const states = block.permutation.getAllStates()
const kv = []
Object.entries(states).forEach(([key, value]) => {
kv.push([key + ':' + value])
});
new ActionbarMenu()
.title('BlockStates')
.pattern(kv)
.show(player).then(({ slot, line }) => {
/**@type {string} */
const result = kv[line][slot].split(':')
const perm = BlockPermutation.resolve(block.type, { result[0]: parseInt(result[1]) + 1 });
block.setPermutationperm)
})
im trying to create a debug stick
is that right?
BlockPermutation.resolve(block.type, { [result[0]]: parseInt(result[1])+1 });
world.afterEvents.itemUseOn.subscribe(({ source: player, itemStack, block }) => {
if (itemStack?.typeId !== 'worldedit:debugstick') return;
const states = block.permutation.getAllStates()
const kv = []
Object.entries(states).forEach(([key, value]) => {
kv.push([key + ':' + value])
});
new ActionbarMenu()
.title('BlockStates')
.pattern(kv)
.show(player).then(({ slot, line }) => {
const result = kv[line][slot].split(':')
console.log(result[0])
const permId = result[0]
// the next line does throw
const perm = BlockPermutation.resolve(block.type, { [permId]: true });
block.setPermutation(perm)
})
})
permId isnt working why?
found out that arg[0] is block type not permId so the error was that i needed to use typeId instead of type
isnt that what the log already says?
yes but i was thinking the arg[0] was the permId
it is not reading the ${slot}
system.runInterval(() => {
for (const player of world.getPlayers()) {
let slot = player.selectedSlot;
player.runCommand(`scoreboard players set @s hotbar ${slot}`);
}
});```
.selectedSlot => .selectedSlotIndex
ok gonna try it
That script is quite outdated righ? (Cuz that change has been in the api for maybe like 3 updates or more)
what is the playsound for tnt exploding? I can't get it to work
random.explode
random.fuse
anyone know how i can format something to look like this?
.body(`§bWelcome §e${player.name}, §bYou have §2$§a${money}§b. §3Please select an option from down below!`)
i would also like it to be put in this
Description
Calculate player's vector offset.
Credits
These scripts were written by GlitchyTurtle32
import { world } from "@minecraft/server"
world.beforeEvents.playerPlaceBlock.subscribe((eventData) => {
const blockGP = eventData.permutationBeingPlaced.type.id
const blockBPO = eventData.block
if (blockGP === "minecraft:soul_torch" && !blockBPO.matches("bedrock")) {
eventData.cancel = true
} else if (blockGP === "minecraft:soul_torch" && blockBPO.matches("bedrock")) {
world.sendMessage({
rawtext:
[
{
text: `§5§o${playerName} has placed a torch`
}
]
})
}
}) ```
Why can’t I place the soul torch ANYWHERE?
minecraft:bedrock?
That’s so dumb. I used block.typeId === “minecraft:bedrock” before and it didnt work
well wait, thats what the code does though, to cancel...
if its not bedrock, itll cancel
are you are asking why you cant place it anywhere...
i mean. Not even on bedrock
weird wording.
I’ll try adding the namespace and I’ll be damned if somehow that works
Still doesn’t work
Torch does not get placed and no message is sent
Although i did forget to add a system.run so I’ll do that but still
your code is asking if the block is soul torch but not bedrock
you cannot check what its being placed on
I mixed up the variables :(
What what
use beforeEvents interact with block
Then what’s with “blockpermutationbeingplacedon”
then cancel that
its "permutationBeingPlaced"
not "permutationBeingPlacedOn"
Wow I’m incredibly dumb
misread 🤷♂️
.
There is a way to detect when a player mounts an entity?
§fBalance: $§b
?
Riding component
Any examples?
Ty
Is there a way to save any kind of data. Like if I want to save a string of data for when the world is closed or a server stops running?
thanks!
Cam you register multiple components with the same world.before.events?
AYO IM THE MESSAGE 100K
[Everyone](#1067535608660107284 message) has [been](#1067535608660107284 message) message [100K,](
#1067535608660107284 message), it's [not](#1067535608660107284 message) really [that](#1067535608660107284 message) special [to](#1067535608660107284 message) get [anymore](#1067535608660107284 message) .
I have a "system.runInterval()" that every 2 seconds gives an effect to all players using "for (let player of world.getAllPlayers()) {}" but for some reason it only targets one player, I do have other things that run inside the "for".
Do world.getplayers().foreach(player => {
})
Thanks
Anyone know of the world.beforeEvents.chatSend event is currently working? I get an error saying that it is undefined when I try to use it.
You are probably in stable?
I do have beta apis turned on in the world though, so idk
You should also use the beta version of apis in your manifest
can anyone tell me what's the right number for the y part in my apply knockback script if I wanted my mob's jumping range to be far as 24 - 27 blocks?
system.afterEvents.scriptEventReceive.subscribe((event) => {
const source = event.sourceEntity
const target = source.target;
const dimension = world.getDimension("overworld");
try {
switch (event.id) {
case "cod:event_knockback":
if (target !== undefined) {
source.applyKnockback(source.getViewDirection().x, source.getViewDirection().z, 9, 0.5);```
https://jaylydev.github.io/scriptapi-docs/latest/modules/_minecraft_server-1.html
you need to use beta api module, and use beta typings if you're using vscode
Thank you
fitting name too
Is it a good idea to have an instance for each player to run parallel tasks instead of just doing a for loop? This is an example of one
export class PlayerInstance {
private static players: PlayerInstance[] = [];
private readonly entity: Player;
private readonly routine: number;
constructor(entity: Player) {
this.entity = entity;
this.routine = system.runInterval(() => this.update(), 1);
}
private update(): void {
this.entity.onScreenDisplay.setActionBar(`§6Sneaking: §c${this.entity.isSneaking}§6 | §eSwimming: §c${this.entity.isSwimming}§6`);
}
public close(): void {
system.clearRun(this.routine);
}
public static getPlayer(entity: Player): PlayerInstance | undefined {
return this.players.find(player => player.entity === entity);
}
public static getPlayers(): PlayerInstance[] {
return this.players;
}
}
I think yes,because then you got a better control for each player
You cannot compare objects. Compare their IDs
What did they change to this? 😭
let component = itemFormatted.getComponent("minecraft:enchantable");
component.addEnchantment({ type: new EnchantmentType(`${enchant.type}`), level: enchant.level })```
Apparently itemStack.getComponent(„minecraft:enchantable“) returns undefined
why?
Hillo
It sets that to „unbreaking“ for example
Yeah, but why put that on a string instead of just writing enchant.type
does the player leave before event work now?
Great!! Thank you so much!!
Yeah, exactly
Why it doesn't work
private update(): void {
if (world.getPlayers({ name: this.name }).length === 0) {
this.close();
return;
}
this.entity.onScreenDisplay.setActionBar(`§6Sneaking: §c${this.entity.isSneaking}§6 | §eSwimming: §c${this.entity.isSwimming}§6`);
}
public close(): void {
system.clearRun(this.routine);
const index = PlayerInstance.players.indexOf(this);
if (index !== -1) {
PlayerInstance.players.splice(index, 1);
}
}
Is there any other way that I can check if the player left the server? I feel like the method I used might use more resources
if (player.isValid())
Why not just use a loop in system.runInterval that loops through all players
I fear it might be a cost on performance, and when you want to have 100 players on a single server, every bit of optimization is important
So I'm trying to run things in parallel instead
Minecraft itself can’t even handle 100 players… right
Only if your host is not a quantum computer
I didn't say it can't, it's just difficult
Especially with BDS
this isnt working:
world.beforeEvents.playerLeave.subscribe(({player}) => {
const item = player.getComponent("inventory")?.container?.getItem(player.selectedSlotIndex);
system.run(() => {
player.dimension.spawnItem(item, {
x: player.location.x,
y: player.location.y,
z: player.location.z + 5
})
})
})
its not spawning the item
How are you testing it? Singleplayer?
yes
does it only work on non-host players?
bruh
I just realised I made a spelling mistake
How will the code be executed if there is no host?
it was still executing tho
I forgot to use system and it said "does not have privileges" error, so that means it does run
Yes, because this is before player has left, and after that if you use system.run nothing will work. Because there is no host
oh
