#Script API General

1 messages · Page 49 of 1

misty dagger
#

I need WASD specifically because the different directions have non-movement related functions.

#

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?

distant tulip
#

keepVelocity?

misty dagger
#

I tried that, but it didn't seem to do anything.

#

Even on my previous project, keepVelocity never really worked.

distant tulip
#

i meant on mount
not the player

misty dagger
#

Yeah, the mount is being teleported with keepVelocity set to true.

distant tulip
#

or you can just get velocity before tp

misty dagger
#

Lemme see if that would work.

#

Nope. The velocity is still locked to 0, even if you get it before the teleport.

distant tulip
#

how are you teleporting the mount
what condition

misty dagger
#

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.

distant tulip
#

maybe do

if(vel.x != 0 || vel.y != 0 || vel.z != 0){
  //tp
}

if that won't cause problems for u

misty dagger
#

The entity will be moving constantly.

distant tulip
#

for a tick

misty dagger
#

Lemme try teleporting it every other tick.

wheat condor
#

I think ill just re texture useless blocks

misty dagger
#

Teleporting the mount every other tick permits gathering velocity data every other tick also.

dim tusk
#

Umm, yeah detecting velocity or player while reading is kinda weird than just not riding.

misty dagger
#

Seems so. Unfortunately it is necessary that the player is riding a mount here.

dim tusk
#

and you can't detect the velocity of the entity riding since it has the same results

misty dagger
#

The every other tick approach seems like it will work though, at least for my purposes.

woven loom
#

I see many new players, nice

neat hound
#

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...

woven loom
#

Which part you are referring to?

neat hound
#

does it do it each time

woven loom
#

No, I don't think so, unless the script re-runs every time qhile being imported

neat hound
#

So imports, imports the final version

woven loom
#

test it with Date.now() 🙂

#

It will have different times if it re-runs every time; else will be static.

celest abyss
#

How to detect when a player steps on a specific block

glacial widget
#

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);
round bone
#
import { world, system, PlatformType } from "@minecraft/server";

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        switch (player.clientSystemInfo.platformType) {
         case PlatformType.Console:
              break;
       };
    };
});
remote oyster
#

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.

true isle
#

is their any way to compile identifiers in a single file?

obtuse cypress
#

what exactly is read only mode and how its useful?

valid ice
#

It prevents the world from being changed at all while it’s active. Read-only mode is active when a before event is ran

distant tulip
true isle
#

made a .py to compile all the ids in my pack

gentle hemlock
#

yo

#

can some1 help

shell sigil
#

Guys how I can get the location of structure example a village that near in my location using script

rotund sequoia
#

Hello one question, you can deny damage via script?

rotund sequoia
valid ice
#

Damage sensors still the best option

rotund sequoia
knotty plaza
#
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);
}
unique acorn
#

what is messageRecieve after event supposed to be?

unique acorn
#

its item.typeId not item.id

slim spear
distant tulip
unique acorn
#

in the docs it says This event is an internal implementation detail, and is otherwise not currently functional.

distant tulip
#

that most be new
didn't see it last time i checked

verbal slate
#

Guys, do you know how to track damage received from a player?

warm mason
wheat condor
#

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

warm mason
wheat condor
acoustic basin
#

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

warm mason
acoustic basin
# warm mason 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

warm mason
#

I don't understand what's in your code. Tell me what you want to do

acoustic basin
# warm mason 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

remote oyster
#

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.

warm mason
# acoustic basin all other events r: - entity gets damaged when there's lit copper campfire under...

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)
acoustic basin
hardy tusk
#

Omg

#

Guys 100,000 messages

hardy tusk
warm mason
sage sparrow
#

hi there, is it possible to use EntityQueryOptions to filter family type to get entities?

sage portal
acoustic basin
#

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

simple zodiac
#

system.run wants a function as an input. Make sure that is the case

acoustic basin
#

i have a const for launchingInterval system.runInterval, and that's how im triggering it

simple zodiac
#

const launchingInterval = system.runInterval(() => ...)
does not return a function but rather a number. You can not pass that to system.run

acoustic basin
#

oh, so how do i make it like u said as a case?

simple zodiac
#

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

acoustic basin
acoustic basin
distant tulip
#

that's how im triggering
you don't need to trigger it, it run automatically
not like functions

simple zodiac
#

