#Script API General
1 messages · Page 40 of 1
i dont even use github for this anymore
idk how to unsync it
import { system } from "@minecraft/server";
let cooldowns = new Map();
function useItem(player, item) { // example function, only for educational purposes, do not copy paste
let cooldownKey = `${player.id}:${item.typeId}`;
if (system.currentTick <= cooldowns.get(cooldownKey)) return function(){player.sendMessage('Whoa This Item Is Still On Cooldown!'); player.playSound('random.bassattack');}();
cooldowns.set(cooldownKey, system.currentTick+(16*20)); // 16 seconds delay
// run some code
system.runTimeout(() => {
cooldowns.delete(cooldownKey);
});
}
Really, do they? No. It's "extras" if you wanna do it, do it, if you wanna listen to me sure, it's up to you, but I have learnt from the hard way not to focus too much on the outerview.
Wow! Great commands! Thanks!
does anyone know a way to apply enchant to an in-hand tool ?
/enchant command
?
....is there a direct way with scripting ?
Player.runcommand(<command here>)
I mean it does exist it's just not the easiest method for what you want,
https://discord.com/channels/523663022053392405/1272737613496844379
import { EnchantmentType } from "@minecraft/server";
let item = player.getComponent('inventory').getItem(player.selectedSlotIndex), enchComp = item?.getComponent('enchantable');
if (!enchComp) return;
enchComp.addEnchantment({type: new EnchantmentType('fire_aspect'), level: 2});
player.getComponent('inventory').setItem(player.selectedSlotIndex, item); // sets item back to the same slot because mc doesn't register enchant unless you do this
Thanks ya
(Of course assuming player is a valid player variable), and you're welcome :)
Yo Emwynn, u writing a paragraph?
Hey what would be the best practice for saving data to a block while trying to to conserve space. I've been using
world.setdymanicProperty(Json.stringify(block.location),number)
But I feel like it's gonna take up a LOT of space
Depends, can you provide more details & context?
I'm making an "hp" for block's that are stepped on, if you step on them too much they'll downgrade from grass into coarse dirt, then into paths, then into gravel
I just wanted to see what the effect would be
Ah
No, it won't be very much data. You should be fine. Include the dimension id in the key though
Yes
Oh right, yep almost forgot about that lol
Like a million blocks or more probably
I should probably add a forget response just in case, that way if a block hasn't been stepped on more than once in like x amount of time it won't still be counted
Okie thanks just wanted to check there wasn't a safer or smarter way I was overlooking
go into your project folder and delete the .git folder
^
I know this is off topic, but since we are js coders, I'm wondering what is the best way to get the device width? I'm using window.innerWidth but idk it isn't working with my formula to resize navbar and other elements on certain browsers like the kiwi browser & the acode html viewer
innerWidth should work
maybe try clientWidth or screen width
Thanks
When I use this on custom blocks with the liquid detection component, it says the block type can't be waterlogged. What should I do?
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]
yo
how can I get the effect of an entity/player
also whats wrong with this
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const poison = Entity.getEffect('poison')
if (poison) {
Player.addTag('poison')
}
}
})```
it says the problem is with getEffect
Entity and Player variable is not defined
in @minecraft/server?
It's in your code. You simply don't have them. You are referring to a non-existent object
Debug result for [code](#1067535608660107284 message)
Compiler found 2 errors:
[36m<REPL0>.js[0m:[33m3[0m:[33m31[0m - [31merror[0m[30m TS2339: [0mProperty 'getEffect' does not exist on type 'typeof Entity'.
[7m3[0m const poison = Entity.getEffect('poison')
[7m [0m [31m ~~~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m5[0m:[33m20[0m - [31merror[0m[30m TS2339: [0mProperty 'addTag' does not exist on type 'typeof Player'.
[7m5[0m Player.addTag('poison')
[7m [0m [31m ~~~~~~[0m
ESLint results:
<REPL0>.js
2:16 error 'player' is assigned a value but never used @typescript-eslint/no-unused-vars
Why do you need a debugger now?
Where do I find list of criteria for query? Like for
const query = { type: 'item', closest: 1, location: { x, y, z } };
const drop = dim.getEntities(query)[0];
import { system, world, EntityHealthComponent, Player, Entity } from "@minecraft/server";```
is this what u reffering to?
You import classes and try to call their methods. You can't do this if the method is not static. And since the method is not static, you need to create an object of this class, but you cannot create it via new, you need to create an entity via dimension.spawnEntity or get it via world.getEntity or dimension.getEntities
didnt I did that here?
I highly recommend familiarizing yourself with Git, as it’s an invaluable tool for managing your code. Git makes it easy to track changes, so you can see exactly what was modified, when, and by whom. If you make a mistake, Git allows you to revert to earlier versions of your code, saving you time and frustration. It also lets you experiment with new ideas by creating branches, so you can test changes without affecting your main codebase. Git provides a clear and organized way to manage your code, making it much easier to navigate mistakes and improvements as your project grows.
oh thats for players
@warm mason Hey, me again, do you know anything from entities? if yes, can you meybe pls look in entities general? it's probably really easy but can't get it fixed, Thanks!
I didn't understand the question. What do you need
if a entity dies, it plays a sound and partcile, i don't want that
#1067869022273667152
I know I put it there, but wanted to ask to you if you could help 😄
Please dom't do this. Fishing for help is annoying.
Guys help
Why does Minecraft says (beforeEvents) "worldInitialize" is undefined?
Im using the 2.0.0-alpha for the server module
code...
Code? why?
mc.world.beforeEvents.worldInitialize.subscribe(...)
You cant use 2.0.0
And after the update it doesn’t work, as you can see.
Yes.
Go to 1.18.0-beta
but why can i use 2.0.0-alpha in my other addon? it doesnt throws any errors
idk
weird
I have a more general js question but how would I make something that takes “value” and divides it by 32. I want value to be a separate thing so I can set values to it automatically I don’t want it to be a set number or something if that makes sense
let a = 1231236/32

well. like you can see, 1.18.0-nbeta isnt valid
Do you know the JavaScript basics? just a question
For minecraft version 1.21.50 use 1.17.0-beta
alright
My guy, 2.0.0 has not been around for years.
I do yea I’m just a little lost here
I literally can’t remember how
.
I just said "for years"
i used it for like months to be exct and it worked without problems
value / 32
Did you think that your addon will not break after updates?
It shouldn't if you use stable 👍 .
That's the whole premise of stable APIs, it shouldn't break after updates.
i always use experimental soo
Yes, yes. I remember that “wonderful” day when all my items said bye because they were not satisfied with the version format. Although it was an old addon, which was the field for my training... At least nothing broke in my new addon

