#Script API General

1 messages · Page 28 of 1

prisma shard
#

it does work here

granite badger
#

yeah the admins disabled my bot in that channel

prisma shard
#

alrighty

halcyon phoenix
#

hey is it possible to contain data inside an item?

#

I want to save strings or integers in an item

slow walrus
#

yes it's possible

#

items have dynamic properties

halcyon phoenix
#

when setting a lore is it possible to do breakline??

slow walrus
#

yes

#

\n

halcyon phoenix
#
item.setLore(["That's Overkill"]\n["wow])
#

like that?

shy leaf
#

it technically breaks line visually but its not the same as \n

distant tulip
#

to break lines use

item.setLore(["That's Overkill\nwow"])```
can be useful to avoid lore limit
halcyon phoenix
#

what's the difference of usin ' and \n?

shy leaf
shy leaf
remote oyster
#

Correct

shy leaf
#

both visually does the same but there are limits of how much letters you can put in a line and how many lines you can use for the lore

halcyon phoenix
#

welp thanks a lot people

distant gulch
#

Is there a way to open a gui from a block that have the player inventory in it without using entities

#

Opening something like this

ruby haven
#

Is it possible to add lore to items

distant gulch
ruby haven
#

How?

ruby haven
thin steeple
ruby haven
#

Oh I already figured it out it was actually in the loot table where you set the lore function I thought you need scripts haha silly me

north rapids
#

Is it possible to change entity health and speed via script?

#

Without using effects

loud brook
shy leaf
north rapids
#

I have to get the health component right?

#

And then change it

shy leaf
#

both speed and health are attributable component

#

and yes you have to

north rapids
#

can i change the damage too?

shy leaf
#

nah

#

only the stuff in attributable component

#

some components can be changed too but its only few

#

and damage cant be changed

north rapids
#

were can i find them?

north rapids
#

Tks bro

shy leaf
#

its attribute, not attributable

#

oops

north rapids
distant tulip
north rapids
#

Or it's permanent

odd sky
#

@distant tulip Iirc you tried to detect double chests before, did you manage to get that working? Nvm

distant tulip
north rapids
#

ok tks

distant tulip
odd sky
#

Interesting

distant tulip
#

maybe try getting the chest inventory?
but i thing it will give you just half of it

odd sky
#

Yeah, found this #1196695930104205393 so problem solved. Thanks

frozen vine
#

Does this work individually in multiplayer?

#

for example I want to summon something only for the player who died and not for all players on the map

last latch
#

entity after the if is the dead player

clear pendant
#

i want to shrink the player down

#

but the camera won't scale with the player

#

how can i move it

flat dew
#

how long until server 1.15.0 is out of beta?

thin steeple
flat dew
#

when is that?

#

sorry, I don't keep up with a lot of the updates and official events

winged gull
#

only on bedrock dedicated server

#

there you can use the @minecraft/server-net module

#

but sadly it does not work on realms and worlds

clear pendant
#

I saw there is a /connect command

#

Or a /wsserver

celest relic
#

Is it possible to test what biome a player is in?

thorn flicker
#

this is something I really want in the api, but its sadly not possible yet.

celest relic
lone thistle
celest relic
random flint
#

Isn't Dimension.findClosestBiome a thing? or is it still on preview?

tawny jungle
#

how can i get itemuseon to fire regardless of whether or not there is something in the hand?

thorn flicker
#

and it takes time to execute

little sphinx
#

`function isHoldingRequiredItem(player) {
const inventory = player.getComponent("minecraft:inventory").container;

if (!inventory) return false;

const mainHand = inventory.getItem(player.selectedSlot); 

return mainHand?.typeId === REQUIRED_ITEM;

}`
what the error??

abstract cave
#

What is block tick and how do i use it

little sphinx
#

I managed to solve it

distant gulch
#

why the hell do i keep getting this error
for this code


      Kits_Settings(player) {
        // Retrieve the current kit settings
        let kitsEnabled = world.getDynamicProperty('kits_enabled')
        let maxKits = world.getDynamicProperty('max_kits')
        let MoneySystem = world.getDynamicProperty('MoneySystemName')
             const form = new ModalFormData()
               .textField('Kits Limit (default is 10)', '10', maxKits)
               .toggle('Kits Enabled §cOFF§r/§aON', kitsEnabled)
               .textField('Defualt Money Scoreboard', 'money', MoneySystem)
               form.show(player).then((data) => {
                
                const KitsLimit = data.formValues[0]
            
                if (NaN(KitsLimit) || KitsLimit <= 0) {
                    player.sendMessage(`Error: ${Errors.NotANumber}`)
                    return;
                }



               })

    }
[Scripting][error]-Unhandled promise rejection: TypeError: Native optional type conversion failed.



shy leaf
distant gulch
shy leaf
#

a dynamic property might be having wrong type

#

like it might need number but it could be getting string

distant gulch
#

i just redid them with new names and stuff and it still breaks...

abstract cave
#

Is it possible to increase the tick speed of a certain area using script

slow walrus
slow walrus
#

you can't change tick speed at all in bedrock

abstract cave
# slow walrus no

oh, is there a workaround,
Im trying to make crops within a certain radius of a block grow faster,
is there a way i can simulate this

slow walrus
#

yes probably

#

not easily though

#

you'd have to find all the crops in that radius, keep track of them, and then set up your own random ticking interval to grow them

abstract cave
#

💀

random flint
#

If it returns Vector3 then just check if the player's location is within or near that Vector3

unique dragon
#

:yes_cat:

terse spindle
#

How would I detect the block permutation so that way my code avoids the block the state lb:opened set to true?

wheat condor
#

how do i get the container component of a chest?

idle dagger
#

How to teleport player to where is he facing?

wheat condor
wheat condor
idle dagger
tawny reef
#

can i get help please

unique dragon
last latch
# idle dagger how to player repair item that he holds?
const itemStack = player.getComponent("inventory").container.getItem(player.selectedSlotIndex);

itemStack.getComponent("durability") ? itemStack.getComponent("durability").damage = 0 : null;

player.getComponent("inventory").container.setItem(player.selectedSlotIndex, itemStack)
wary edge
#

@tawny reefDont go crossposting please

tawny reef
abstract cave
#

Umm, how do i use a block to get other blocks within a set radius

serene lava
#

question: in the newest versions of MCPE the new scripting works for IOS like in PC?

valid ice
#

Yep; script API works for all platforms, all users.

flat dew
#

is this still true?

open urchin
#

you can't modify ore ui with add-ons

flat dew
#

how do you use it then?

#

I'm just trying to make scoreboard variables show up above the hearts and armor for my world/realm

open urchin
#

you can still do that since the HUD isn't ore UI yet

flat dew
#

so ore ui isn't ready yet and we still use json ui until it is?

slow walrus
#

yes

abstract cave
#

When using custom commands, is there a way i can force the player chat menu to close after executing the commands

halcyon phoenix
#

is it possible to create a custom bundle?

wary edge
halcyon phoenix
#

oh sorry

halcyon phoenix
#

is it easier to use?

slow walrus
#

you cant

thorn flicker
idle dagger
#
const itemStack = player.getComponent('equippable')?.getEquipment('Mainhand');
          if (itemStack) {
          system.run(() => {
          itemStack.getComponent("durability") ? itemStack.getComponent("durability").damage = 0 : null;
            player.getComponent("equippable").container.setItem(Mainhand, itemStack)```

Error: cannot read property ‘setItem’

helppp
gaunt salmonBOT
# idle dagger ```js const itemStack = player.getComponent('equippable')?.getEquipment('Mainhan...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 4 errors:

<REPL0>.js:1:19 - error TS2552: Cannot find name 'player'. Did you mean 'Player'?

1 const itemStack = player.getComponent('equippable')?.getEquipment('Mainhand');
                    ~~~~~~

  @minecraft/server.d.ts:4559:15
    4559         class Player extends Entity {
                       ~~~~~~
    'Player' is declared here.

``````ansi
<REPL0>.js:5:13 - error TS2552: Cannot find name 'player'. Did you mean 'Player'?

5             player.getComponent("equippable").container.setItem(Mainhand, itemStack)
              ~~~~~~

  @minecraft/server.d.ts:4559:15
    4559         class Player extends Entity {
                       ~~~~~~
    'Player' is declared here.

``````ansi
<REPL0>.js:5:65 - error TS2304: Cannot find name 'Mainhand'.

5             player.getComponent("equippable").container.setItem(Mainhand, itemStack)
                                                                  ~~~~~~~~

``````ansi
<REPL0>.js:5:85 - error TS1005: '}' expected.

5             player.getComponent("equippable").container.setItem(Mainhand, itemStack)
                                                                                      

  <REPL0>.js:3:28
    3           system.run(() => {
                                 ~
    The parser expected to find a '}' to match the '{' token here.

Lint Result

ESLint results:

<REPL0>.js

5:84 error Parsing error: '}' expected

winged gull
grave thistle
#

How do i run a function on all entities from within a system.runInterval?

frozen vine
#

I made a script, on mobile it is working correctly, but on Windows it is not working as it should, does it make sense that this is happening?

wary edge
grave thistle
frozen vine
frozen vine
distant tulip
distant tulip
#

what is supposed to happen?

frozen vine
#

he should save the mob and then remove it from the world, after using the received item on a block he would load the saved mob only once

#

Now in Windows the whole process is correct, the only problem is when loading the mob, you save a single mob and it loads 2 mobs

#

in short the mob is being multiplied

subtle cove
#
world.beforeEvents.itemUseOn.subscribe(async({
  itemStack: item, source: player, block, isFirstEvent
}) => {
    if (!isFirstEvent) return;
subtle cove
#

i think so, try it

frozen vine
#

Okay

frozen vine
#

Is there no other way?

#

I wouldn't want to get rid of a script that took a lot of work to produce.

subtle cove
subtle cove
# frozen vine I wouldn't want to get rid of a script that took a lot of work to produce.
world.beforeEvents.itemUseOn.subscribe(async ({
    itemStack: item, source: player, block
}) => {
    const lore = item.getLore()
    if (item.typeId === "mc:genie_lamp_captured" && lore[0]) {

        if (player[item.typeId]) return
        else player[item.typeId] = true
        
        await null;
        system.runTimeout(()=> delete player[item.typeId], 10)
        
        player.onScreenDisplay.setActionBar({ translate: "function.lampe" })

        // Usando as coordenadas do bloco no qual o item foi usado
        world.structureManager.place(`${Number(lore[0].split("§fID: ")[1])}_mob_capture_device`, player.dimension, block)
        player.getComponent("equippable").setEquipment("Mainhand", new ItemStack("mc:genie_lamp"))
    }
})
untold magnet
#

dynamic properties are so much better than scoreboards for something like machines

#

for me i will use dynamic properties for all of my machines in my addon, i can use scoreboards but dynamic property is much easier and better

steady canopy
fallow minnow
#

anyone know if custom fishing would be possible?

#

I would like to NOT use entity.json's and purely script api

#

so like test when they catch a fish and do something

thin steeple
#

just remake the entire fishing system

#

have a custom fishing rod item, a hook entity, use scripts to determine where it goes when your fishing rod is used.

#

and have another system that randomly creates bubbles that move towards your rod entity. if in a distance of 1, make it so you can interact again and get a fish

runic crypt
#
import { world, system } from "@minecraft/server"

this is correct right ?
because bridge is acting weird :<

runic crypt
#

why is this not working ??

#

the import part that is

acoustic basin
#

hey guys! im thinking of switching to VSCode, what extension would u recommend for scripting?

keen thorn
acoustic basin
#

and for coding itself?

keen thorn
#

I don’t use any

#

Well I use a uuid extension

granite badger
#

Install the npm packages then it should provide types.

acoustic basin
wheat condor
#

how to get where the block is facing?

untold magnet
runic crypt
#

thanks tho

#

made this

#

clans, chat ranks, changeable names

untold magnet
#

ah, servers things

#

i don't want to make something like that bec i have no friends to play with anyway

fair quarry
#

Is there a way to spawn XP orbs with specific values?

#

Like in java there's "value" but in bedrock idk

coral ermine
#

How to change player holding item name or lore?

wise raft
#

How can I spawn a cat with a specific variant?

thorn flicker
#

entity.triggerEvent('event_name')

#

the spawnEntity method returns entity, so you can just do

spawnEntity('minecraft:cat', player.location).triggerEvent('event_name')

wise raft
#

Do you know how the event is called?

thorn flicker
#

no

#

take a look in this file

wise raft
#

There are only events for random variants

thorn flicker
#

well the variant value cannot be change in scripts

wise raft
#

thats bad

#

so there is no way to do that?

thorn flicker
#

I guess its not possible then

#

sorry

#

unless you want to change the cat.json to work how you want it to

wise raft
#

that is impractical

thorn flicker
#

lol

grave thistle
#

I'm struggling to make a type of display block like an item frame. I'm trying to make a sort of pedestal that will display the item used on it but can't seem to wrap my head around about doing in

meager cargo
#

I have issue with native method of spawning items on ground.

      case "apple":
        source.dimension.spawnItem("minecraft:golden_apple", endPosition);
        break;

Every time it shows me error that expected itemStack, native conversion failed. But whenever I'm changing this item to itemStack it is showing error in full script

wary edge
#

So:

new ItemStack('minecraft:golden_apple');
meager cargo
#
          const apple = new ItemStack("minecraft:golden_apple", 1); 
          source.dimension.spawnItem(apple, endPosition);           
#

Nevermind, it's late, It's working now

#

😄

#

Thank you!

junior hill
#
import { world, system } from "@minecraft/server"
import { ActionFormData, ModalFormData } from "@minecraft/server-ui"

world.beforeEvents.itemUse.subscribe(data => {
    let player = data.source
    let title = "§l§o§uWelcome"
    if (data.itemStack.typeId == "minecraft:compass") system.run(() => main(player))
    if (data.itemStack.typeId == "minecraft:clock") system.run(() => main_armor(player))
    if (data.itemStack.typeId == "minecraft:diamond") system.run(() => main_backpack(player))
    if (data.itemStack.typeId == "minecraft:emerald") system.run(() => main_radio(player))

After i added more system.runs, stuff starts not working

#

can someone help me why the ui wont open anymore?

#

with just the compass it works

#

but after i added more it stopped working

thorn flicker
junior hill
#

nvm, changing pack from vscode to bridge

#

just changed my manifest

#

and got rid of my modules

thin steeple
thorn flicker
thin steeple
#

stay vscode

thorn flicker
#

but I recommend using braces for those if statements

junior hill
#

just wanted to use some autocorrecting

#

for my stuff

#

bc using .json entites and adding events and component_groups sometime i miss a brace or parentheses and screws up the whole thing and vs code plugins dont catch the error

junior hill
thorn flicker
#

im talking about the if statements.

junior hill
#

i just send a part i thought there was an issue

#

the brackets are far down there somewhere

#

it works

thin steeple
junior hill
#

im just learning

#

i will see about that

#

question

                player.runCommandAsync("execute as @s at @s at @s if score @s DC17MSniperClassAmmo > @s lucky run give @s swmc:dc_17m_sniper_ammo")
                player.runCommandAsync("scoreboard players remove @s DC17MSniperClassAmmo 1")

these two commands when activated they intefer with each other or go in order?

thin steeple
# thin steeple why not use afterEvents to avoid having to use `system.run`? that repetitive fe...

also, i have a few suggestions.

  1. if you choose to use if statements and you have multiple near eachother, use braces. it's much better than not using them and they help you find the statements.

  2. use a switch statement, it will simplify having to use a bunch of if statements and make things a lot easier

  3. make a variable for your item so it won't always have to be data.itemStack.typeId // kind of long

junior hill
junior hill
#

i want to give and item depending if the score is less than 10

#

ik commands well and i just execute commands lol

shy leaf
#

try learning native API because it would be better that way in long term

shy leaf
junior hill
#

Jitter

#

interesting titles lol

thin steeple
# junior hill i want to give and item depending if the score is less than 10
const score = world.scoreboard.getObjective("DC17MSniperClassAmmo");
const score2 = world.scoreboard.getObjective("lucky");
const inv = player.getComponent("inventory").container;

if(score.getScore(player) < score2.getScore(player)) {
inv.addItem(new ItemStack("swmc:dc_17m_sniper_ammo", 1))
score.addScore(player, -1)
}
junior hill
#

wow thanks, this does look better

#

i will look into this more for other stuff

thin steeple
junior hill
#

docs always been confusing

#

more like the website

shy leaf
#

check microsoft official docs and jayly docs

junior hill
#

never got around finding them

#

on jayly docs

#

i press buttons

#

but they lead me no where

shy leaf
#

can be confusing at first though

thin steeple
zinc flax
#

How many scripts can you import into a main.js ?

fiery solar
# wise raft How can I spawn a cat with a specific variant?

Since the cat variant is random you can spawn one and check the variant through scripts. If it isn't the right one remove it and try again.

Sucks that we have to do it this way, but it's pretty fast. 99% chance that it won't take more than 50 tries to get the right variant.

valid ice
slow walrus
#

easier to read

tiny tartan
#

why entity.target is still beta? 😔

warm mason
#

to then change its name to targetEntity

distant tulip
abstract cave
#

Is there a way to control the time between events , onRandomTIck in block events

heady scarab
#

I need this now

distant tulip
acoustic basin
#

guys, how do i use isFirstEvent for playerInteractWithBlock?

#

i want ti stop the interaction to spam, but i dont understand how to use it

#
world.beforeEvents.playerInteractWithBlock.subscribe(data => {
    const item = data.itemStack
    const block = data.block
    const player = data.player
    const isFirstEvent = data.isFirstEvent
    isFirstEvent == true
    if (block?.typeId === 'minecraft:flower_pot' && item?.typeId === 'pd:mini_cactus') {
        system.run(() => {
            isFirstEvent == true
            block.setType('pd:potted_mini_cactus')
            if (player.getGameMode() !== 'creative') {
                player.runCommand(`clear @s pd:mini_cactus 0 1`)
            }
        })
    }
})```
this is what i have, but im sure im using it wrong
sharp elbow
#

It needs to be part of your if condition. Having isFirstEvent == true on its own line will perform a comparison (returning either true or false), but nothing is done with the result.

acoustic basin
#

okey, thank u so much!!

buoyant canopy
#

i have just discovered a shortcut to open the content log history

buoyant canopy
#

no, straight up keybind for it

open urchin
#

Ctrl + H?

buoyant canopy
#

Ctrl H

#

no body told me about it

#

THIS IS DAMN USEFUL

chrome flint
#

oh that's useful i didn't knew that keybind exist

wary edge
#

It's common knowledge lol

distant tulip
#

"discovered " lol

buoyant canopy
#

I even made a texture pack that places the history button on top of the settings screen because it's that important to me

#

and now I won't need it anymore XD

distant tulip
#

someone should make a hud button for mobile users

abstract cave
#

true

abstract cave
distant tulip
abstract cave
#

😮

#

thanks

buoyant canopy
#

what other shortcuts i don't know about?

abstract cave
#

Is there a way to get the permutations of a block

buoyant canopy
junior hill
#

Is binary teleporting a script thing?

scarlet lynx
#

Hey, I am in a rush to release my server in a hour.. How do I see if a item has a cooldown like if it currently has a cooldown as I want to only let it run if it doesn't have a cooldown through minecraft

open urchin
scarlet lynx
#

do I put my item name in there?

open urchin
#

which item do you want to check for?

scarlet lynx
#

pa:powerup1

#

ect I got more

open urchin
#

does it have the cooldown component? the category should be defined there

scarlet lynx
#

ye

#

ok ty

oblique eagle
#
    console.warn(entity)
    let player = data.player
    let entity = data.target

    if (entity.typeId == "myth:trade_market_guy") {
        Market.MarketMenu(player)
    }
})``` does anyone know why this isnt working?
thin steeple
oblique eagle
#

for some reason it worked perfectly fine with itemUse

buoyant canopy
oblique eagle
#

thats what i did

#

let entity = data.target

buoyant canopy
#

console.warn(entity)

oblique eagle
#

that was just for testing, i didnt have that before and it still didnt work

buoyant canopy
#

the rest looks good to me, then the problem might be in that Market class thing

oblique eagle
#

i tried putting the console.warn after

#

still didnt work

#

no matter what entity i click on, it doesnt work (the console.warn)

buoyant canopy
#

you are logging the entity itself, maybe log the typeId of the entity

oblique eagle
#

im logging a string

#

its just 'entity'

buoyant canopy
#

what does your code look like now?

oblique eagle
#
    
    let player = data.player
    let entity = data.target
    console.warn(`entity`)

    if (entity.typeId == "myth:trade_market_guy") {
        Market.MarketMenu(player)
    }
})```
thin steeple
#

do ${entity}

buoyant canopy
#

is beta Api active and you are using a the correct script version in the manifest

oblique eagle
buoyant canopy
#

do console.warn before the event?

#

and reload

thin steeple
oblique eagle
#

console.warn(`entity`) let player = data.player let entity = data.target console.warn(`entity`) none of these warns work lol

#

im not getting any errors in the log either

thin steeple
#

what if you got the typeId wrong

buoyant canopy
#

no, i mean outside the world.afterEvents

oblique eagle
#

yeah it works

buoyant canopy
#

hmmm

thin steeple
#

if it works fine with itemUse, then your function isnt the problem

oblique eagle
#

not even console.warn works

thin steeple
buoyant canopy
oblique eagle
#

inside the event it doesnt work

buoyant canopy
oblique eagle
#

my function is a form

thin steeple
buoyant canopy
# oblique eagle yeah

interesting, so the beforeEvents detects the interaction but the afterEvents doesn't?

thin steeple
#

the function

oblique eagle
#

thats weird

#

why wouldnt the afterEvent work?

thin steeple
buoyant canopy
olive rapids
#

Does anyone here have a teaching video to learn Script? basic level

twilit tartan
#

can someone help me with my questionNOOO

abstract cave
#
onTick(event) {
        const {
            block,
            dimension
        } = event

        const above = block.above(1);
        const below = block.below(1);
        const north = block.north(1);
        const south = block.south(1);
        const east = block.east(1);
        const west = block.west(1);

        const blockN = north.permutation.getAllStates()
        if (blockN == {
            "growth": 0
        }) {
            north.setPermutation(BlockPermutation.resolve("minecraft:air"));
        }
    }

nothing happens, no errors, no nothing

#

im trying to set the permutation of a block if its state is a certain number

oblique eagle
#

let blockFromViewDirection = player.getBlockFromViewDirection({ maxDistance: 30 }) anyone know if its possible to check how far the block the player is looking at is?

abstract cave
#
north.setPermutation(BlockPermutation.resolve("minecraft:wheat", growth:7));
#

how do i set the permutation

thorn flicker
oblique eagle
chrome flint
round bone
heady scarab
halcyon phoenix
#

how do you read a bundle's inventory?

#

I don't see a method on docs to read it

thorn flicker
halcyon phoenix
#

is there any way though or workaround?

abstract cave
#

What is this vector differences and how do i use it to get multiple blocks within a radius

distant tulip
#

get the blocks in an area and filter out blocks that there distance is larger than the radius (using the differences between there location and the original location)

halcyon phoenix
#

there might be better method but that's how I do it

slim spear
#

How would i get a left and right offset based on the player's camera in scripts? been trying to figure it out for a bit but my brain is mush

#

like how /particle minecraft:basic_flame_particle ^-1^^ is right and /particle minecraft:basic_flame_particle ^1^^ is left

slim spear
#

now i'm trying to figure how how to turn rotation values into a vector3

slow walrus
#

you'll needa calculate the forward and right direction vectors from the camera's view rotation

#

right will be the camera rotation + 90 degrees

#

or -

#

depends which way it rotates

#

then you just use trig functions to calculate the x and y components of the direction vector

honest spear
#

its same for vectors

#

(aV - bV)

#

the result is difference verctor

#

the vector difference in meaning of gettings blocks in radius is just cutting the block offset so you have to do the

(blockToTestVector - entryPointVector).length < radius

runic crypt
#

can anyone help me with a script in which if i place a sponge, it clears all lava in a 5 block radius ???

#

if you can please ping me

buoyant canopy
#

can we get the location of the nearest custom structure with script api?

wheat condor
buoyant canopy
#

yeah, but i want to locate the structure even if unloaded

wheat condor
#

that isnt possible unless you generate structures with script api

buoyant canopy
#

ok, thank you

vestal violet
#

How to detect when an entity is inside a block, something similar to this, but with script

                                            "test": "in_block",
                                            "value": "tall_grass",
                                            "subject": "self",
                                            "operator": "=="
                                        }```
misty pivot
#

how do i use setHudVisibility?

distant gulch
#
world.afterEvents.playerInteractWithEntity.subscribe(({ player, target }) => {
    if (target.hasTag("SpawnCow")){
        player.runCommand("/tp @s 1118 116.5 805")
    }
})``` 
I Need help this doesnt work on 1.21.30 for me
unique dragon
#

oh wait

#

haven't read the question

unique dragon
distant gulch
unique dragon
distant gulch
#

its for my lobby

#

trying to make it so if u right click a npc it will run a custom command we made

#

which will redirect the player

unique dragon
#

ok but, also beta apis experiment toggle on?

#

cause it's strange

distant gulch
#

yes

junior hill
#

Does anyone know how to turn script ui text field into a const?

#

So i can use like in teleporting coordinates?

unique dragon
unique dragon
distant gulch
#
    "format_version": 2,
    "metadata": {
        "authors": [
            "HiveLanky"
        ]
    },
    "header": {
        "name": "§l§uB+ S5.2",
        "description": "",
        "min_engine_version": [
            1,
            20,
            80
        ],
        "uuid": "40f7605b-e51c-4dd5-a89c-64cd929c9e69",
        "version": [
            1,
            0,
            0
        ]
    },
    "modules": [
        {
            "type": "data",
            "uuid": "0f3d8e5f-a6b2-4e36-bfce-92f51f021bdb",
            "version": [
                1,
                0,
                0
            ]
        },
        {
            "type": "script",
            "language": "javascript",
            "uuid": "127111b6-49cb-440c-8e0c-0da777c8444c",
            "entry": "scripts/main.js",
            "version": [
                1,
                0,
                0
            ]
        }
    ],
    "dependencies": [
        {
            "uuid": "a48d4554-bdf3-4393-87d9-73edb910996b",
            "version": [
                1,
                0,
                0
            ]
        },
        {
            "module_name": "@minecraft/server",
            "version": "1.15.0-beta"
        },
        {
            "module_name": "@minecraft/server-gametest",
            "version": "1.0.0-beta"
        },
        {
            "module_name": "@minecraft/server-ui",
            "version": "1.4.0-beta"
        }
    ]
}```
unique dragon
#

change afterEvent to beforeEvent

#

that should work

distant gulch
#

world.beforeEvents.playerInteractWithEntity.subscribe(({ player, target }) => {
if (target.hasTag("SpawnCow")){
player.runCommand("/tp @s 1118 116.5 805")
}
})

#

like that?

unique dragon
#

yes, just remember that before events can't modify the world, so your runCommand, put it inside of a system.run()

distant gulch
#

wat?

unique dragon
#

also you should use teleport method of entity

unique dragon
distant gulch
#

im going to change it so instead of /tp it will be /transferserver

#

are you able to just quickly write something out

unique dragon
# unique dragon let me make an ex
world.beforeEvents.playerInteractWithEntity.subscribe(({ player, target }) => {
    if (target.hasTag("SpawnCow")){
    system.run(() => {
player.runCommand("/tp @s 1118 116.5 805")
    });
    }
})
#

like that

runic crypt
#

@distant tulip
i made something wanna see ??

tardy wraith
#

there's a way to give a player an item with different enchants in it?
for example a sword already enchanted with sharpness and unbreaking

unique dragon
#

itemStack is a constructor

#

just add the enchantments

#

and then set the item

coral ermine
#

Where is an error here?
it not showing errors but not working when I shoot bow and arrow hitting entity

world.afterEvents.projectileHitEntity.subscribe(event => {
     const { source, projectile } = event;
     if (projectile.typeId === 'minecraft:arrow') {
       if (source?.typeId === 'minecraft:player') {
            const hitEvent = event.getEntityHit()?.entity;
            source.playSound("random.orb")
            hitEvent.playSound(“random.orb”)
       }
    }
});```
sharp elbow
#

Your hitEvent.playSound(“random.orb”) uses non-standard quotation marks. Look closer at this line

meager zenith
#

can anyone help me, how do you get enchantments from an item

wheat condor
meager zenith
#

thank you

wheat condor
meager zenith
wheat condor
runic crypt
coral ermine
sharp elbow
#

I'm guessing that the module (or script) is failing to validate entirely. Does the rest of your scripting work fine?

#

Generally syntax errors will prevent a script from validating. That is different from a run-time error

coral ermine
sharp elbow
#

Does fixing the quotation marks also fix the projectile issue?

grim raft
#

yo how can I detect if someone doesnt have a tag, ik about hasTag(), do I need to put a "!" in it or is there another way

grim raft
#

wait hasTag on an item?

open urchin
#

oh misread

#

you can do that for entities too

grim raft
#

ik I can but never saw hasTag for items

#

how does that work?

open urchin
#

the item JSON file contains a minecraft:tags component which is a list of tags that the item has

grim raft
#

oh

#

tbh you helped me with something else at the same time lol

#

was searching for that too

olive rapids
#

can someone help me create a script?

jaunty relic
#

what is the best method to do an event with items and also use the cooldown and durability system with the item?

  • CustomComponent
  • beforeEvent.itemUse
jaunty relic
thin steeple
jaunty relic
junior hill
#
}
        function main_radio() {
            const form = new ActionFormData()
                .title("radio")
                .body("textures/ui/gui_blue")
                .button(`Plugin Cordinates\n§8[ Click to View ]`)
                .button(`Radio Options\n§8[ Click to View ]`)
                .button("§cExit Menu")
            form.show(player).then(r => {
                if (r.selection == 0) cord(player)
            })
        }
    function airStrike(player, location) {
    const oldLoc = player.location
    player.teleport(location)
                    player.dimension.spawnEntity('minecraft:warden', location)
    player.teleport(oldLoc)
}
function cord(player) {
    new ModalFormData()
  
        .title("airStrike")
        .textField("X coordinate:", "", "0")
        .textField("Y coordinate:", "", "0")
        .textField("Z coordinate:", "", "0")
        .submitButton("SEND AIR STRIKE")
        
        .show(player).then(({ formValues: r }) => {

            if (r.every(value => Number.isInteger(value)))

                airStrike(player, { x: r[0], y: r[1], z: r[2] });

            else player.sendMessage("Value not accepted")
            })
        }

Could someone help me find the error, i hope fresh eyes can find it?

gaunt salmonBOT
# junior hill ```js } function main_radio() { const form = new ActionFormD...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 3 errors:

<REPL0>.js:1:1 - error TS1128: Declaration or statement expected.

1 }
  ~

``````ansi
<REPL0>.js:9:23 - error TS2552: Cannot find name 'player'. Did you mean 'Player'?

9             form.show(player).then(r => {
                        ~~~~~~

  @minecraft/server.d.ts:4559:15
    4559         class Player extends Entity {
                       ~~~~~~
    'Player' is declared here.

``````ansi
<REPL0>.js:10:44 - error TS2552: Cannot find name 'player'. Did you mean 'Player'?

10                 if (r.selection == 0) cord(player)
                                              ~~~~~~

  @minecraft/server.d.ts:4559:15
    4559         class Player extends Entity {
                       ~~~~~~
    'Player' is declared here.

Lint Result

ESLint results:

<REPL0>.js

1:0 error Parsing error: Declaration or statement expected

fading sand
#

how do i check if an player is getting kicked?

junior hill
serene radish
#

does anyone have a script that immitates the clearvelocity function but for players?

sage portal
serene radish
#

not sufficient since it messes with player head rotation

#

and teleport itself doesnt clear velocity very well

ripe swan
#

I had no idea there was a VectorXZ...

#

Thanks for pointing that out, SmokeyStack

jaunty relic
#

Hi how i do to implement minecraft:cooldown & minecraft:durability with custom component ?

oblique eagle
#

is it possible to draw a line with particles from one pair of coordinates to another?

buoyant canopy
#

why does itemStack.hasComponent("minecart:food") always return false?

#

even if the item is food

#

what am i doing wrong?

#

i am using it in a itemCompleteUse after event

#

oh no... it says this component only applies to data driven items.

#

is there another way to tell if an item is a food item or not?

dense skiff
#

What is the max chars or bytes for a dP?

fallow minnow
#
function loadingForm(player: Player) {

    const run = system.runTimeout(() => {
        uiManager.closeAllForms(player);
        system.clearRun(check);
        console.warn("finished");
    }, 20 * 5);

    const check = system.runInterval(() => {
        console.warn(run);
    }, 20 * 0.5);

    new ActionFormData()
        .title("panel1")
        .button(`a`)
        .show(player).then((result) => {
            if (result.canceled) system.clearRun(run);
        });
}``` is "run" supposed to keep increasing by 2? Or is that not supposed to happen..
fallow minnow
dense skiff
fallow minnow
#

characters

#

i believe

buoyant canopy
fallow minnow
#

there is a way

#

test if the item has the "minecraft:food" component

#

like this js if (player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand).hasComponent("minecraft:food")) return console.warn("this is food!!");

#

u can split it up but i wasnt bothered

#

i think thats right

thin steeple
slow walrus
#

it that makes sense

fallow minnow
#

I was just wondering if it was supposed to reset after I clear a run..

#

Like it always goes up by 2

#

well 1 now

#

So itll start at 0 and if I run that function 10 times it'll be 10

#

And to reset it I have to reload

#

So are those runs still running in the background?

fiery solar
fallow minnow
abstract cave
#
if (blockGottenId.includes(cropList)) {
                        blockGotten.setPermutation(BlockPermutation.resolve("minecraft:torchflower_crop", {
                            "growth": 7
                        }))

for some reason the .includes part aint working do you know why

fallow minnow
abstract cave
fallow minnow
#

you're supposed to check if the array includes the value

halcyon phoenix
fallow minnow
#

not value includes array

halcyon phoenix
#

is there no listeners for bundles?

#

when item is inserted or when item is removed?

fallow minnow
abstract cave
#

[Scripting][error]-TypeError: not a function at onTick (custom_components/crop_growth.js:
why this error

if (cropList.includes(blockGottenId)) {
                        switch (blockGottenId) {
                            case 'minecraft:wheat':
                                blockGottenId.setPermutation(BlockPermutation.resolve("minecraft:wheat", {"growth": 7}))
                                break;
                            
                            default:
                                // code
                        }
abstract cave
fallow minnow
abstract cave
#

[Scripting][error]-TypeError: not a function at onTick (custom_components/crop_growth.js:54)

#

this is the error

#

i think i accidentaly deleted something

fallow minnow
#

where is onTick

abstract cave
fallow minnow
#

idk i can't see everything

abstract cave
fallow minnow
abstract cave
#

[👀 ]

elder heath
halcyon phoenix
abstract cave
#

In block permutations, whats the difference between resolve and withState

subtle cove
#

resolve allows u to make default/edited states,
withState just have one state to edit

dense skiff
#
{
    "hud_title_text": {
        "type": "image",
        "size": [ "100%c + 10px", "100%c + 8px"],
        "alpha": 0.8,
        "anchor_from": "top_right",
        "anchor_to": "top_right",
        "offset": [ 0, 0 ],
        "texture": "textures/ui/Gray",
        "layer": 30,
        "controls": [
            {
                "title": {
                    "type": "label",
                    "text": "#text",
                    "layer": 31,
                    "localize": false,
                    "font_size": "small",
                    "font_scale_factor": 1.6,
                    "bindings": [
                        {
                            "binding_name": "#hud_title_text_string",
                            "binding_name_override": "#text",
                            "binding_type": "global"
                        }
                    ]
                }
            }
        ]
    }
}```
Why do I get this error? There is no orientation property lol.
subtle cove
long cargo
#

How do I make it so that players with certain tags cannot be hit or hit other players and entities?

subtle cove
#

iirc, there's no proper script-api way
player.json damage_sensor is one of the options

misty pivot
#

how does setSpeedAndDirection work? i know if it's syntax, what i mean is what do i need to add in the custom particle file? (im using snowstorm btw)

pseudo timber
#
export function openSellPad(player) {
let sellPadForm = new ModalFormData()
.title("Sell an Item")
.dropdown("Select an item to sell", [
"Apple",
"Carrot",
"Potato",
"Golden Carrot",
"Golden Apple",
"Diamond",
"Gold Ingot",
"Iron Ingot",
"Cobblestone",
"Stone",
"Oak Log",
"Spruce Log",
"Birch Log",
"Jungle Log",
])
.slider("Select a Quantity",1,64,1,1);

sellPadForm.show(player).then((response) => {
let selectedItem = ["Apple","Carrot","Potato","Golden Carrot","Golden Apple","Diamond","Gold Ingot","Iron Ingot","Cobblestone","Stone","Oak Log","Spruce Log","Birch Log","Jungle Log"][response.formValues[0]];
let selectedQuantity = response.formValues[1];
let sellPrice = 0;

switch (selectedItem) {
case "Apple":
sellPrice = 5;
break;
case "Carrot":
sellPrice = 3;
break;
case "Potato":
sellPrice = 2;
break;
case "Golden Carrot":
sellPrice = 15;
break;
case "Golden Apple":
sellPrice = 20;
break;
case "Diamond":
sellPrice = 100;
break;
case "Gold Ingot":
sellPrice = 50;
break;
case "Iron Ingot":
sellPrice = 10;
break;
case "Cobblestone":
sellPrice = 1;
break;
case "Stone":
sellPrice = 2;
break;
case "Oak Log":
sellPrice = 5;
break;
case "Spruce Log":
sellPrice = 5;
break;
case "Birch Log":
sellPrice = 5;
break;
case "Jungle Log":
sellPrice = 5;
break;
}

let count = 0;
for (let i = 0; i < player.getComponent("minecraft:inventory").container.size; i++) {
let item = player.getComponent("minecraft:inventory").container.getItem(i);
if (item && item.name == selectedItem) {
count += item.amount;
}
}

if (count >= selectedQuantity) {
player.runCommand(`clear @s "${selectedItem.replace(' ', '_')}" ${selectedQuantity}`);

let totalSellPrice = sellPrice * selectedQuantity;

// Add money to player's scoreboard
player.runCommand(`scoreboard players add @s Money ${totalSellPrice}`);
player.sendMessage(`§aYou have sold ${selectedQuantity} ${selectedItem}(s) for §e${totalSellPrice} coins!`);
} else {
player.sendMessage(`§cYou don't have enough ${selectedItem}(s) to sell!`);
}
});
}

I know its done wrong need help selling the item/getting rid of it and testing for item

worn palm
#
// item_and_price.js
export default {
    "minecraft:apple": 5,
    "minecraft:carrot": 3,
    // rest of the items and their price
}

in the file where your switch-case is

import items from "./item_and_price.js"
// your codes here
// remove switch case and put this
for(let [item, price] of Object.entries(items)) {
    if(selectedItem == item) {
        sellPrice = price;
    }
}
#

@pseudo timber

#

this will fix the mess of switch case

pseudo timber
worn palm
#

check if it works

buoyant canopy
# fallow minnow yes

wow, you are so smart!
I can't believe i didn't think of that, tried it, got confused about why doesn't it work, came here, and found out why

wheat condor
sharp elbow
idle dagger
#

what does itemUseOn event do?

halcyon phoenix
#

if we could just read bundle inventory. Sigh

warm mason
drowsy scaffold
#

how do I check if an entity is in creative?

#

nvm got it

stone bridge
#

Hi ther

#

What does "?" in function does? Is it actually needed

#

Script is not mine, one guy copied it from examples from somewhere

warm mason
#

It checks the previous parameter. (if it is undefined and you write a dot, it will give an error, but if with "?" then there will be no error)

stone bridge
#

Thx

warm mason
# stone bridge

|| Крутое сообщение о смерти кстати) ||

stone bridge
distant tulip
#

it is kinda pointless there btw

warm mason
quartz token
#

привет?)

distant tulip
warm mason
stone bridge
stone bridge
distant tulip
quartz token
#

я тоже.....

#

крч какой вопрос

warm mason
#

The rules don’t seem to say that you can’t communicate in your native language, but I would do it more carefully

distant tulip
#

this is English only server @quartz token @stone bridge

stone bridge
# quartz token я тоже.....

Лучше переведи, а то можешь и бан ненароком словить. Сервер чисто англоязычный

quartz token
#
import { world, Player, EntityInventoryComponent, EquipmentSlot } from "@minecraft/server";

world.afterEvents.entityHitEntity.subscribe((event) => {
    const attacker = event.damagingEntity;
    const target = event.hitEntity;
    world.sendMessage('dasd')
    if (attacker instanceof Player) {
      
        const inventoryComponent = attacker.getComponent("minecraft:inventory") as EntityInventoryComponent;
        const itemInHand = inventoryComponent.container?.getItem(attacker.selectedSlotIndex); 
        if(String(itemInHand?.typeId) == "minecraft:stick"){
          attacker.sendMessage((target.typeId+    " был(а) вьебан(а) "+ attacker.name))
          target.applyKnockback(0,0,0,5)
        }   
}});

warm mason
warm mason
distant tulip
quartz token
stone bridge
quartz token
# quartz token

Perhaps "inventoryComponent" has the value undefined.ts(18048)

distant tulip
quartz token
#

yes

distant tulip
#

maybe add ? after get component

quartz token
#

everything worked on the newest version, but there was an error on 1.20.50

warm mason
#
import { world, Player, EntityInventoryComponent, EquipmentSlot } from "@minecraft/server";

world.afterEvents.entityHitEntity.subscribe((event) => {
    const attacker = event.damagingEntity;
    const target = event.hitEntity;
    world.sendMessage('dasd')
    if (attacker instanceof Player) {
      
        const item = attaker.getComponent("minecraft:equippable").getEquipment("Mainhand")
        if(String(item?.typeId) == "minecraft:stick"){
          attacker.sendMessage((target.typeId+    " был(а) вьебан(а) "+ attacker.name))
          target.applyKnockback(0,0,0,5)
        }   
}});
wheat condor
stone bridge
#

Didnt knew it can be added in the middle

distant tulip
#

that is a player
container should be defined
that error is just from ts or idk

quartz token
#

Perhaps the object is undefined.ts(2532)

idle dagger
distant tulip
#

same thing

warm mason
quartz token
warm mason
#

if you're talking about the one in the code editor, then change the editor

warm mason
#

well, or put "?" before the points

quartz token
warm mason
#

where is it written

quartz token
warm mason
# quartz token

don’t pay attention to this, either change the editor or try switching to js (it’s faster by the way)

warm mason
#

item = item.getEquipment("Mainhand")

warm mason
quartz token
quartz token
warm mason
#

what a mistake

quartz token
quartz token
warm mason
quartz token
warm mason
wheat condor
#

how do i fix after events on use on not working?

#
world.afterEvents.itemUseOn.subscribe(({ source, itemStack, block }) => {
    console.warn("click")
})

doesnt work, i also have the custom component of the block to make the item can right clicked

quartz token
#

how to fix it?

distant gulch
wheat condor
#

i fixed it with before events somehow

distant gulch
wheat condor
distant gulch
distant gulch
#

@wheat condor but if you want to check if he interacts with the block use this:

world.beforeEvents.playerInteractWithBlock.subscribe((evd) => {

});
wheat condor
wheat condor
#

wait

#

wahts the name of thje durability component

#

getComponent("durability") ?

distant gulch
#

yeah

#

or minecraft:durability

wheat condor
#

why does auto completions not work for components for me

distant gulch
#

maybe it isnt installed

wheat condor
distant gulch
#

hmm with bridge i can't help you, ive never used it before

quartz token
distant gulch
# quartz token <@851647086571290685>

Check if the scripts folder exists: Ensure that the scripts folder exists and contains TypeScript (.ts) files. If it's located elsewhere, modify the path in the include section.

wheat condor
distant gulch
wheat condor
#
if (dmg < durability) {
    dmg += 1
} else {
    itemStack = null
}
//set itemstack in inv

thats the right syntax?

distant tulip
#

there is really no point in using ts without knowing what is used for

wheat condor
#

for items durabilitty?

wheat condor
#

for damage and max durability

distant gulch
#

yes should be

distant gulch
#

yes its right

quartz token
distant gulch
#

huh

quartz token
#

why does everything work in the single world and when I upload it to the server it doesn't work(?

warm mason
#

Are you using beta api?

quartz token
#

yes

warm mason
#

Are you sure they are enabled in the world on the server?

quartz token
#

yes

warm mason
#

What error will you get?

quartz token
quartz token
distant tulip
#

see the server log

#

it should have a console

warm mason
#

How did you realize that something wasn’t working?

quartz token
#

well, in my solitary world, when I beat someone, an event was triggered, but not here

#

I found the valid_known_packs file.json now try to come up with something

warm mason
#

By the way, yes. Your packs should be in json files in the world folder

quartz token
#

He's not even here.

distant tulip
#

behaviors are server side

quartz token
distant tulip
#

hmm?
you said it is not working on a server

quartz token
distant tulip
#

so.. what is the point of both screenshots?

quartz token
distant tulip
jaunty relic
proper forum
#

How does system.runJob() know when to proceed in the next tick? Does it limit iterations based on device specifications (such as chunk limits) or does it notice that execution becomes slow?

distant gulch
crude bridge
#

How can i create a button that create another botton but only for you, and nobody sees them

pale terrace
#

getBlocks is in stable in some preview?

unique acorn
#

can i use minecraft/server-net on a realm?

warm mason
cinder shadow
#
const volume1 = {x:location.x - 1, y:location.y, z:location.z - 1};
    const volume2 = {x:location.x + 1, y:location.y, z:location.z + 1};
    const combinedVolume = new BlockVolume(volume1, volume2);
    const blocks = block.dimension.getBlocks(combinedVolume, {includeTypes: ['runecraft:white_rose']}, false);``` does anyone see something wrong with this?
#

the block in questions is surrounded by the block

#

oh wait

#

I forgot getBlocks was totally useless

true isle
#

Is it possible to do setblock from an array so it's like a randomized setblock

drowsy scaffold
#

how do I access an entities time of fire duration? like how long it's still on fire for

#

holy crap I can be message 100k

#

boom

simple zodiac
#

nah

#

there have been a bunch of 100.000th messages

granite cape
misty pivot
#

if a player or entity dies, does isValid() set to false? or only when they despawn/leave?

ruby haven
#

Where should I ask about feature and feature rules

wary edge
ruby haven
#

Thanks bro

limber dove
#

Hello

limpid parcel
#

Which is better to store data, scoreboard or dynamic properties?

wheat condor
limpid parcel
wheat condor
distant tulip
#

probably not faster but it is the safer and intended way of storing stuff

honest spear
#

dynamic properties are way more faster

#

Scoreboards are no competition

#

only upside for scoreboads are shareablity between packs and way to split data based on objectives

distant tulip
#

oh alr
i was searching for a benchmark you posted and couldn't find it
i remembered someone saying scoreboard are faster

wheat condor
#

i think scoreboard runs only on next available tick so it can have like 0.05 ms of latency

honest spear
#

afaik

distant tulip
#

i may be wrong then (in saying i heard it somewhere)

honest spear
#

its all right, i just got confused

shut citrus
#

how to lock mob's direction in 8 ticks

pseudo timber
#

anyone help me with this

#

ik i need to remove or add but everytime i try it messes up

distant tulip
pseudo timber
#

Yeah I'm trying to fix but everytime I remove etc it breaks

pseudo timber
distant gulch
pseudo timber
distant gulch
#

i removed them for you instead

pseudo timber
distant gulch
#

wait or did i missunderstood it

#

show me where you use the split method

pseudo timber
distant gulch
#

where do you use it?

#

if you have it mutliple times in there you can try it by dong this:

pseudo timber
#

:/

distant gulch
#
// the split method
console.warn('SPLIT-01 WORKS') // will not get called when error in the upper split method occours
#

so you can identify the location of it

pseudo timber
#

still says this with that

distant gulch
#

i meant put this below the split method

#

lets chat via dm @pseudo timber

idle dagger
#

How to make mob attack his family mob? Like skeleton attack skeleton or skeleton attack zombie

Without making them shooting themself

pseudo timber
#

@distant gulch ^^ where to put it

round bone
#

is therr any way to get player XUID via this API?

#

currently using IPC and looking for something more efficient

#

every module allowed btw

round bone
fallow minnow
#

But maybe in 1.20.50 🧐

#

Not too certain if you'll be able to read packet data or not

round bone
fallow minnow
#

So like a BDS server

round bone
#

i js need xuid to have unchangable primary key for my external db

fallow minnow
#

yeah

fallow minnow
round bone
#

join packet is probably sending XUID of a player

fallow minnow
#

Supposedly people were saying you can only read the packet size, send, and cancel them

round bone
#

yeah

#

docs told me the same

#

so just need to wait for new methods

#

or there might be a small chance that PlayerJoinAfterEvent.playerId might be it

#

but it's a string, so it's probably an entity id

distant tulip
untold magnet
#

hm

#

entity?.extinguishFire should detect if the entity is on fire?

#

apparently i can use entity.getComponent('minecraft:onfire') too

distant tulip
untold magnet
#

ah,

crude bridge
#

Someone can help me

untold magnet
#

im trying to make a small system that will detect if the entity is on fire or not.

crude bridge
#

How can i make a function that make 34 command all the sale but with 34 number

crude bridge
crude bridge
#

But not in 34 line of code

untold magnet
distant tulip
untold magnet
#

ah, mybad

marsh pebble
#

pls

pseudo timber
marsh pebble
#

everythinmg

#

it says not enough money

#

const plotBorderBlock = "minecraft:polished_blackstone";
Should be a boprder block

wary edge
marsh pebble
#

i have no idea wjat that is

#

i just started jslike 3 days ago

wary edge
marsh pebble
#

yes

#

1 hour ago

pseudo timber
marsh pebble
#

um

pale terrace
#

getBlocks is in stable in some preview?

granite badger
#

no

pale terrace
#

thx

round bone
subtle cove
# idle dagger anyone

Not possible to manipulate mob behavior, but u can trigger entity.json events using script

slow walrus
# pseudo timber

remove the comma all the way at the end, before the array's closing bracket. it's adding a null value to the end of the array, which is why you're getting the error

quartz token
#

I'm here again) how do I make a delay before teleporting?

import { world, system } from '@minecraft/server';
import {
  ActionFormData,
  MessageFormData,
  ModalFormData
} from "@minecraft/server-ui";

world.beforeEvents.playerBreakBlock.subscribe(event => {
  const item = event.itemStack; if(item?.typeId == "minecraft:compass" && item.nameTag == "§l§bМеню"){
    event.cancel = true;
  }
  return;
});

world.beforeEvents.itemUse.subscribe(data => {
  const player = data.source;

  if (data?.itemStack?.typeId == "minecraft:compass" && data?.itemStack?.nameTag == "§l§bМеню") {
    system.run(() => form(player));
  }

  function form() {
    const form = new ActionFormData();
    form.title('§l§1МЕНЮ');
    form.button('§lТп на спавн', 'textures/ui/check');
    form.button('§c§lЗакрыть', 'textures/ui/cancel');
    
    form.show(player).then(r => {
      switch(r.selection) {
        case 0:
            tp(-7, -53, 1);
            player.runCommandAsync('playsound note.harp @s');
          break;
        default: return;
      }
    });
  }

  function tp(x, y, z) {
      player.runCommandAsync('effect @s blindness 2 255');
      player.runCommandAsync(`tp @s ${x} ${y} ${z}`);
  }
});


cold grove
#

system.runTimeout(tp(), ticks);

quartz token
distant tulip
#

you need the callback

#

system.runTimeout(() => {
player.teleport(vector3)
}, Ticks);

quartz token
quartz token
cold grove
sage portal
#

is there any component I need to add to an item before using the itemUse event?

quartz token
sage portal
#

asked in the wrong channel, whoops

#

I get the script side, I was asking for .JSON

quartz token
#

how do I give the player an item with my own name(compass name=Menu)

slow walrus
#

new ItemStack, Item.nameTag = "Menu"

#

or something like that

untold magnet
#

is it possible to make a daylight sensor using scripts only?
daylight sensor works when the block is facing the sunlight and if the block above the daylight sensor is blocking the sunlight it will stop working

#

how can i do that using scripts?

rapid sail
#

a script where it plays custom audio then loops?

untold magnet
#

hmm,

#

what does block.dimension.getTopmostBlock even do?

wary edge
untold magnet
winged gull
#

just get the game time and weather for that

untold magnet
#

i just want to make the system works only when the block is facing the sun, just like how zombies burns in daylight

#

but for the block, without adding entities

winged gull
#

oh then i guess in that case it could be used

#

you would use it to see if the top solid block is above that block's position

untold magnet
#

only if any of the above blocks is solid / cannot block the sunlight like glass

untold magnet
untold magnet
#

ah, there's a getBlockFromRay for the block

winged gull
#

yes

untold magnet
#

i dont have to use entities for that,

winged gull
untold magnet
#

is it will throw errors if the detention is detecting blocks outside the high limit?

quartz token
untold magnet
#

like if i place the block at y200 and it start detecting blocks that above the y limit it will throw errors?

winged gull
untold magnet
#

so i can make the ray of it infinity and it shouldn't throw any errors rightpepe_listening

#

lemme try and see.

winged gull
#

not infinity

#

just 9999

untold magnet
#

ik

winged gull
wheat condor
#

0.05 seconds

winged gull
wheat condor
winged gull
wheat condor
#

finally mojang is adding customizable dimension

winged gull
#

only works for overworld though

#

and makes world generate as void

wheat condor
#

cant wait for dimension creation

winged gull
#

so you have to modify chunks beforehand to stop them from dissappearing

#

this has been a feature since 1.18.30 btw

wheat condor
quartz token
#

I can't get a name tag in the last event

and only lock_in_slot

like I have a compass locked in the 8th slot

if I don't put a locked object there, then everything is ok

world.afterEvents.entityHitBlock.subscribe(data => {
  var player = data.damagingEntity;

  const item = player.getComponent("minecraft:inventory").container.getItem(8);
  player.sendMessage(String(item?.nameTag))
  player.sendMessage(String(item?.typeId))
  if (String(item?.typeId) == "minecraft:compass") {
    item.nameTag = "§l§bМеню"
  }
});
wheat condor
untold magnet
#

uh,

#

getBlockFromRay(block.location, { y }, { maxDistance: 999 })?

#

that should detect blocks from above?

winged gull
untold magnet
#

idk about Victor3 thingt17xBoost

wheat condor
#

you also need to replace the old compass with the new one created by your script

player.getComponent('inventory').container.setItem(player.selectedSlotIndex, itemStack)

@quartz token

winged gull
untold magnet
#

ah

#

done, what next?

winged gull
#

for the direction do {x: 0, y: -1, z: 0}

untold magnet
#

noticed

winged gull
#

wait nvm y should be 1

untold magnet
#

done, it should detect blocks above it?

winged gull
#

yes

untold magnet
#

infinitely?

#

no y limit thing or only one block above it?

#

ah wait

#

nvm

winged gull
#

up until height limit

untold magnet
#

i get it

winged gull
#

there can't be any above the height limits

untold magnet
#

adding maxDistance is for making the system has a limited distance not infinity

winged gull
untold magnet
#

now if (!block.isSolid()) console.warn('7') should work just fine?

winged gull
#

yes

#

wait

#

no

#

block.block.isSolid()

untold magnet
#

already

winged gull
untold magnet
#

const ray = block.dimension.getBlockFromRay(block.location, { x: 0, y: 1, z: 0 }).block

winged gull
#

yes

untold magnet
#
const ray = block.dimension.getBlockFromRay(block.location, { x: 0, y: 1, z: 0 }).block;
if (!ray.isSolid()) console.warn('Hi')```done ig
winged gull
#

do you want it to include liquid and passable blocks

untold magnet
#

does solar panels works underwater?

winged gull
#

so yes?

untold magnet
#

i don't think so but why not, yes i will make it works under the liquid thing

winged gull
#

add this as options: ```js
{includeLiquidBlocks: true, includePassableBlocks: true}

untold magnet
#

understood

winged gull
#

t︦h︦a︦t︦ ︦s︦h︦o︦u︦l︦d︦ ︦b︦e︦ ︦g︦o︦o︦d︦

#

untold magnet
#

what if i didn't add that possible blocks?

winged gull
#

then it would ignore them

untold magnet
#

ah, alright understood

#

now i have to make it detects the daytime / the weather

#

sunrise is 23000
sunset is 36000

#

i have to detect them using a script

#

welp, t17x-brain was slain by Javascript

#

how can i detect numbers between 23,000 and 36,000?

#

const time = world.getTimeOfDay;
if (time <= 23000 && time >= 36000) { ,,, };?

untold magnet
#

sorry for the ping

quartz token
#

I don't understand why, but it only works after the event is triggered 2 times

winged gull
winged gull
untold magnet
quartz token
untold magnet
#

here const time = world.getTimeOfDay;not a function log

winged gull
#

you forgot the ()

#

add those

untold magnet
#

uh,

winged gull
untold magnet
#

not working

winged gull
#

what the error now

untold magnet
#
  • getTicks isn't very working
#

I mean

untold magnet
#

no logs

#

not working for some reason

#

and most importantly, day 1 is 23000, day 2 is 46000, the day time ticks changes and not resetting

winged gull
#

getTimeOfDay(): Returns number - The time of day, in ticks, between 0 and 24000

shut junco
winged gull
#

caps at 24000

#

rolls back to 0 each day

shut junco
#

getTime does what Im thinking then

winged gull
#

yeah lol

untold magnet
#

so how can i detect the day time?