oh of you want to clear the interval you have to use system.clearRun(runId (in your case launchingInterval ) )

distant tulip
#

the question is why do you need an interval to run a code once

acoustic basin
# distant tulip 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..

distant tulip
#

you can send the file
but why?

acoustic basin
#

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

thorn flicker
#

you should probably just make this an entity and use animations for the visual stuff..

distant tulip
#

why not use on step on event

acoustic basin
#

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

thorn flicker
acoustic basin
#

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

distant tulip
#

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)
acoustic basin
#

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

warm mason
#

It would be better to use WeakMap

distant tulip
#

you can use maps, but same deal

warm mason
#

Dynamic properties can clog files over time. This is not very critical, but why?

distant tulip
#

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

warm mason
distant tulip
#

yeah, that is true

hardy tusk
warm mason
hardy tusk
#

Damn

acoustic basin
#

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

simple zodiac
#

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

plush moss
#

one question can you cancel the event from taking out stuff like from chests or shulker boxes?

warm mason
meager cargo
#
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?

meager cargo
#

This is error

plush moss
#

you have to use system.run i think

warm mason
meager cargo
plush moss
# meager cargo This is 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

plush moss
meager cargo
plush moss
#

on my world this is working xd

#

lets write in private chat

meager cargo
#

submitButton is doing errors

#

I get rid of that and it worked

#

xdd

#

Thank you very much!

distant tulip
verbal yew
#

Did i do this right

world.events.hasTag.subscribe((eventData) => {
    let player = eventData.player;
    if (player.hasTag("warp")) {
        showWarpMenu(player);
    }
});
verbal yew
#

iv changed it like 12 times

#

I dont mess with World events

warm mason
verbal yew
#

Well yhay i did not think it that way

warm mason
#

copy again

verbal yew
neat hound
# verbal yew 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

inland merlin
#

We "can't" get player alt accounts with script api yet right?

#

What's the method currently used rn?

#

For bds only?

valid ice
#

There's a way to get alts!?

inland merlin
valid ice
#

Hmm

inland merlin
#

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

jolly veldt
#

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

inland merlin
inland merlin
#

Lol

#

I guess im.outta the loop

valid ice
#

Epoxy? Uhhhh yeah you use it to glue stuff together

inland merlin
distant tulip
inland merlin
#

I don't mind acting dumb here, I get roasted regardless

distant tulip
#

i wasn't roasting you lol
who ever told you you can do that is just saying random stuff

inland merlin
#

Ok cool thanks for info

thorn flicker
#

why was pistonActivate beforeEvent removed?

distant tulip
thorn flicker
#

hm

marsh pebble
#

Is there a way to disable / change crafting recipies for like wooden sword or diamond leggings.

thorn flicker
strong oar
#

Is there a resource for connecting blocks?

green bison
#

is it possible to make blocks breakable in adventure?

unique dragon
#

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

warm mason
green bison
#

yeah was gonna do that originally, wanted a cleaner alternative but this works

strong oar
#

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)

drifting ravenBOT
#
How To Ask Good Questions

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?

https://xyproblem.info/

warm mason
#

|| We are not super people and we cannot know your code until you send it to us. ||

strong oar
warm mason
#

blockTypeRegistry -> blockComponentRegistry

#

and i don't recommend using ai unless you know what you're doing

strong oar
#

ohh thanks

runic crypt
#

is there a way to give a player op using scripts ?

#

If anyone knows pls ping me

warm mason
sage portal
#

It makes some sense, in case some addon developers made some backdoor to operator status in order to grief servers.

runic crypt
#

will it just return a true/false value that player is op or not ?

sage portal
#

Oh that's a beta feature

#

Well, pre-release

#

I didn't know they were working on that, I stick to stable

sage portal
# runic crypt so this wont work ?

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.

runic crypt
#

alright 🫡

#

Ill try 🫡

#

thanks for the help :D

warm mason
runic crypt
runic crypt
#

like !op

#

or something

warm mason
runic crypt
#

then what did you use tho ?

#

just curious

warm mason
runic crypt
#

it should still work ig

