#Script API General
1 messages · Page 95 of 1
I have to rig it up through an attachable?
I'm just playing the animation direction from a command. Shouldn't the arm move regardless? Or is it named different in FP... Im'a check.
Not sure tbh
I had a swing animation before but it did work in both
A bit weird in fpp but it did trigger
Need me to send it?
Actually I think I got the values from you XD. Coddy posted it a long time ago, and I searched and found it. He said it was your values:
{
"format_version": "1.8.0",
"animations": {
"animation.cnb_ppl_swing": {
"loop": true,
"animation_length": 0.2917,
"bones": {
"rightArm": {
"rotation": {
"0.0": [0, 0, 0],
"0.0833": [-5.41199, 23.06265, 5.38894],
"0.125": [-13.31634, 36.7612, 56.32978],
"0.1667": [-58.11073, 6.44931, 8.72102],
"0.25": [-28.77157, -5.28699, -10.94791],
"0.2917": [0, 0, 0]
}
},
"leftArm": {
"rotation": {
"0.0417": [-8, 0, 0],
"0.1667": [-16, 0, 0],
"0.2917": [-8, 0, 0]
}
},
"body": {
"rotation": {
"0.0417": [0, 0, 0],
"0.1667": [0, 7.5, 0],
"0.2917": [0, 0, 0]
}
}
}
}
}
}
So I guess... thank you haha.
I had one before that was pretty bleh and not accurate, so thanks for that!
It's strange that it doesn't play in first person hmm.
Maybe it needs position and not rotation?
Yeah, lol
Used it in my addon and replay craft yoinked it too
Maybe sit it to override
Planning to do so soon!
It is hard to deal with dups when setting items tho
You mean by doing -this?
Tried position that didn't do anything.
no, the override property in animations
Ooooh the bool property thingy. Got it.
That ok if I use this for my future animations?
yeah it is alright, i had problem with the other guy sense he practically used all my code
Yikes, sorry. Yeah, I usually don't copy paste unless I fully understand it, then I change it to the way I want it just to save time. But yeah no one should have their stuff stolen.
Hmm that didn't work, I tried changing some of the components for the item too, I think attachable might be the only way.
you don't have any other animation, right?
Correct, that's the only one.
So replacing last animation would only remove any hidden ones from vanilla, but I dont' think there are any.
weird
Yeh, the only thing I can think is it's not carrying the variable to do it in first person... but Idk if that makes sense either.
I'm going to keep messing around with the "animation_controllers" part of the command and see if I can get soemthing to work. I'll let you know if I do.
Playerinteractwithentity after event doesnt work for me for some reason
im using it correctly too
no errors
i only get response when i use before event
but that comes with its own set of issues
if it works whats problem 🤔
oh
yk what i meant -_-
nu uh
Is it possible to disable scripted damage?
For example: if the player has a TAG and is attacked, the damage is canceled
yeah but not through scripts
use uh
player.json
or i imagine u could like
nvm
Okay, thnk
can i use server-net on 1.21.90
yeah
The @minecraft/server-net module contains types for executing HTTP-based requests. This module can only be used on Bedrock Dedicated Server.. Latest version: 1.0.0-beta.11940b24, last published: 3 years ago. Start using @minecraft/server-net in your project by running npm i @minecraft/server-net. There are 2 other projects in the npm registr...
ok thanks
how do i make it so that any system.runtime out inside an if statement will keep running until finished like when i exit the game and rejoin the system will re run
world.afterEvents.scriptEventCommandMessage.subscribe(event => {
const player = event.sourceEntity;
if (event.id === 'player_breaking_block') {
const block = player.getBlockFromViewDirection();
if (block) meleeAttackControllers(player, true);
}
});```
What is going?
run it in the next available tick by using system: run(), runInterval() or runTimeout()...
-# yes, very late response.
Uhh, entity doesn't have the interactable component.
It's in the name, afterEvents or beforeEvents
scriptEventReceive is not working for me too
it would never go after since the entity isn't interactable.
that's under system.afterEvents right?
not world.
wdym, i need to add the interactable component to the entity?
InteractAfter requires the interactable component and or you to have an item equipped. InteractBefore does not.
can you check my dm plsss its not about code
Is there any way to check if a block has been destroyed without me having to constantly check it? For example, I want to detect the blocks that an entity broke; is there a way to do this?
There aren't an event listener for it afaik.
yeah, I saw that... I didn't respond because I am not interested or sure yet.
Sorry
okay you can tell me your answer when youve made your decision then
But isn't there a way to detect this?
just telling you that checking hotbar change via runInterval is faster than the event
it was tested back in preview so i dunno if thats still the case now
nope, checking it constantly is the best you can do rn
Is it possible to stop EVERY SINGLE SOUND, even the mining or whatever with scripts, or if you know any other way?
Use a resource pack to disable every sound.
I meant temporarily
Thanks
This can also work for player class
its safe to use player.name cause the game does not allow a player with the same name
use player.id if ya wanna store things for each unique player
what if i join and rejoin will the id change?
no
const playerName = player.id;
const entity = player.dimension.spawnEntity("mz:smile", spawnPos);
if (entity) {
entity.addTag(`owner_${playerName}`);
player.teleport(player.location, { facingLocation: entity.location });
entity.teleport(entity.location, { facingLocation: player.location });
player.addTag("logic_done");
}``` this is the summoning logic where i form a bond between the entity and the player
world.afterEvents.entityDie.subscribe(({ damageSource: { damagingEntity }, deadEntity }) => {
if (deadEntity.typeId !== 'minecraft:player' || !deadEntity.hasTag("finalDay")) return;
const ownerTag = `owner_${deadEntity.id}`;
const dimension = deadEntity.dimension;
const nearbySmiles = dimension.getEntities({ type: "mz:smile" });
const center = getArenaCenter();
if (!center) return;
for (const smile of nearbySmiles) {
if (smile.hasTag(ownerTag)) {
smile.triggerEvent("mz:possesing");
smile.clearVelocity;
smile.teleport(center, dimension);
deadEntity.addTag("possesion");
break;
}
}
});``` this is how i use it and it is not working why?
define it's not working. Do you get any errors?
can you edit starting variable on particles using setFloat on molangVariableMap?
well so basically when the player summuns the boss the players forms a bond via id to the summuned entity and when the player dies the specific entity with bond will be tp in the center of the arena activate some functions etc.
Did you try printing out variables to see if you're using the right variables?
oh i found out the issue its the way i stored the location of arena center thats why lots of function is not working
Also is there a reason you're using tags instead of dynamic properties?
export let arenaCenter = null;
export function setArenaCenter(center) {
arenaCenter = center;
}
export function getArenaCenter() {
return arenaCenter;
}```
how do i make this sa that the things stored here are persistent even after restarting the game
what type is arenaCenter
a location
store it. either on the player or on the world
using a DP
If you have multiple well then you're gonna have to write your own loading manager
I'm making proximity voice chat. I don't have time to work on other things
oh okay thanks for helping
TIL that molangVariableMap basically just sets a new variable in a particle you don't need to add a startingVariable
are you talking to me?
ok quick question guys
In debug shapes, in the constructor it has location object but it also has a property setting the location object too, what's the difference?
const box = new DebugBox({ x, y, z });
box.location = { x, y, z };```
molang is piece of packed up thins
you're gonna set a
const rgb = {red: 0, green: 0, blue:0}
molang.setColorRGB("colors", rgb);
then inside the particle:
mojang is an incosistent piece of crap
confused ko gawa s gusto mo hambalon 😭
How to change player's rotation to up,down,left and forward relative to the world
how do i set the gamemode of player to hardcore trhough scripts?
anyone know how to remove the blocked message in discord?
You can't
You can do a similarly implemented version yourself but tbh there's not much of a point
i have this addon with an outro scene and i wanna end it like game over where the player can play anymore gues ill just use spectator mode and some functions
Force set the player to spectator then 
i dont think thats possible
runcommand as player I guess cause you can only read the gameMode not set it
Long time iirc
player.applyImpulse Which script version does it work on?
2.1.0-beta
isn't there a /difficulty command?
you can probably use runCommand with that
thx
oh you meant hardcore
I read it as hard
mb lol
nah its hard difficulty not hardcore
ye ik
getDifficulty, setDifficulty look in the world class.
not possible
doesn't have hardcore either
We talking difficulty, hardcore im not sure
Can detect if hardcore tho,
"isHardcore
read-only isHardcore: boolean;
we cant know if a player stopped mining a block right?
nor how much it was broken like a %
right?
yes
there is no way to check if a block is being mined and the progress of it being mined, iirc there's no event for it nor a poperty on a block
aw man, i really need it
thanks tho
I don't know if you can check the mining animation
if you can do that then you can surely do it
Start a timer once player starts punching which there's an event for
I think at least
But yeah actually could be very tricky so yeah I'll too say no
and combine it with EntityHitBlock AfterEvent
then you can do it but the % I don't know if you can get the block toughness
Hardcode everything
Like you usually do in bedrock
welp, that's the wall he needs to surmount
Those at least are on the wiki, can just copy those with a script and add them in
Unlike literally every other block property that requires more painful hardcoding like hitbox, replaceable, survivability and whatnot
yep just manually add the toughness of more than 500 blocks
Nah not manually I said with a script
yeah this one's better but just tedious
yeah but you need to add the values from the wiki to the script
That's what the script is for, you send doing your job as a programmer properly if you don't automate the tedious tasks that can be easily automated
if you could possibly explain, ill appreciate it!
Imagine we didn't have that, we would have needed to kill the player to confirm his mode
100,000 msg!
let's go!
how to load and unload chunks manually via scripting
this happens every other month
nu uh...
can @mental shadow check out my horror game cmds in the develpment
const tracks = [
{ id: "background_music.1", duration: 55, repeat: 3 },
{ id: "background_music.2", duration: 21, repeat: 6 },
{ id: "background_music.3", duration: 19, repeat: 6 },
{ id: "background_music.4", duration: 26, repeat: 6 },
];
const tracked = new Map();
function getRandom(exclude) {
const list = exclude ? tracks.filter(t => t.id !== exclude) : tracks;
return list[Math.floor(Math.random() * list.length)];
}
function playTrack(p, track, remaining, lastTrack) {
if (!world.getPlayers().some(pl => pl.id === p.id)) return;
try {
p.playSound(track.id);
} catch {
system.runTimeout(() => playTrack(p, track, remaining, lastTrack), 20);
return;
}
if (remaining > 1) {
system.runTimeout(() => {
if (!world.getPlayers().some(pl => pl.id === p.id)) return;
if (p.getDynamicProperty("music_track") === track.id) {
playTrack(p, track, remaining - 1, lastTrack);
}
}, track.duration * 20);
} else {
let next;
do {
next = getRandom(track.id);
} while (next.id === lastTrack);
p.setDynamicProperty("music_track", next.id);
playTrack(p, next, next.repeat, track.id);
}
}
world.afterEvents.playerSpawn.subscribe(e => {
if (!e.initialSpawn) return;
const p = e.player;
tracked.set(p.id, { lastLoc: p.location });
});
system.runInterval(() => {
for (const [id, { lastLoc }] of tracked) {
const p = world.getPlayers().find(p => p.id === id);
if (!p) {
tracked.delete(id);
continue;
}
const curr = p.location;
if (curr.x !== lastLoc.x || curr.y !== lastLoc.y || curr.z !== lastLoc.z) {
tracked.delete(id);
const current = p.getDynamicProperty("music_track");
const startingTrack = current
? tracks.find(t => t.id === current) ?? getRandom()
: getRandom();
p.setDynamicProperty("music_track", startingTrack.id);
playTrack(p, startingTrack, startingTrack.repeat);
}
}
}, 5);
My background music works fine, but one issue. Whenever you're in the pause menu you don't hear it, but the ticks are still running and going on to play the next song.
How can I fix this?
Is it only the case while in single player (where the game pauses), or also in multiplayer (when it does not pause)?
It only happens in singel player
Okay, so you need to detect when the game gets paused and pause your music player.
^ I forgot to ping (again) so...
yes
It is beyond my knowledge for how to detect it. I still need to [re-]learn how Add-ons work.
Music is not paused?
Apparently system.runTimeout does not pause when the game is in a paused state.
- Does the music go silent when you open the menu or does it actually pause?
- Does the music track get abruptly cut off at the end if you had it paused?
Can you add console.log to see if the runInterval is running? If nothing logs, it could mean that runTimeout doesn't respect it then.
runInterval has a value of 5... is that in seconds?
single player...
Pausing is a thing in Bedrock now.
And what Smokey stated.
ig only client pauses
The music pauses which is the issue
And I assume it resumes when unpaused?
Yes
u can use Date.now() to detect pauses then
Doesn't Date.now() always change?
ye
It doesn't. I've tested and system.runInterval pauses. I'm wondering if it's an issue with runTimeout.
If he wants to detect pauses that is one way.
Probably is
Intriguing.
I guess you checked with a long interval and pausing between an interval starting and stopping?
No I did runInterval logging each tick.
Hm, that would test a different edge case.
Try setting it to a more manageable time so you can check if it just postpones the timer until the user finally unpauses the game.
I would expect that, if the interval is 50 ticks, and the user waits X ticks before pausing, then after unpausing the interval should wait the remaining 50 – X ticks before invoking the callback
The duration that they paused for, Y, should be irrelevant
Try using wait ticks maybe
I recall that setTimeout and setInterval on web browsers will queue their callbacks to run when it is next possible (so if the user had an alert / prompt / confirm open, it would just wait until it is finally dismissed, and then trigger.
It is possible that they can be doing the same.
They are flushed at the end of the tick.
I would expect that, since those methods operate on ticks, they would be of the same measure as currentTick on System
- Multiplayer = On
- Player access = Invited players
- Visible to LAN = On
hm
function start() {
for(let i = 10; i < 0; i--){
system.runTimeout(()=>{
if(i==0) {
const startstart = getScore("start", "start", true);
const starts = ["scoreboard players set start1 start 1",]
system.run(()=>{
starts.forEach(start => {
try {
world.getDimension('overworld').runCommand(`${start}`);
if (startstart == 0) {
f.role();
f.startGame();
}
} catch (error) {
console.error(`Erreur d'execution ! executer les commandes suivantes : "${start}":`, error);
}
})})
return runCommand(`title @a title §6§lBon Jeu !`)
}
runCommand(`title @a title §6§l${i}`)
},20)
}
}```
```js
export async function config(player) {
new ActionFormData()
.title("Menu")
.body(`§8Bienvenue §e${player.nameTag} §8Que voulez vous faire ?`)
.button(`§8Controle Game`,'textures/ui/darkness_effect')
.button(`§8Config In-Game`,'textures/ui/free_download')
.button(`§8Activer/désactiver des évènements`,'textures/ui/darkness_effect')
.show(player)
.then((r) => {
if (r.selection == 0) controle(player);
if (r.selection == 1) ingame(player);
if (r.selection == 2) activation(player);
});
}
export async function controle(player) {
new ActionFormData()
.title(`Menu Controle`)
.body(`Que voulez-vous faire ?`)
.button(`Start`,'textures/items/potion_bottle_splash_saturation')
.button(`Destart`,'textures/ui/equipped_item_border')
.show(player).then((r) => {
if (r.selection === 0) {
player.sendMessage(`§aVous avez start la partie !`);
f.start();
}
if (r.selection === 1) {
player.sendMessage(`§aVous avez stoppé le start la partie !`);
f.destart();
}
});
}```
Hi, I wanted to know what was wrong with my code. Basically, what I want is for the function to run as a game start so I can launch the game.
... was this code AI-generated?
Also, I see some places where a semicolon is at and others where you completely omitted it.
no its with a friend
First, lets go over the function start() { ... } you made...
- You first do a
forloop 10 times. - You then queue another function to run after 1 second.
- It immediately goes and repeats the loop until the 10 times are over.
The tick ends...
sad to know theres no faceLocation on beforeOnPlayerPlace
All 10 callbacks are queued to happen on the same tick... I don't understand why you are expecting them to be one second apart.
system.runTimeout() adds a function to call in the future after a specific number of ticks have happened -- It is not a "wait" / "delay"
it's to do a 10 second descending countdown
Nope...
When start is called, it adds the function 10 times and tells each one to "run after 20 ticks have elapsed", then start exits.
After that 20 ticks have passed, all 10 of them trigger, one after the other.
What is wrong with that?
system.runTimeout runs immediately, but the function inside of it is put off until later.
Meaning you rapid-fire 10 system.runTimeout calls on the same tick, then after 20 ticks, every one of them fires back-to-back.
yes that's it I want
start()is called.- 10 nearly-identical functions are queued to run exactly 20 ticks after the current tick.
start()ends.- The game can now process other calls happening on the same tick.
- The game can now process other ticks before then.
- 20 ticks pass and the every one of them are called.
^ Read it carefully, especially the part in bold.
ahhh ok I understand better, well honestly I don't know how to do that I'll admit to you
to count down and then activate another function
If you want it to increase delay between each run of the for loop, you’d have to multiply the 20 ticks by the current index of the loop, so it increases the time for every callback
The better way would be to use a function and an object in the script's scope... this way the count-down timer can be cancelled.
Assuming minimal modifications to existing code is wanted, multiplying by the loop index would do so
Fixing something broken is what they asked, and there ya go
Optimizing it, on the other hand
I'd say learning JavaScript better should be the primary goal before continuing... so I won't help further on this task.
Isn't the server's principle to help you progress?
equippable component is still disabled to entities afaik
dm me
oh well, i guess I'll have to use commands then
bruh try system.run
any ideas why this is causing a stack overflow? I am clearly guarding against that in two ways. been trying to figure it out for almost an hour now
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
if (!event.isFirstEvent) { return; }
const player = event.player
if (!player.canInteractWithBlock) {
return;
}
console.warn(event.block.typeId)
})
Object.defineProperties(Player.prototype, {
blockInteractCooldown: {
get() { return this['blockInteractCooldown'] },
set(cooldown: number) { this['blockInteractCooldown'] = cooldown }
},
canInteractWithBlock: {
get() {
return playerCanInteractWithBlock(this)
}
}
})
export function playerCanInteractWithBlock(player: Player): boolean {
if (player.blockInteractCooldown > Date.now()) { return false; }
player.blockInteractCooldown = Date.now() + 500;
return true;
}
it's acting like none of the guards are working
get() { return this['blockInteractCooldown'] },
is line 7 in the JS output.
return playerCanInteractWithBlock(this);
line 14
canInteractWithBlock: {
12
beforeEvents shenanigans
The problem is here:
Object.defineProperties(Player.prototype, {
blockInteractCooldown: {
get() { return this['blockInteractCooldown'] },
set(cooldown: number) { this['blockInteractCooldown'] = cooldown }
},
The following line calls the getter recursively, because you're referencing blockInteractCooldown inside its own getter.
return this['blockInteractCooldown']
When player.blockInteractCooldown is accessed, it calls the getter. Inside the getter, this['blockInteractCooldown'] is used, which again accesses the getter. So it recurses indefinitely until it overflows: get() → this[...] → get() → ...
Similar behavior is happening with your setter too. You're not guarding against recursion because your getter/setter access themselves.
I see. I didn't realize what ['foo'] was actually doing. Pretty new to TS.. mainly a rust dev. That makes sense now I think. So, defining the prototype / d.ts interface is essentially doing the same thing as ['foo'] which is causing recursion in that specific scenario because they are named the same thing?
export function playerCanInteractWithBlock(player: Player): boolean {
if (player['blockInteractCooldown'] > Date.now()) { return false; }
player['blockInteractCooldown'] = Date.now() + 500;
return true;
}
was my previous code, was just trying to make it cleaner lol
In JavaScript/TypeScript:
this['blockInteractCooldown']
…is exactly the same as:
this.blockInteractCooldown
They both invoke the getter if one is defined. So when you define:
Object.defineProperty(Player.prototype, 'blockInteractCooldown', {
get() { return this['blockInteractCooldown'] }
})
You're effectively saying:
When someone accesses
player.blockInteractCooldown, call this function, which returnsplayer.blockInteractCooldown.
An Infinite loop.
Perfect. Thank you for explaining that. Makes complete sense.
I'm not sure why, probably lack of sleep, was assuming that obj['foo'] was setting something else.
Recursion can be a pesky little thing. Especially when you anticipate your code to behave a different way so it doesn't make blatant sense at first lol.
Yeah, expecting it to work how you planned it out definitely hurts the troubleshooting lol. And the JS stack traces don't help a ton, but looking at them now make sense in this context 🙂
rust / cargo errors have spoiled me
Lol
I am really surprised how nice TS is though. Is making me want to give Deno a try lol
TS is good. I personally can't find myself writing in JS unless I use TS.
Object.defineProperties(Player.prototype, {
_block_ICD: {
value: Date.now(),
writable: true,
},
blockInteractCooldown: {
get() { return this._block_ICD; },
set(cooldown: number) { this._block_ICD = cooldown }
},
easy fix. thanks again
vanilla JS is masochism. there's really people out there getting paid to write that.
one of my coworkers is doing a python class at the moment and I've been helping him at points and it blows my mind that there are widely used languages that just... dont have any concept of types
Yea, they have attempted to patch things up in Python a little bit since 3.5 after the devs realized it's limitations.
Can implement optional typing with some additional tooling.
it's a good language for smaller scripting. he's doing it for a cybersecurity course. neat how much it can do in a small amount of code. TS feels like a really nice balance too
wish it was easier to set up with node though
TS was definitely a blessing to the JS community. People were using patterns from typed languages (like Java, C#), but the tooling couldn’t help back when TS didn't exist so Microsoft said let's change that. One of the few things I believe Microsoft did right.
I feel they should have made it its own thing honestly, but that would have broken browser compatibility and probably would have never been widely adopted since there was already so much literal garbage out there
Yea, it's only purpose was to bring better support for static types, classes, interfaces, enums, compile-time checking (really important and saves a lot of time debugging), and ECM support during its early stages.
wasm is a good start though, but still continues to have a lot of issues with FFI and threading
I haven't messed with web assembly yet.
Its neat but doesn't deliver on its promises yet. even with a compiled language -> wasm output, it is hard to make it faster than native js because there is so much overhead on function calls
Nope, that's a no-go for me. Unnecessary resources.
yep. eventually itll get there im sure. and it does provide code protection for those that care about that. the current deal breaker for me is that it is still single-thread only so not really viable for ECS architecture
anyway, thanks for the help, I really appreciate it 🙂
No, problem.
what is this in js? never used it before
reference to itself
class Player {
thing: number
constructor(thing: number) {
this.thing = thing;
}
}
make sense?
class MyClass {
value: string = "Hello";
greet() {
console.log(this.value); // 'this' refers to the MyClass instance
}
}
another example
depend on the environment, in browsers in the global scope it refer to the window
@distant tulipYo minato
sup
What do i put into the terminal to make the ts compile?
i did it yesterday with crafter but i forgot the command
tsc
thats it?
you do have a tsconfig.json?
do you mind sending it
give me a sec
alright thanks
Thanks
I need to learn more about classes
yes understood it clearly
someone pls help 🙏
Why u asking that in the script channel
oh whoops i thought i was in json ui
Oh gosh not mobile, pleaaasseee, anything but a mobile, ILL USE ASSEMBLY IF I HAVE TO BUT NOT MOBILE!
imagine making programs in mobile
however I long to see arduino compatible ones
Helix better
what's helix
Why is lables and dividers get passed to the response form values
really?
what are they passing?
Yeah, was debugging a friend script and we found that the reason, it is so stupid
That log
[Scripting][warning]-,a,,,a,a,a,,,2,,,a,
what would you guys say is a good limit for Dynamic Properties?
if it's undefined, you can atleast filter these out
what do you mean by a limit?
it's pretty hard to hit the limit of keys stored
Input value can be undefined to
I guess we can do
[,name,,,sec,min,hou,,,time,day,] = respone2.formValues;
But bruh
a limit where it doesn't start to cause lag
Just don't abuse the use of it
Write and read using it constantly is not a good idea
And there is a limit of 10mb per min
use some caching maybe
isn't textField returning an empty string?
const [name,sec,min,hou,time,day] = respone2.formValues.filter((value) => value !== undefined);
Can't remember, just saying what i heard from my friend
Anyway i think this should be treated as a bug and get reported
so i am confused on why i have to wrap the methods sometimes in system.run(() =>{}); and sometimes it's fine
import { world } from "@minecraft/server";
world.afterEvents.entityDie.subscribe(bg =>{
const player = bg.damageSource.damagingEntity;
if( player && player.typeId == "minecraft:player" && player.hasTag("origins:power_bftbg") )
{
const effect = player.getEffect("strength");
if(effect == undefined)
{ player.addEffect("strength",300,{amplifier:0,showParticles:false}); }
else if(effect.amplifier == 4)
{ player.addEffect("strength",100,{amplifier:4,showParticles:false}); }
else
{ player.addEffect("strength",300,{amplifier:(effect.amplifier+1),showParticles:false}); }
}
});
import { system, world } from "@minecraft/server";
world.beforeEvents.itemUse.subscribe(pm =>{
const player = pm.source;
const item= pm.itemStack;
if( player.hasTag("origins:power_pig_ancestry") && (item.typeId == "minecraft:porkchop" || item.typeId == "minecraft:cooked_porkchop"))
{
pm.cancel = true;
system.run(()=>{ player.addEffect("poison", 30 , {"amplifier":0 , "showParticles":false}); });
}
});
if i remove the system.run wrap from this one ^^^^ , i'll get this error
is it because the second script is using a beforeEvents listener?
Precisely, yes
In a BeforeEvent subscription, that code executes in a read-only context, where the world state cannot be changed.
Moving code into a system.run invocation will defer execution until later in the tick, when the world state can be changed.
get(key: any, player = null) {
let value = (player || world)?.getDynamicProperty(key);
try { value = JSON.parse(value); } catch (e) {}
return value;
},```
Why did this error spawn in
It's telling you that JSON.parse cannot accept an undefined value.
Indeed, if that dynamic property is not set, getDynamicProperty returns undefined
You could coalesce that null value into "{}" on the line where you define value
let value = (player || world)?.getDynamicProperty(key) ?? "{}";
ive done this and its still the same outcome
Depends on what you're trying to do.
Directly, not really. You could store the tick that it should execute on into a dynamic property and do some shenanigans to schedule it again when the world reopens, but the API cannot perfectly store a function's state; the callback function must be pure and not dependent on external information.
Could you be more specific on what you want to do? There may be a way to implement it
It's a different outcome; now Intellisense says "number" is not assignable to type "string"
i fixed it lol
thanks though
hello
in player.applyImpulse What is the value system that y receives?
For example, if y = 1 like player.applyImpulse({ x: 0, y: 1, z: 0 })
how high will it rise?
mass?
-# (edited)
You should test that i guess
i will
but its hard to have a currect value
Yeah

