#Script API General
1 messages · Page 49 of 1
If necessary, the player could be nearby (but not exactly) where the mount is, and then the camera could maybe be projected there (this to prevent constantly teleporting the player/mount, which disrupts velocity and thus prevents WASD detection).
Are there ways to detect the velocity of a player or mount if the mount is teleported every tick?
keepVelocity?
I tried that, but it didn't seem to do anything.
Even on my previous project, keepVelocity never really worked.
i meant on mount
not the player
Yeah, the mount is being teleported with keepVelocity set to true.
or you can just get velocity before tp
Lemme see if that would work.
Nope. The velocity is still locked to 0, even if you get it before the teleport.
how are you teleporting the mount
what condition
The mount obeys a physics simulation, and must teleport every tick.
Though the entity that is doing the physics simulation and the entity that the player is actually riding do not necessarily have to be the same entity.
maybe do
if(vel.x != 0 || vel.y != 0 || vel.z != 0){
//tp
}
if that won't cause problems for u
The entity will be moving constantly.
for a tick
Lemme try teleporting it every other tick.
I think ill just re texture useless blocks
Teleporting the mount every other tick permits gathering velocity data every other tick also.
Umm, yeah detecting velocity or player while reading is kinda weird than just not riding.
Seems so. Unfortunately it is necessary that the player is riding a mount here.
and you can't detect the velocity of the entity riding since it has the same results
The every other tick approach seems like it will work though, at least for my purposes.
I see many new players, nice
Quick JS question...
If I have something like this js export const vanillaItems = Object.values(MinecraftItemTypes); export const vanillaBlocks = Object.values(MinecraftBlockTypes).filter(b => vanillaItems.includes(b)); export const woodTypes = vanillaBlocks .filter(block => block.endsWith('_planks')) .map(s => s.replace('_planks', '')); does it evaluate all of that each time I access woodTypes or is it set once? Trying to see if I should make a one and done class and import that so extra work is not done...
Which part you are referring to?
the last const.. woodtypes. Does it run the filters/maps and does that cascade back up the chain?
does it do it each time
No, I don't think so, unless the script re-runs every time qhile being imported
So imports, imports the final version
test it with Date.now() 🙂
It will have different times if it re-runs every time; else will be static.
How to detect when a player steps on a specific block
can someone tell me what am doing wrong
system.runInterval(() => {
const platform = PlatformType
switch (platform) {
case platform.Console:
console.warn("Running on a Console.");
break;
case platform.Desktop:
console.warn("Running on a PC.");
break;
case platform.Mobile:
console.warn("Running on a Mobile.");
break;
}
}, 20);
you should loop through players
import { world, system, PlatformType } from "@minecraft/server";
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
switch (player.clientSystemInfo.platformType) {
case PlatformType.Console:
break;
};
};
});
I would like to add that if PlatformType is defined somewhere else as player.clientSystemInfo.platformType then you shouldn't be checking each switch case for platform.Mobile, platform.Desktop, or platform.Console since player.clientSystemInfo.platformType will return the type itself and those properties don't even exist. Therefore checking for "Console", "Desktop", and "Mobile" would be the appropriate way. I can only speculate because your segment of code appears incomplete so I'm unsure what other bits you have @glacial widget.
is their any way to compile identifiers in a single file?
what exactly is read only mode and how its useful?
It prevents the world from being changed at all while it’s active. Read-only mode is active when a before event is ran
compile identifiers? wdym?
nvm i got it
made a .py to compile all the ids in my pack
Guys how I can get the location of structure example a village that near in my location using script
Hello one question, you can deny damage via script?
Maybe you can use commands? /locate but via script and after that look for the callback, i don't know if it's possible but there's an idea
Can’t really
Damage sensors still the best option
thnks
function repairItem(player) {
const equip = player.getComponent('equippable');
const item = equip.getEquipment('Mainhand');
if (!item) return;
const durability = item.getComponent('durability');
if (durability) durability.damage = 0;
equip.setEquipment('Mainhand', item);
}
what is messageRecieve after event supposed to be?
its item.typeId not item.id
chat message i assume?
in the docs it says This event is an internal implementation detail, and is otherwise not currently functional.
that most be new
didn't see it last time i checked
Guys, do you know how to track damage received from a player?
world.afterEvents.entityHurt.subscribe(data => {
let entity = data.hurtEntity
let damage = data.damage
if (data.damageSource.damagingEntity?.typeId == 'minecraft:player') {
// code
}
})
Thanks a lot
is it better to do a runinterval with 20 ticks that has all the work on it
or
is it better to have 1 runinterval with 10 ticks but with half the work alternated between cycles?
let cycle = false
system.runInterval(() => world.getPlayers().forEach(player => {
const inv = player.getComponent('inventory').container;
const size = Math.floor(inv.size / 2)
for (let slot = cycle ? 0 : size; slot < cycle ? size : inv.size; slot++) {
// other long code
}
cycle = !cycle
}), 10);
// or
system.runInterval(() => world.getPlayers().forEach(player => {
const inv = player.getComponent('inventory').container;
const size = Math.floor(inv.size / 2)
for (let slot = 0; slot < inv.size; slot++) {
// other long code
}
cycle = !cycle
}), 20);
whats more performance friendly
let playerIndex = 0
system.runInterval(() => {
let player = world.getAllPlayers()[playerIndex]
if (player == undefined) {
playerIndex = 0
} else {
//code
}
})
thank you i didnt think about this method
guys, im having this last piece of script i pretty much need to optimize, can i get some help pls? this is the one that causes slowdowns as i found out, i need to do something with it, but i cant find any alternatives and afraid i lack some knowledge to figure it all out by myself
these r the events that r running every tick, because i dont know about any other aletrnatives for these events to be more optimized or work in a different way except for running every tick
I think if you tell me what you want, I can write another script for you
i think everything that i want is written in that script, but alr there r a few events, rn, im getting an idea for geyser erupting event, to make it so the interval wasnt running all the time for entities, checking if the block under them is the erupting geyser, but call this interval once the entity steps on the erupting geyser, and when entity steps off the erupting geyser, clear the interval
but that's an idea only for geyser, then there r others
I don't understand what's in your code. Tell me what you want to do
all other events r:
- entity gets damaged when there's lit copper campfire under it
- entity gets damaged and set on fire for 8 seconds when it is in copper fire
- if a digging woodlouse detects bedrock under itself, it runs event on itself
- player gets stunt when it is in mobtrap, can move again when not in a mobtrap anymore (if mobtrap is broken), and gets damaged when in the mobtrap
- player gets health boost when wearing a full emerald armor set
- when player is wearing strider boots and steps on lava, player fill lava and flowing lava in 2x1x2 radius under itself with fragile magma block
- the fog script which adds the fog to the player when it is in the end and it is above certain block, and fog gets removed when player is not above certain blocks or isnt in the end anymore
- item lore getting added to the items in player's inventory
i'll deal with geyser script myself since ive got an idea that could really work
i dont really want someone to write the whole script for me, its my duty, and i just dont want to put it on someone else since its my problem, but on the other side i need help
Some of the stuff can be replaced with native methods, but given what you are aiming for, I would recommend using runJob() versus runInterval() and yielding after each player in the for loop.
I can suggest this:
- Use custom components for campfire, run interval when an entity steps on a campfire and do whatever you want, delete interval if the entity is no longer above the campfire
- You can run interval for all entities, to search for bedrock. Or just use sensor in json entity.
- Use custom components for traps
- To detect armor on a player, use interval with a delay (or look at the code I wrote above to optimize the interval)
for traps and copper fire, not really bcs it require the block to have a small collision, but this mobtrap is like a plant, it doesnt have any collision, so onStepOn wouldn't work, and, running the intervals once triggered and then deleting them, im starting to understand it and experimenting on it rn with geyser, and then will move it to other blocks like campfire if the plan works
This is the 100k'st
|| hundredth message which was "hundred thousandth" ||
hi there, is it possible to use EntityQueryOptions to filter family type to get entities?
#1067535608660107284 message
alr, so, everything is working, but i'm getting this error
17:35:35[Scripting][error]-TypeError: Native type conversion failed. Function argument [0] expected type: class Scripting::Closure<void __cdecl(void)> at <anonymous> (geyser.js:36)
and this is what i have
if (lavaGeyser && block.isValid() === true) {
block.dimension.spawnParticle('v360:lava_geyser', { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 })
block.dimension.spawnParticle('v360:lava_geyser_smoke', { x: block.location.x + 0.5, y: block.location.y + 0.5, z: block.location.z + 0.5 })
block.setPermutation(erupting)
system.run(launchingInterval)
}```
that system.run() is the 36th line
i dont understand y im getting this error
system.run wants a function as an input. Make sure that is the case
i have a const for launchingInterval system.runInterval, and that's how im triggering it
const launchingInterval = system.runInterval(() => ...)
does not return a function but rather a number. You can not pass that to system.run
oh, so how do i make it like u said as a case?
you don't need to do it at all
I don't even know what you are trying to do
but
runInterval already schedules the operations into ticks
yes actually
i just need to run this interval first, and then remove it
that's how im triggering
you don't need to trigger it, it run automatically
not like functions
oh of you want to clear the interval you have to use system.clearRun(runId (in your case launchingInterval ) )
the question is why do you need an interval to run a code once
no no no, look, i have a geyser, and when it erupts, an interval needs to be triggered, that will make entities above the geyser get launched every tick, and when the geyser stops erupting, to not cause lag from this interval that runs every tick, i want the interval to stop, and then get triggered again when geyser erupts again
can i send the whole code? it's just quite big..
you can send the file
but why?
bcs i need some help with it and if i'll try to explaine what im trying to do i'll probably confuse u
so here, i have a onRandomTick event, and so on random tick geyser erupts, and while its erupting it needs to constantly lauch entities above it up a lil bit, and when it stops errupting, i want to clear the system.runInterval to it didnt lag out the game
you should probably just make this an entity and use animations for the visual stuff..
why not use on step on event
bcs if the entity is already standing on the block and the geyser erupts, the code won't work, entity will have to walk away and then step on the block
it wont constantly affect the entity, its only when they first move on the block.
basically, all i need to do, is trigger system.runInetrval and then clear it, so it wasnt ticking all the time and would work only on needed occasion, so it didnt lag the game
store the run id in a dp:
const launchingInterval = system.runInterval(() => {...}
world.setDynamicProperty(JSON.stringify(block.location), launchingInterval)
to clear it, use:
const launchingInterval = world.getDynamicProperty(JSON.stringify(block.location))
system.cleratRun(launchingInterval)
i kinda get it
i haven't learnt about dynamic properties yet, but im understanding how this works
it works🥹
i checked if the interval is still running but testing for other block tag under entity, and it isnt running anymore, its getting cleared
Why use DP?
It would be better to use WeakMap
the variable is in a different scope
you can use maps, but same deal
Dynamic properties can clog files over time. This is not very critical, but why?
he is clearing it...
you can also clear it when the block is broken
maps are a good idea, but not persistence between world restarts
i mean, you can suggest a better option if you have any
system.runInterval is cleared after a restart and DP may remain and WeakMap will be cleared, so there are no disadvantages in it
yeah, that is true
It said 99998 before tho
There are already 400,000 messages here..
Damn
what's the minimum size of a block collision block (in height) there has to be for onStepOn to work? i have a 16x2x16 block collision, but the onStepOn event isn't being triggered
y needs to be 4.
Oh
well
the way we did it in our JAM submission was that we made it a full block, but visually slightly larger for the pressure plate to make mines
one question can you cancel the event from taking out stuff like from chests or shulker boxes?
You can cancel the chest opening event, or lock all items in their slots
function testing(player) {
new ModalFormData().title('test')
.textField('test2')
.slider('test3', 0, 3, 1, 0)
.submitButton('testbutton')
.show(player)
.then((response) => {
if (response && typeof response.selection === 'number') {
switch (response.selection) {
case 0:
function1(player);
break;
case 1:
function2(player);
break;
case 2:
function3(player);
break;
case 3:
function4(player);
break;
}
}
})
}
What's wrong here?
yeah ik this but thx xd
wait im testing this
This is error
you have to use system.run i think
.textField('test2') -> .textField('test2', '')
Now there is an error
function testing(player) {
new ModalFormData()
.title('test')
.textField('test2', 'Enter text here')
.slider('test3', 0, 3, 1, 0)
.submitButton('testbutton')
.show(player)
.then((response) => {
if (response && typeof response.selection === 'number') {
switch (response.selection) {
case 0:
function1(player);
break;
case 1:
function2(player);
break;
case 2:
function3(player);
break;
case 3:
function4(player);
break;
}
}
});
}
here
@meager cargo is this working?
The same error: TypeError: not a function
submitButton is doing errors
I get rid of that and it worked
xdd
Thank you very much!
item lock don't work outside player inventory
Did i do this right
world.events.hasTag.subscribe((eventData) => {
let player = eventData.player;
if (player.hasTag("warp")) {
showWarpMenu(player);
}
});
no
What part is wrong
iv changed it like 12 times
I dont mess with World events
system.runInterval(() => {
for (let player of world.getPlayers({tags: ['warp']})) {
player.removeTag('warp')
showWarpMenu(player)
}
})
Well yhay i did not think it that way
What the hell
copy again
Thanks
May want to add the interval so it is not going every tick. Humans only need 10-20 tick for 0.5-1 second response
We "can't" get player alt accounts with script api yet right?
What's the method currently used rn?
For bds only?
There's a way to get alts!?
I thought there was for bds, it's been mentioned before
Hmm
Or i could be loosing it
Lmao
Some people from another server said they used to have a flag system for alt accounts
Idk, I'm not saying it's true or not
Could be a mix up
I don't host or have a server so I don't have enough experience in this stuff
So uhh
I'm trying to make it so that damage can be cancelled if the other player has a certain tag but I can't find a beforeEvent for it
Unless i need to do that with player.json
No before event yet for scripts, have to use player.json for now
Epoxy? Uhhhh yeah you use it to glue stuff together

someone tossing random tech words at you
Yeah haha
I don't mind acting dumb here, I get roasted regardless
i wasn't roasting you lol
who ever told you you can do that is just saying random stuff
Alrighty haha, nah I'm just saying in general I get roasted all the time, not you specifically
Ok cool thanks for info
why was pistonActivate beforeEvent removed?
bugged or something
https://wiki.bedrock.dev/meta/blocks-items-qna.html#immovable-blocks
hm
Is there a way to disable / change crafting recipies for like wooden sword or diamond leggings.
not a script api question
you can download the bedrock samples to find recipes and you can change them
https://github.com/Mojang/bedrock-samples/releases
Is there a resource for connecting blocks?
is it possible to make blocks breakable in adventure?
no
the only way that I think you can do is, detect which block the player is watching, and if it's that block, change the gamemode to survival, unless to adventure again
You can also put “allow” under this block or give the player a pickaxe that breaks this block
yeah was gonna do that originally, wanted a cleaner alternative but this works
how to fix this?
[Scripting][error]-TypeError: cannot read property 'registerCustomComponent' of undefined at <anonymous> (onInteract.js:7)
[Scripting][error]-TypeError: cannot read property 'registerCustomComponent' of undefined at <anonymous> (onTick.js:7)
[Scripting][error]-TypeError: cannot read property 'registerCustomComponent' of undefined at <anonymous> (onPlayerDestroy.js:7)
[Scripting][error]-TypeError: cannot read property 'registerCustomComponent' of undefined at <anonymous> (onPlayerPlaced.js:7)
Be specific and include relevant details about the question upfront.
- What are you trying to accomplish?
- If you have code, which part is not working? Any content logs?
- What have you already tried?
- Have you searched the Bedrock Wiki?
|| We are not super people and we cannot know your code until you send it to us. ||
ohh sorry, its from here
blockTypeRegistry -> blockComponentRegistry
and i don't recommend using ai unless you know what you're doing
ohh thanks
so it is possible right ?
if I sent you a link to the documentation, then it's obvious that it's possible
No. Operator status is apparently too powerful to risk giving it away with script
It makes some sense, in case some addon developers made some backdoor to operator status in order to grief servers.
hm alright
so this wont work ?
will it just return a true/false value that player is op or not ?
Oh that's a beta feature
Well, pre-release
I didn't know they were working on that, I stick to stable
In that case, it should work if you're using beta script, but do be mindful that there's always the risk of Mojang changing it or removing it.
when i tested it, it worked but i tested it on server not in normal world
ah okay
ill try as well
did you use chat events ?
like !op
or something
No
it doesn't matter
cuz im thinking of using an item
it should still work ig
hey guys, so i figured out a way to remove another event from my constant running system.runInterval, for mobtrap, and got everything to work perfectly, thank u Minato, i figured out how to use dynamic proprties pretty much! they only problem i have is, and will also happen to campfire, is that onStepOn isnt triggered when i step on it, bcs the block is like, on ground, like, i step on a plant, i step up, and for some reason, when stepping up, the evet isn't triggering, so i have to step on this mobtrap from another mobtrap, or jump on it... any solutions?
import { world, system } from '@minecraft/server'
world.beforeEvents.worldInitialize.subscribe(initEvent => {
initEvent.blockComponentRegistry.registerCustomComponent('v360:mobtrap', {
onStepOn({ block, entity }) {
const checkingInterval = system.runInterval(() => {
if (!entity?.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 0.2, z: entity.location.z })?.typeId.includes('mobtrap')) {
entity.inputPermissions.movementEnabled = true
entity.removeTag('v360:mobtrap')
system.clearRun(checkingInterval)
}
if (entity.hasTag('v360:mobtrap')) {
entity.applyDamage(1)
}
})
if (entity?.typeId === 'minecraft:player') {
if (!entity.hasTag('v360:mobtrap')) {
entity.inputPermissions.movementEnabled = false
entity.addTag('v360:mobtrap')
entity.setDynamicProperty('v360:mobtrap', checkingInterval)
}
}
}
})
})```
how tall is the block collision box
in height 4 pixels
onStepOn should work with that
btw, you are overriding other blocks Interval here
entity.setDynamicProperty('v360:mobtrap', checkingInterval)
its trying to trigger, i c the screen moving for a split sec, but its not triggering
y?
the block id isnt v360:mobtrap, its v360:crimson_mobtrap, i just also have warped mobtrap and using one custom component for both blocks since they're pretty much the same
that most be a bug
try using 5
all blocks use the same
oh
i'll c how all of these will work together, since im not using all block intervals at the same time lol
nope, also not triggering
6 
nope
i cant go any higher, it would look strange for this block
but just for test i'll try 8, like a full sized slab
try a full block
just for testing
i'll have to jump on mobtrap and ofc it will work then
and also no, not working
weird
i really dont want to make a constant system.runInetrval not that will be checking for mobtrap under player all the time😭
type console.warn("triggered") in the start of onStepOn and see if that trigger or not
most be your conditions
well these r my conditions and what's being triggered
if (entity?.typeId === 'minecraft:player') {
if (!entity.hasTag('v360:mobtrap')) {
console.warn('trigy')
entity.addTag('v360:mobtrap')
entity.setDynamicProperty('v360:mobtrap', checkingInterval)
if (entity.getGameMode() !== 'spectator') {
entity.inputPermissions.movementEnabled = false
}
}
}```
uh
why are you using
!entity?.dimension.getBlock({ x: entity.location.x, y: entity.location.y - 0.2, z: entity.location.z })?.typeId.includes('mobtrap')
to check if there's no mobtrap under the player...
actually that could be the problem
the event only trigger for blocks that have that custom component
so no need for it
it is
no, like, if the player breaks the mobtrap, player needs to check if he broke the mobtrap
onStepOff won't work here, player won't still be able to move
or for example if i even do onPlayerDestroy, what if water breaks the mobtrap since i have liquid detection in this block, and there's no such custom component as onLiquidTouch
so i removed, and the event is triggered, i get stunned and the interval strats running, im getting damaged. but not if i break the mobtrap im still stnnued, the interval isnt stopping, and im getting damaged
so i just need to somehow check for the block under the player while player is in trap, of the block is not mobtrap, than give the player back movement input permission and remove the tag, if which player has, player gets damaged with the interval
the block is not always under the player
and that's also the case
what if i do if (!block.isValid()) in the interval, for checking the block, than remove interval and do all other stuff?
no check if it is air
block is always valid unless unloaded
block.typeId == "minecraft:air"
block.isAir also works
and it works
y didnt i think of that
now perfect
thank u again Minato, my savior!!
actually im gonna so !block.hasTag('v360:mobtrap') bcs i just tested breaking the block with water, and when the block is broken and im flowing in water, im still getting damaged, the interval isnt getting canceled until the block air
just check for the block id
nvm, if you have multiple blocks,the tag is a good way of doing it
Guys how I let a NPC entity walk forward 100 blocks with api
Can gametest do this? BC Json is also difficult to implement
You can gradually TP it, except if they added AI goals in a recent™️ update
Can U give me an example of impulse to forward ?
impulse where the entity is actually looking?
yeah
-# very helpful information
Bc someone is requested help to me
He is doing a NPC entity then he wants it to walk forward 100 blocks maybe via API or json
But Json is hard to do it
silly question, how do you make an item spawn in the player's inventory when they first load an addon? tryna figure out the book thing that marketplace projects do
Use itemStack
Did U alr have code rn?
i'm set up with scripting yeah
i can figure out getting the item in their inventory. i'm stuck on detecting first-time loading into the world
player.getComponent('inventory').container.setItem(4, new ItemStack('minecraft:compass', 1));
Like this
i had forgotten to save a link to it sadly, but i know there's a way to save JS variables to players/worlds
Put it on top of the script or also can put in world initialize event
this is super helpful though! thank you!
U are welcome😙
it's just a simple example
@vital halo if U want to set the item lock
let menu = new ItemStack('minecraft:compass', 1);
menu.lockMode = 'slot';
player.getComponent('inventory').container.setItem(4, menu);
Try multiplying view direction by distance
How
view.x * <value>```
function applyImpulseInViewDirection(entity, multiplier) {
const viewDirection = entity.getViewDirection();
const scaledImpulse = {
x: viewDirection.x * multiplier,
y: viewDirection.y * multiplier,
z: viewDirection.z * multiplier,
};
entity.applyImpulse(scaledImpulse);
}
that won't work if you did that
you need the player for that
use spawn or join event
how would u get dynamic properties of armors in armor slots like head?
Get Equippable component -> Read the item in the slot.
thanks
can i ask something else too?
if i was making a custom enchant, lets name it xyz for now, it technically decreases damage from axes, lets take iron axe for now, should i use health component and add the hp back? or is there another way
Yes that can work, however, it will "fail" if the Iron Axe damage kills the entity before you can add the health back.
hmm, who cares, no one will find hehehehe
Can also use damage sensors and rebuild the damage system from the ground up 
.., im lazy 😭
- i suck at scripting, still wanna do stuff
Is there a way to detect if a given block (i.e. onRandomTick) is the topmost block?
I mean, I imagine there is one, I can already envision it, but it's not a very optimized solution
Documentation for @minecraft/server
Is there a "cause" for EntityRemove?
hi there, is the getViewDirection the rotation of the body or the rotation of the head?
Head.
are we able to get the time of day in stable?
any kind of example to use this?
world.getTimeOfDay()
how would i use this to get a time of day between sunset and sunrise to set a block or load structure?
use /time query daytime to find the numbers between sunset and sunrise and use world.structureManager if it fits your needs.
if (world.getTimeOfDay() > 16000) { ... }
`
So I am trying to make a skyblock server, and want to use structures to save/load plots in preset locations. Is it efficient to use structures/structureManager, or would that take up too much storage or memory? I am not really sure how much storage they take up and if it would be an issue.
Structures seem to take up the same amount of space as blocks in the world, so it's unlikely to take up a lot of memory
Yeah it sounded dumb but was just trying to make sure.
Not really any other way if I wanted to, anyway
const night_time = world.getTimeOfDay() > 12000 && world.getTimeOfDay() < 24000;
i got this to work with on interact but not on randomtick idk why theyre basicly the same script
What is your code?
#debug-playground message
shows no errors and the rest of the script works besides that section that uses nighttime for randomtick
Tysm
Unhandled promise rejection TypeError: not a function
I have this error but it doesn't tell me which line it is on
Something in your code isn't correct api wise, or there isn't an import at the top for something
Send code?
The error appears when I use the slider and send it in a form
"format_version": "1.20.10",
"minecraft:recipe_shaped": {
"description": {
"identifier": "minecraft:wooden_shovel"
},
"tags": [ "crafting_table" ],
"pattern": [
"X",
"#",
"#"
],
"key": {
"#": {
"item": "minecraft:stick"
},
"X": {
"tag": "minecraft:planks"
}
},
"unlock": [
{
"item": "minecraft:stick"
}
],
"result": {
"item": "minecraft:wooden_shovel"
}
}
}
How whould i make where people cant craft a wooden shovel
This isn't scriptAPI question.
What is it then
#1067869659757543555 or #1067869136606220288 .
You'd want to run a command from the dimension, not system
Oh
What coding app Ur use, ar U phone coder?
that looks like bridge
Website version?
But it's hard to use on phone
I think he's' on pc
I am now using mt manager to code
It's a mobile
lol
If your wanting to run a command, you can do it if the player is defined like
player.runCommand('')
Otherwise the world can run it,
world.getDimension('overworld').runCommand('')
ok i'll try it
Well it works but the /Tag @r add doesn't work
I already fixed it
Yey, I made vanilla like doors
-# not that impressive.. mehh
thanks to the redstone conductivity shii and bug that let block have more than 1 block of collision
Lol nice the transform?
I wish they allowed larger collision not sure why they dont
Yah... I'm doing some side projects, since I'm so exhausted by my chess script
Lol
I could imagine lmao
how do you get the coordinate of a player
get the number of coordinate of the player in a dimension ?
hello ?
player.location
example ?
o
export class MoonCoordinate {
static #locationMap = new Map(player.location);
so its...this ?
Wait, what are you trying to do?
well i get the player location minus it by something something
i am trying to basically get the location of a player on a "planet" which are regions of the end
So if your real coordinate is 1000 20 1000, then your "moon" coordinates are different, like 100 20 100?
function getMoonCoordinate(player) {
const offset = { x: -50000, y: 0, z: -50000 };
const { x, y, z } = player.location;
return { x: x + offset.x, y: y + offset.y, z: z + offset.z }
}
damn i almost got a script working the 1st try
This is greatly simplified by using a vector math library, like the one I posted in #1325881561656197229. An example of that would be:
function getMoonLocation(player) {
return Vec3.add(player.location, Vec3.from(-50000, 0, -50000));
}
system.runInterval((data => {
const player = data.source;
const inv = player.getComponent('minecraft:inventory').container;
world.getAllPlayers().forEach(player => {
for (let i = 0; i < inv.size; i++) {
const item = inv.getItem(i);
if (item.typeId === 'minecraft:dirt') {
player.sendMessage("Dirt detected");
}
}
});
})); ```
is this how you loop all players and detect an item in inv?
Is it possible to set boundaries that people can't go beyond using script API?
Without performance drops
runInterval doesn't have any callback parameters, so data.source is invalid
Move the const inv = ... to inside the forEach method and delete const player = data.source
Thanks man, is there a better practice to run a loop through someone's inv or is this fine?
I'm not sure if this would be better, but you could just listen to the scriptevent command and run a mcfunction every tick
execute as @a[hasitem={}] at @s run scriptevent prefix:something
Just put your item info in the selector
Yeah true, I might give it a try thank you
thanks you ! do i need to give credits ?
can you give me this vector library ?
just click the link.
mhm
Can anyone check if this is correct syntax?
if (entity.typeId !== "testing:npc" || player.scoreboardIdentity?.getObjective("npc") === '0' || player.typeId !== "minecraft:player") return; {
player.runCommand("tp @s -9 -31 360")
}
no
if (entity?.typeId != "testing:npc" || !world.scoreboard.getObjective('npc')?.getScore(player) || player.typeId != 'minecraft:player') return
player.teleport({ x: -9, y: -31, z: 360 })
Are we able to obtain tipped arrows via scripting yet?
no
If there is .getScore(player) it will check player score for now - can I somehow check if it's equal to 0?
just do != because of the return
"!" before checking, this is a logical negation, in JS the values 0, undefined, null, when converted to a logical value, turn into false, that is, if the score is 0 or does not exist, the function will end
If the player doesn't have a score then this won't work
so give them the score if the score doesnt exist and then check for it.
Use a function to make your life easier (assuming you're gonna be fetching more scores in the future)
/**
* Gets the score of an entity for a specific objective
* @param {Entity|string} entity - The entity or player name to get the score for
* @param {string} objective - The name of the scoreboard objective
* @returns {number} The score value, or 0 if not found
*/
export function getScore(entity, objective) {
const obj = world.scoreboard.getObjective(objective);
try {
return obj.hasParticipant(entity) ? obj.getScore(entity) : 0;
} catch (e) {
system.run(() => {
obj.setScore(entity, 0);
})
}
}
You can use it like this
const score = getScore(player, "npc")
if (score == 0) {
// your function
}
you can just put "!"
okay.
Thanks!
All the information you should need about using is included in the post I linked. Is there anything specific I didn't mention there?
I have question, is there any possibility to increase radius of tickingarea by scripts? Or is there a script which can be constantly running detecting player location and adding and removing new tickingarea? So all commands will run without issues?
you cannot increase it with scripts and there's no native methods to set ticking areas in the script api.
Ehh, that's a pity, thank you!
you can run the ticking area command
then do a lot of math since we can only have 10 ticking areas saved iirc... So that it doesn't waste another ticking area if it's close to the other ticking area that is saved already .
I've done it like this:
const LOOP_INTERVAL = 20;
system.runInterval(() => {
const players = world.getAllPlayers();
for (const player of players) {
player.runCommandAsync("tickingarea add circle ~ ~ ~ 4 loopedArea true");
}
system.runTimeout(() => {
for (const player of players) {
player.runCommandAsync("tickingarea remove loopedArea");
}
}, 10);
}, LOOP_INTERVAL);
why make a variable to store how many intervals? Can't you just directly do it.
preference?
If you say so... Tho it's kinda annoying for me lol
Does it cause lag
hey guys! im back =P
after a lot of work, this is everything left in my "beloved" system.runInterval, but i think i can clear this up even more for even more performance improvements... does anybody has any idea for these 4 events left? they r when player walks into copper fire, player wears emerald armor he gets health boost, my fog in the end biomes (depending on block under the player) script, and entity getting damage if has the enderjelly tag and has more than 1 health
it's really unoptimised tbh
you have n*m iterations
try just iterating through every dimension
n*m?
2 nested for loops
For every N players, it iterates over M entities
let block = player.dimension.getBlock(player.location)?.below();
block = block.below()```
This part confuses me because it kinda doesn't make any sense
So if you have one player and 150 entities, the loop is executed 150 times. Each added player is another 150 loop executions; it grows quickly
import { world, system, Dimension } from "@minecraft/server";
/**
* @type {readonly Dimension[]}
*/
const DIMENSIONS = [
world.getDimension("overworld"),
world.getDimension("nether"),
world.getDimension("the_end")
];
system.runInterval(() => {
for (const dimension of DIMENSIONS) {
const entities = dimension.getEntities();
for (const entity of entities) {
};
};
}, 2);
its for testing if the player steped on the end soil or lloumelium and got the fog, but if he flies up without this thing, player would lose the fog bcs the block under the player is not air, i got help on this actually
it's already a bit better approach
i c...
That's not what I mean... So block is a let right? if you're assigning the block, where did you get the block to assign?
You're just reassigning to itself.
let block = block.below()```
You don't need to redeclare the variable. It is declared just above.
let block = player.dimension.getBlock(player.location)?.below();
while (block?.isAir) {
block = block?.below();
}
also the block already has ?.below() why assign another .below()??
The idea is the location of block will move downward until it hits a non-air block.
Hmmm...
Hello
Is it possible to save data for an item?
İtem.setDynamicProperty("id", 1);
Like this
unstackable items only
Where is the exit?
if item's max amount is 1, you can save it
any node can be start and end
👀 is that for mc?
const itemStack = // some ItemStack class instance
if (itemStack.maxAmount === 1) itemStack.setDynamicProperty("key", /* some value */);
Sword,armor etc.?
Nice, great job!
@fallow rivet
Which is faster, for of or for let i = 0; i < ...?
if you don't need an index, use for of loops
- they're faster
The distinction is negligible. Using one or another is really a premature optimization.
yes
That should come down to either preference or what information you need. As m0lc says, use C-style for loops when you need an index; you can also use Array.prototype.forEach for this too
my fav for i
how do you get the block you interact with to appear on the console log?
console.error(block.getTags);
console.error(block.typeId)
those just return undefined
a server for what?
Could use console.warn()
Oh
Bds (bedrock dedicated server)
console.log(block.location.x, block.location.y, block.location.z)
why can i debug a script?
system.runInterval(() => {
for (const player of world.getPlayers()) {
player.teleport({x: 0, y: 100, z: 0})
}
})
Oh it requires location
?
getTags()
Nvm
so I put block.location within getTags?
He shared this
One sec
I dont see the command debug
https://jaylydev.github.io/posts/jaylybot/#script-api-debugger this is how you use it
thx
block needs to be defined with block coordinates then it can getTags() from that block location / block
Oh ok
Wait then how the hell does my other script work without defining block location
Probably defined earlier
It's not
Hmm
Actually
It's also the same class of events
world.beforeEvents.playerInteractWithBlock
Yeah it's defined in the block class (targeted by the event)
It just depends how you define it
No errors in [code](#1067535608660107284 message)
but it dosent work...
it dose work
no, it is optional
Awhh ok
Does it need an interval defined or will it be constant without a delay?
Like system.run
Im just thinking of issues I haven't really run into or tried
optional too
default to 1
Show content log please
Lmao
Good to know these defaults
I have always added something
Is the script imported
The file
Otherwise nothing* will happen
not for me?
wait
lol
it is for aim assist...
🧠
it is hard to aim in custom camera view, they added that as a way of helping to aim in those
skill issue
someone feel attacked
Me 😀
nah, i didn't say that...
can we somehow configure a structure block with scripts?
Elaborate.
like the structure name... save mode, type, orientation, includeEntitues... etc
mostly interested about the structure name.
seems impossible now i think about it.
Documentation for @minecraft/server
no i mean the physical blocks
i needed that to place prepared structure blocks for exporting structures.
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]
hitEntity.nameTag = "Owner > {hitEntity.name}"
does this work?
Sure
How do I change the name of the entity?
hitEntity.nameTag = `Owner > ${hitEntity.name}`
template literals are backticks, not double or single quotation marks.
.
in applyDamage how to make the damagingEntity a player....?
the thrown error i am getting is
[Scripting][error]-TypeError: Native variant type conversion failed. Interface property ['damagingProjectile'] expected type: Entity (failed parsing interface to Interface property ['cause'], failed parsing interface to Function argument [1]) at <anonymous> (main.js:52)
"damagingProjectile"?
so it is expecting a projectile entity?
Add cause, otherwise the code thinks you want to use damagingProjectile
thanks
Hey hey, is there a chance to use script API to make that player can see entity's nametag from like 10 blocks away? Like checking radius and if player is near he can see it. I know in entity.behavior.json there is component of that, but I want not see this always
that's not a script API related.
How I can use rawtext on the leaderboard here?
system.runInterval(() => {
const entities = [...world.getDimension("overworld").getEntities()];
const test1 = world.scoreboard.getObjective("test1 ");
const test2 = world.scoreboard.getObjective("test2 ");
for (const entity of entities) {
if (entity.hasTag("test_scores")) {
const players = world.getAllPlayers();
let leaderboard = [];
for (const player of players) {
const c_score5 = test1 .getScore(player) ?? 0;
const r_score5 = test2 .getScore(player) ?? 0;
leaderboard.push(`${player.name}: Cyber Cores: ${c_score5}, Robotic Parts: ${r_score5}`);
}
entity.nameTag = leaderboard.join("\n");
}
}
}, 1);
Okay, I will reach json ui or just do it somehow different
you can make the name tag disappear or not visible in a distance but other players will be affected by the view too
Ooo, that's a great idea! I will do that, cuz I don't need more players in that case
Can you help me with leaderboard, please?
oh we need to add and remove component to your mob btw to your entity
I think you can't use rawtext for nametags
Guys may I ask if you can help of a script that when you place a block which is my block then automatically when it is placed, on the top of it there will be another block that was placed for example a stone?
If I have mob spawners on a skyblock island that are able to be clicked, opening a GUI for upgrades, removing it, etc., how should I save the data in the mob spawners of their "level" and stuff? Block Tags?
block.above().setType('stone');
block tags are static and cannot be changed you could try to use dynamic property and store it on the world
Then how would I point each mob spawner to its own dynamic property?
On the other hand, do the block tags stay when loaded with a structure?
make the id the location of the block.
I am using a plots system so there's only 10 skyblock islands maximum at one time, then they're unloaded manually or when you leave
world.setDynamicProperty(`zap:${block.location.x},${block.location.y},${block.location.z}`, <values>);
I get the idea, but the location will change based on what plot the player is in
unless I do relative coordinates to the plot
you can do what you want.
This is true
Wdym by that.
Yes, they will stay in the block no matter what but you can't add or remove a tag to the blocks
Just like items
also if you don't want to use dynamic property, you could try to use states on blocks but there's still a limit to how many you can add.
I need help
i want to make a method that gets the player position at 75000 75000 and minus it to zero
static getPosition(player) {
return Vec3.add(player.location, Vec3.from(+750000, 0, +750000));
}
}
is this correct ?
can you rephrase it again?
so basically
the center of the "dimension" i am making is at 75000 75000
then.
the, i am trying to make a static method that allows you to get the current location of the player relative to the dimension 0 0
ie at 75000 75000
Ahh... I get it. When the player is in your dimension the location is 75000 ~ 75000 and you want to make that it acts as 0 0 0 of the player?
i want it to get the location of the "dimension" coordinate
import { world } from "@minecraft/server";
const blocksToReplace = ["minecraft:air"];
world.beforeEvents.playerPlaceBlock.subscribe((event) => {
const block = event.block;
const maxHeight = block.dimension.heightRange.max;
if (block.typeId === "minecraft:my_block") {
const aboveBlock = block.above();
if (block.location.y >= maxHeight-1 || !blocksToReplace.includes(aboveBlock?.typeId)) {
event.cancel = true;
return;
}
aboveBlock.setType("minecraft:stone");
}
});
Your calculation is correct then.
so basically if the real location is 75000 75000 it returns 0 0
const { x: locX, z: locZ } = player.location;
const dimension = { x: 75000, z: 75000 };
console.log(locX - dimension.x, locZ - dimension.z);```
if the player's location is at the dimension's origin it will turn 0 0
I just ignore Y since you didn't include it on your original sceipt
const the_end = world.getDimension('the_end');
/**
* Class containing methods relating to the Moon
*/
class Moon {
/**
* Range of blocks in the end that the Moon takes up
*/
static range = { start: { x: 50000, z: 50000 }, end: { x: 100000, z: 100000 } };
/**
* Center block of the Moon
*/
static origin = { x: (this.range.start.x + this.range.end.x) / 2, z: (this.range.start.z + this.range.end.z) / 2 };
/**
* Checks whether a given location is in the Moon
* @param {import("@minecraft/server").Vector3} location location to check
* @returns {boolean} Whether or not the location is in the Moon
*/
static isInLunar(location) {
return this.range.start.x <= location.x && location.x <= this.range.end.x && this.range.start.z <= location.z && location.z <= this.range.end.z;
}
/**
* Gets all entities in the Moon that match the EntityQueryOptions
* @param {EntityQueryOptions} entityQueryOptions Query to use for search
* @returns {Entity[]} All entities matching the query
*/
static getEntities(entityQueryOptions) {
return the_end.getEntities(entityQueryOptions).filter((entity) => this.isInLunar(entity.location));
}
/**
* Gets all players in the Moon that match the EntityQueryOptions
* @param {EntityQueryOptions} entityQueryOptions Query to use for search
* @returns {Player[]} All players matching the query
*/
static getPlayers(entityQueryOptions) {
return the_end.getPlayers(entityQueryOptions).filter((entity) => this.isInLunar(entity.location));
}
/**
* Get the player location on Mars
* @param {Player} player - The player object to get the location from
* @returns {Vec3} The adjusted position on Mars
*/
static getPosition(player) {
return Vec3.add(player.location, Vec3.from(-750000, 0, -750000));
}
}````
this works though ?
I'm not sure about the y axis in your current script, when the player spawns is the origin at 0?
If yes then good to go I guess? Try it out.
well, the y axis is the same everywhere
Ohh, ok.
Yeah, the y axis in 75000 75000 is the same as 0 0
well, the y axis is +0
can someone help me why does this doesnt return the translated text and it returns [object object] i am using it on ActionForm
const itemsList = craftingGuideData.items
? Object.entries(craftingGuideData.items)
.map(([key, value]) => {
const text = { rawtext: [{ translate: `item.${value}` }] };
return `${getColorForLetter(key)}${key}§r = ${text}`;
})
.join("\n")
: "";
probably the value is an object. Try stringifying the value
still the same
i also tried stringify the text and this comes out
You're using rawtext wrong then.
Documentation for @minecraft/server
how is it wrong?
You're not translating it at all.
i know thats why i am asking why does this line doesnt translate it
const text = { rawtext: [{ translate: `item.${value}` }] };
Because it's an interface. Did you read the docs I sent?
you're turning the object into a string ````${getColorForLetter(key)}${key}§r = ${text}`;```
@balmy mason what does vec3.from do
is it possible to force close chat
Nope without damage.
if you're opening a form you could use forceShow to show the form constantly till there's no obstructions for the form to be opened
ok
Forms a Vector3 from different inputs. It supports 3-element arrays, 3 parameters, and 1 parameter to assign all three components.
@balmy mason can you check if this is correct to what i am doing
Thanks ! 😭
As long as you're importing the library your usage of Vec3.add looks correct.
The function additionally supports arbitrary amounts of vectors to be added together, as long as they all follow the same Vector3 interface.
You can actually further improve the legibility of your code to calculate the range as well.
function forceCloseChat(p: Player) {
p.applyDamage(0.001, { cause: EntityDamageCause.void });
}```this just damages the player and doesnt close chat?
applying damage to the player to close a ui doesn't work 100%
so if the player got already damaged before showing the any forms of ui, damaging player again won't trigger closing the form
either you need to kill the player or change gamemode from current gamemode to creative then back to the old gamemode.
ok
Hillo
const tag = source.hasTag('one_mana');
if (!tag) {
How would I stop the item from throwing its projectile when the certain things are met
event.cancel is only for blocks (i think) and I can't think of any other way to stop the item from throwing the projectile
Intro to ScriptAPI: https://aka.ms/startwithmcscript
Intro to Tests: https://docs.microsoft.com/en-us/minecraft/creator/documents/gametestgettingstarted
Official Docs: https://docs.microsoft.com/en-us/minecraft/creator/scriptapi
Community Docs: https://wiki.bedrock.dev/scripting/game-tests
Script API examples: https://github.com/JaylyDev/ScriptAPI
2021 Q&A: https://wiki.bedrock.dev/scripting/gametest-qna.html
2022 Q&A: https://wiki.bedrock.dev/scripting/scripting-editor-qna.html
is my usage of Vec3.from correct too ?
Yes, but couldn't you test that just through seeing the type definitions for the function in VS code? If you copied both files they should be there. Otherwise I can send the comments right here if needed, theye are available on the github repo as well
Yeah, i don't see any comments the current vec3 lib i am using have add but doesnt have from.
I thought you were using my library, sorry
I can't speak to the functionality of other libraries
Yeah, i am using yours
just not understanding how your Vec3.from means
I am trying to make static method Moon.getPosition() returns the player location on the moon relative to the origin(the 'dimension' 0 0)
You should be able to see all of the relevant documentation by hovering over the function name:
If you can't see this then either you don't have the .d.ts file imported into your scripts folder with the .js file, or if you're using a bundler you haven't installed the npm module for the library
How can I make custom states or properties of a block that save?
Could you clarify a bit more? This seems like a #1067876857103536159 question.
Basically how can I save data to a specific block that I can use in scripts? I want to have "upgradeable" mob spawners and such, with levels and custom data, but need a way to save that data to the block. I can use dynamic properties for that data, but I need a way to know which block needs that data if it's moved, removed, etc.
Not sure how to explain it differently, I'm sorry
You'll need to store the block location as a key or something then store the data to the key.
So that saves the data itself, and I will use block location to retrieve the data for the block, but I want to know if it's possible to make the script know that if you move that block, where to send the data to after it's placed again
If nothing similar to that is possible or viable, I can always just make it a "move block mode" that doesn't give you the block, but asks you where you want it and it just moves the block using scripts
with only 1 block at a time
ohh, when you place the block there's a saved data when you break it and place it again. You want to load the saved data?
since dynamic property doesn't work on stackables items you could try to store it on a lore of the item with the ID and you can grab the lore of the item to load the dynamic property
world.beforeEvents.playerLeave.subscribe(data => {
const player = data.player;
const {location} = player
if (getScore(player, "combatTicks") > 0 && !player.hasTag("safe")) {
world.getDimension(`overworld`).spawnEntity(`summon power:player_soul ${locationx} ${location.y} ${lcoation.z}`)
}
//ignore this below, for another system
system.run(() => {
let dogID = getScore(player, "dogID")
world.getDimension(`overworld`).runCommand(`kill @e[type=wolf,scores={dogID=${dogID}}]`)
})
})
``` im trying to summon an entity on the players location when they leave but it keeps saying smt abt permissions or wtv
also not actual code ^
wrap that part with system.run
heh?
it's before events you can't modify anything in the world before it happens that's why we use system run to run things in the next tick
e.g. add tags, spawn entity, kill entity, add item in inventory and many more
but if i run it in the next tick, it wont be able to get the players scores or tags
right?
It gets an old score so you don't need to worry about the script getting the new score
It just execute things in the next tick.
i get this
world.beforeEvents.playerLeave.subscribe(data => {
const player = data.player;
const {location} = player
system.run(() => {
if (getScore(player, "combatTicks") > 0 && !player.hasTag("safe")) {
world.getDimension(`overworld`).spawnEntity(`summon power:player_soul ${location.x} ${location.y} ${location.z}`)
}
let dogID = getScore(player, "dogID")
world.getDimension(`overworld`).runCommand(`kill @e[type=wolf,scores={dogID=${dogID}}]`)
})
})
``` with this
Wrap the spawnENtity and the runCommand in system.run, not the if condition.
You can't do anything iirc beforeEvents of playerLeave except setting or getting dynamic property
world.beforeEvents.playerLeave.subscribe(data => {
const player = data.player;
const {location} = player
if (getScore(player, "combatTicks") > 0 && !player.hasTag("safe")) {
system.run(() => {
world.getDimension(`overworld`).spawnEntity(`summon power:player_soul ${location.x} ${location.y} ${location.z}`)
})
}
system.run(() => {
let dogID = getScore(player, "dogID")
world.getDimension(`overworld`).runCommand(`kill @e[type=wolf,scores={dogID=${dogID}}]`)
})
})
``` so this?
the error shows that the player isn't accessible since it already left.
^
it worked before tho
just realized i had a command in spawn entity lmao 2sec
But does a placed block have lore
then i dunno. The error literally shows that the player isn't accessible since it already left.
or even the block.getItemStack
the if runs fine
its the spawn entity
then ok
I'm not sure either if it didn't work just be creative how to implement it...
if you want we can just sue one dynamic property to store those datas.
we can store a location of the block there with its data but still needed the lore
world.beforeEvents.playerLeave.subscribe(data => {
const player = data.player;
const loc = player.location;
world.setDynamicProperty(`leaveLoc`, loc)
if (getScore(player, "combatTicks") > 0 && !player.hasTag("safe")) {
system.run(() => {
world.getDimension(`overworld`).spawnEntity(`power:player_soul`, world.getDynamicProperty(`leaveLoc`))
})
}
system.run(() => {
let dogID = getScore(player, "dogID")
world.getDimension(`overworld`).runCommand(`kill @e[type=wolf,scores={dogID=${dogID}}]`)
})
})
works now
Should it?
our conversation is me asking how to save custom data to specific blocks in order to move/remove them and place them elsewhere with that information going to the new location of the same block
like "upgrading" mob spawners but being able to move one or multiple and get the information of specific blocks from dynamic properties
I can get and write info of the block using relative coords etc and dynamic properties, but I want to be able to move the block and still get the same data
Use block properties
well, specifically what and how?
so make a new permutation in the block.json?
In the block BP file
Are block BP files in the vanilla packs?
I can show you an example spawner file- I have three properties. ones, tens and hundreds for the spawner stack value
They are not
Sounds good with me
Like spawner stacking as in 1 block that you click on and it adds spawners, multiplying rates?
Yeah
Was trying to see if the data saving stuff was possible in vanilla but a custom block with all these custom permutations sounds better
Block dynamic properties cannot come any sooner.
It’s a lot easier lol
How would that work after u break the block if item dynamic properties can't be set on stackable items and most blocks are stackable...
Will we get also block dynamic properties only for non stackable blocks...
that would be dumb
Might be unstackable with the same type without the same dynamic properties
Like blocks that are placed in the world, I think Sean means
Yeah it sounds counterintuitive but also logical, somehow
they are the same.
Oka good, because the docs said"permutations" instead of "states" like his file
if (hitEntity.typeId == "power:player_soul") {
if (attacker.typeId == "minecraft:player") {
attacker.runCommand(`scoreboard players add @s healthMax ${getScore(hitEntity, "healthMax")}`)
let hitEntityName = hitEntity.getTags().filter(t => t.startsWith("name:")).map(e => e.slice(5))
console.warn(hitEntity.getTags().filter(t => t.startsWith("name:")).map(e => e.slice(5)))
attacker.sendMessage(`§aYou have received §2${getScore(hitEntity, "healthMax")} §aMax Health, which was §710%% of §8${hitEntityName}'s §aMax Health because they left §cin combat!`)
}
}
``` it says failed to getTags for some reason and im not sure why..
import { BlockPermutation } from '@minecraft/server';
const perm = Block.permutation.getState('<name>');
Block.setPermutation(Block.permutation.withState('<name>', <value>));
Block.setPermutation(BlockPermutation.resolve('<block id>', { <state name>: <value>, <state name>: <value> });
Is the entity able to have a tag?
yeah
that getTags
works for updating the entities name somewhere in my code
but doesnt work here
^ here @deep yew
Yeah mojang changed the wording a lil bit ago, it's the same thing
Thank you so much. But what's the difference between the first setPermutation vs the second?
As expected
is 800-1600 ticks actually a normal spawn rate ?
In the vanilla spawners
i see
nvm fixed
the first one you're just setting that state without touching other states, it means when i changed a specific state it retains other states while the second one will set what you just defined so it resets the whole block permutation saved
Ohhh okay yes I am slow
Nah you're not, I just have a shit English and explanation lmfao
just getting the key and setting the value vs making a new block and giving it a key
No you're good, I should've thought about it more
Huh?
We're talking about block dynamic properties. Which stores data on the block.
Items are something different. Its no longer a block when destroyed.
Or perhaps it makes the block unstackable like how items with different lore cannot be stacked.
Yes thats exactly what I mean. People think the blocks in the inventiry are blocks when in reality theyre all items. Blocks are the physical cubes in the world.
I could imagine the pain you could cause the world by assigning every block placed a million properties 
Its no different than creating a custom item with 64 tags, each with 65536 characters.
fair
I mean you could just use one dynamic property and create another one if it reaches the limit 32k character limit
ig items can be especially bad; I remember my world lagging when I moved a cheest filled with shulker boxes around my inventory
Oh actually I misread the docs. "states" is in the "description" and is just a key with string[] | bool[] | number[] values. Permutations use conditions and components with molang
And that's exactly what i said...
A block is a cube in the world
And you want to save dynamic properties on that cube
but if you break it
How does it save those properties
If you kill an entity does it save the properties?
No but we're talking about blocks. For example you can get a chest with it's items as an item and when you place again the chest, it will have those items inside even tho IT WAS A ITEM
so it wouldnt make sense to create block dynamic properties
if you cant keep them after breaking the block
that would be the same as just
using the block location as key
for a world dynamic property
youre saving it on a location not on a block.... Blocks should be more than just a position in the world when we are talking about saving properties on it
For example you can get a chest with it's items as an item
That is a block entity. Not dynamic property.
You are talking about a completely different thing.
What about spawners keeping their entity when you use ctrl scroll ?
yeah but there's still the same
Again, you are talking about block entities.
What the hell is a block entity 😭
Then you are saying dynamic properties should only be saved in a particular location
in that case dont ask for block dynamic properties
simply use world dynamic properties with block location as key
That is a horrible implementation.
Please, don't use ItemStack dynamic properties or Entity Dynamic Properties. Just use their ID and ContainerSlot as the key.
i guess what you're asking for would be just a simplified way of doign that.
block entities are sands, anvils, gravels etc.
Please learn the basics of technical Minecraft.
that doesnt make sense at all
They are not block entities.
really?
those are falling blocks lol
Still if they are block entities
they are blocks that keep their stuff when you take them as an item
Block Dynamic properties are NOT block entities.
paintings, item frames, etc.
thats my point
Bro i know they are not
but what about that
That's not the point of dynamic properties.
You are talking about something entirely different that I neveer brought up.
You are talking about something entirely different. Not going to continue this conversation anymore.
k
Thank y'all for the help, it goes a long way
The real help was the friends we made along the way.
how do you make it so that once you destroy something every similar blocks above it also get destroyed ?
world.beforeEvents.playerBreakBlock.subscribe(ev => {
const { block, player, itemStack } = ev;
if (block.typeId === block.above()?.typeId) {
system.run(() => block.dimension.runCommand(`setblock ${block.above().x} ${block.above().y} ${block.above().z} air destroy`) );
}
});```
it's kinda like this.
Vines destroy kind
how can I import Vector3?
it was from something like math but I don't remember anymore
Vector3 the class or the interface?
class
I tried using this but didn't work
{
"module_name": "@minecraft/math",
"version": "2.0.1"
}
It's not a module. You'll need to separetly install it then bundle it with your code.
bruh why
it doesn't interact with minecraft at all, so there's no need for it to be part of the game
I also didn't like that.
I just want to share some "fun" information. Some people know that I am developing JSUI and so, it takes about 2-3 ms to calculate all the parameters for text per 1000 characters. So, here's some interesting information: rendering text takes 90 ms, 3 of which are parameter calculations, the rest is calling the spawnParticle function. And I'm actually shocked at how unoptimized this function is.
Were you able to get the type definitions imported?
When the player holds the diamond sword, an entity will spawn and when the player does not have the sword in his hand, this entity will die. How can I do this?
system.runInterval(() => {
for (let player of world.getAllPlayers()) {
if (player.dimension.getEntities({tags: ['swhds:' + player.id]})) continue
if (player.getComponent('equippable').getEquipment('Mainhand')?.typeId != 'minecraft:diamond_sword') continue
let entity = player.dimension.spawnEntity('armor_stand', player.location)
entity.addTag("swhds:" + player.id)
entity.addTag("swhds_sys")
entity.setDynamicProperty('playerId', player.id)
}
})
system.runInterval(() => {
for (let id of ['overworld','nether','the_end']) {
for (let entity of world.getDimension(id).getEntities({tags: ['swhds_sys']})) {
if (world.getEntity(entity.getDynamicProperty('playerId'))?.getComponent('equippable')?.getEquipment('Mainhand')?.typeId != 'minecraft:diamond_sword') {
entity.remove()
}
}
}
})
system.runInterval(() => {
for (const player of world.getPlayers()){
const equip = player.getComponent('equippable')
const hand = equip.getEquipmentSlot(EquipmentSlot.Mainhand)
if (!hand.hasItem() || hand.typeId !== 'minecraft:diamond_sword') {
if (player.hasTag('hasEntity')){
const entities = player.dimension.getEntities({ tags: [`owner:${player.id}`]})
entities.forEach(e => e.remove())
player.removeTag('hasEntity')
continue;
} else continue;
}
if (player.hasTag('hasEntity')) continue;
player.addTag('hasEntity')
/**
* Replace yourEntityId for your actual entity ID.
*/
const entity = player.dimension.spawnEntity(`yourEntityId`, player.location)
entity.addTag(`owner:${player.id}`)
}
})
Lmao i was doing the same
😂
Thanks
Js or ts?
js
is there something like entity.extinguish or some way to make an entity no longer be on fire
extinguishfire( true )
The default value option in the slider doesn't accept float? Just wanna confirm since in the docs it says number not float
Thank you!!
uis dont support float ig that is why but u can work around it
Yeah lol, I'm dealing with an RGBA type thing so I just made it accept value from 0 to 255 and change the value displayed in form by dividing the value to 255 to fake it as 0 to 1 float value
Your working with the particle? Is the coloring working well?
Yah, and yes it works perfectly
Did you keep the same base color grey or change it?
Change it to pure white.
That's awesome it's working! Pure white makes sense
If you want your particle to have highlights thingy, you should make it have a highlight but also white
Ever seen leather armor .tga texture image?
No actually
This is sheep tga file since they changed color, they made it like this.
Oh ok
ignore the thing in the background I use that to real-time color preview lol
Unimportant but this is my little RGBA lmfao
There's no way to open an NPC dialogue with body text set by a script, right?
Oooo nice
No...
anyone seen this error?
I have a stupid idea but not a feasible sat So in json UI you could cut off strings to be displayed, you could probably make that it gets the title from string 0 to string 10 and get the body from string 11 to string whatever. Since the title of npc screen is based on the name of the npc itself you can probably do that.
you should use queue_command
and what's the line 149?
i will grab it for you
system.beforeEvents.watchdogTerminate.subscribe(data => {
data.cancel = true;
});