acoustic basin
#

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)
                }
            }
        }
    })
})```
distant tulip
acoustic basin
distant tulip
#

onStepOn should work with that

#

btw, you are overriding other blocks Interval here
entity.setDynamicProperty('v360:mobtrap', checkingInterval)

acoustic basin
#

its trying to trigger, i c the screen moving for a split sec, but its not triggering

acoustic basin
#

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

distant tulip
distant tulip
acoustic basin
#

oh

#

i'll c how all of these will work together, since im not using all block intervals at the same time lol

acoustic basin
distant tulip
#

6 bao_ext_toldyouso

acoustic basin
#

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

distant tulip
#

try a full block
just for testing

acoustic basin
acoustic basin
distant tulip
#

weird

acoustic basin
#

i really dont want to make a constant system.runInetrval not that will be checking for mobtrap under player all the time😭

distant tulip
#

type console.warn("triggered") in the start of onStepOn and see if that trigger or not

acoustic basin
#

one sec

#

its sending the message!!

#

but i set the collision height back to 4

distant tulip
#

most be your conditions

acoustic basin
#

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
                    }
                }
            }```
distant tulip
#

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')

acoustic basin
#

to check if there's no mobtrap under the player...

#

actually that could be the problem

distant tulip
#

the event only trigger for blocks that have that custom component

#

so no need for it

distant tulip
acoustic basin
#

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

acoustic basin
#

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

distant tulip
#

the block is not always under the player

acoustic basin
#

what if i do if (!block.isValid()) in the interval, for checking the block, than remove interval and do all other stuff?

distant tulip
#

no check if it is air
block is always valid unless unloaded

#

block.typeId == "minecraft:air"

acoustic basin
#

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

distant tulip
#

just check for the block id
nvm, if you have multiple blocks,the tag is a good way of doing it

quick shoal
#

Guys how I let a NPC entity walk forward 100 blocks with api

#

Can gametest do this? BC Json is also difficult to implement

carmine yarrow
#

You can gradually TP it, except if they added AI goals in a recent™️ update

dim tusk
#

why tp if applyImpulse exist?

#

Oof, I've been gone for 2 days?

quick shoal
dim tusk
quick shoal
#

I think yes

#

Just impulse to forward

#

Maybe viewDirection

dim tusk
#

yeah
-# very helpful information

quick shoal
#

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

vital halo
#

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

quick shoal
#

Did U alr have code rn?

vital halo
#

i can figure out getting the item in their inventory. i'm stuck on detecting first-time loading into the world

quick shoal
#

Like this

vital halo
#

i had forgotten to save a link to it sadly, but i know there's a way to save JS variables to players/worlds

quick shoal
#

Put it on top of the script or also can put in world initialize event

vital halo
quick shoal
#

@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);
vital halo
#

oh sick

#

i didn't even know there was an item lock

quick shoal
#

It appears in vanilla command

#

U can get it from /give or /replaceitem command

dim tusk
quick shoal
dim tusk
distant tulip
# quick shoal Maybe viewDirection
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);
}
distant tulip
stark kestrel
#

how would u get dynamic properties of armors in armor slots like head?

wary edge
stark kestrel
stark kestrel
wary edge
stark kestrel
valid ice
#

Can also use damage sensors and rebuild the damage system from the ground up trollformation

stark kestrel
#
  • i suck at scripting, still wanna do stuff
vital halo
#

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

wary edge
#

Thinkdricks Is there a "cause" for EntityRemove?

sage sparrow
#

hi there, is the getViewDirection the rotation of the body or the rotation of the head?

true isle
#

are we able to get the time of day in stable?

true isle
#

any kind of example to use this?

warm mason
true isle
#

how would i use this to get a time of day between sunset and sunrise to set a block or load structure?

deep yew
#

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.

warm mason
deep yew
#

Yeah it sounded dumb but was just trying to make sure.

#

Not really any other way if I wanted to, anyway

true isle
#

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

true isle
#

#debug-playground message

#

shows no errors and the rest of the script works besides that section that uses nighttime for randomtick

celest abyss
#

Unhandled promise rejection TypeError: not a function

#

I have this error but it doesn't tell me which line it is on

inland merlin
#

Send code?

celest abyss
marsh pebble
#
  "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

wary edge
marsh pebble
#

What is it then

wary edge
celest abyss
#

Line 56

#

Line 82

broken jolt
#

You'd want to run a command from the dimension, not system

celest abyss
#

Oh

quick shoal
unique dragon
quick shoal
#

Website version?

unique dragon
#

v.2

#

yes

quick shoal
#

But it's hard to use on phone

unique dragon
#

I think he's' on pc