disable player movement, then re-enable 200 ticks later (10 secs)
Going on an assumption here since quickJS doesn't have JIT. JSON marshalling slow? At work so can't test, just mentally trying to think of how to store data
do custom item components exist in the 2.0.0 stable release or do I have to use the 2.1.0-beta?
Item custom components have existed since 1.20.80.
oh, I think I am confusing myself then
Was thinking to create a cache map split into chunks of per chestUI page (keys) and value would be a BankPage class that holds a map of <itemID_enum, number> then using a reverse map that just returns the minecraft:itemid string to recreate the items. Sounds good in my head but no way to test at the moment 🫤
Then just saving as JSON to dynamic properties on player logout and on an interval per player started when they logged in, recreating cache on server start
hello
in player.applyImpulse What is the value system that y receives?
For example, if y = 1 like player.applyImpulse({ x: 0, y: 1, z: 0 })
how high will it rise?
Not sure there's an easy way to get the exact height because an impulse vector is based upon the velocity when the impulse is applied as far as I know
are there any doc for that ?
Then I just googled impulse vector
You’ll be disappointed to find out the effect is different for every entity
I want it only for the player
Still different depending on the condition, you’d have to guess the values
What do you mean by "condition"?
does anyone have an example of what the header, divider and label look like on forms?
personally, i was coding my addons using normal file editor and my skills, but currently bec i have a laptop now, i am coding my addons using vscode just bec i can not bec i need or have to.
minecraft is weird as hell
i think coding minecraft my own and making it moddable is easier than understanding what the hell the script api will do
seriously there are times i fell the engine simply ignores some pieces of code
such as itemStack?.getComponent('minecraft:food') doesn't work for vanilla food items
for no reason
the reason is becouse they re hard coded
im trying to make a script where you step on a block and your leggings get enchanted with swift sneak 3 and your boots get enchanted with soul speed 3
custom block?
yes
check out register block components thing
i know how to make block compoents its the script to apply the enchantments to the armor
Is it possible to get the maximum and minimum of the block state values using scripts?
Yes.
Do note however if multiple blocks use the same state, it will return the min and max of all the blocks.
Oh, okay. Thanks anyway.
import { EquipmentSlot, ItemStack, Player, EntityComponentTypes, ItemEnchantableComponent } from '@minecraft/server';
import { MinecraftItemTypes } from '@minecraft/vanilla-data';
function giveEquipment(player) {
const equipmentCompPlayer = player.getComponent(EntityComponentTypes.Equippable);
if (equipmentCompPlayer) {
let itemStack = equipmentCompPlayer.getEquipment(EquipmentSlot.Feet);
if (itemStack) {
let enchant = itemStack.getComponent( ItemEnchantableComponent.componentId )
if (enchant)
enchant.addEnchantment( { type: "", level: 0 } )
}
}
}
i'll give this a shot real quick
would the function go inside the OnStep registry? or above it?
???
make sure its in the manifest
heres the error
Minecraft/vanilla-data is unrecognized if this is a Native module, did you remember to add it to your manifest.json
well...
read the error?
so i apply it I'm sorry i have no Internet rn again our router sucks
add the module to your manifest dependencies
no version is need for it?
so do i put the node_modules in the script folder?
mk cool
is applyKnockback is also the same? different across every entity?
is there any method to break a block? I can't find a method on the block class.
there was this old vid i watched on yt where i think he canceled the block i dont know
no ig, use setblock with runCommand
Yes
Nuh uh. Only setblock and destroy thing.
Btw, for the debug utilities shape thing rotation property.
where's the pivot point of it, I mean where it will rotate? The center of the start and end location?
and before saying "test it". No I can't.
cancelled?
welp I was setBlockType() it is then manually adding the blockBreak particle and the item drop
Thanks
Execute this example just before that line giving you a problem and you should understand why:
const formattedResults = JSON.stringify(formData.formValues, null, 2);
players[0].sendMessage(`Modal form results:\n${formattedResults}`);
what does this do?
That assumes you named it formData. Change it accordingly. It will print and show you what formValues consist of.
alright thanks
it's impossible to getBlock() on an unloaded chunk, is there any way to load it? I have a chunk scanner
you can load it using /tickingarea or some loading entity I think
guys, how do i get rid of Has Custom Properties text on an item
gamerule showtags false
my item has custom component v2.0, but sure it's not the reason. the reason must be that there are also dynamic properties on the item, how to get rid of it?
this shows when an item has a dynamic property you can disable it via gamerule
so this gamerule work only on these texts from dynamic properties, and nothing else, right?
like entity tags and stuff
nametags
yes
okey, thank you
it also hides the item lock / keep on death text
oh okey, i think not a really big deal. thank you for letting me know
the circle option in ticking area is a chunk right?
I mean it considers the min height and max height?
const line = new DebugLine(
pts[i],
pts[j]
);
line.timeLeft = 60;
debugDrawer.addShape(line);
^^ please help. I am drawing some lines using debug drawer. But the lines just appears for 1 or half second and dissapears immediately.
The timeLeft property doesn't work . isn't it meant to remove the line after 60 seconds, if i set the timeLeft to 60?
I tried runInterval but it sets the line forever, even if i tried clearRun() and removeAll() in debugDrawer, doesnt work.
and for clarification meow
@distant tulip *calling the debugdrawer specialist meow
Check the duration with totalTimeLeft
I have no idea, i used it once
Is it possible to detect rightclicking a non interactive block ?
world.beforeEvents.playerInteractWithBlock.subscribe(ev => {
const { block, player, itemStack, faceLocation, blockFace, isFirstEvent } = ev;
if (block.typeId === 'minecraft:bedrock') {
// ...
}
});```
isnt it only for intereactable blocks like crafting tables and furnaces?
So in script API there's something called beforeEvents and afterEvents
It's in the name itself, before it happens and after it happens.
i only tested afterevent of this and assumed its for intereactables only
since the block isn't interactable the "after" wouldn't be triggered since it never successfully happened unlike before since it's "before" no matter if successful after or not.
gonna try it
before event work without the interact component
tho it will trigger multiple times iirc
there is a property to filter out first interact
Just use isFirstEvent
Thanks
anybody know how to compile this?
public static completeJob(generator: Generator<void, void, void>, onComplete: () => void): number {
function* jobWithCompletion() {
yield* generator
onComplete()
}
const job = jobWithCompletion()
const runId = system.runJob(job)
return runId
}
Aeverkan is not replying
Wdym compile?
I don't know how to run it
I was trying to get help if it's possible to run something after a runJob finishes.
Are Jigsaw structures still experimental? Are custom mini-biomes experimental as well?
Yes
Generally, you can use the TypeScript Compiler to turn TypeScript into JavaScript. I found this neat tutorial online: https://til.simonwillison.net/typescript/basic-tsc
Alternatively, you can convert TypeScript code into JavaScript code by removing TS-specific features: Those are primarily type annotations, and TS-specific keywords, like interface, type, namespace, and satisfies
In this case, the only TS-specific features are the type annotations in the method declaration
public static completeJob(generator, onComplete) {
function* jobWithCompletion() {
yield* generator
onComplete()
}
const job = jobWithCompletion()
const runId = system.runJob(job)
return runId
}
Will these new properties work on non-player entities? Or is the equippable component still out-of-order?
equippable component is still disabled
Sad
Would there be any way to get if the player is in the first camera or third camera through the script?
Not as far as I know.
I have a delay between each tick and tick in system.runInterval(() => { what is the solution ?
What do you mean?
I have a code in wich system.runInterval(() => {,runs every tick. For example, when the player reaches the ground, activate player.applyImpulse, but sometimes it takes a while to activate the ifs.
Maybe a second (it makes a difference in my code)
I didn't understand!
Well it's hard to help when you don't fully show your code and properly explain things alongside video to showcase your issues.
import { world, system, Player, Dimension, EquipmentSlot } from "@minecraft/server"
const fallingPlayers = new Map();
system.runInterval(() => {
for (const player of world.getPlayers()) {
if (player.isFalling && !fallingPlayers.has(player.id)) {
const startY = Math.floor(player.location.y);
fallingPlayers.set(player.id, {
startY: startY,
fallDistance: 0,
isTracking: true
});
}
if (fallingPlayers.has(player.id) && fallingPlayers.get(player.id).isTracking) {
const data = fallingPlayers.get(player.id);
const currentY = Math.floor(player.location.y);
data.fallDistance = data.startY - currentY;
const loc = player.location;
const hitBlock = player.dimension.getBlockFromRay(loc, { x: 0, y: -1, z: 0 }, { maxDistance: 2, includeLiquidBlocks: false })
if(hitBlock && data.fallDistance >= 3) {
const boot = player.getComponent("equippable").getEquipment(EquipmentSlot.Feet)
if (boot?.typeId == "minecraft:leather_boots") {
player.addEffect("resistance", 1, { amplifier: 255, showParticles: false });
}
}
if (!player.isFalling) {
data.isTracking = false;
const blockBelow = player.dimension.getBlock({
x: Math.floor(player.location.x),
y: Math.floor(player.location.y) - 1,
z: Math.floor(player.location.z)
});
if (blockBelow.typeId !== "minecraft:air" && blockBelow.typeId !== "minecraft:water" && blockBelow.typeId !== "minecraft:lava") {
const boot = player.getComponent("equippable").getEquipment(EquipmentSlot.Feet)
if (boot?.typeId == "minecraft:leather_boots") {
const fallDistance = data.fallDistance;
if (fallDistance >= 3 && fallDistance < 7) {
player.applyImpulse({ x: 0, y: 0.7, z: 0 });
} else if (fallDistance >= 7 && fallDistance < 10) {
player.applyImpulse({ x: 0, y: 1.1, z: 0 });
} else if (fallDistance >= 10 && fallDistance < 15) {
player.applyImpulse({ x: 0, y: 1.3, z: 0 });
} else if (fallDistance >= 15 && fallDistance < 22) {
player.applyImpulse({ x: 0, y: 1.5, z: 0 });
} else if (fallDistance >= 22 && fallDistance < 30) {
player.applyImpulse({ x: 0, y: 2.1, z: 0 });
} else if (fallDistance >= 30 && fallDistance < 40) {
player.applyImpulse({ x: 0, y: 2.5, z: 0 });
} else if (fallDistance >= 40 && fallDistance < 55) {
player.applyImpulse({ x: 0, y: 3, z: 0 });
} else if (fallDistance >= 55) {
player.applyImpulse({ x: 0, y: 3.3, z: 0 });
}
player.playSound(`mob.slime.death`)
}
}
fallingPlayers.delete(player.id);
}
}
}
Upon reaching the ground, player.applyImpulse is supposed to activate immediately and quickly. + Sometimes it doesn't activate because the tick action doesn't sync with the player's arrival on the ground (like the end of the video).
From what I remember, applyImpulse on the player has some desync issues. Try applyKnockback?
Thanks a lot sprunkles somehow copilot Claude can compile it too, well obviously cause it's an AI
it's rubberbanding
iirc applyImpulse is directly set on the "server" unlike applyKnockback which are handled on the clientside
Is the value system received the same as player.applyImpulse ?
Pretty similar. It takes two arguments, a Vector3 like applyImpulse and a vertical knockback number
what is the "vertical knockback number" ?
You can think of it as the y-component of the vector3
Okay... but I don't think the problem is from applyImpulse. Because even the code before it that gives the player the "resistance" effect didn't work.
Well, then let's examine what the code is doing
ok
Seems like you are guesstimating how long it takes for the player to hit the ground. If the player is within 2 blocks of the block beneath them, we apply resistance. What if the player falls farther than 2 blocks in that tick? (this will vary with server latency)
I tested with applyKnockback and it felt pretty responsive, at least on PC, so I don't think it's an issue with runInterval.
But I was able to die consistently if I fell from 100 blocks up
If I were you, I would take the player's y-velocity and compare it against the distance left to travel. If the velocity is greater, then we know the player will likely hit the ground that next tick.
// find the distance expected to fall given the player's xz coordinates
// compare against their y-velocity
// if the y-velocity offset would result in hitting the ground, apply resistance
const loc = player.location;
const hitBlock = player.dimension.getBlockFromRay(
loc,
{ x: 0, y: -1, z: 0 },
{ includeLiquidBlocks: false }
)
if(hitBlock) {
const hitLocation = {
x: hitBlock.block.x + hitBlock.faceLocation.x,
y: hitBlock.block.y + hitBlock.faceLocation.y,
z: hitBlock.block.z + hitBlock.faceLocation.z,
}
const deltaLocation = {
x: hitLocation.x - loc.x,
y: hitLocation.y - loc.y,
z: hitLocation.z - loc.z,
}
const distance = Math.hypot(deltaLocation.x, deltaLocation.y, deltaLocation.z);
const velocity = player.getVelocity();
if (Math.abs(velocity.y) + 0.08 > distance) {
const boot = player.getComponent("equippable").getEquipment(EquipmentSlot.Feet)
if (boot?.typeId == "minecraft:leather_boots") {
player.addEffect("resistance", 1, { amplifier: 255, showParticles: false });
}
}
}
This still isn't quite accurate though, as while it's mathematically sound, it can still vary with server latency
(Best solution is to prevent damage with the "minecraft:damage_sensor" component, but I suspect that's not an option for your development)
Oh, and you could reduce your large number of else if statements to a single applyImpulse with a math function. Math.log(Math.min(fallDistance, 100) / 4) (for all x ≥ 4) feels like a sweet spot
feel weird seeing a friend ask here instead of our server lol
lol
What's the site's name?
Ah, Desmos' graphing calculator
there is also this for molang
https://jannisx11.github.io/molang-grapher/
Installation for @minecraft/server-net
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Oh..
I think I saw that in snowstorm iirc
because it's made by same developer lol
blockbench, snowstorm, molang grapher, dialogue designer...
I might have missed something
ok
hardcoded? you mean theyre native?
i mean that they re in the minecraft code they re not items done with json like custom foods
is the locator bar data driven in anyway in bedrock?
Where can I change the fishing loot from water?
loot tables
is it smart to create a new dynamic property on the world for each playert
like could that affect the world/performance in any way
i did save player loc and rot for each tick for more than 10 min without any problems
im talking about like
indefinitely
just one per player or what are you thinking here?
yeah one per player
im guessing only on join right?
every tick?
each player will have their own dynamic property
on join itll create one
and then ill cache it
yeah
and then once they leave itll save
that should be no problem
I dont see a issue in one dynmic property
its on the very low side actually
idk if u understand
like
if i have 250 players
each player gets their own dynamic property on the WORLD not the player
no yeah, thats fine
so that would be 250 individual properties on the world
250 is not that much
what about 1000
with no performance changes?
nope, not gonna change anything perfomance wise
its stored on storage
it will only take storage, but not perfomance. It only takes perfomance, if you read/write
you can test it, by just filling a random world with millions of dynamic properties
Yeah, i know
I storred them indefinitely
1000 is nothing compared to that
hello can i dm you?
has there been any cases where classes where used inside addons?
const target: Player = players[r.formValues[1]];
const obj = variables[r.formValues[2]];```
anyone know why this just appeared
I just switched to ts
now random errors be spawning
the errors are at r.formValues[1] and r.formValues[2]
The errors may be at r.formValues[1] and r.formValues[2], but they come from further up.
That first error is TypeScript saying it isn't 100% sure r.formValues is valid.
I can't really help without seeing more of the code.
Those other errors are likely related, it's saying you're trying to treat something that isn't an array as one.
You obviously cannot do this: true[2]. true isn't an array.
the only other line regarding r.formValues is this one
const unparsedPrice: string | number | boolean = r.formValues![0] as string```
is the problem here?
That looks a bit strange, that's likely the reason.
You don't need both type definitions, you have that
string | number | boolean
As well as as string. They don't go together.
so which should i get rid of
The first one is if you're making a new value. You're not, so get rid of that one.
as string is a type cast, and that's you telling TypeScript you're 100% sure it'll be a string.
i got rid of the first ones and the error is exacatly the same
what does it mean that boolean values or undefined cant be used as an index type
i never used them?
do i need to specify that its not?
Probably should've asked this first: What's the exclamation mark for in r.formValues![0]? I've never seen it myself.
I suspect that's where the boolean is coming from.
its because the top error
My friend told me when i see that error
i add an exclaimation mark
it does wor
work
in getting rid of the error
but the rest stay
which is what i need to get rid of
Are those other errors coming from that line?
yes
oh no sorryu
they are from here
const target: Player = players[r.formValues[1]];
this line shows no errors
but when i remove the "!"
it does
Does
const unparsedPrice = r.formValues[0] as string
work?
error "r.formValues is possibly undefined"
Where is that variable coming from?
Can you show all of your code? It's really hard to tell from just 3 lines.
sure
import { Player, world } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { addScore, getScore } from "utils";
const variables = [
`Coins`,
`Gems`
]
export default function PayUI(player: Player) {
const f = new ModalFormData();
const players = world.getAllPlayers().filter((p) => p.name != player.name);
if (players.length == 0) {
player.sendMessage(`Theres Nobody Else Online!`);
return player.playSound('note.bass');
}
f.title("§gPay Players");
f.textField("price", "e.g. 20");
f.dropdown("Choose Player", players.map((p) => p.name));
f.dropdown("Choose Score", variables);
f.show(player).then(r => {
if (r.canceled) return;
const unparsedPrice = r.formValues[0] as string;
const target = players[r.formValues[1]];
const obj = variables[r.formValues[2]];
if (!unparsedPrice || !target) return;
const payAmount = parseInt(unparsedPrice);
if (payAmount < 1) {
player.sendMessage(`Number Has To Be More Than 0!`);
return player.playSound('note.bass');
}
if (getScore(player, obj) >= payAmount) {
// Removes money
addScore(player, obj, -payAmount);
// Adds money
addScore(target, obj, payAmount);
player.sendMessage(`§dYou have just sent §g${payAmount} ${obj}§d to ${target.name}!`);
target.sendMessage(`§dYou have just recieved §g${payAmount} ${obj}§d from ${player.name}!`);
target.playSound('note.pling');
}
else {
player.sendMessage(`You dont have enough money!`);
player.playSound('note.bass');
}
})
}
thats the whole thing
there
Which errors is it showing now? Is it still showing the undefined error?
these 3
first line error is "r.formValues is possibly undefined"
the other 2 are
bruh please just make it more readable
sorry mate i just started coding im just trying to learn how to actually code
dont worry its just a tip to make others help you easily
can you tell me what would tell apart a non readable code to a readable one
like what would make it more readable
That's TypeScript saying it's not 100% sure formValues will always be valid. That's from the built in ModalFormResponse class.
You can either tell TypeScript it'll always be valid or do a runtime check.
You can do a runtime check like this:
if (!r.formValues) return
dont use r.formvalues
wherer would i stick this
Right under your other guard if (r.canceled) return;
It doesn't matter the order, it just has to be before the rest of the code. Because it's a guard.
It thinks you're trying to do this:
true[1]
Not that.
It thinks you're trying to do this:
Players[true]
you know in callbacks you can do
then(({ canceled, formValues: [ value0, value1, value2 ]}) => {
if (canceled) return;
if (value0 == 10) something()
})
alright thanks
that's just a tip to not write r.formValues[0]
no problem
i made this code when i knew basically 0 about coding it was heavily helped by friend
A good rule is to not write anything you don't understand. That's what I do.
Can you see the vanilla type declaration? Go to that.
actually the rule is if someone writes something for you ask what he done
this?
that is the npm pack
Yes, that's the one. Now see that readonly formValues?: (boolean | number | string)[]?
yes i do
That's telling you that formValues is an array that contain booleans, numbers, or strings. TypeScript does not know what those array elements will be, just that it'll either be a boolean, string, or number.
Therefore, when you do formValue[2], to TypeScript, that could be either a boolean, string, or number.
Also, the question mark ? at the end means that the array might not even exist. That's why you were getting that "r.formValues is possibly undefined" error earlier.
so i need to tell it which it will be?
Before. It looks a bit strange:
const obj = variables[r.formValues[2] as number];
thanks very much i will test it now
ill never understand typeScript users its just like java but more complex
It makes your variables more certain; you won't end up accidentally putting a number where a string will be.
Even better: If you know exactly how many values you will pass, you could enforce formValues to be a tuple. Then accessing certain indices would return the specific type at that index.
I haven't worked with forms enough to have a specific pattern to suggest, though.
let fieldOffset = 0;
let fieldZ = 100000;
world.afterEvents.playerSpawn.subscribe((event) => {
if (hasPlayerJoined === false) {
hasPlayerJoined = true;
nullTploc = event.player.location;
}
if (dimensionGenerated === false || dimensionGenerated === true) {
dimensionGenerated = true;
function* fieldLoop(){
for ( ; fieldZ <= 500000; fieldZ += 16) {
for ( ; fieldOffset <= 400000; fieldOffset += 16) {
if (Math.random() < 0.5) {
overworld.runCommand(`structure load mystructure:fieldtree ~ ~200 ~${fieldZ}`);
overworld.runCommand(`structure load mystructure:fieldtree ~${100000 - fieldOffset} ~200 ~${fieldZ}`);
} else {
overworld.runCommand(`structure load mystructure:fieldbase ~ ~200 ~${fieldZ}`);
overworld.runCommand(`structure load mystructure:fieldbase ~${100000 - fieldOffset} ~200 ~${fieldZ}`);
}
if (Math.random() < 0.5) {
overworld.runCommand(`structure load mystructure:fieldtree ~${100000 + fieldOffset} ~200 ~${fieldZ}`);
} else {
overworld.runCommand(`structure load mystructure:fieldbase ~${100000 + fieldOffset} ~200 ~${fieldZ}`);
}
yield;
}
}
}
system.runJob(fieldLoop());
}
});
This only generates straight for some reason and not sideways too
try logging the values of the fieldOffset variable.
Also BTW will removing the dimensionGenerated check cause hang or internal error if player dies multiple times or multiple player join?
It might do that...
How to use debug script??
???
can we tag a player with something that isn't saved on relog?
the only thing i can think of, is adding the player id to a list, and check if it is in it.
Well you can use a Set for it.
const playerIds = new Set();
// Add player
playerIds.add(player.id)
// Remove player
playerIds.delete(player.id)
// Could also be remove() not sure atm
// Check if player is inside
playerIds.has(player.id)
that's basically the same thing i said, but thanks anyway
Well you said to a list so i thought you meant an array
what's the differrence between set and map?
Array vs object
set is an array?
so basically map is faster
The map is key value based.
Yep like that
Set is good if you have an array like
const invalidItems = new Set([
....
]);
Does anyone know where dynamic properties get stored?
.dat files
it the world db
Nbt
does mcc toolchest pe not show them?
Whats the best to use for a giant world lol
that's what i use, they are located in db/DynamicProperties
I only used UMC editor
It's not like there are any other options
Dm
Ye
But like i said I remember someone using mcc
Is there a way to cancel riding?
Try Cancel interact with entity event
You can disable input permission as well.
But is having an active ticking area for a game area not recommended?
I'm kind of confused how this relates to the previous problem unless this is a new question.
Yes it's a new question, I'm trying to understand if it affects the game performances having an area that loads the entities constantly, if there are other ways to reset a game area in a better way
Well, the bigger question is what is in those ticking chunks.
A ticking chunk that has basically nothing vs a ticking chunk that has redstone machines and lots of mobs
Dummy entities that generate random loot and some immobile entities
Yeah that shouldnt be a major issue but as always, do some testing yourself. Your mileage may vary depending on your device.
Then I have to restore parts of maps like barriers and restore chests, I've always used ticking areas for these things, but I don't know if it's the cleanest way.
This code works well..
But as soon as I remove console.warn....
Of course, I may not know something, but it seems to me that something is definitely wrong here.

Have you happened to walk over a biome that contains a dripstone or lush cave yet?
you'll find something very funny
._.
oh wait maybe they finally fixed it when they started doing all of their biome work
for a while getting someones biome when they were above one of those biomes would say they were in that one, even when on the surface
and the surface one would be in the cave
what exactly is the issue with the images though
isi t just me or you're vsc font is in minecraft?
what's the difference between a container and a containerSlot?
You can likely infer the difference from the name: Containers are used for multiple ContainerSlots. A chest will have a Container component.
You can use more sorting related methods if you have the Container.
The ContainerSlot will have more information about what's specifically inside it.
The player's equipment slots are not within a Container, they are all ContainerSlots.
I see so thanks a lot
on the other hand I got this bug? where it seems that setting item dynamic property has a delay compared to setting entity dynamic property. Is there really a delay?
the shrine is an entity
I don't see the problem you're referring to.
The console looks like it prints it out in the correct order: shrine energy, then item energy. That's the way you've ordered your print statements.
yes however at the code it should reduce by 1 for the item and +1 for the shrine
I added some delay counts and it fixed it but I don't know why that happens
show updateLore function
function updateLore(itemStack, currentEnergy, maxEnergy, blockName) {
itemStack.setLore([
`§r§6Life Energy:`,
`§r§c${JSON.stringify(currentEnergy)} / ${JSON.stringify(maxEnergy)}`,
`§r§6Block Essence:`,
`§r§c${JSON.stringify(blockName)}`
]);
};
hmm
Why do you stringify a primitve value?
primitive value?
do integers work inside lores?
what do you think?
its just
beforeEventInteract
system run
itemVal -=1
item.setDynamicProperty(itemVal)
entityVal +=1
entity.setDynamicProperty(entityVal)
What do i do if i need to do world.getAllEntities but its not a thing
loop through all dimension and
getEntities
alr ty
Primitive means Numbers, strings or booleans.
If you do ${myNumber} it will be a string. So you dont need to stringify it
oh yeah now that I look at this I basically just turned it to string twice
kindof :)
any example to make custom commands
Can't decide if I should do my database server with TS/deno, Go, or Rust lol. Only issue I have with doing it in TS is the cached DB memory size since JS classes are pretty large and no structs
map is the only way I can store new DebugLine() right?
I need to still have access it since I am removing them sometimes.
no
Btw, there is a bug where it draws shapes in all dimensions at the same coordinates.
oh that's fire 😀
Wdym "no"?
What
That's my sarcastic answer here 😭
Oh xd
Have we found a way to localize texts which have linebreaks in them?
I wasn't expecting that
does it work anywhere? forms, hud, how to play screen?
Oh my god it works!
did developers fix the player.applyImpulse in latest previews?
last time i checked it was broken
in 1.21.100
#1019692489596215388 message
it's video with first preview with player applyImpulse
now it does'nt work like that?
does anyone know the intrisic block state for whether a campfire is lit?
Check the mc wiki.
yeah i checked ms docs but its not on there
found it anyway
its extinguished
I said mc wiki.
no in 2.1.0-beta
Is it possible to put a name on the item with translate?
Something like this:
item.nameTag = {
rawtext: [
{
translate: "item.enchanted_book.name"
}
]
}```
Name tags and lore don't support translate
why isn't onPlayerBreak triggering in my custom block component? I have another event in the same component which works fine and I have reloaded my world.
onPlayerBreak: ({block}) => {
world.sendMessage("ran");
let below = block.below();
if (below.type === "fb:dragonberry_plant"){
below.setPermutation(below.permutation.withState("fb:stage", 0));
}
}
TypeID not type l
ah yes, but that doesn't fix the fact that the message doesn't even trigger
How are you testing it? Any content log? Can you try debuggging it using console log?
no log
@north rapids
I was in an old script version
does applyImpulse work on players in v2?
ye
I'm staying on stable
oh that's right
pretty new to JS/TS.. not seeing a direct way to do this in the docs; I am trying to make my bedrock server's main script listen for events from my database server. I see that we are limited to HTTP so that makes it a bit tricky. anyone done something like this? the main reasoning is that I want my database server (written in Go) to do a majority of the world/logic processing because I don't want hundreds of different things running on the quickJS runtime for obvious reasons
Send a request for receiving events every so often 
hmm. yeah, that actually seems kind of obvious now lol. thanks. probably just way overthinking/overcomplicating it
could probably make a basic RPC api to handle that to keep packet sizes small
it doesnt throw error anymore
thats all
client doesnt like a sudden shift in player's velocity so youll have a lot of rubberbandings
so then what's the difference with applyKnockback
applyKnockback works by sending the info from server to client, and client handles how to knockback the player
but applyImpulse directly sets the velocity, and client doesnt have anything that handles this
that has to be the dumbest thing I've ever heard
why would they not just use knockback when running applyImpulse
heres a thing, applyImpulse isnt affected by knockback resistance
bruuuh
they really don't have a way to tell the client to change velocity
this has to be the most absurdly fixable problem I've seen
i dunno, i feel like theres something deep in the root
there are a lot of instances where you can cause rubberbands
like auto step component on player entity
If I had to guess it's probably just because it would be too much of a pain in the ass for them to add a packet for it
for some reason this doesnt have any visual effect on client but theyll constantly rubberband on serverside, so you can somehow touch lava without actually touching lava
well actually, applyImpulse actually does work
its just that it doesnt work 99% of times
hence the rubberbanding
this is probably related with server authoritative movement change
like this for example where server and client's knockback is desynced
its normal on serverside but the knockback is way lower and snapp-ier clientside
cant wait for beforeEvents playerplaceblock to be released from beta
just use beta
that's not the point, the point is you don't need to constantly change version to -beta
oh yeah for updates
and -beta is like an experimental version they are waiting it to be done.
hasn't chatSend been in beta for months now 😭
idk why they don't just release that event atp
yeah thats annoying
what version currently script api stable version?
2.0.0
thankss
It’s been beta for years at this point
For years*
what happened to itemUseOn event in the latest beta
Removed or deprecated I believe.
In favour for player interact.
oh, lol i thought it is the other way around
#1344352315825586259 message
how to detect player place block?
world.afterEvents.playerPlaceBlock.subscribe(data => {
const block = data.block;
const player = data.player;
})
because of marketplace stuff
player.spawnParticle() is client sided right?
Yes.
man idk why I open this channel for no reason I don't even ask a question
but I feel like I should
"anything that related to js 😍" - you
tbh me too. same
I like watching people getting problems solved
And actually you can learn from it
Am I right that headers and titles are count into modal form data's return values?
they do
does debugDrawer.removeAll(); just not work?
i like whatching other people dont get their problem solved
same problem here
Mine shapes immediately disappear after like half a second
I tried runInterval but then I can't remove it
import { world, system } from "@minecraft/server"
import { debugDrawer, DebugLine } from '@minecraft/debug-utilities';
function getBoxVertices(A, B) {
const xMin = Math.min(A.x, B.x), xMax = Math.max(A.x, B.x);
const yMin = Math.min(A.y, B.y), yMax = Math.max(A.y, B.y);
const zMin = Math.min(A.z, B.z), zMax = Math.max(A.z, B.z);
return [
{ x: xMin, y: yMin, z: zMin },
{ x: xMin, y: yMin, z: zMax },
{ x: xMin, y: yMax, z: zMin },
{ x: xMin, y: yMax, z: zMax },
{ x: xMax, y: yMin, z: zMin },
{ x: xMax, y: yMin, z: zMax },
{ x: xMax, y: yMax, z: zMin },
{ x: xMax, y: yMax, z: zMax }
];
}
function drawBoxOutline(cornerA, cornerB) {
const pts = getBoxVertices(cornerA, cornerB);
const edges = [
[0, 1], [0, 2], [0, 4],
[7, 6], [7, 5], [7, 3],
[1, 3], [1, 5],
[2, 3], [2, 6],
[4, 5], [4, 6]
];
for (const [i, j] of edges) {
const line = new DebugLine(
pts[i],
pts[j]
);
line.timeLeft = 60;
debugDrawer.addShape(line);
}
}
world.beforeEvents.playerBreakBlock.subscribe(async ({ block, itemStack, cancel }) => {
if (itemStack?.typeId === "minecraft:stick") {
cancel = true;
world.setDynamicProperty("l1", block.location);
world.sendMessage("set pos")
}
if (itemStack?.typeId === "minecraft:blaze_rod") {
cancel = true;
const l2 = block.location;
const l1 = world.getDynamicProperty("l1")
world.sendMessage("set pos 2")
drawBoxOutline(l1, l2)
}
})
Here's my script
Which does not work
can you see what's the problem
Select a stick and break block then take blaze and break select block
It'll draw the debug shape
@sterile epoch
maybe identify the problem for me