because beforeEvents.chatSend is only included in beta versions
Hey, How do you do with a script, if you left click, and try to hit something with a sword, that you can do a effect and sound effect, or activate a function? I think this works with scripts like the 'on use' but can't figure it out :C
Animation Controlles + ScriptEvent
owww animation controllers, i will have a look at that Thanks!
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/debug-utilities
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
cause that method only allow if the block can be waterlog
they recently added the liquid detection to custom block
add that component to your block
That's what I was saying, it DOES have the component, still doesn't work.
However, it may be because the component was in a permutation.
The permutation was still met though, I'm not sure why it didn't allow it
how do I run a script based on what someone clicks in actionFormData
I want them to switch to a new form depending on which option they click
You check the response and if the response matches your condition you execute whatever it is that you need to execute.
https://stirante.com/script/server-ui/1.4.0-beta.1.21.50-stable/classes/ActionFormResponse.html
Documentation for @minecraft/server-ui
Thanks, I'll test it out
It seems I have to switch to typescript, to do that would I go to manifest, and change entry to "script/main.ts" and language to "typescript"?
Nah, the example is in typescript but you can do so using JavaScript.
Just remove the Types in the example.
well for some of the stuff, my console showed that I can only do it in typescript
specifically the
(log: (message: string, status?: number)
tho actually
do I even need that?
I don't think I do
I'll try without it lol
thanks
That's in TS because message and status are expressing the Type for each one.
Remove the Types and it's basically JS.
Example TS:
const example: string = "This is a string";
Example JS:
const example = "This is a string";
Must be in JS when applying to a world. Some of us use TS because it speeds up development, maximizes efficiency, and immensely assists at detecting realtime mistakes before getting to runtime testing.
I’m so confused why doesn’t this work it says NaN for Seconds
Here’s another example
This is what I get out
Use () so the math ecuation is made before joining with the string
||you should use template strings instead||
uh... you are adding a string to an array
Can I do this in a better way?
just remove the []
I did that before it didn’t fix anything
send that code
Oh wait
let comparators = 4;//input from the command
let batteries = 2;//input from the command
let c = [comparators]*32*[batteries]*15/20;
let m = Math.floor(c/60);
console.log('GameTicks:'+ comparators*32*batteries*15, 'Seconds:'+ c-m*60, 'Minutes:'+ m)
Yeah no this doesn’t work I originally had the [c] still but it seems that wasn’t the reason
you should send code instead of images in the future
let comparators = 4;//input from the command
let batteries = 2;//input from the command
let c = comparators*32*batteries*15/20;
let m = Math.floor(c/60);
console.log('GameTicks:'+ comparators*32*batteries*15, 'Seconds:'+ c-m*60, 'Minutes:'+ m)
import { world, BlockComponentTypes} from "@minecraft/server";
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const player = event.player;
const block = event.block;
if (!player || !block) return;
if (block.getComponent(BlockComponentTypes.Sign)) {
event.cancel = true;
const sign = block.getComponent(BlockComponentTypes.Sign);
if (sign) {
try {
const rawText = {
rawtext: [
{ text: "§aClicked" }
]
};
sign.setText(rawText);
} catch (error) {
}
}
}
});
Does anyone knows how to set a text to a sign
was geht
lmao
bin da gerade bisschen am verzweifeln xd
setText need the side of the sign
its optional
The thing I’m still getting NaN
it doesnt need it
nvm it is optional
what is the exact error
Debug result for [code](#1067535608660107284 message)
Compiler found 0 errors.
ESLint results:
<REPL0>.js
22:22 error 'error' is defined but never used @typescript-eslint/no-unused-vars
22:29 error Empty block statement no-empty
Theoretisch sollte das funktionieren
[Scripting][error]-ReferenceError: Native function [BlockSignComponent::setText] does not have required privileges. at <anonymous> (index.js:20)
gibt das immer wieder aus
ahh
wrap it in a system.run
hello ente
hi
Ok du musst den Code in system.run(()=>{}) wrappen
teste ich mal wait
also in den {} dein code
This is all I’m getting
meinst jetzt den setText oder den raw text oder alles davon xd
das wird dann nächsten Tick ausgeführt, das is damit so ne Interaktion durch Script API nicht so lange verzögert wird, weil sonst müsste Minecraft warten bis dein Code komplett fertig is bevor es die eigentliche Interaktion durchführt
Das mit dem Component und setText
also alles ab if(block.getComponent...)
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const player = event.player;
const block = event.block;
if (!player || !block) return;
if (block.getComponent(BlockComponentTypes.Sign)) {
event.cancel = true;
system.runTimeout(() => {
const sign = block.getComponent(BlockComponentTypes.Sign);
if (sign) {
const rawText = {
rawtext: [
{ text: "§aClicked" }
]
};
sign.setText(rawText);
}
})
}
});
meinst ja so
ja thx
Ja so würd ichs machen ```js
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const player = event.player;
const block = event.block;
if (!player || !block) return;
const sign = block.getComponent(BlockComponentTypes.Sign);
if(sign) {
event.cancel = true;
system.run(()=>{
if (sign) {
const rawText = {
rawtext: [
{ text: "§aClicked" }
]
};
sign.setText(rawText);
}
})
}
});
'Seconds:'+ (c-m*60)
Much appreciated
hast die klammern falsch gesetzt sonst checke
xd
geht aber so auch nicht mehr xd
k
aber den component kannst du trzdem in ner variable vorher speichern
du gettest den 2 mal
das nicht gut
guys
please keep it in English
👀
jedes mal wenn du das machst schwitzt Script API richtig
ok
glow ink sacks
aso
vllt wenn du ne helle farbe mit setTextDyeColor machst idk
ansonsten geht das einf nd
aber du kannst trzdem theoretisch n schild das schon glowing hat nehmen und das kopieren und den Text darauf printen dann jedes mal
checke auch smart eig
👀
welp there is a way
but sense i don't speak what ever is that ... i can't help you
ente speaks english
Maybe its a block state but I doubt that
you can check tho
it is not
k
@hardy tusk man kann immer noch nicht die block facing direction holen mit scripts right?
Doch
save a glowing sign in structure block and reuse it
Thats a block state
Why event.cancel after system.run?
@hardy tusk wie xd
block.permutation.getState()
je nach block entweder einer von denen oder von den anderen
weirdo direction is my favorite
ah nice seit welcher version geht das
..........
hahahaha
#add-ons message
oh sry than bro
hello how are you
tf
Maybe you can just tell us in a language that everyone understands what you need and we will help you?
they have a translate thing here
im done with it
he already got help xD
me and creepy are good friends btw
ye
that doesn't matter
move to dm if you don't need public help
ok bro
np bro
machen wir 👍 💀
شكرا
@hardy tusk
?
cuz u messed up
brother how do you make this setWaxed
the translate works well but hahaha
sign.setWaxed(true)
setWaxed(bool)
ye sign.setWaxed(true)
this one is right
How does chatSend work?
world.beforeEvents.chatSend.subscribe((e) => {
if (!e.sender.isValid) return;
if (e.message.startsWith('!')) {
e.sender.sendMessage("Working")
}
})
Console says that subscribe is undefined
show manifest
alr one sec
dependancies or all of it?
this is the dependancies
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.16.0"
}
]
1.16.0 is no longer beta I don't think
Use beta
Chatsend is still beta that's why
1.16.0-beta?
1.17.0-beta
yo, just to make sure:
is it possible to detect the itemStack of entities?
like detecting the item that the entity is holding.
Is there a way to get ontick to run runinterval only once?
Custom Blocks?
You can set loop to alse in the tick component.

player or none player?
non player
testfor command with hasitem selector
kinda?
unless you are willing to test for all the items one by one
i think i can use something else
is there a way for me to save entities data then spawn the exact same entity again?
all i know is how to save the location and typeId
How do I remove errors on tests
Where do I add the '?'
for like
state.?toLowerst
LowerCase*
?.
.toLowerCase()
I did that, but when it's invalid in my function
it shows in console
that it can't run toLowerCase to an undefined property
Just save them in a structure block 🤷
ye ive figured that out
about 2 hours ago ..
well ty for help
how do I apply knockback from a Vector3 location? I have a sumo ring but want to remove people who are wearing netherite from it without teleporting them
I made an arena a 30 block wide radius and I made a death scene of the boss and the player within that arena using tp there is one major flaw though if the player killed the boss on the side of the arena the death scene will not be seen correctly because the camera is being blocked by the arenas walls is there any way to tp the entity on the center of the arena?
can the player get out of the arena at all?
No cause it cannot move after the scene, cause basically it is already dead
like it wouldn't trigger an afterDeath event handler?
because I think you can still access a location property even after death
Well my boss has a minimum health value so it doesn't actually die so I can still tp it however the problem is don't know if it is possible to tp it in the center of the arena
So after entitydie I tp the boss in the center of the arena so the death scene can be seen clearly
get the center of the arena and get the entity you want to tp
I'll try that I saw that there is a dimension parameter in the tp function
Wait the structure actually generates in the center of the player so what if I save the coordinates in a variable then later use that to tp the boss?
Anyone know if there's a script API equivalent to the q.is_charging molang query on the front end?
itemStartUse after event?
It's not an item, it's an entity (vex) doing the charging attack
I tracked down how the animation controller is changing the texture to an is_charging query, but there isn't an isCharging entity property on the entity object, so I'm not sure how to detect it from the script api
Is there a way to make a player not die after being hit like having a minimum health component
player.json
Not scripts
The problem with having a minimum health component is after you die your actually immortal so I don't like that
totem of undying
Then make a component group for it. If the player receives fatal damage, remove the "immortality" component group
Is it possible to track the damage value of the entity then compare that to the health of the player then I substract damage how many I want
you want to get the melee damage player dealt?
You can't get the melee damage of player without attacking something, I'm not kinda sure tho
No the boss melee damage dealt to the player
entityhurt can check the damage boss made
There's applyDamage() if you want the damage to be done through Script, but the rest of the damage calculation (armor, enchantments, potion effects) is outside your control, so you can't guess every time if this damage is "fatal" or not
Just make a component group, and damage sensor that detects and cancels fatal hits, then remove the component group afterward bruh. ( It run entity event )
Yeah this is a lot easier
Quick question, if the player is damaging a mob with armor can you detect how much damage armor resisted?
Not in a direct way.
You can Map each vanilla wearable Item attributes (armor and toughness)
Dynamically, If you want it to be compatible with other custom armor outside your pack, you could make a custom entity, and iterate each ItemTypes class for all possible wearable itemStack, then test each Armor Points and Armor Toughness by damaging the custom entity.
-# Probably run once on world load.
Then, using runCommand() or the async variants to get the armor dmg reduction, you'll use the hasItem={} selector to check each equipment slot for each typeIds, then calculate it according to the formula in Minecraft wiki.
It has a flaw tho, not being able to detect enchantments. However, you can barely distinguish "armor dmg reduction" and "enchantment dmg reduction" using an additional check of changing the damage cause between "entityAttack", "magic", "explosion", "projectile" etc
-# You'll be copying the hurtEntity using a structure, and a lot of copy-paste to isolate each armor for accurate reading. (Unless the getEquipment() works)
What does fatal detect if the damage is enough to kill the entity?
Fatal detects if this damage could Kill this entity iirc.
"Fatal - Any damage which kills the subject"
Not worth it to do such a big thing just for that.. ditching that too
How about having a resistance effect? Can you detect the damage absorbed?
you can use getEffect on all entities. Just take the amplifier and put it in the resistance formula
Yeah I'm stupid asf i forgot it existed lmao... Thanks to
can somone help?
the problem is that that is already being used for a redstone event
Is it possible to change death messages?
Nvm, I take back what I said in ditching this... I'll just use it on the player to detect how much damage the player resisted and absorbed
My weakness is the custom items
it means the entity you are trying to get the component of wasnt found or does not exist
Oh, I'm so happy, I've finally finished my addon
and I LOVE IT
I'm nerding out rn
thanks for trying to help with the uppercase things Coddy
That's the only reason I pinned u lol, just a thanks
Ayy lmao... Why people keep thanking me even if I only did help 0.01% in their coding life 😭 tho you're welcome still
yearh, u rlly didn't help with my code, but u tried with one small part of it
lol
Wanna see my addon?
It's 1011 lines
its actually quite a simple program
but I had to add a LOT of data
Is there a way i can break a block using scripts
it was very tedius
Yeah I guess so... 1k lines is small for me but go ahead
set the block to air?
I won't inv u, but I'll explain
So you type '-help'
and it gives instructions
but basically
you set your yearly income
the state u live in
and the value of ur house
and it then tells you
when u type 'stats percent'
'-stats percent'*
it tells u:
Property Taxes:
State Taxes:
FICA Taxes:
Federal TaxesL
and Total Taxes:
Tf 😭😭
then if u type '-stats cost'
Chill out on messages
And I feel like you replied to the wrong person
nah, u and one other dude mentioned something abt toUpperCase
and I alr thanked the other dude
but yeah, it tells u ur taxes based on income, state, and property value
I'm 800 lines deep already
I didn't bother adding filing status
dang
mines just a bunch of data from tax websites
each state is different in every field, and some have income brackets, some don't
and I had to look up (on a laggy laptop)
every single stat for every state
and then use chatSend and calculations, which I've never done before with either
oh my god bro just make a mathematical model for the tax percent
or something
so many if elses lmao
ah wait Ig it's not a continous func
nvm
just
yeah, nothing is continuous
every single state is different, every single value is different, every single if (income < ) is different
yeah ik
there's better ways to do it than a else if chain though
yeah, I realized that 1/3 way thru
but if it restarted, it would've taken longer
bc I'd have to go back and redo the values
which are a lot
And it's not like this is laggy
it runs with no delay ingame
so I don't see a point in changing it this far in lol
I could've just made every single thing easier by not changing the dynamicProperties until the end and just putting the array in the case of the 3 values based on income lol
then every state would only have 3-15 lines to it
btw, I would use <= instead of just <, then you don't have to add 1 to every number
makes it nicer to read
and your last else if can just be an else
Y'know what's funny I will literally bonk you just to do it like this... js if () sender.setDyna.... else if () sender.setDyna...
Especially if you're doing one thing inside of the bracket
I like the seperatation
makes me feel correct
it's not adding additional lag rlly
use map instead objects
I kinda hate it cause the readability will be bad... When it's only one but two yeah you need to use bracket
I ain't using it completely, I'm just using that for simple calling
Map.get(<identifier>, 0);
yeah, but the readability is easier for me, as I'm just a weird individual lol.
And this script isn't for other ppl. It was just to prove to myself that I could make it
I know okay... I said I ain't using objects in the future
I'm kinda confused with the calculation
So I'm in hard mode and zombie attacks me it's 4.5 and when I have resistance effect 3 the damage is 0.9
Which is way of with the calculation in the wiki
Which is 0.2 x level
When I do damage - (0.2 * 3) it's equal to 0.3
So 0.3 + 0.9 = 1.2 which is way way off of 4.5
Each level of resistance effect reduces damage by 25%
Ohh my goodness
The wiki said 20%... Lma
so inventory and equippable doesnt exist?
inventory = this.#simulatedPlayer?.getComponent("inventory").container
equipment = this.#simulatedPlayer?.getComponent("equippable")
or
inventory = this.#simulatedPlayer?.getComponent(mc.EntityComponentTypes.Inventory).container
equipment = this.#simulatedPlayer?.getComponent(mc.EntityComponentTypes.Equippable)
they don't exist
there's no difference
yeah but number 2 was the one I used
so if these don't exist (apparently) what should I do then?
im using the 1.17.0-beta server module
Do they just return undefined?
they just return undefined ig because as shown by my snip they return undefined
so yes ig
Maybe it's because simulatedPlayer is undefined
its not undefined though
const simulatedPlayer = SimulatedPlayer.test.spawnSimulatedPlayer({ x: 0, y: 1, z: 0 }, username, gamemode)
if (sender) {
simulatedPlayer.teleport(sender.location, {
dimension: sender.dimension,
facingLocation: sender.getViewDirection()
});
} else {
throw new Error("sender's location is not initialized.");
}
this.#simulatedPlayer = simulatedPlayer
this.#intervals = {}
this is in my
constructor
Check it out. Before receiving components, print simulatedPlayer to the console
do I just do
console.log(string | number | etc...)
just to clarify?
console.warn("Player: " + this.#simulatedPlayer)
okay I managed to get it to work
Is it possible to change death messages?
isn't your equation wrong? you want to remove 25% of damage (per level), but here you're jsut removing 0.25 per level
do damage - (0.25 * 3 * damage)
mhm
Turn off the default death message through the settings and when a player dies, display what you need
Oh I thought you can fully manipulate them through scripts, gues I have to give up on this idea
For me it kinda don't make any sense because I tried to grab the damage of the zombie per level of resistance players have when the base is 4.5
zero: 4.5
one: 3.6000003814697266
two: 2.6999998092651367
three: 1.8000001907348633
four: 0.8999996185302734
20% -> 25% -> 33.33% -> 50%
Stop what. Doesn't level four completely absorb damage?
That's not the point
The point is the percentage is not flat
And I obviously know that information.. k?
is this total percent or compounding?
cause if it's total for each level then your maths is completely wrong
I didn't use math I literally just grabbed the damage Zombie gave to me
zero: 4.5 (100%)
one: 3.6000003814697266 (80%)
two: 2.6999998092651367 (60%)
three: 1.8000001907348633 (40%)
four: 0.8999996185302734 (20%)
I'm talking about your percentages
you've done them wrong
there's a 20% reduction in damage per resistance level
prob wrong
yeah ik he's wrong
I'll check my system now. Maybe I'm really wrong
Lemme try this...
what damage value are you trying to calculate?
the final damage after resistance reduction?
I was trying to grab the damage player resisted
ah ok, then do
const damage_reduction = 0.20 * resistance_level * damage
oh wait
no
cause your damage will be after reduction
so you gotta get the original damage first
which should be
class EnchantDeshPickaxe {
constructor(player) {
this.player = player;
}
enchantSelectedItem() {
// Retrieve the currently selected item from the player's inventory
let item = this.player.getComponent('inventory').getItem(this.player.selectedSlotIndex);
// Check if the item is the pickaxe and is enchantable
if (item && item.typeId === "cosmos:desh_pickaxe") {
let enchComp = item.getComponent('enchantable');
if (!enchComp) {
console.log("The selected item is not enchantable.");
return; // Exit if the item is not enchantable
}
// Define the enchantment to be added
const enchantment = { type: new EnchantmentType('silk_touch'), level: 1 };
// Add the enchantment to the item
enchComp.addEnchantment(enchantment);
// Update the item in the player's inventory to register the enchantment
this.player.getComponent('inventory').setItem(this.player.selectedSlotIndex, item);
}
}
}```
@dim tusk is this a valid class ?
const original_damage = damage / (1 - 0.2 * resistance_level)
and then the damage reduction is original - damage
const damage_reduction = original_damage - damage
That's why the damage resisted is wrong when I'm trying to add it on the current damage.
Damage: 1.8000001907348633 | Resisted Damage: 0.7200000762939454
or just
const damage_reduction = damage / (1 - 0.2 * resistance_level) - damage
Yes, I did have the original damage calculation wrong
yeah
no
how so, elaborate please.
getItem() is a method of the Container class, and you want to call this method directly on the EntityInventoryComponent class
And it's the same here
you should store part of that in a variable so you can use it again below
.getComponent("inventory").container.getItem()
class EnchantDeshPickaxe {
constructor(player) {
this.player = player;
}
enchantSelectedItem() {
let inv = this.player.getComponent("inventory").container
let item = inv.getItem(this.player.selectedSlotIndex);
if (item && item.typeId === "cosmos:desh_pickaxe") {
let enchComp = item.getComponent('enchantable');
if (!enchComp) {
console.log("The selected item is not enchantable.");
return; // Exit if the item is not enchantable
}
const enchantment = { type: new EnchantmentType('silk_touch'), level: 1 };
enchComp.addEnchantment(enchantment);
inv.setItem(this.player.selectedSlotIndex, item);
}
}
}
👍
In general, it’s not very clear why create an entire class just for the sake of adding enchantment to a certain pickaxe
Thanks
It looks cooler
i should've make it a function but i want to make it a class for the sake of syntactic flowery
looks lol
Well, okay.. Btw I don't think you need to waste time on useless comments that just comment on methods
This is a class, want to make sure everyone understand everything
Thanks though 😍
some people just like adding comments to their code
nothing wrong with that
ehehehe
pun intended >:) ?
Well, sometimes it's useless. As in the addEnchantment method, for example, it’s clear what it does and why write there that it “adds enchantment”
readability
most of the time the functions names are self explanatory
As for me, on the contrary, when the code is separated by a bunch of text, it’s not very clear
for readability just avoid confusing stuff that not widely known (if possible)
I'd like to pretend JS is like Java
As a result, it's all classes
doesn't reduce speed anyway
Ok so Umm did I do something wrong?
world.afterEvents.entityHurt.subscribe(({
hurtEntity, damage
}) => {
if (hurtEntity instanceof Player) {
const resistance = hurtEntity.getEffect('resistance');
console.error(`Damage: ${damage.toFixed(1)} | Resisted Damage: ${resistance ? damage / 1 - (0.20 * resistance.amplifier) - damage: 0.0}`);
}
});```
I have "Resistance II" btw
Ohh lmao
true.
amplifier starts at zero, you need to add 1 to get its level
world.afterEvents.entityHurt.subscribe(({
hurtEntity, damage
}) => {
if (hurtEntity instanceof Player) {
const resistance = hurtEntity.getEffect('resistance');
const originalDamage = damage / (1 - (resistance.amplifier+1)*0.2)
console.warn("Damage: " + damage + " | Original Damage: " + originalDamage)
}
});
Ok that's why I keep changing the values it's still not working lmao
Lemme try this first...
why are you adding 1 to the amplifier?
ah right
Made a command manager.
the command looks like hell himself
I'm starting lost my mind here....
"?" ?
I don't have effect but why it's 5.625
imma take a look, wait
You need to check for the presence of the effect
I know that's why I put it 0
forget it, i made a mistake
Where did you put 0?
world.afterEvents.entityHurt.subscribe(({
hurtEntity, damage
}) => {
if (hurtEntity instanceof Player) {
const resistance = hurtEntity.getEffect('resistance');
const originalDamage = damage / (1 - ((resistance?.amplifier || 0) + 1) * 0.2);
console.error("Damage: " + damage + " | Original Damage: " + originalDamage);
}
});```
put -1
no..
world.afterEvents.entityHurt.subscribe(({
hurtEntity, damage
}) => {
if (hurtEntity instanceof Player) {
const level = (hurtEntity.getEffect('resistance').amplifier + 1) || 0;
const originalDamage = damage / (1 - level * 0.2);
console.error("Damage: " + damage + " | Original Damage: " + originalDamage);
}
});
I changed something, copy again
@dim tusk
Yeah I copied it already
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
I can say it's working but not 100% accurate
One message removed from a suspended account.
You can use this random and do it something like this
let menu = new ActionFormData()
for (let i = 0; i < 4; i++) {
menu.button(Random.element(["Button 1", "Button 2"]))
}
Because having no effect returns 4.5 flat, while having an effect the original damage returns 4.50000000.... and other numbers instead of just flat 4.5
const originalDamage = Number((damage / (1 - level * 0.2)).toFixed(1))
One message removed from a suspended account.
const cards = [].sort(() => Math.random() - 0.5).slice(0,4)
One message removed from a suspended account.
[] will be ur part to fill in, with string (list of all cards)
The for loop starts creating the button 4 times, and when creating the button you specify random text via Random.element
But in general, you will still need to remember what text each button has, so..
let menu = new ActionFormData()
let buttonValues = []
for (let i = 0; i < 4; i++) {
let value = Random.element(["Button 1", "Button 2","Button 3..."])
buttonValues.push(value)
menu.button(value)
}
floating point error
Damn, looks like I need to take account other effects too, like regenerations or instant health
damage in entityhurt just returns how much health entity lsoe
Yo does the block in playerPlaceBlock beforeEvent return the block being placed's location? (I assume not because there is a permutationBeingPlaced so how would I get the new block's location?
world.beforeEvents.playerPlaceBlock.subscribe(data => {
let block = data.block
})
It says block being impacted by this event
and?
And why would they have permutationBeingPlaced if I can just get the typeId from the block straight up... right?
TypeId & perm and anything else
You can’t, because the block is still only air
Okay so basically what you are trying to say is block is the block being placed but isn't Readable until I exit read only mode right?
data.block is an object with the Block class with which you can do anything, but you have no information about what block the player is placing because data.block is air since the block has not yet been placed, for this there is permutationBeingPlaced which tells you what the player is going to place
beforeEvent means it runs BEFORE the event happens.
In this case, the code runs before the block is placed physically in the world. So its block.typeId would still be air.
This is where permutationBeingPlaced comes into play, containing future information about what's being placed.
is it possible to rotate the camera in the z axis?
Tilting? no
pain
What extension do you use to make it show the result of the operation?
how minecraft caculates fishing rod pull mechanic?
loot?
I'm using the Inline Math Extension
how do i make it drop the item
bro what, you need help
While reading the list, I fell like living in germany (I'd live there)
how to make an entity break a specific block so that it executes the entityHitBlock event?
does the sign component have setGlow() or something like that?
Nope
Probably might be within it's states
The like block permutation's states ig
Take a look ig: https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.BlockSignComponent-1.html
but there is only face direction
it is not
Don't spite me y'all, I said "probably"
Not straight up "it is"
Also BTW does the permutation of the spawner return the mob spawner type?
Probably not right?
that why i said "it is not"?
so there is not space for doubt
mob spanner type?
Alright then, problem resolved, have a great day sir!
Yes
you are referring to the mob?
Yes, like the mob that is getting spawned within that spawner
no it is not a permutation
wait for a mob to spawn...
Welp :)
How can I detect when the player is sneaking?
player.isSneaking
Thanks
? Its fun lol. I'm just a nerd
Are there any fixes in the api to the current dupe which involves leaving
Use setblock or fill to destroy block...
What's the error?
LINE 41 -->mc.world.beforeEvents.worldInitialize.subscribe(initEvent => {
initEvent.blockComponentRegistry.registerCustomComponent('hash:tube_component', tubeComponent);
});
Isn't this afterevents not beforevents?
This worked before the mine update
Change the version of the scripts in the manifest from 1.16.0-beta to 1.17.0-beta
I'm using 2.0.0-alpha
Ok
Is there no official version that works? Or just beta?
for minecraft version 1.21.50 maximum you can use 1.17.0-beta
Okay, thanks
for (let i in ['red', 'green', 'blue']) {
console.log(typeof i)
}
What do you expect this loop to output?
string
yes, this has me stomped for a while
whats wrong?
you would expect i to be 0, 1, 2
but it is '0', '1', '2' which got me confused for my code isn't working
Why? loop iterates through the array
Yeah I expect i to be a string since its looping through an array.
thats what a for of loop does. A for in loop loops through the object keys as far as i know
Oh, well, yes. in iterates over the properties of the object so the output should be number
In this case yes
i am even more confused now
nah the object keys will always be strings regardless
Just tell me what you need to iterate through the loop
it outputs 0,1,2 but as strings as arrays are just objects where the key is the index
i have my problem solved, i am just mad this was the reason
so in gives you the keys of the object?
if i replace my array with an object i would get the keys?
You might wanna do of instead.
I dont even know what you are trying to do so I can't tell you
i just added a plus sign before it and that solved my issue
+i convert i into a number
@simple zodiac
What's your problem? The loop iterates over the object's keys, the key is always a string so typeof i outputs a string
again, i don't have a problem, i find it interesting that i is a string and not a number, but now i know why
so does of return the values an object?
yes
that means i could use:
1 of [1, 2, 3]
instead of:
[1, 2, 3].includes(1)
no
huh
of only works in loops as I know and it returns an iterator of the object's values
why does in work outside loops while of doesn't
Maybe it works, but I don't know
👀
I am running my bedrock server in a Docker on my unraid server. And i cant get server -net activated in my permission file in the config folder. I do delete the file you need to delete to add a new config. But at startup it just overwrites the new config file with the old one. Can it be because im not running the official server on Windows? Or a Docker bug?
it doesn't return anything
it is used to iterate over the values of an iterable object, for...of loop is the only use case for "of"
I made a script that activates a death scene after the player is killed by a certain entity the problem is that entity summons another entity so the script won't work how do I make the entity be treated as the same as the original entity?
yeah, kinda weird tbh
how so
i mean, in when used outside a for loop returns if a key is found in an object: 'x' in {x: 1} returns true, you would expect the same works for of but it checks if x is found as a value in the object
One message removed from a suspended account.
One message removed from a suspended account.
Use forEach
function zanjutsulevel(player) {
let zanjutsumoves = [
{ texture: "textures/ui/levelup/whirlwindslash.png", tag: "whirlwindslash" },
{ texture: "textures/ui/levelup/nightjarslash.png", tag: "nightjarslash" },
{ texture: "textures/ui/levelup/ichimonji.png", tag: "ichimonji" },
{ texture: "textures/ui/levelup/cross.png", tag: "cross" },
{ texture: "textures/ui/levelup/flash.png", tag: "flash" }
];
let randomZanjutsu = zanjutsumoves.sort(() => Math.random() - 0.5).slice(0, 4);
const zanjutsulevel = new ActionFormData();
zanjutsulevel.title("§d");
zanjutsulevel.body("");
randomZanjutsu.forEach((move, index) => {
zanjutsulevel.button(`§d${move.tag}`, move.texture);
});
zanjutsulevel.show(player).then((res) => {
if (res.selection !== -1) {
player.runCommand(`say card ${res.selection + 1} chosen`);
player.runCommand(`playsound jjk.menuclick1 @s ~~~ 10000 1 10000`);
}
});
}
One message removed from a suspended account.
One message removed from a suspended account.
You want every button has its own run command?
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
function zanjutsulevel(player) {
let zanjutsumoves = [
{ texture: "textures/ui/levelup/whirlwindslash.png", tag: "whirlwindslash" },
{ texture: "textures/ui/levelup/nightjarslash.png", tag: "nightjarslash" },
{ texture: "textures/ui/levelup/ichimonji.png", tag: "ichimonji" },
{ texture: "textures/ui/levelup/cross.png", tag: "cross" },
{ texture: "textures/ui/levelup/flash.png", tag: "flash" }
];
let randomZanjutsu = zanjutsumoves.sort(() => Math.random() - 0.5).slice(0, 4);
const zanjutsulevel = new ActionFormData();
zanjutsulevel.title("§d");
zanjutsulevel.body("");
randomZanjutsu.forEach((move, index) => {
zanjutsulevel.button(`§d${move.tag}`, move.texture);
});
zanjutsulevel.show(player).then((res) => {
if (res.selection !== -1) {
player.runCommand(`say card ${res.selection + 1} chosen`);
player.runCommand(`playsound jjk.menuclick1 @s ~~~ 10000 1 10000`);
const selectedMove = randomZanjutsu[res.selection];
switch (selectedMove.tag) {
case "whirlwindslash":
player.runCommand("say whirl!");
break;
case "nightjarslash":
player.runCommand("say nightjar!");
break;
case "ichimonji":
player.runCommand("say ichimonji!");
break;
case "cross":
player.runCommand("say cross!");
break;
case "flash":
player.runCommand("say flash!");
break;
default:
break;
}
}
});
}
I'm not kinda sure if this works well you can just try it
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
Lol didn't think it'll actually work... Your welcome tho
All I want for Christmas is to be able to detect the data and set the data of the item using script's
How do I set up VS Code?
I want it to work like bridge, but without using bridge lol
first step... At least have a device that can handle the heavy loading
Second step... download vscode 🤷
I did
What next?
checking it out
How can I pass the responsibility of being a damagingEntity cause I have an entity called smile there is this attack called stomp where it summons another entity called mz:stomp, this entity disappears after 0.1 seconds so how can I pass it's responsibility of being a damagingEntity to the original entity smile
Is there a way i can run a command in a specific location, via dimension
whenever i use it, i only runs at 00 can i change the location
Does anyone know how to add extra buttons to the normal player interface?
Damn, three questions in a row
answer mine first 🥺
What are you trying to do why you want to change location of running the command?
Or what command you trying to run?
Wym by normal player interface???
I guess this is not possible then?
Yes, I once saw a "Chinese" addon in which there were 3 buttons apart from the normal ones that executed abilities after being pressed
It's quite old and I couldn't find the video, but the addon was paid
Umm, Chinese mods are kinda different to ours, it's easy for them to add buttons that run commands or whatever compared to ours yes we can add buttons on screen but limited to
I understand
im trying to break a block using scripts, so i want to run a fill command at the location of the block
Any alternative ways around this?
A question someone here who knows to update custom npc please thank ????
Wdym
???
Guys is this possible?
how can a memory leak be caused by script api
run a setblock then if you want to drop its loot too
How do I set a volume with world.getDimension().getBlocks()?
what behaviour haves the "stomp"?
like, melee attack?
Yes its another entity with an area attack
just area attack?
Yes
you can make via scripts that attack and set the damageSource to the original entity
Oh so it's possible can you give an example
but you should remove every damage behaviour in your json
Well the entity disappears for 0.1 seconds so no problem
your original entity uses an event fot that specific attack?
Yes, I have a component called timer_flag_1 and in the animation behavior side that's where I activate the event
const attacker_original = ...;
const attacker_summoning = ...;
const maxDistance = 5;
attacker_original .dimension.getEntities({ location: attacker_summoning .location, maxDistance })
.forEach((e) => {
e.applyDamage(10, { damagingEntity: attacker_original });
});```
then you should use dataDrivenEntityTrigger after event
I see okay I'll try doing that
Are you doing the "stomping" mechanic?
?
This is what I'm trying to achieve
import BlockVolume in server
use entityspawn you can get the cause of spawning
Wait my entity smile is summoning an entity through a component called spawn_entity and the method I assigned is born in the spawnEntity event listener there are only 2 parameter which is the entity spawned and the cause how can I check the entity that spawned it?
alr thanks
hey guys, do you know how to read shulker box content from the inv of a player? I tried it via playerBreakBlock and it worked with BlockComponentTypes, but if I try that with the inventory container of a player and blockcomponenttypes it doesn't really work (it doesn't give out any info). Does anyone know how to get that info?
Nope
You can't read shulker box contents from the inv of a player
do you know any other method that could bring this to work?
You could read it if you placed it because of the block inventory component much like the entity inventory component
There are no other methods
What's the new chatsend subscribe?
I mean just ask the player to place the shulker then on the playerPlaceBlock after event, read all it's data, and use setblock (block coords) air destroy and get the nearest item in that coord, and give the player a copy and kill it... ig?
It has existed for centuries at this point. It fires after a message is sent in chat
Doesn't work for some reason
But only the beforeEvent has existed tho, now you have an afterEvent! yay!
Why isn't it working used to work before
I'm getting a error that the subscribe isn't right
I tried before events
You can't cancel an afterEvent.
No like the whole subscribe is wrong it says
Also why use ```js
for (const recipient of world.getPlayers()) {
recipient.sendMessage(formattedMessage);
}
When you literally don't have a dead players system, not a trolling system or anything to filter who to send the message to?
cause it's AI generated
the AI doesn't know to just use world.sendMessage
How can I do this?
Really...?
If you fed it enough docs & npm it still wouldn't know?
nope, it's stupid as hell
first time it'll just hallucinate like shit, then you tell it your errors, then it'll go "Ah you're right, here's a slightly fixed version!"
rinse and repeat
and it eventually ends up with obscure redundant code
I mean I don't rely on AI except on a bit of language assignments as I am pretty dumb in German but yeah I double check the answers
that works, but there's better ways
because it'll get stuck on how it wants to do it
Is possible to detect if an entity spawned detect the entity that spawned it?
Otherwise I haven't used more then like 4 times to create some php & sql code examples.
no
entitySpawn afterEvents
Nah. Just use playerInteractWithBlock beforeEvent or afterEvent and pair it with entitySpawn & an entity map to get a pretty accurate who spawned the entity detector
Help
it's getting spawned through a diff entity, so no player
Welp
It has only 2 parameters the entity spawned and the cause not the spawner
Switch your manifest @minecraft/server depedency to the latest beta
- Delete whichever AI you're using, as I've told you before
- Use the chatSend before event, you can't cancel the afterEvent
- check that you are using the beta api, the chatSend beforeEvent isn't available on stable.
- quick tip, replace the last player loop with just
world.sendMessage()
1.17.0-beta
Okay why not, trigger an event with the spawn_entity thing and in the event make it queue a scriptevent command and detect that signal and it's source and do your code ez
That's not ai that's my old cose
Code
I tried beforeevents
You've used AI before, and I don't believe you. That is AI generated code
as per the comments
very easy to tell
Did you even read the rest, check ur manifest.json
My pc discord not working
- Rejoin the world.
- Maybe the older version of the pack got cached onto the world folder
-# screenshot will be saved to your clipboard
bump your version up to 2,0,1 and then reimport
Need to clear cache
Can you explain this more
You guys thing the prefixes are pretty "readable" and easy to keep in mind?
-n <repeat_count: number>
-c <command: string>
-p* <raw_parameters: string>
-rx* <feedback_receiver: player>
Why not just compile the js code from the message via eval? Why invent your own language?
Reinstall it or kill the Task in the Task Manager
Its more like a command manager in minecraft
Not a own lang.
This looks like something that is very difficult to read
thats a simple use of it
*tp -l 0 0 0
// or
*tp -p "player1" -l 0 0 0
Is this still diff. to read?
-_-
Well, you gotta add a lot of instructions or references and what each keyword does
what does - signify? l?
-l is a parameter
i say that -l haves 0 0 0 and -p haves "player1
Kinda like in python when you say
arg1 = value inside a function call
It's pretty compact, but without context, we can't really rate it if it "readable" or not
How?
Scrap that, Look at other approach
i got a help command that shows the given parameters and their types.. so i think with a little instroduction it will be understandable
Oh I thought you know something that I dont
@warm mason why not?
Okay so I'm not too good with entities butt, yes with another t, I'm pretty sure you can trigger an event like "event": "ds:sayWhoSpawnedMe" and then have an event setup (all this is within the entity file still),
// events object of your entity
"events": {
"ds:sayWhoSpawnedMe": {
"queue_command": {
"command": [
"scriptevent ds:sayWhoSpawnedMe 0123210"
]
}
}
// any other events if you have any (make sure to put "," at the end of this event if you you wanna make other events)
}
and in your Scripting part do:
system.afterEvents.scriptEventReceive.subscribe((data) => {
let entity = data.sourceEntity, id = data.id, verificationCode = data.message;
if (id !== 'ds:sayWhoSpawnedMe') return;
//if (verificationCode !== "0123210") return;
world.sendMessage(entity.typeId);
});
BTW verificationCode is extra from me, you don't need to use it.., if you want to use it just uncomment it.
@ruby haven
Oh I never new there is a method called scriptEventsReceive thank you so much this unlocks a lot of more possibilities for me
I edited it again, use it now, and you're welcome!
How do I grab every block from an area and run something from it?
I've tried -
const test = new BlockVolume({x: 0, y: 0, z: 0}, {x: 0, y: 0, z: 0})l
const blocks = world.getDimension().getBlocks(test);
obv the coords are diff
but it doesn't give me the array of blocks
and I want to run a forEach on all the blocks in that volume
and I'd rather not do a getBlock for each individual block location in an area
getBlocks returns another block volume. What you need to do is
for (const block of blocks.getBlockLocationIterator()) {
...
}
ah, thanks! And that runs from every block?
I didn't know LocationIterator grabbed the,
them*
thanks
unfortunately, it's saying that the value in not an iterable
nvm, ignore me
forgot to make it a function
/docs info
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]
curiosity got the best of me.
Aside from the ambiguous wiki that just lists functions, components and modules.
Is there a resource that explains how to just write a script in simple terms.
Namely, if you were to make a custom block component with an interaction, place, detect other blocks, or just do an event.
Isn't there a document that explains how to format/assemble a script file?
And if the answer is learning JavaScript, would this mean doing a whole course on that would magically mean you can write Scripts for Minecraft Bedrock addons?
And if the answer is learning JavaScript, would this mean doing a whole course on that would magically mean you can write Scripts for Minecraft Bedrock addons?
Yes.
If I do so and find out that the way the scripts are formatted is not the same. Imma be upset.
(all of this over a project with friends that did not need these things......)
Scripts are run on quickJS. Which get compiled into c++.
They don't get compiled. They're just interpreted at runtime
@wary edge Hey, do you know if there is a area where I can reach out to Scripting Devs ( mojang ) of ideas for stuff
🤷 Devs always lurk here. You can always brainstorm or use the official feedback discord.
Okay thanks, I want to try to get them to add more Behavior pack readings to scripting like Display Names as a example
Display name is client side tho
yet its defined in the BP
Ohhhhh that part
blame them for having so many format for key translations
Translation keys are so cooked 😭
uh wdym
wth is dat
RP lang file translations
Yeah, they could do the BP pack side though
i recently made a mapping for vanilla item translations, it was a lot of effort
is server-net not able to use express servers??
i've used a http request in minecraft and the same for fetch in node.js both to the same server same setup fetch worked and gave the data but minecraft server-net didnt
it returned an empty object
Guys, can you detect if banner have designs already like you already used them in loom....
If not can commands do it?
no to both
commands can only detect the base color
Damn that's sad.
Is there a method to manually load a chunk script side?
Terrible practice for learning a language actually, I can tell u from learning spanish
I wish there was something that would hit you upside the head and say... you hjave single equal signs in your IF statement...
Vscode extension 
There is also a practice for that, that says you should never do var == 1 but rather always 1 == var so the engine can throw an error for that
/tickingarea and entities with component tick_world only way that can load unloaded chunks
(But I forgot the name of it since I dont ever run into that problem and wrote it off as irrelevant)
I have a ton of extensions, but non that catch that slip up... I have to catch it after I pull my hair out
thats what I thought
wondering if there was a js api i didnt know about
Remember that tickingarea can save 10 areas only
How is chunks loaded actually calculated in the debugger?
I could imagine there being a vscode extension just for that single purpose lol, considering how many there are
I have 12 chunk radius, 12*12 at most should be 144?
Check the documentation of that plug-in maybe you'll get math used
Is that vscode?
yes
(Apparently) found one!
https://marketplace.visualstudio.com/items?itemName=PhilHindle.errorlens
😂
feels cursed
Agree
Ticking chunks are the "loaded" chunks, where stuff is actually happening
loaded just means they're been loaded from the disk into memory
Yes I understand that
But nothing should be happening, sicne its just me with a 12 render distance
wait
the chunks still tick
I installed it and did this.. and nada ```js
let v = 0;
if (v = 4)
return;
Damn
you will notice it overtime
I am usually pretty good about it.. except when I'm not... I tend to write a lot of code and then test.. I've gotten good enough to do that... but when I miss this occasionally... takes a while to troubleshoot. I had this... js if (grid4.y = 0) newBlockFace = 'down'; else if (grid4.y = 3) newBlockFace = 'up'; else if (grid4.x = 0) newBlockFace = getPerpendicularFace(eventFace, 0); else if (grid4.x = 3) newBlockFace = getPerpendicularFace(eventFace, 1); ); else newBlockFace = eventFace;
const sign = world.getDimension("overworld").setBlockType({ x, y: y + 2, z }, "minecraft:oak_sign");
``` Has anoyne tried messing aorund with signs?
Seems as if signs are not a block
What about it?
How does one place a sign?
try standing sign instead.
MinecraftBlockTypes dosnt seem to be a valid export from @minecraft/server
is there a raw id for that?
Check in-game or the mc wiki. I can't check right now.
thanks
should just be oak_standing_sign... should
what is the difference between in and of in a foor loop? i used in accidentally instead of 'of' and it didn't work
in - keys
of - values
ahhh, thank you
const signBlock = world.getDimension("overworld").getBlock({ x, y, z });
const signPerm = BlockPermutation.resolve('minecraft:standing_sign', { ground_sign_direction: 0 });
signBlock.setPermutation(signPerm);
const signComponent = signBlock.getComponent(BlockComponentTypes.Sign);
signComponent.setText({ translate: 'item.skull.player.name', with: ['Steve'] });```
just BlockTypes
Because it's in vanilla-data
Which is not built in you need to get the bundle
An you can just signBlock.getComponent('minecraft:sign')
I have a simple functions that detects detects if player eats a cake but if the cake is in last eaten state when player interact it, it can't detect since it disappears do anyone knows a fix?
const blockPerm = new WeakMap();
world.beforeEvents.playerInteractWithBlock.subscribe(({
block, player
}) => {
blockPerm.set(player, block.permutation);
});
world.afterEvents.playerInteractWithBlock.subscribe(({
block, player, beforeItemStack, itemStack
}) => {
const stats = JSON.parse(player.getDynamicProperty('stats') || '{}');
const blocks = blockMap[block.typeId];
const perm = blockPerm.get(player);
if (blocks) {
if (perm && perm !== block.permutation) {
switch (perm.type.id) {
case 'minecraft:cake':
console.error('Eat Cake!');
break;
default:
break;
}
} else if (
perm.type.id !== 'minecraft:cake'
) {
console.error(`${block.typeId}`);
}
}
});```
You can npm it
npm i @minecraft/vanilla-data
into a separate folder, then go into folder in picture... (the other folders, is cause I NPM everything in one place. Index.js has a ready to use file, but yse the Prettier formattin on it, so it is more readable
drag and drop where you need it.
Thank you for your help
import { world, GameMode } from "@minecraft/server";
/** @type {import("@minecraft/server").BlockCustomComponent} */
const CreativeModeOnlyBlockComponent = {
onPlayerDestroy(event) {
event.block (block.typeId === "jay:coal_ore")
event.player (entity.typeId === "minecraft:player")
entity.runCommandAsync("execute @s ~~~ say broke coal ore");
}
}```
im trying to make it so when I break my custom block it runs a command but im not getting any errors logs?
in my content log
what is "onPlayerDestroy"?
oh I see, I was very confused by the variable
no your okay
It may be due to the execute command being changed from the old format
execute as @s run say broke coal ore
no my other pack with scripts work without the new one
interesting