quick shoal
#

I am now using mt manager to code

celest abyss
unique dragon
#

lol

inland merlin
#

Otherwise the world can run it,

world.getDimension('overworld').runCommand('')

celest abyss
#

Well it works but the /Tag @r add doesn't work

inland merlin
#

Don't add the / remove that

#

Just tag @r add tnt

#

Wait one sec

inland merlin
#

Can you send more info or the full script

celest abyss
#

I already fixed it

dim tusk
#

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

inland merlin
#

I wish they allowed larger collision not sure why they dont

dim tusk
#

Lol

bright dove
#

how do you get the coordinate of a player

#

get the number of coordinate of the player in a dimension ?

#

hello ?

knotty plaza
bright dove
knotty plaza
#

Thats literally it

#

Just call the location property

bright dove
#

o

bright dove
#

so its...this ?

knotty plaza
#

Wait, what are you trying to do?

bright dove
#

i am trying to basically get the location of a player on a "planet" which are regions of the end

knotty plaza
#

So if your real coordinate is 1000 20 1000, then your "moon" coordinates are different, like 100 20 100?

bright dove
#

Yup

#

get the real coordinate, minus by 50k or smth

knotty plaza
#
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 }
}
tidal wasp
#

damn i almost got a script working the 1st try

balmy mason
green bison
#
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?
stark kestrel
#

Is it possible to set boundaries that people can't go beyond using script API?

#

Without performance drops

knotty plaza
#

Move the const inv = ... to inside the forEach method and delete const player = data.source

green bison
knotty plaza
#

execute as @a[hasitem={}] at @s run scriptevent prefix:something

#

Just put your item info in the selector

green bison
bright dove
bright dove
thorn flicker
bright dove
#

mhm

meager cargo
#

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")
    }
warm mason
lone thistle
#

Are we able to obtain tipped arrows via scripting yet?

meager cargo
thorn flicker
warm mason
warm mason
thorn flicker
#

so give them the score if the score doesnt exist and then check for it.

lone thistle
# meager cargo If there is .getScore(player) it will check player score for now - can I somehow...

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
}
thorn flicker
#

okay.

meager cargo
#

Thanks!

balmy mason
meager cargo
#

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?

thorn flicker
meager cargo
#

Ehh, that's a pity, thank you!

thorn flicker
dim tusk
meager cargo
#

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);
dim tusk
dim tusk
meager cargo
#

I don't check with all my scripts, but I think it doesn't

#

Cuz it's not every tick

acoustic basin
#

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

round bone
#

you have n*m iterations

#

try just iterating through every dimension

acoustic basin
#

n*m?

round bone
sharp elbow
#

For every N players, it iterates over M entities

dim tusk
#
let block = player.dimension.getBlock(player.location)?.below();
block = block.below()```

This part confuses me because it kinda doesn't make any sense
sharp elbow
#

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

round bone
#
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);
acoustic basin
round bone
#

it's already a bit better approach

dim tusk
#

You're just reassigning to itself.

#
let block = block.below()```
sharp elbow
#

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();
}
dim tusk
#

also the block already has ?.below() why assign another .below()??

sharp elbow
#

The idea is the location of block will move downward until it hits a non-air block.

dim tusk
#

Hmmm...

acoustic basin
#

😵‍💫

#

alr, i got everything

#

i understood

#

gonna put it to practice now

fallow rivet
#

Hello

#

Is it possible to save data for an item?

#
İtem.setDynamicProperty("id", 1);
#

Like this

distant tulip
sharp elbow
#

Where is the exit?

round bone
woven loom
round bone
#
const itemStack = // some ItemStack class instance
if (itemStack.maxAmount === 1) itemStack.setDynamicProperty("key", /* some value */);
fallow rivet
distant tulip
fallow rivet
#

Ok

#

Thanks

warm mason
#

Which is faster, for of or for let i = 0; i < ...?

round bone
#
  • they're faster
sharp elbow
#

The distinction is negligible. Using one or another is really a premature optimization.

woven loom
#

yes

sharp elbow
#

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

woven loom
#

my fav for i

tidal wasp
#

how do you get the block you interact with to appear on the console log?

inland merlin
#

Does bds have a server for jist that?

#

Discord server

tidal wasp
#

those just return undefined

tidal wasp
inland merlin
#

Could use console.warn()

tidal wasp
#

no it does appear