Any chance we can get the type of item from an item entity in scripting?
yes.
get the item component.
Documentation for @minecraft/server
oh righttt
dimension.getEntities({ type: "minecraft:item"}).forEach(entity => {
const itemType = entity.getComponent("minecraft:item")?.itemStack?.typeId
})
Is there a quick way to access all spawn eggs (item ids)? or do I need to make a library
import { ItemTypes } from "@minecraft/server";
function getSpawnEggs() {
const spawnEggs = [];
for (const type of ItemTypes.getAll()) {
const itemStack = new ItemStack(type.id);
const isSpawnEgg = itemStack.hasTag("minecraft:spawn_egg");
if (isSpawnEgg) spawnEggs.push(type.id);
}
return spawnEggs;
}
oh thats smart, ty!!
onStepOn(event) {
event.block // Block impacted by this event.
event.dimension // Dimension that contains the block.
event.entity // The entity that stepped on the block. May be undefined.
}
how can i use this script to make a block that will break if you step on it?
you need to use the setblock command and make it destroy it, theres no native method to destroy blocks yet.
within the setblock command, you need to enter the block's coordinates through template literals
I miss my goofy ahh helping every people in this channel every damn second lmao
huh
need help with this code i tried asking ai but it didn't work
// Create scoreboard objectives if they don't exist
function createScoreboardObjective(name) {
try {
world.scoreboard.getObjective(name);
} catch {
world.scoreboard.addObjective(name, name, name);
}
}
createScoreboardObjective("isRightClicking");
createScoreboardObjective("isLeftClicking");
// Reset scores every tick to 0
system.runInterval(() => {
for (const player of world.getPlayers()) {
player.scoreboard.setScore("isRightClicking", 0);
player.scoreboard.setScore("isLeftClicking", 0);
}
}, 1);
// Detect right-click (item use)
world.events.itemUse.subscribe(event => {
const player = event.source;
if (!player || !player.isPlayer()) return;
player.scoreboard.setScore("isRightClicking", 1);
});
// Detect left-click (attack)
world.events.entityHit.subscribe(event => {
const player = event.source;
if (!player || !player.isPlayer()) return;
player.scoreboard.setScore("isLeftClicking", 1);
});
what i want here is to detect whenever a player right-clicks with any item and left click and convert it into a score
so what is the issue here
is there any error?
ye alot
[Scripting][error]-TypeError: cannot read property 'setScore' of undefined at <anonymous> (main.js:18)
a lot of these
and some
I can't send it i reach text limit
seems like yhe setScore can't be read in line 18 or so
is it made by ai?
Player class doesn't have a scoreboard property lol
that's the problem
kinda because i sent this to ai to fix it but it made it worse
you must access the scoreboards via
world.scoreboard.getObjective(name).getScore(Player)
yeah i supposed that
also events property doesn't exist in world
it's either afterEvents or beforeEvents
isPlayer() method doesn't exist :v
a lot of things are wrong there
can you fire and event in an unloaded chunk?
no unless u load it ig
depends on the event you mean.
so umm, iirc addObjective() only accepts 2 params... id and display name of the objective... Setting score of player isn't easy as just that.
you need to get the objective first and use that objective to setScore()
const obj = world.scoreboard.getObjective(objectiveId: string);
obj.setScore(participant: Entity | ScoreboardIdentity | string, scoreToSet: number):```
same goes to addScore()
I'll try to rewrite the code
How do I detect enchantments on the item a player is holding and display something like: Diamond Sword [Sharpness I]?
Get the Item the player is holding -> getComponent('enchantable') -> read the enchantment contents
oh thanks
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
if (!event.block.permutation.matches('minecraft:jukebox')) {
if (event.itemStack?.typeId === "space:disc_14") {
system.run(() => {
event.block.dimension.playSound("broken.disc14", event.block.location);
});
} else if (event.itemStack?.typeId === "space:disc_15") {
system.run(() => {
event.block.dimension.playSound("broken.disc15", event.block.location);
});
} else if (event.itemStack?.typeId === "space:disc_16") {
system.run(() => {
event.block.dimension.playSound("broken.disc16", event.block.location);
});
}
}
}
});
It shows unhandled promise rejection at last line
is gametest still on beta?
Yes.
can someone look at my line 82 and check why my hit reduction logic not working? i'll consider it working if the debug message gets printed :DD
Would like to make a correction. EntityLoad does work, EntityInitializationCause.Loaded does not work.
anyone know an script to make a 2d block behave like this?
#1067876857103536159
How to give a tag after this entity spawns?
mc.world.afterEvents.playerPlaceBlock.subscribe(event => {
const block = event.block;
const loc = block.location;
const player = event.player;
const dim = player.dimension;
if (block.typeId == "minecraft:dirt") {
dim.spawnEntity("hash:shooting.machine.1", loc);
player.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air`);
}
});```
const entity = dim.spawnEntity("hash:shooting.machine.1", loc);
entity.addTag("name")
or just
dim.spawnEntity("hash:shooting.machine.1", loc).addTag("name")
Oh, thanks
I just experienced a Mandela effect
i thought it was possible to save dynamic properties on Blocks
i think theres an extra }
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const { block, itemStack } = event;
if (block.typeId !== "minecraft:jukebox") {
let toPlay;
if (itemStack?.typeId === "space:disc_14") toPlay = "broken.disc14"
else if (itemStack?.typeId === "space:disc_15") toPlay = "broken.disc15"
else if (itemStack?.typeId === "space:disc_16") toPlay = "broken.disc16"
if (toPlay) system.run (() => block.dimension.playSound(toPlay, block.location))
}
});
how do i detect when the attachable equipped by the player is being used to attack like right clicking or left clicking?
anybody her has any idea why setFloat() doesn't set tickVariables and staringVaribales?
it creates it's own variable
world.afterEvents.playerBreakBlock.subscribe(event => {
try {
const { player, block, brokenBlockPermutation } = event;
const blockId = brokenBlockPermutation.type.id;
const droppedItemId = getItemIdFromBlockId(blockId);
if (droppedItemId) {
event.setDrops([]); // Likely around line 95-100
const inventory = player.getComponent("inventory");
if (!inventory || !inventory.container) {
player.sendMessage("§cLỗi: Không thể truy cập kho đồ của người chơi.");
return;
}
const container = inventory.container;
const itemStack = new ItemStack(droppedItemId, 1);
const overflowItems = container.addItem(itemStack); // Likely around line 100-105
if (overflowItems) {
player.dimension.spawnItem(overflowItems, block.location);
}
player.playSound("random.pop", { location: player.location });
}
} catch (e) {
console.error("Lỗi chung trong addon tự động nhặt đồ:", e.stack);
}
});
How to fix
Compiler found 2 errors:
[36mmine.js[0m:[33m95[0m:[33m19[0m - [31merror[0m[30m TS2339: [0mProperty 'setDrops' does not exist on type 'PlayerBreakBlockAfterEvent'.
[7m95[0m event.setDrops([]); // Likely around line 95-100
[7m [0m [31m ~~~~~~~~[0m
``````ansi
[36mmine.js[0m:[33m110[0m:[33m67[0m - [31merror[0m[30m TS2339: [0mProperty 'stack' does not exist on type 'unknown'.
[7m110[0m console.error("Lỗi chung trong addon tự động nhặt đồ:", e.stack);
[7m [0m [31m ~~~~~[0m
Please help, I have a script that works fine in a single world, but when I uploaded the world to a server (in my case, aternos) the script does not start at all
What to do in this case, I have never worked with scripts on servers
the error is self-explanatory.. the property .setDrops() does not exist in the event
These properties do not exist in these classes
const equipmentInventory = entity.getComponent(mc.EntityEquippableComponent.componentId);
if (equipmentInventory) {
const chestArmor = equipmentInventory.getEquipment(mc.EquipmentSlot.Chest)?.typeId;
if (chestArmor) {
adminDebug(source, Chest armor equipped: ${chestArmor});
if (ARMOR_PROTECTION[chestArmor]) {
adminDebug(source, Hit to the chest! Chestplate: ${chestArmor});
damageMultiplier -= ARMOR_PROTECTION[chestArmor];
}
} else {
adminDebug(source, "No chest armor equipped.");
}
const headArmor = equipmentInventory.getEquipment(mc.EquipmentSlot.Head)?.typeId;
if (headArmor) {
adminDebug(source, `Head armor equipped: ${headArmor}`);
if (ARMOR_PROTECTION[headArmor] && hitPart === "Head") {
adminDebug(source, `Hit to the head! Helmet: ${headArmor}`);
damageMultiplier -= ARMOR_PROTECTION[headArmor];
}
} else if (hitPart === "Head") {
adminDebug(source, "No helmet equipped.");
}
}
im gonna go nuts
the script aint reading the armor protection thingy
D:
looking good
blablablablublu
why are you trying to cram so much code into one line, it makes it all less readable
Looks normal to me ngl...
do you really write stuff with the "," operator?
i think that at least [player, playerPos] = [v.player, v.player.position] is more readable
Tbh didn't notice that. Eh
bruh thats all need to reload when the db is updated
I don't like structures that are too clean
can addon read others addon dynamicproperty?
No.
so the scope of getDynamicProperty() is only in the addon itself?
What gets me is the lack of var/let/const in declaring those variables. "player" and "playerPos" are scoped globally here
is there a way to detect or modify hunger points?
the unique way to transfer the data is by getting the result and passing to another addon via system message
system message?
i forgot the name
that shit on system
its got a command as well
this lil guy
yeah i totwlly forgot its name
ohhh thanks
i think there are 2 projects that help doing so
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]
Installation for @minecraft/server-ui
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]
Are player.ids exclusive to each world or do the same ids persist in every world?
exclusive
But the host always has the same ID
Got it, thanks
You're welcome