Are you in beta?
system.beforeEvents.watchdogTerminate.subscribe(data => {
data.cancel = true;
});```
What version are you on?
No errors in [code](#1067535608660107284 message)
mc version 1.21.51
manifest
{
"format_version": 2,
"header": {
"name": "Forest Vaults - v1.0.0",
"description": "Forest Vaults - v1.0.0",
"min_engine_version": [1, 20, 0],
"uuid": "c1009f52-8eab-4e99-89fc-44774fd4cdf3",
"version": [1, 0, 0]
},
"modules": [
{
"description": "Data Module",
"type": "data",
"uuid": "b8a89370-6787-4111-a904-89a54cd5f732",
"version": [1, 0, 0]
},
{
"description": "Gametest Module",
"language": "javascript",
"type": "script",
"uuid": "20301768-94eb-4344-838a-fc80aeb68343",
"version": [1, 0, 0],
"entry": "scripts/main.js"
}
],
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.8.0"
},
{
"module_name": "@minecraft/server-ui",
"version": "1.4.0-beta"
}
],
"metadata": {
"authors": ["Forest Vaults"],
"license": "MIT",
"url": ""
}
}
oh you're not in beta that's why... You should be 1.17.0-beta
I'm talking about the minecart server script version not UI
got it
Are you in the latest stable or preview?
stable I would prefer this to be usable for a while
ah thanks for the help
script semi works
now i got to figure out what i was thinking awhile ago
now try HUE 👀
chill
Hey new problem with this
[Scripting][warning]-Failed to import command: vault, SyntaxError: Could not find export 'Vector' in module '@minecraft/server'
this is from my db
import { system, world, Vector } from "@minecraft/server";
Vector doesn't exist in there anymore.
either you create custom class or download a bundle
there's a lot online just check them out
how to optimize system.runInterval?
make it run every 1 or 5 or 10 ticks?
is there any other way than that?
What are you doing inside of the ruInterval?
if (player.hasTag(`clan:`) || player.hasTag(`clan:`)) return;
const equipment = player.getComponent("minecraft:equippable");
const chest = equipment.getEquipment(EquipmentSlot.Chest);
if (chest?.typeId === "minecraft:elytra") {
equipment.setEquipment(EquipmentSlot.Chest, null);
player.dimension.spawnItem(chest, player.location);
}
}```
let playerIndex = 0;
system.runInterval(() => {
const players = world.getAllPlayers();
const player = players[playerIndex];
if (!player) {
playerIndex = 0;
} else {
elytra(player);
playerIndex = (playerIndex + 1) % players.length;
}
});
is it better than just
system.runInterval(() => {
for (const player of world.getPlayers()) {
elytra(player);
}
}, 20);
Why do this?
idk
you can just do this.
okay
Does onPlace work on natural generation too or just player placing?
Should work for natural generation.
It works with the setblock/fill command or when some mob places it (enderman for example). But this is unlikely to work with generation, since chunks are generated at a larger radius than the loading area, so this will be an attempt to get a block in the unloaded chunk
i was gonna say that too since Poggy (i forgot who), made a post that onPlace in custom components doesn't trigger with natural generation.
|| It was King and he was talking about onTick ||
oof, mybad lol
since chunks are generated at a larger radius than the loading area
Visually yes.
This needs to be checked
Last I checked onPlace works.
guys do you know where to find the complete minecraft id list on the latest version of minecraft bedrock
ids of...?
system.runInterval(() => {
for (const player of world.getPlayers()) {
if (player.hasTag("test")) {
player.removeTag("test");
const inventory = player.getComponent("minecraft:inventory").container;
const selectedSlotIndex = player.selectedSlotIndex;
const selectedItem = inventory.getItem(selectedSlotIndex);
if (selectedItem) {
player.setDynamicProperty("item", selectedItem);
const barrierItem = new ItemStack("minecraft:barrier", 1);
inventory.setItem(selectedSlotIndex, barrierItem);
}
}
if (player.hasTag("give")) {
player.removeTag("give");
const savedItem = player.getDynamicProperty("item");
if (savedItem) {
const inventory = player.getComponent("minecraft:inventory").container;
inventory.addItem(savedItem);
}
}
}
});
Not work why?
What exactly does not work? You're doing a lot of things.
You cannot save items to dynamic properties. Use this -> https://discord.com/channels/523663022053392405/1252014916496527380
Ok
Hello!
cool, the api do have them btw
damn it
Microsoft Docs, Stirante, Jayly website.
link
So how do I do this?
uhm? just like you said
Do you have a sample code?
bruh you literally sent it
This doesn't work