#

just undefined

inland merlin
#

Oh

inland merlin
granite badger
crude bridge
#

why can i debug a script?

#
system.runInterval(() => {
    for (const player of world.getPlayers()) {
            player.teleport({x: 0, y: 100, z: 0})
    }
})
inland merlin
#

Oh it requires location

crude bridge
inland merlin
#

getTags()

inland merlin
#

Nvm

tidal wasp
#

so I put block.location within getTags?

inland merlin
#

One sec

crude bridge
granite badger
inland merlin
tidal wasp
#

Oh ok

inland merlin
#

So Jayly shows you can add location

#

In his example

#

X y z

tidal wasp
#

Wait then how the hell does my other script work without defining block location

inland merlin
#

Probably defined earlier

tidal wasp
#

It's not

inland merlin
#

Hmm

tidal wasp
#

Actually

#

It's also the same class of events

#

world.beforeEvents.playerInteractWithBlock

inland merlin
#

Yeah it's defined in the block class (targeted by the event)

#

It just depends how you define it

crude bridge
#

someone can debug this

gaunt salmonBOT
# crude bridge
No Errors

No errors in [code](#1067535608660107284 message)

crude bridge
distant tulip
inland merlin
#

Do you need to define dimension there?

#

Doesn't throw error?

distant tulip
#

no, it is optional

inland merlin
#

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

distant tulip
#

optional too
default to 1

granite badger
inland merlin
#

Lmao

inland merlin
#

I have always added something

inland merlin
#

The file

#

Otherwise nothing* will happen

crude bridge
crude bridge
crude bridge
#

it work

inland merlin
#

Lmao

#

Ggs

#

I only laugh because this happens to every one of us

warm drum
#

guy

#

what the aim assist abt?

distant tulip
#

it is for aim assist...

unique dragon
#

🧠

distant tulip
dim tusk
#

Don't be too rude

distant tulip
#

someone feel attacked

dim tusk
distant tulip
#

nah, i didn't say that...

buoyant canopy
#

can we somehow configure a structure block with scripts?

buoyant canopy
#

like the structure name... save mode, type, orientation, includeEntitues... etc

#

mostly interested about the structure name.

#

seems impossible now i think about it.

buoyant canopy
#

no i mean the physical blocks

#

i needed that to place prepared structure blocks for exporting structures.

gaunt salmonBOT
celest abyss
valid ice
#

Sure

celest abyss
#

How do I change the name of the entity?

thorn flicker
#
hitEntity.nameTag = `Owner > ${hitEntity.name}`
#

template literals are backticks, not double or single quotation marks.

thorn flicker
distant tulip
#

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?

warm mason
distant tulip
#

thanks

meager cargo
#

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

meager cargo
#

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);
meager cargo
dim tusk
meager cargo
#

Can you help me with leaderboard, please?

dim tusk
round bone
strong oar
#

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?

deep yew
#

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?

dim tusk
dim tusk
deep yew
#

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?

dim tusk
deep yew
#

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

dim tusk
deep yew
#

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

dim tusk
#

you can do what you want.

deep yew
#

This is true

dim tusk
#

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.

bright dove
#

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 ?

bright dove
#

the center of the "dimension" i am making is at 75000 75000

dim tusk
#

then.

bright dove
# dim tusk 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

dim tusk
bright dove
distant tulip
# strong oar
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");
  }
});
dim tusk
bright dove
dim tusk
#

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

bright dove
#

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 ?

dim tusk
#

If yes then good to go I guess? Try it out.

bright dove
dim tusk
bright dove
empty tapir
#

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")
        : "";
dim tusk
empty tapir
#

i also tried stringify the text and this comes out

empty tapir
wary edge
empty tapir
wary edge
open urchin
#

you're turning the object into a string ````${getColorForLetter(key)}${key}§r = ${text}`;```

bright dove
#

@balmy mason what does vec3.from do

naive tinsel
#

is it possible to force close chat

dim tusk
#

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

naive tinsel
#

ok

balmy mason
bright dove
balmy mason
#

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.

naive tinsel
# dim tusk Nope without damage.
function forceCloseChat(p: Player) {
  p.applyDamage(0.001, { cause: EntityDamageCause.void });
}```this just damages the player and doesnt close chat?
dim tusk
naive tinsel
#

thats so bad

#

bruh

dim tusk
#

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.

naive tinsel
#

ok

amber granite
#

Hillo

steady raptor
#
        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

bright dove
balmy mason
# bright dove 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

bright dove
balmy mason
#

I thought you were using my library, sorry

#

I can't speak to the functionality of other libraries

bright dove
#

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)

balmy mason
#

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

deep yew
#

How can I make custom states or properties of a block that save?

wary edge
deep yew
#

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

wary edge
deep yew
#

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

dim tusk
#

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

dawn zealot
#
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 ^

dim tusk
#

wrap that part with system.run

dawn zealot
dim tusk
# dawn zealot 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

dawn zealot
#

but if i run it in the next tick, it wont be able to get the players scores or tags

#

right?

dim tusk
#

It just execute things in the next tick.

dawn zealot
#

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
wary edge
dim tusk
dawn zealot
#
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?
dim tusk
dawn zealot
dawn zealot
deep yew
dim tusk
deep yew
#

or even the block.getItemStack

dawn zealot
#

its the spawn entity

dim tusk
dim tusk
#

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

dawn zealot
#
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

deep yew
#

placed blocks, when doing getItemStack(), do not save lore.

#

using beforeBlockPlace

subtle cove
#

Should it?

deep yew
#

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

valid ice
#

Use block properties

deep yew
#

well, specifically what and how?

valid ice
deep yew
#

so make a new permutation in the block.json?

valid ice
#

In the block BP file

deep yew
#

Are block BP files in the vanilla packs?

valid ice
#

I can show you an example spawner file- I have three properties. ones, tens and hundreds for the spawner stack value

valid ice
deep yew
#

Like spawner stacking as in 1 block that you click on and it adds spawners, multiplying rates?

valid ice
#

Yeah

deep yew
#

Was trying to see if the data saving stuff was possible in vanilla but a custom block with all these custom permutations sounds better

wary edge
#

Block dynamic properties cannot come any sooner.

valid ice
#

It’s a lot easier lol

steady canopy
#

Will we get also block dynamic properties only for non stackable blocks...

#

that would be dumb

deep yew
#

Might be unstackable with the same type without the same dynamic properties

valid ice
#

Like blocks that are placed in the world, I think Sean means

deep yew
#

Yeah it sounds counterintuitive but also logical, somehow

valid ice
deep yew
#

How would you modify/get "states" versus "permutations"?

#

or is it the same?

dim tusk
deep yew
#

Oka good, because the docs said"permutations" instead of "states" like his file

dawn zealot
#
            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..
dim tusk
#
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> });
dim tusk
dawn zealot
#

that getTags

#

works for updating the entities name somewhere in my code

#

but doesnt work here

valid ice
deep yew
#

Thank you so much. But what's the difference between the first setPermutation vs the second?

steady canopy
# valid ice

is 800-1600 ticks actually a normal spawn rate ?

#

In the vanilla spawners

valid ice
#

Just a value I've set for my custom spawners

steady canopy
#

i see

dim tusk
deep yew
#

Ohhh okay yes I am slow

dim tusk
#

Nah you're not, I just have a shit English and explanation lmfao

deep yew
#

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

wary edge
#

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.

wary edge
valid ice
#

I could imagine the pain you could cause the world by assigning every block placed a million properties drevil

wary edge
valid ice
#

fair

dim tusk
valid ice
#

ig items can be especially bad; I remember my world lagging when I moved a cheest filled with shulker boxes around my inventory

deep yew
# dim tusk they are the same.

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

steady canopy
#

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

wary edge
#

If you kill an entity does it save the properties?

steady canopy
#

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

wary edge
#

You are talking about a completely different thing.

steady canopy
dim tusk
wary edge
steady canopy
#

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

wary edge
#

Please, don't use ItemStack dynamic properties or Entity Dynamic Properties. Just use their ID and ContainerSlot as the key.

steady canopy
#

i guess what you're asking for would be just a simplified way of doign that.

dim tusk
#

block entities are sands, anvils, gravels etc.

wary edge
steady canopy
wary edge
dim tusk
steady canopy
dim tusk
#

then wadahel you mean by that.

#

oh yeah make sense lmfao

steady canopy
#

they are blocks that keep their stuff when you take them as an item

wary edge
steady canopy
#

and when u place them again

#

you have that stuff in the block again

#

so

wary edge
#

Block Dynamic properties are NOT block entities.

deep yew
#

paintings, item frames, etc.

steady canopy
#

thats my point

steady canopy
#

but what about that

wary edge
#

That's not the point of dynamic properties.

#

You are talking about something entirely different that I neveer brought up.

steady canopy
#

Dynamic properties is persistent data

#

why wouldn't it be

wary edge
#

You are talking about something entirely different. Not going to continue this conversation anymore.

steady canopy
#

k

deep yew
#

Thank y'all for the help, it goes a long way

dim tusk
#

The real help was the friends we made along the way.

bright dove
#

how do you make it so that once you destroy something every similar blocks above it also get destroyed ?

dim tusk
#

it's kinda like this.

subtle cove
#

Vines destroy kind

cold grove
#

Wdym by destroy kids

#

Oh- my bad

weary umbra
#

how can I import Vector3?

#

it was from something like math but I don't remember anymore

wary edge
weary umbra
wary edge
open urchin
#

it doesn't interact with minecraft at all, so there's no need for it to be part of the game

woven loom
#

I also didn't like that.

warm mason
#

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.

balmy mason
fallow rivet
#

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?

warm mason
# fallow rivet When the player holds the diamond sword, an entity will spawn and when the playe...
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()
      }
    }
  }
})
steady canopy
# fallow rivet When the player holds the diamond sword, an entity will spawn and when the playe...
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}`)
    }
})
steady canopy
warm mason
fallow rivet
#

Thanks

warm mason
#

js

steady canopy
#

This will work in ts or js

empty light
#

is there something like entity.extinguish or some way to make an entity no longer be on fire

dim tusk
#

The default value option in the slider doesn't accept float? Just wanna confirm since in the docs it says number not float

woven loom
dim tusk
#

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

inland merlin
dim tusk
inland merlin
dim tusk
#

Change it to pure white.

inland merlin
#

That's awesome it's working! Pure white makes sense

dim tusk
#

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?

inland merlin
#

No actually

dim tusk
#

This is sheep tga file since they changed color, they made it like this.

inland merlin
#

Oh ok

dim tusk
#

ignore the thing in the background I use that to real-time color preview lol

#

Unimportant but this is my little RGBA lmfao

sleek nexus
#

There's no way to open an NPC dialogue with body text set by a script, right?

inland merlin
vague helm
dim tusk
#

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.

dim tusk
#

and what's the line 149?

vague helm
#

i will grab it for you

#

system.beforeEvents.watchdogTerminate.subscribe(data => {
data.cancel = true;
});

vague helm
vague helm
#

yes

#

this was a pack from 9 ish months ago im trying to update it

dim tusk
#
system.beforeEvents.watchdogTerminate.subscribe(data => {
    data.cancel = true;
});```
dim tusk
gaunt salmonBOT
vague helm
#

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": ""
}
}

dim tusk
#

I'm talking about the minecart server script version not UI

vague helm
#

got it

dim tusk
vague helm
#

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

dim tusk
#

Nah jk

cold grove
vague helm
#

import { system, world, Vector } from "@minecraft/server";

dim tusk
#

either you create custom class or download a bundle

vague helm
#

got it thanks

dim tusk
#

there's a lot online just check them out

full brook
#

how to optimize system.runInterval?

deep yew
#

make it run every 1 or 5 or 10 ticks?

full brook
#

is there any other way than that?

dim tusk
full brook
# dim tusk 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;
    }
});
full brook
full brook
#

idk

full brook
#

okay

jolly veldt
#

Does onPlace work on natural generation too or just player placing?

wary edge
warm mason
dim tusk
#

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.

warm mason
dim tusk
wary edge
warm mason
#

This needs to be checked

wary edge
#

Last I checked onPlace works.

strong oar
#

guys do you know where to find the complete minecraft id list on the latest version of minecraft bedrock

fallow rivet
#
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?

wary edge
#

What exactly does not work? You're doing a lot of things.

strong oar
#

i did find it btw thanks

hazy vessel
#

Hello!

distant tulip
distant tulip
#

@granite badger your docs are down

granite badger
#

damn it

dim tusk
#

I was gonna say that too.

#

Lmfao

olive rapids
#

What website do I learn scripts on?

#

?

dim tusk
olive rapids
#

link

dim tusk
fallow rivet
distant tulip
#

uhm? just like you said

fallow rivet
distant tulip
fallow rivet