#Script API General

1 messages · Page 4 of 1

viscid horizon
#

I embedded a healthbar by actually adding it to my entity’s model and using molang to scale it based on its health. This is way cooler

viscid horizon
shy leaf
#

yuh uh to me

#

you can get the rotation to camera with models

viscid horizon
shy leaf
#

which cant be done with nametags

viscid horizon
#

I could show you mine rn

shy leaf
viscid horizon
shy leaf
#

is the scale done via property

viscid horizon
amber granite
shy leaf
#

oh hmm

#

with models i can lerp the hp bar

#

which means less strain(in my brain) getting heal and damage

#

ok im putting that into my todo list

viscid horizon
shy leaf
#

ty

viscid horizon
woven loom
short cliff
#

How can I detect the player equipment when I step on a specific block?

shy leaf
short cliff
# shy leaf content log?

TypeError: cannot read property 'getComponent' of undefined at onEntityFallOn (onStep.js:30) and cannot read property 'getEquipment' of undefined at onStepOn (onStep.js:9)

shy leaf
#

is it made with stable api?

#

@short cliff #debug-playground message

amber granite
#

Hilp

shy leaf
amber granite
#

?

#

I m hopeless

shy leaf
#

dw

amber granite
#

Now i know why they hate programming

short cliff
#

Ok so it is working but it's not running when the slot is empty

#

[Scripting][error]-InvalidContainerSlotError: The container slot is either empty or is no longer loaded. at onStepOn (onStep.js:17)

unique dragon
#

change this:

const equipment = player.getComponent(EntityComponentTypes.Equippable);

to:

const equipment = player.getComponent('equippable');

valid ice
#

Both should work

random flint
#

why slot though, just get the itemStack

neat hound
valid ice
#

Common isValid() W

short cliff
#

I'm pretty dumb at scripting

valid ice
#

.typeId ?

short cliff
valid ice
#

Just use getEquipment() not getEquipmetSlot()

short cliff
#

yeah but i'm using 1.12.0-beta

#

so it stills throws me an error saying that Feet is not valid

neat hound
#

isValid is a function.. so && boots.isValid() && boots.typeId.....

#

as soon as something fails in the && line, it stops, so it will not evaluate the next thing

valid ice
#

^
|| and && are very useful for order evaluation

#

If you really want, you can replace if statements with &&
if (condition) executable -> condition && executable

bao_ext_aintbutter

neat hound
# short cliff so it stills throws me an error saying that Feet is not valid

This does not error```js
function listEquippablesBygetEquipment(player){
const armor = player.getComponent(EntityComponentTypes.Equippable)
if (!armor || !armor.isValid()) return

for (const key in EquipmentSlot) {
    if (armor.getEquipment(key))
        player.sendMessage(`ItemStack ${key} = ${armor.getEquipment(key).typeId}`)
    else player.sendMessage(`ItemStack Nothing -> ${key}`)
}   

}I cannot find a way to test the validity of a ContainerSlot. I suggest using getEquipment for that, then is that if valid, can use the slot, like this JS
function listEquippablesBygetEquipmentSlot(player){
const armor = player.getComponent(EntityComponentTypes.Equippable)
if (!armor || !armor.isValid()) return

for (const key in EquipmentSlot) {
    if (armor.getEquipment(key)) {                        
        player.sendMessage(`ContainerSlot ${key} = ${armor.getEquipmentSlot(key).typeId}`) 
    }
    else player.sendMessage(`ContainerSlot Nothing -> ${key}`)
}   

}```

#

If you just want to test the typeId and do not need anything from the ContainerSlot, then just use getEqipment() and not getEquipmentSlot

shy leaf
#

i did the math

granite badger
#

Does ContainerSlot class avoids the item hold animation when setting item?

dense skiff
#

When I do a sendMessage(%); then % doesnt show up in chat. I'm trying to display a percentage does anyone know the proper way to do this lol

#

oh! it's just %% lmao and it only displays one

#

is % minecraft's escape character?

amber granite
random flint
shy leaf
#

so its only slightly larger than iron golem

tight plume
granite badger
subtle cove
#

it follows the slot so yeah...

#

w8 no...

#

setItem is inevitable, prob

valid ice
fast lark
#

Detect if the player has moved by seeing if their positions have changed or by velocity, and if they have moved, cancel system.runTimeout

#

how can i make it in this script

#
world.beforeEvents.chatSend.subscribe((data) => {

        const player = data.sender;

    switch (data.message) {
        case '-rtp':
            data.cancel = true;
            player.sendMessage(`§l§a${player.name}, §o§fwait 5s for the random tp`)

            system.runTimeout(() => {
                player.runCommand('spreadplayers 0 100 10 10000 @s');
                player.runCommand('effect @s feather falling 30 1')
            }, 100);
            break;
    }
});
#

any suggestion?

valid ice
#

Animation controller which triggers a script event

sharp elbow
#

If you are wanting to cancel the timeout, you would necessarily need access to the handler, right?

amber granite
#

Need help

sharp elbow
#

I suppose that could be stored as a property on the player

amber granite
#

I want to create an object within an object like this :
let object = {}
object.object = {}
object.object.key = "something like that"

#

But after i write that the the second object only has one proprety!

#

Someone knows why ?

sharp elbow
#

Isn't that what you told it to have? That is functionally the same as this:

let object = {
  object: {
    key: "something like that"
  }
};
amber granite
#

Yeah but there are another keys

#

Get added in it

#

But only the last one appears

#

Ok , wait...

#

My bad i didn't declare the second object in the right please

sharp elbow
#

Yeah, seeing the full order of things should make this clearer

amber granite
#

Thank u for ur help

sharp elbow
#

If you aren't aware of it already, check out Object.assign. This would be right up your alley

amber granite
#

Thx

static nebula
#

How to check if the player doesn't have a dynamic property

#

?

subtle cove
#

getDynamicPropertyIds().length

sharp elbow
#

Do you mean not having any dynamic properties? Or not having a specific one?

amber granite
#

If u get undefined

#

This proprety dosen't exist

#

In

getDynamicPr...("id")
static nebula
sharp elbow
#

Then try kiro's solution

static nebula
#

It didn't work

sharp elbow
#

Can you share what you wrote?

static nebula
#

Yeah

#
system.runInterval(() => {
  world.getAllPlayers().forEach(player => {
    const getTime = getDynamicPr...("Time");
    
    if (!getTime) {
      player.setDynamicProperty("Time", 7)
    }
  })
}, 20);
sharp elbow
#

Ah, getDynamicPr... should be written in full, getDynamicProperty

static nebula
#

Ohh

#

I am dumb

#

Sorry

halcyon phoenix
#

how do you push an entity around a circle?

static nebula
#

It worked

static nebula
hazy nebula
#
world.afterEvents.entityHitEntity.subscribe(data => {
    let health = data.hitEntity.getComponent("minecraft:health");
    let tags = data.hitEntity.getTags();
    let SlapperCommand = [];
    for(const tag of tags) {
        if(tag.startsWith('SlapperCOMMAND:')) {
            SlapperCommand.push(tag.replace('SlapperCOMMAND:', ''));
        }
    }
    if(data.hitEntity.hasTag("Im Slapper")) {
    health.resetToMaxValue();
    for(let player of world.getPlayers())
        world.getDimension('overworld').runCommandAsync(`execute as "${player.name}" run ${SlapperCommand}`);
    }
});```
#

When a player hits an entity, all players can run world.getDimension('overworld').runCommandAsync(execute as "${player.name}" run ${SlapperCommand}); is there any way to fix it? ?

valid ice
#

Remove the for loop at the end

hazy nebula
# valid ice Remove the for loop at the end
world.afterEvents.entityHitEntity.subscribe(data => {
    let health = data.hitEntity.getComponent("minecraft:health");
    let tags = data.hitEntity.getTags();
    let SlapperCommand = [];
    for(const tag of tags) {
        if(tag.startsWith('SlapperCOMMAND:')) {
            SlapperCommand.push(tag.replace('SlapperCOMMAND:', ''));
        }
    }
    if(data.hitEntity.hasTag("Im Slapper")) {
    health.resetToMaxValue();
        world.getDimension('overworld').runCommandAsync(`execute as "${player.name}" run ${SlapperCommand}`);
    }
});```
#

like this?

valid ice
#

Sure, but make sure to update the player object in the command to be hitEntity, as player does not exist in that event

#

Alternatively, you can do hitEntity.runCommandAsync(SlapperCommand)

empty spruce
#

yo guys, can anyone help me with listing all the features / explaining them (of a utility adddon) as a "reward" i will give the pack : dm me if ur intersted guys !
its a pretty big pack tho so be prepared !

tiny tartan
#

data.hitEntity

fast lark
#

#1263861834478260274 someone can help?

hazy nebula
valid ice
#

oh, I assumed SlapperCommand was a string to begin with

#

What is the purpose of it being an array? As the command will not run due to it being in an array, even if you convert it to a string

fast lark
#

realy*

#

Really*

valid ice
#

Don't we all

fast lark
#

.-.

hazy nebula
valid ice
#

But why an array? Wouldn't you just want the first SlapperCOMMAND tag? Or do you want it do multiple commands are ran if multiple tags exist on the entity?

hazy nebula
fast lark
#

someone have a site for thr list of all texture/ui/ like textures/ui/icon_deals

valid ice
#

then you could do something like:

world.afterEvents.entityHitEntity.subscribe(data => {
    let health = data.hitEntity.getComponent("minecraft:health");
    let tags = data.hitEntity.getTags();
    let SlapperCommand = data.hitEntity.getTags().find(tag => tag.startsWith('SlapperCOMMAND:'))?.replace('SlapperCOMMAND:', '');
    if(data.hitEntity.hasTag("Im Slapper")) {
    health.resetToMaxValue();
        if (SlapperCommand) data.damagingEntity.runCommandAsync(SlapperCommand);
    }
});```
valid ice
fast lark
#

thx

neat hound
misty pivot
#

when i interact with my block it opens multiple forms on desktop

world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
    const player = data.player;
    const block = data.block;
    if (!player.isSneaking && block.typeId == "example:my_block") {
        data.cancel = true
        system.run(() => {
            openForm(player)
        })
    }
})```
#

well technically desktop, i connected my mouse and keyboard to my phone lmao

valid ice
#

Yeah, the interact event runs many, many times.

#

One way to prevent it would be to use a temporary cooldown-

if ((player.__tempCooldown ?? 0) > Date.now())  return;
player.__tempCooldown = Date.now() + 500; //Half a second of delay
tiny tartan
#

or

    if (player.lastTick == undefined) player.lastTick = 0
    if (system.currentTick - player.lastTick > 5) {
        system.run(() => {
            openForm(player);
        })
        player.lastTick = system.currentTick;
    }```
neat hound
misty pivot
#

ah i see, when i click i technically hold it longer than a tick

#

i see the problem, thx guys bao_bee_happy

misty pivot
tiny tartan
misty pivot
#

interesting, does it get the tick that the player last did the event?

tiny tartan
#

with first if statement it put lastTick as 0 then when we run our code next to it it put system.currentTick as lastTick so it will check if its not higher than 5

misty pivot
#

ah i see

#

it's something like a variable

tiny tartan
#

kinda

valid ice
#

lastTick is a variable that does not exist in the docs, because you as the coder are defining it.

tiny tartan
#

thx for info

hazy nebula
#
world.afterEvents.entityHitEntity.subscribe(data => {
    for (const player of data.damagingEntity) {
        const equip of player.getComponent('equippable')) 
        const item = equip.getEquipment('Mainhand');
        if (!item) continue;
        const lore = item.getLore();
        if (lore.includes('lightning')) {
            if (getRandom(20)) {
                data.hitEntity.runCommand(`summon lightning_bolt`)
            } else {
                return;
            }
        }
    }
})```
#

@valid ice Is such a for loop correct?

tiny tartan
#

i dont think you need loop

valid ice
#

You do not

#

damagingEntity is not an array

hazy nebula
valid ice
#

What did you have before adding the loop

#

And just because it does not give an error does not mean it is correct

hazy nebula
valid ice
#

Yes, because you are looping over all players in the world

hazy nebula
valid ice
#

Delete the loop entirely

#
world.afterEvents.entityHitEntity.subscribe(data => {
    const player = data.damagingEntity;
    if (player.typeId !== 'minecraft:player') return;
    const equip of player.getComponent('equippable')) 
    const item = equip.getEquipment('Mainhand');
    if (!item) return;
    const lore = item.getLore();
    if (lore.includes('lightning')) {
        if (getRandom(20)) {
            data.hitEntity.runCommand(`summon lightning_bolt`)
        } 
    }
})
stray gate
#

Any suggestions for my crate menu? also, is it possible to make a loading animation/screen within the crate menu? For example: I open up the crate and the pattern blocks changes 3 times with some sort of sound effect within minecraft files.

valid ice
#

oh

#

replace the "of" with "="

hazy nebula
valid ice
#

Mainhand not mainhand

#

Why did you change that, it was fine how it was

hazy nebula
sudden nest
#

does the Player.addExperience(...) goes to the equipped tool / weapon the player is holding with mending? I tried with Player.Dimension.spawnEntity(MinecraftEntityTypes.XpOrb.id, Player.location); it works, but with this Player.addExperience(...) , it doesn't.

cinder shadow
cinder shadow
distant tulip
#

is the lore optional? (your chest ui)

#

@valid ice

valid ice
#

yep, you can just do [] for it

distant tulip
#

ok
tnx

somber echo
#

Quick question, custom components work with js or only ts?

open urchin
#

APIs are never limited to ts

#

only exported types and interfaces

empty quail
#

What's the best way to adjust scoreboard values through scripting
.getObjective().setScore()?

somber echo
#

Thank you quazchick

empty quail
#

How do I escape read-only mode

valid ice
#

wrap the code in system.run() or use the after event instead

empty quail
valid ice
#

it also depends on what you're trying to edit. I assumed you were using before events and attempting to write to the world. What are you trying to do?

distant tulip
#

kinda off topic but whats the unkown texture path? (the black and purple one)

empty quail
valid ice
#

what's the part that you are running into read-only at?

distant tulip
empty quail
wary edge
valid ice
empty quail
#

Ok appreciated

glacial widget
#

oh

golden badge
#

Can I save data using script api?

#

If so, can someone reffer?

valid ice
#

Dynamic properties

amber granite
#

Yes

golden badge
#

How can I access this data, using NBT editor?

#

outside of minecraft I mean

amber granite
#

No

valid ice
#

Yes- third party editors can access the saved data

amber granite
#

I thought that impossible

valid ice
#

I’ve accessed them from MCCtoolchest & UME before

golden badge
#

didn't find

#

is it comperhansive enough?

amber granite
#

world.setDynamicProprety("id" , data )

valid ice
#

Probably the best you’ll get

amber granite
#

world.getDynamicProprety("id")

golden badge
#

Can I get dynamic property data via command?

#

in game

valid ice
#

You cannot, no

amber granite
#

No

golden badge
amber granite
#

But u can make a command

valid ice
#

You could do that for sure

#

scriptevent command

sudden nest
#

idk, but have you tried creating a minecraft:book and adding enchantments to it?

It creates a enchanted book not the enchanted_book. I am currently at 1.20.51 im fixing my slightly large old scripts, but have you guys tried in the latest?

#

i think it's a bug

amber granite
#

id

#

U can put the id i guess

#

Every enchanted book has its id

#

In the game

sudden nest
#

Here's a normal enchanted_book using the give command without enchantments.

amber granite
#

Wait

#

Lemme check

sudden nest
#

Enchanted enchanted_book

amber granite
#

I think u need nbt

valid ice
#

Pretty sure it’s intentional. They are two different items.

amber granite
#

For that

sudden nest
#

Enchanted book

amber granite
#

Ahhh

#

Just use
"enchanted_book" as an id

#

That s a glitch

sudden nest
#

oh okay, i was confused earlier

#

give book then giving it enchantment with command gives you enchanted_book with specific enchantment, but using script with addEnchantment(...) to a book gives you an Enchanted book, which doesn't work with anvils

amber granite
#

Yeah it s a glitch

#

U made a glitch

sudden nest
#

oh okay

amber granite
#

That s good

sudden nest
#

;_;

amber granite
#

It s something like glitch but it s not

#

Because the script api is not dealing with items the same way as the vanilla

burnt remnant
#

How do i subtract from a stack?

empty spruce
#

yo @valid ice

#

u got time for like probably a quic kfix ?

#

its like an update thingy but i cant figure it out

#
 getPlayersFaction(player) {
        const factionTag = player.getTags().find(tag => tag.startsWith(factionPrefix));
        const factionName = factionTag?.replace(factionPrefix, '');
        return factionName;
    }``` not a function at line 2
#

i think thats like the get tags function

valid ice
#

That looks fine

tawny peak
#

please help, what does this mean?
[2024-07-19 14:02:44:513 ERROR] [Scripting] Plugin [Main - 1.0.0] - [index.js] ran with error: [ReferenceError: Module [@minecraft/server] not found. Native module error or file not found.] i've tested it on a different server and it worked, but on my main server it gives an error

empty spruce
glacial widget
#
import { system, world, Player } from '@minecraft/server';
import { ChestFormData } from './extensions/forms.js';

function ChestTest(player) {
    const chestui = new ChestFormData('27')
    .title('§l§d      Pickaxe shop V2')
    .button(10, '§l§3Tier 6', ['$50,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/netherite_pickaxe')
    .button(11, '§l§bTier 7', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
    .button(12, '§l§9Tier 8', ['$55,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/amethyst_pickaxe', true)
    .button(13, '§l§5Tier 9', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
    .button(14, '§l§5Tier 10', ['$65,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/emerald_pickaxe')
    .button(15, '§l§dTier 11', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
    .button(16, '§l§dTier 12', ['100,000', '§r§7Pickaxe', 'Click any item!'], 'textures/items/echo_pickaxe')
    .show(player).then(response => {
        if (response.canceled) return;
        switch(response.selection) {

            case 10:
                for(const player of world.getAllPlayers())

                    player.sendMessage("heyy")
                    const Money = world.scoreboard.getObjective("Money")
    

                    if (Money.getScore >= "50000"){
                        for(const player of world.getAllPlayers())
                        player.runCommand("give @s netherite_pickaxe")
                        for(const player of world.getAllPlayers())
                        player.runCommand(`scoreboard players remove @s Money 50000`)
                    } 

                    if (Money.getScore < "50000"){
                        for(const player of world.getAllPlayers())
                        player.sendMessage("§l§d HCV KitPvP >> §l§4You do not have enough for a Tier 6 pickaxe")
                    }

            break;


            case 11:
    
            break;


            case 12:
                player.sendMessage("hey 2")
            break;


            case 14:
                player
            break;


            case 15:
                player
            break;
        }
    })

}

world.afterEvents.playerInteractWithEntity.subscribe((event) => {
    let entity = event.target;
    let player = event.player;

    if (entity.hasTag("pickui")) ChestTest(player)
  });

Herobraine64 could you help me with your chestui system, am trying to remove score from a player but for some reason i cantjoesob

empty spruce
#

but nvm imma get that off my pack

distant tulip
#

i am using runJob to achieve this but my game tps drop a lot
way is that?

valid ice
#

Are you looping through every item in the game?

distant tulip
valid ice
#

I would recommend using a shorter array of common items, so the game does not take as long then

distant tulip
#

that a good idea
is there a way to make the function more like async functions?

valid ice
#

Besides using run job… dunno lol

#

When are you yielding?

distant tulip
#

can i dm you the code?

valid ice
#

Shore

distant tulip
next frost
#

does anyone know what the replacement for "q.block_neighbor_has_any_tag" is in scripting?

distant tulip
#

what q.block_neighbor refer to?

next frost
#

it is to detect the position of a certain block, practically to detect a block on the sides using "0,0,0"

and what i want to do is be able to know how to use something similar to that but in scripts since I am trying to make a block connect to another with only 2 sides, either north and south or west and east

#

a picture of what i want to try to do (i did this with HCF events)

neat hound
# next frost it is to detect the position of a certain block, practically to detect a block o...

If I recall correctly, that molang took a relative direction and a list of tags, correct. So

  1. if you have your block object, you have it's location,
  2. then can do the vector3 math to any of the surrounding blocks,
  3. then get that block object and use the hasTags method.

Turn this into a function with similar parameters.

Also, Kaioga in his gitHub (see resourses), may have code that did connected blocks in scripts, so he would have something that is similar, if he used tags, but he would have to check neighboring blocks.

knotty plaza
#

Is anyone else having an issue with the Equippable and Inventory components from the player?

#

Sometimes when I do /reload the components become undefined for every player

#

And it fixes itself by doing /reload again

random flint
#

You gotta make your own texture for each possible connection

chrome flint
shy leaf
#

ikr

hazy nebula
#

does aynyone have setTickTimeOut code?

chrome flint
knotty plaza
#
import { system } from "@minecraft/server";

system.runTimeout(() => {
  // Code
}, 20);
spring dove
#

i have to download @minecraft/vanilla-data' ?

#

to have it in game?

spring dove
#

so then

distant gulch
#

it only requires a valid manifest to use the api and import system

#

basicly the code RedTnT provided

halcyon phoenix
#

trying to make a util and I found that they export like this why is there a variable that contains the same thing?

halcyon phoenix
distant gulch
#

hmm idk, thats weird

halcyon phoenix
#

shuld I just remove it?

distant gulch
#

Nope, iguess he wanted to like classify the thing

distant gulch
spring dove
#

putting there the vanilla server?

distant gulch
#

if you need it you can add the module for it

gaunt salmonBOT
#

Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
spring dove
#

and which version should i use

distant gulch
#

uhmm wait

spring dove
#

alr

distant gulch
#

it will install the like ressources what vanilla-data contains to your code engine

#

and then you can use it

#

you dont need to add a module to your manifest

distant gulch
spring dove
cold grove
cold grove
ancient sierra
#

vanilla-data is only for types and autocompletions

Mainly useful for typescript

#

I believe you don't need it if you're in javascript?
Correct me if im wrong since I always use typescript

cold grove
spring dove
#

so, i just learned i little bit more about javascript, what are the differences between typescript and javascript

cold grove
#

just use js

spring dove
#

alr

chrome flint
distant gulch
cold grove
distant gulch
distant gulch
#

i find it haves some differences, but wich programming langues dont haves it

cold grove
#

the distance between js and java is huge ☠️

distant gulch
#

i meant TypeScript

cold grove
#

yeah

#

both are the same

distant gulch
#

Yeah mb, i correct my sentence: the only difference is, the typification

#

for a "better" usage

#

(it broked me)

cold grove
#

thats true

distant gulch
#

i couldnt use TypeScript sadly.. i needed to install many shit for it so i gave up

halcyon phoenix
#
system.runInterval(() =>{
    while (switch1) {
      statement....
    }
},20)
#

what's the correct way to do this?

cold grove
halcyon phoenix
#

the one above

distant gulch
#

this would trigger the code in the box every 20ticks

halcyon phoenix
#

yeah

distant gulch
#

so depends on your plans, it would work

halcyon phoenix
#
while (switch1) {
    system.runInterval(() =>{
   },20)
}
#

doing this doesn't work

fiery solar
distant gulch
#

this would not be good

#

just do:

halcyon phoenix
distant gulch
#
system.run(() => {
  <your code>
}, <tick Delay>);
valid ice
#

while (true) {} bao_ext_aintbutter

halcyon phoenix
#

let switch1 = false;

world.afterEvents.chatSend.subscribe((event) => {
    const { sender, message } = event;
    if (message == "test1") {
        switch (switch1) {
            case true:
                switch1 = false
                world.sendMessage("Off")
                break;

            case false:
                switch1 = true
                world.sendMessage("On")
                break;
        }
            
        
    }
});
distant gulch
valid ice
distant gulch
#

and why do you even use switch for a boolean?

halcyon phoenix
distant gulch
#

wait

halcyon phoenix
#

the while loop doesnt work when it'ts true

distant gulch
#
let switch1 = false;

world.afterEvents.chatSend.subscribe((event) => {
    const { sender, message } = event;

    if (message == "test1") {
        sender.sendMessage(switch1 ? 'On' : 'Off');
        switch1 = !switch1;
    };
});
#

this is better

halcyon phoenix
#

yeah that's a lot mor better but that is not the problem though, the while loop doesn't start when it's true

grave nebula
#

can someone send the most recent manifest.json and package versions

distant gulch
#

it needs to get triggered

grave nebula
#

ive not scripted in months lol

distant gulch
halcyon phoenix
#

how do I trigger it?

gaunt salmonBOT
#

Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
distant gulch
valid ice
#

(Chat flood but those are latest versions)

distant gulch
#

np

cold grove
#

how dare you-

grave nebula
distant gulch
halcyon phoenix
distant gulch
valid ice
halcyon phoenix
fiery solar
distant gulch
#

@valid ice have you time for a short question?

#

@halcyon phoenix if you dont know, a while loops runs the code in his block till statement is false

fiery solar
#
system.runInterval(() => {
    if(switch1) {
      world.sendMessage('looping');
    }
}, 20);

I think this is what you're looking for.

distant gulch
#

A while usage @halcyon phoenix

let counter = 0;

while (counter <= 10) {
  console.log(++counter);
};
distant gulch
valid ice
#

what

distant gulch
#

the script was for @halcyon phoenix

halcyon phoenix
distant gulch
#

wait then make it like that:

halcyon phoenix
distant gulch
#

let me send a perfomant version okay?

halcyon phoenix
#

I don'w even know why I got the idea to use a while loop

distant gulch
# halcyon phoenix I don'w even know why I got the idea to use a while loop
let switchState_1 = false, runId = undefined;

const intervallCallback = () => {
    // code of the interval
};

world.beforeEvents.chatSend.subscribe((evd) => {
    const { sender, message } = evd;

    if (message.startsWith('test1')) {
        evd.cancel = true;

        // switch state
        switchState_1 = !switchState_1;
        sender.sendMessage(switchState_1 ? 'Loop: on' : 'Loop: off');

        // "cancel" or "add" interval
        if (switchState_1) {
            runId = system.runInterval(intervallCallback, 20);
        } else {
            if (runId) {
                system.clearRun(runId);
                runId = undefined;
            };
        };
    };
});
distant gulch
valid ice
#

While loops are good in moderation- be careful to keep them in check.

distant gulch
#

This code wont call uselessy the interval when its not true

distant gulch
distant gulch
valid ice
#

Like make higher than 20 TPS?

distant gulch
#

Yes

valid ice
#

Nop

distant gulch
#

Okay, i think the game wouldnt survive 60 TPS 💀

#

relatable

grand heart
#

how to know if itemstack is block? (isBlock(ItemStack))

distant gulch
#

wait a sec

distant gulch
#

i used this

#
import { BlockTypes, ItemStack } from '@minecraft/server';
distant gulch
halcyon phoenix
ancient sierra
#

Does <Entity>.clearVelocity() freeze projectiles?

#

Im trying to set its velocity, although using .clearVelocity() made my arrow freeze, reloading the world deletes it as well for unknown reason

#

New thing I found, after waiting for a bit, it disappears but retrying it works

#

Nevermind, that's the arrow's despawn interval, although reloading it makes it disappears instantly

#

Is that some sort of bug or?

abstract cave
#

is there an official documentation for the syntax of minecraft script

granite badger
#

it’s just JavaScript (es module)

deep quiver
deep quiver
ancient sierra
#

Arrows can't also set its velocity again after hitting a block for some reason so that also solves why apply impulse doesn't work

#

You have to apply it after spawning

abstract cave
drifting ravenBOT
#
Learn JavaScript

As the Script API is a framework built on JavaScript code, having an understanding of JavaScript is key.

If you are being shown this, then you most likely are a beginner with JS and could use a little guidance.

Videos on Learning JavaScript
Javascript in 1 hour
Javascript Classes in 1 hour

Web Guide:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

Reference Sites:
https://www.w3schools.com/jsref/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://javascript.info

honest spear
#

real

static nebula
#

Does anyone know how I can set a money score for a player in the first time event entering the map without using player.runCommand?

honest spear
#

first get scoreboard objective

#

then set value or add value with that entity

static nebula
#

I tried but it says that the setScore was not defined

honest spear
#

may you share your code here

static nebula
#

k

#
world.afterEvents.playerSpawn.subscribe((eventData) => {
  const initialSpawn = eventData.initialSpawn
  const player = eventData.player
      
    if (!initialSpawn)
      return;
    
    if (!player.hasTag("Member")) {
      player.runCommand("scoreboard objectives add deathTime dummy");
      const scoreboard = world.scoreboard.getObjective('Money');
      scoreboard.setScore(player, 10);
      player.addTag("Member");
    }
})
honest spear
static nebula
#

Yeah

honest spear
#

not defined is not really specific tho

static nebula
#

Ok

#

Wait a moment

#

Oh

#

Now it worked

#

I changed the order and it worked

#

Thanks

honest spear
#

np

#

:)

halcyon phoenix
#

DM me or open a thread

#

I'll help

abstract cave
hazy nebula
#

What event is click block? Like if a person clicks on a stone block at x y z, it will teleport that person to a certain location

halcyon phoenix
#

there's a event for that?

subtle cove
#

either entityHitBlock or playerInteractWithBlock

fading sand
#

why is this error happening when my entity does have that property?

subtle cove
#

entity is unloaded

fading sand
#

huh

#

but it works for my other addon

glacial widget
#

does anyone know how to detect a player phasing though a block?

hazy nebula
fading sand
hazy nebula
fading sand
#

damn

subtle cove
#

that error usually occurs when an entity not in loaded chunk or entity is gone

#

"Failed to ..."

fading sand
subtle cove
#

r u using runInterval?

fading sand
subtle cove
hazy nebula
#
world.afterEvents.playerInteractWithBlock.subscribe(data => {
    if(data.block.typeId == "minecraft:ender_chest" && data.block.x === -13 && data.block.x === -38 && data.block.x === -12) {
        data.damagingEntity.runCommandAsync(`tp 200 -60 200`)
    }
});```
tiny tartan
#

damagingEntity?

fading sand
# subtle cove code...
world.afterEvents.projectileHitEntity.subscribe((data) => {
    const {projectile, source} = data 
    
    if (projectile.typeId.endsWith('_projectile')) {
        let hitEntity = data.getEntityHit().entity;
        if (!hitEntity.typeId.startsWith('sw_')) {
                  let value = (0.1 * projectile.getProperty("projectile:damage"));
                  let sourcePlayer = damageSourceEntity.get(projectile);
                  hitEntity.applyDamage(value , { cause: `overwrite`, damagingEntity: sourcePlayer });

        }
};
})
hazy nebula
#

When I click the ender chest, what happens? What's the problem?

tiny tartan
fading sand
#
world.afterEvents.projectileHitEntity.subscribe((data) => {
    const {projectile, source} = data 
    
    if (projectile.typeId.endsWith('_projectile')) {
        let hitEntity = data.getEntityHit().entity;
        let sourceEntity = sources.get(projectile);
     if (hitEntity.typeId.startsWith('sw_') && (hitEntity.id != sourceEntity)) {
                  let shield = 0
                  if (hitEntity.getProperty("fighter:shield")==undefined) {
                      shield = 0
                  } else {
                      shield = hitEntity.getProperty("fighter:shield")
                  }
                  let value = shield - (0.1 * projectile.getProperty("projectile:damage"));
                  
                  if (hitEntity.getProperty("fighter:shield")!=undefined) {
                  hitEntity.setProperty("fighter:shield", ( 0 >= value )? 0 : value);
                  console.warn("PROPERTY:"+hitEntity.getProperty("fighter:shield"));
                  };
                  if (value <= 0) {
                  let health = hitEntity.getComponent("minecraft:health");
                  health.setCurrentValue(health.currentValue+value);
                  };
                  console.warn("shield1"+shield);
                  console.warn("value:"+value);
                  console.warn(hitEntity.getComponent("minecraft:health").currentValue);
                  console.warn("shield:"+hitEntity.getProperty("fighter:shield"));
    }
};
})

this was the working code in my different addon

#

@subtle cove

hazy nebula
# tiny tartan it should be data.player
world.afterEvents.playerInteractWithBlock.subscribe(data => {
    if(data.block.typeId == "minecraft:ender_chest" && data.block.x === -13 && data.block.x === -38 && data.block.x === -12) {
        data.player.runCommandAsync(`tp 200 -60 200`)
    }
});```
#

nothing happened

fading sand
subtle cove
#

hmmm

tiny tartan
#

and there is native way for tp too

hazy nebula
tiny tartan
#

block.x == -13 && block.y == -38 && block.z == -12

hazy nebula
#

how

fading sand
fading sand
fading sand
#

ohh

#

thx XD

#

now, how do i remove the knockback?

random flint
#

clearVelocity or teleport

fading sand
fading sand
hushed ravine
#

Is @minecraft/server-net still maintained?

random flint
fading sand
random flint
#

"counterweight" it

fading sand
#

hm

valid ice
hushed ravine
valid ice
#

I can't tell if you're being sarcastic or not

hushed ravine
hasty spindle
spring dove
#

Its bad for the performance of the game having a script running constantly?
(2 ticks per code run)

valid ice
#

Depends on what is being ran- runIntervals are not inherently lag-causing.

spring dove
#

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

system.runInterval(() => {
let players = world.getAllPlayers();
let online = players.length;

for(let i = 0;i<online;i++){
    players[i].runCommandAsync("enchant @s efficiency 2")
    players[i].runCommandAsync("enchant @s unbreaking 2")
}

},2)`

#

Its for enchant items as soon as they get it on their hand

neat hound
#

humans are slower than ticks... why you need to run less than 10. 30 ticks probably register before they realize it is in their hands

valid ice
#

That should be relatively safe to run

#

However, native enchant methods would be preferred, albeit the code would be more complicated.

spring dove
spring dove
#

lmao the phantom

neat hound
#

Also should check if holding something enchantable.. commands do not return errors, but you are still registering one in a way, like if on the command line

spring dove
#

im aplying unbreaking also

#

so all items can get unbreaking

#

mmm

#

i think so

#

well i found the first problem

#

it enchants books

#

so ill have to change it

valid ice
#

Imagine if dynamic properties could save ItemStacks

#

Recursive storage in minecraft? Yes please.

spring dove
#

bra

#

i wanted to make recently a script that can storage the items of a dead player in a chest, and i think its not possibly to save the enchantment of the items

valid ice
#

Best you can to is transfer the item between containers, which would preserve all data on the item

spring dove
#

Oh

#

that sounds like an option

#

hey

#

theres like an selectedSlot method no?

valid ice
#

getComponent('equippable').getEquipment('Mainhand')

spring dove
#

uhhh
`for(let i = 0;i<online;i++){
let item = players[i].getComponent('equippable').getEquipment('Mainhand')

    if(item==!"minecraft:book"){
        players[i].runCommandAsync("enchant @s efficiency 2")
        players[i].runCommandAsync("enchant @s unbreaking 2")
    }
}

},2)`

#

this is not working for me then

valid ice
#

item is an ItemStack instance in that case- you have to check the .typeId property to see the item ID.

#

if(item?.typeId !== "minecraft:book"){

spring dove
#

ok let me check

#

it works!

#

thanks

#

holdon

#

it throws me that error when i select the book

#

i can save the error to dont show it or sumn?

#

or maybe it was the hand

#

im || undefined

valid ice
#
import { world, system, EnchantmentType } from '@minecraft/server';
system.runInterval(() => {
    world.getPlayers().forEach(player => {
        const heldItem = player.getComponent('equippable').getEquipment('Mainhand');
        if (!heldItem || heldItem.typeId === 'minecraft:book' || heldItem.typeId === 'minecraft:enchanted_book') return;
        const enchants = heldItem.getComponent('enchantable');
        if (!enchants) return;
        const efficiency = { type: new EnchantmentType('efficiency'), level: 3 };
        const unbreaking = { type: new EnchantmentType('unbreaking'), level: 3 };
        const existingUnbreaking = enchants.getEnchantment('unbreaking')?.level ?? 0;
        const existingEfficiency = enchants.getEnchantment('efficiency')?.level ?? 0;
        if (existingUnbreaking < 3 && enchants.canAddEnchantment(unbreaking)) enchants.addEnchantment(unbreaking);
        if (existingEfficiency < 3 && enchants.canAddEnchantment(efficiency)) enchants.addEnchantment(efficiency);
        player.getComponent('equippable').setEquipment('Mainhand', heldItem);
    })
}, 2);```
spring dove
#

ty it works perfectly tho

tawny peak
#

how do i kill an entity with scripts

wary edge
tawny peak
#

thanks

hasty spindle
#

why my player tellraw is [object Object] [object Object] ?

        tpmenu.show(player).then((r) => {
            const buttonNames = []
            for(let i = 0; i < privatetp.length; i++) {
                buttonNames.push({id: i, name: privatetp[i]})
                if(buttonNames[privatetp.length - 1]) {
                    for(let i = 0; i < publictp.length; i++) {
                        buttonNames.push({id: i + privatetp.length, publictpname: publictp[i]})
                    }
                }
            }
            if(r.canceled) return;
            const selection = [r.selection]
            if(selection[0] === 0) player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"${buttonNames.forEach(element => JSON.stringify(element.name))}"}]}`)
        })```
spring dove
#

@valid ice how do i get the slot.armor.head in container?

#

player.getComponent('equippable').getEquipment('slot.armor.head')

#

?

valid ice
#

getEquipment('Head')

spring dove
#

head

#

ASDKASD

#

I JUST Got it

#

anyway ty

spring dove
# valid ice getEquipment('Head')

and to get it as itemStack? for example player wears a diamond helmet,
const helmetItem = source.getComponent('equippable').getEquipment('head') its not just like this?

valid ice
#

Head, not head. Case is very important.
and getEquipment returns an itemstack

spring dove
#

Alr

#

it worked ty

glacial widget
#

is there anyone who can do a anti-phase?

amber granite
glacial widget
#

willing to pay aswell

amber granite
#

You mean cheat

#

Anti cheat

#

U mean like go through a wall

#

And those types of cheating

glacial widget
#

yeah pretty much, i wanna stop players from going though blocks/walls

glacial widget
amber granite
#

You will use it in realm ?

#
  • stable api or beta one
glacial widget
glacial widget
amber granite
#

Yeah i can do it

#

Did u check first if there free ones

#

Or open sourced ones

#

Or idk

#

Check first

glacial widget
amber granite
#

Ok

#

DM me

#
  • more infos like :
    Wanna kick the player , prevent him from that etc... @glacial widget
amber granite
#

Any other infos

wary geode
#

I made a gametest but when I try to run it, it says that it can't find it even though I'm running /gametest run {classname}:{testname} or in my case, /gametest run pvptest:test1. Any idea on what the issue could be? I just need to know where to begin debbuging because rn, I have no clue.

hasty spindle
#

why my player tellraw is [object Object] [object Object] ?

        tpmenu.show(player).then((r) => {
            const buttonNames = []
            for(let i = 0; i < privatetp.length; i++) {
                buttonNames.push({id: i, name: privatetp[i]})
                if(buttonNames[privatetp.length - 1]) {
                    for(let i = 0; i < publictp.length; i++) {
                        buttonNames.push({id: i + privatetp.length, publictpname: publictp[i]})
                    }
                }
            }
            if(r.canceled) return;
            const selection = [r.selection]
            if(selection[0] === 0) player.runCommandAsync(`tellraw @s {"rawtext":[{"text":"${buttonNames.forEach(element => JSON.stringify(element.name))}"}]}`)
        })```
#

@valid ice can you help me pls ?

fiery solar
wary geode
#

I think so, it's in the behavior pack inside the scripts folder

weary umbra
#

did someone found out what this does?

granite badger
granite badger
#

some of you all asked for it months ago shrug

weary umbra
short cliff
#

How can I execute something when the player gets hit by a projectile?

#

I know that I should use projectileHitEntity but it's just now working

amber granite
#

Hey

#

@cold grove

cold grove
#

Sup

amber granite
#

Do u know what values range of getRotation ?

#

Sorry for ping

cold grove
#

If i remember is min -180 and max 180

#

Degrees

amber granite
#

So

#

0

#

Start in vector :
V : 1 , 0 , 0

#

Right?

cold grove
#

Idk :(

#

But its vec2

#

X, Y

amber granite
#

Ah so

#

I need the block before player rotation in x

#

Stupid math : P

#

I just want to know if player 0 rotation degree

#

Starts with north block face

#

Or not

short cliff
hazy nebula
#

Is there any way to make a Is there any way to make a piece of code run exactly at 8 o'clock? run exactly at 8 o'clock?

amber granite
#

8 o'clock ?

#

Irl ?

hazy nebula
#

like that

amber granite
#

Use Date() object

cold grove
#

Yes

hazy nebula
cold grove
amber granite
#

I really get bad time with rotation

#

Does
getRotation({x , y })
Get me the rotation on game's X and Y
Or
They get swapped

cold grove
amber granite
#

I know

#

X = yaw
Y = pitch

#

?

#

Or swapped i really don't know

cold grove
#

My English not englishing

#

It goes from -180 to 180 so, -180 will be 360

amber granite
#

I know

#

But

#

Is 0 is the same as north face

cold grove
#

At 180> it starts to -x

amber granite
#

Or not

#

I want block Faces

cold grove
#

Maybe someone else can help bao_ext_toldyouso

amber granite
#

There is no one else

#

My brain isn't braining anymore : ' (

#

Bad documentation

cold grove
amber granite
#

Yep

#

I found that

#

So
The function
Return
vec2

#

That mean x and y

#

But x and y in regular Minecraft cordination are the yaws

#

And Y is the pitch

#

But this is something else

#

So
X = pitch
And
Y : yaw

#

And that hurting my brain

cold grove
#

Pitch?

amber granite
#

Yeah

#

It like rotation on Y axis

#

And yaw is rotation on x , z axis

#

And they are vec2

#

X : Y

fervent topaz
#

how to get when player is in diff dimension

amber granite
#

There is an event

#

For that

cold grove
fervent topaz
amber granite
#

Is on the Y axis

cold grove
#

In that case use y hehe

amber granite
#

Yeah

proud cliff
#

Not sure if you found a solution but try blockComponentRegistry instead of blockTypeRegistry, had that fix an error for me today

gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 2 errors:

<REPL0>.ts:4:13 - error TS2552: Cannot find name 'dimension'. Did you mean 'Dimension'?

4             dimension.runCommand("/say tick OR random tick NOT working (tried both)")
              ~~~~~~~~~

  @minecraft/server.d.ts:3987:15
    3987         class Dimension {
                       ~~~~~~~~~
    'Dimension' is declared here.

``````ansi
<REPL0>.ts:7:13 - error TS2552: Cannot find name 'dimension'. Did you mean 'Dimension'?

7             dimension.runCommand("/say works")
              ~~~~~~~~~

  @minecraft/server.d.ts:3987:15
    3987         class Dimension {
                       ~~~~~~~~~
    'Dimension' is declared here.

Lint Result

ESLint results:

<REPL0>.ts

3:23 error 'e' is defined but never used @typescript-eslint/no-unused-vars

4:13 warning The /say command can be fully replaced with the World.sendMessage api in the @minecraft/server module. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/world#sendmessage for more information. minecraft-linting/avoid-unnecessary-command

6:19 error 'e' is defined but never used @typescript-eslint/no-unused-vars

7:13 warning The /say command can be fully replaced with the World.sendMessage api in the @minecraft/server module. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/world#sendmessage for more information. minecraft-linting/avoid-unnecessary-command

granite badger
#

how did this code even work

cold grove
amber granite
#

Yeah i finished my code

#

Thank u for helping

cold grove
#

x = viewDirection.x * r - player.x

cold grove
amber granite
cold grove
amber granite
#

Nothing

#

But r is for what ?

#

Radius?

cold grove
#

The distance between the player and the block you want

amber granite
#

Oh

elder heath
chrome flint
#

can we detect if entities teleport?

elder heath
#

Could you tell me what you mean? Is it about the mob stack, right?

chrome flint
elder heath
#

If I use entities in the blocks??

cold grove
chrome flint
#

i just want my entity to stop teleporting with teleport command

cold grove
#

Wdym

chrome flint
#

i do /tp @e most of the times, and accidentally not putting target selectors because i have like 10+ entities that needs to be stationary

cold grove
#

Nope, just be careful

cinder shadow
#

keep clicking on the wrong server 😔

burnt remnant
#

can you detect what way a block is facing?

halcyon phoenix
elder heath
elder heath
halcyon phoenix
# chrome flint can we detect if entities teleport?

simplest way would be
addTags to the entities that you don't want to get teleported
check for those tagged entities location
if location is changed then it will teleport it back to the location where you added the tag

halcyon phoenix
#

BEHOLD!

#

the power of math

valid ice
#

"Yo momma so fat that cows orbit her" or something

halcyon phoenix
#

LOL

misty cove
#

Guys can i make item lore with translate instead of using string ?

#

I tried using rawMessage but it didn't work

halcyon phoenix
#

can you spawn structures with scriptAPI?

honest spear
misty cove
#

Like what?

honest spear
#

for example

setLore(["%translation.key"]);
misty cove
#

Okey thanks

honest spear
#

but i can't promise it

#

its just an idea

sage portal
#

is there a way to run a function in another js file or do they have to be in the same file?

I separated my scriptevent js in a different file, but I was wondering if there was an alternative way to execute scriptevents without using runCommand.

open urchin
#

onPlayerInteract's faceLocation still seems to be relative to the world origin rather than the bottom north west corner of the block, is there a bug report?

misty pivot
#

how do i get the player's direction? like north, south, east, and west

meager zenith
#

can i set a block's rotation using script

misty pivot
meager zenith
#

so i tried per = block.permutation and then otherBlock.setPermutation(per)

#

but the otherBlock just get deleted

misty pivot
#

use something like this either directly inside the setPermutation or in a variable

block.permutation.withState("example:state", 1)```
open urchin
# misty pivot how do i get the player's direction? like north, south, east, and west

this should work

const directions = [Direction.South, Direction.West, Direction.North, Direction.East];

function getDirection(player) {
    let yRotation = player.getRotation().y;
    if (yRotation < 0) yRotation += 360; // Convert to positive if negative
    
    let cardinalRotation = Math.round(yRotation / 90);
    if (cardinalRotation === 4) cardinalRotation = 0; // 0 and 360 are the same rotation

    return directions[cardinalRotation];
}

const direction = getDirection(player);
grand heart
#

how to check if blocktype is solid (when block is not yet placed on world)?

dire scroll
#

how do i apply knockback/impulse without doing damage?

also make the knockback/impulse stronger the longer the attack lasts

#

i want my entity to pull in mobs

#

the longer the attack lasts, the stronger the pull is

#

basically starts from 0 to 1

hardy tusk
#

are you trying to check that on a permuation

#

or what

grand heart
# hardy tusk wdym?

what i want is to place a random block relative to player location

if the random block is solid the block is placed below
else, the random block is placed at the player's location (at the feet)

north rapids
#

How do i get the block in playerbreakblock event?

wary edge
fickle dagger
#

anyone got a snippet of code to detect if player has an armor set when damaged?

wary edge
fickle dagger
misty pivot
#

what triggers an itemUseOn?

wary edge
fickle dagger
#

if I remember it was something like :

const necroArmor = [
/*Armors Goes Here*/
  'wh:necro_helmet',
  'wh:necro_chestplate',
  'wh:necro_leggings',
  'wh:necro_boots'
]
world.entityHurt.afterEvents.subscribe(event => {
  const source = event.attackingEntity;
  const playerEquippableComp = event.source.getComponent('equippable');
  const equippedHelmet = playerEquippableComp.getEquipment(equipmentSlot.head);
  const equippedChest = playerEquippableComp.getEquipment(equipmentSlot.chest);
  const equippedLegs = playerEquippableComp.getEquipment(equipmentSlot.legs);
  const equippedBoots = playerEquippableComp.getEquipment(equipmentSlot.feet);
  if(necroArmor.includes(equippedHelmet.typeId,0) && necroArmor.includes(equippedChest.typeId,1)  && necroArmor.includes(equippedLegs.typeId,2)  && necroArmor.includes(equippedBoots.typeId,3)){
      //Add Wither Effect Here
    }
})```
misty pivot
thorn flicker
#

and its damagingEntity

fickle dagger
misty pivot
chrome flint
#

what does initialPersistence do?

fickle dagger
#

yeah I forgot it was called that, but it is proper in the actual code

#

I'll guess I have to either test more stuff out or just search for other methods

wary edge
thorn flicker
#

...

fickle dagger
thorn flicker
#

bruh

fickle dagger
#

and I thought it was the only way for stable

#

if it does work on stable then I could've used that instead the entire time

thorn flicker
#

which is just in javascript, and any other language

fickle dagger
#

did notice that when messing around with scripts

wary edge
# fickle dagger if I remember it was something like : ```js const necroArmor = [ /*Armors Goes H...

Personally I would do:

const validEquipment: Set<string> = new Set(["sword", "shield", "armor", "boots"]);

// Example equipped items
const equippedHelmet: string = "sword";
const equippedChest: string = "armor";
const equippedLegs: string = "leggings";
const equippedBoots: string = "boots";

// Check if each equipped item is in the valid set
if (validEquipment.has(equippedHelmet)) {
    console.log("Helmet is valid equipment.");
} else {
    console.log("Helmet is not valid equipment.");
}

// Repeat for other equipped items...
``` Could also do this instead of an array
#

Or just do

equippedHelmet.typeId == "blah"
fickle dagger
#

I'll take notes about these, thank you very much 🙏

wary edge
thorn flicker
#

doesnt look like it

fickle dagger
#

no ts yet

thorn flicker
#

so his example will not be the best for you unless you want to learn ts

wary edge
#

I don't give out actual snippets, just examples so people will actually learn

cinder shadow
#

erm, can you please give me a script that does the griddy?

thorn flicker
wary edge
wary edge
#

Again, it's an example of what I would do, not directly it being, "Hey, copy/paste this"

chrome flint
#

what does this do

#

oh i see, it makes entity not despawn overtime

cinder shadow
#

forgot lore doesn't work with lang keys 😔

pale terrace
sudden nest
#

Is it possible to get all the possible enchantments of not enchanted sword or tool e.g. fishing rod can have mending, unbreaking, lure, and luck of the sea. Like that? Without hardcoding the enchantmentSlot and mapping each enchantment

clear pendant
#

is it possible to read an sqlite file via js when mc loads a world?

round bone
#

you can export data from this file manually to js/ts file

clear pendant
#

oh ok

#

i just wanted a db bc it was really fast to read

round bone
#

you should use dynamic properties to have the fastest speed

simple zodiac
clear pendant
#

k

distant tulip
simple zodiac
#

well yeh but you have to manually connect web sockets

#

there is no automatic way of doing that

distant tulip
#

ah
yeah

burnt remnant
#

question, in the block permutation class, how does getState and withState work

knotty plaza
#

And getState only takes 1 parameter and return the value of that state

open urchin
#

withState returns a new permutation object with a state set to a value
permutation.withState("my:state", "value")

burnt remnant
#

so could i detect if a block has a specific cardinal direction with one of those?

wary edge
#

You can use get state

open urchin
#

permutation.getState("minecraft:cardinal_direction") === "north"

pale terrace
#

autocompletion doesn't work for me in functions, does anyone have a solution? I even tried to use @param but got no result

pale terrace
#

Still saying "any"

wary edge
#

🤷 if you were using TS you can easily define the param type

pale terrace
#

I will try thx

pale terrace
wary edge
#

I mean you dont have to always define everythinf

modest lion
#

Can anyone tell me if this works?

  const domainAround = player.dimension.getEntities({location: player.location, excludeFamilies: ["domain"], maxDistance: 50})
  const domainRay = domainAround[0]
  
  if (domainRay === true) {
    player.runCommandAsync("tag @s add domain_around")  
  } else {
      player.runCommandAsync("tag @s remove domain_around")  
  }
}
pale terrace
modest lion
wary edge
#

Cant really help you if you dont try it yourself

#

Same could be said: Instead of asking if this will work, why dont you try it first?

modest lion
#

Can you tell me if using (domainRay === true) will identify if there is the const entity around me?

modest lion
#

I need someone to help me understand... Saying that kind of thing sounds really rude.

wary edge
#

domainRay seems to be getting the first index of an array of entities so no, it will not work. You need to check if it isnt null. Alternatively, you could just check the array length

modest lion
#

Especially for those who translate this

wary edge
#

I dont see it like that but sure. Everyone interprets things differently

modest lion
#

I wanted to make sure that tag was added if it identified the specific entity within a radius of 50 blocks

modest lion
subtle cove
modest lion
#

So you're telling me to use the const "domainAround" and in the If to use "domainAround length'?

subtle cove
#

For checking if at least an entity is within that radius, Yes

modest lion
#

I thought I was supposed to create this const as an array 😅

subtle cove
#

That's what it looks like

#

It's already an array of entities depending on the query

#

Perhaps

player[domainAround.length ? "addTag" : "removeTag"]("domain_around")
modest lion
#

@subtle cove
I did this, but even without having any entity from the "Domain" family around, the commands are executed

function domainAround(player) {
  const domainAround = player.dimension.getEntities({location: player.location, families: ["domain"], maxDistance: 50})

  if (domainAround.length) {
    player.runCommandAsync("tag @s add domain_around")  
    player.runCommandAsync("say domain_around")  
  } 
}
subtle cove
#

Hmmmm

modest lion
elder heath
#

the creeper says hello

random flint
#

I Didn't know Mace didn't have Enchantable Slot 🤔

#

Scanning Items stuff
-# I ain't mapping this sh*t man
works with other addon ig

chrome flint
chrome flint
random flint
#

yet another hardcoded value xd

wary edge
chrome flint
#

i thought it was the default spawn ticking area?

wary edge
pale terrace
#

how can I create a new Block like "new ItemStack(identifier)"?

pale terrace
pale terrace
#
EnchantmentTypes.getAll()```
why this throw the error is not a function?
#

oh, there is no getAll...

#

so how do I get all enchantments?

knotty plaza
#

Does DataEntityTriggerAfterEvent fire even if the event doesn't exist?

random flint
#

Is onBeforeDurabilityDamage from ItemCustomComponents can cancel attack damage?

chrome flint
burnt remnant
#

anyone have an example of getBlock and it checking if a specific block is there

#

unless you can confirm

block.dimension.getBlock(blockInLeftLocationNorth = "minecraft:dirt")

works

random flint
burnt remnant
#

so is north just 1 block next to the origin block, from the north side of course. cause i was using blockInLeftLocationNorth as my location, which was const blockInLeftLocationNorth = { x: x - 1, y: y, z: z };

random flint
#

yes

#

You can use .offset() too for more range

burnt remnant
# random flint yes

and then i can use .permutation.getState at the end to get the cardinal direction?

#

block.north().typeId == "minecraft:dirt".permutation.getState("minecraft:cardinal_direction") === "north"

burnt remnant
#

well

const testblock = block.west().typeId == "minecraft:dirt"

testblock.permutation.getState("minecraft:cardinal_direction") === "west"

doesnt seem to be working, the error keeps saying cant getState, undefined when im literally defining it up there

knotty plaza
#

Then is there any way to detect an interaction to an entity with stable api?

misty pivot
random flint
knotty plaza
#

The closest player is not always accurate

#

I just found a way

misty pivot
#

ah, i see

hazy nebula
#

how to get an item with name tag and lore = script?

burnt remnant
knotty plaza
#

If you don't mind then do it

knotty plaza
burnt remnant
# knotty plaza You can, but it will result in a really long if statement

😂😂 currently this is my if statement

if (itemInFirstSlot?.typeId === blockBehindN?.typeId && block.permutation.getState("minecraft:cardinal_direction") === "north" && westblock.typeId == "minecraft:dirt" && westblock.permutation.getState("minecraft:cardinal_direction") == "west")

so i dont really mind

#

&& is my favorite apparently

knotty plaza
#

Try like this so its more readable```js
if (itemInFirstSlot?.typeId === blockBehindN?.typeId &&
block.permutation.getState("minecraft:cardinal_direction") === "north" &&
westblock.typeId == "minecraft:dirt" &&
westblock.permutation.getState("minecraft:cardinal_direction") == "west"
)

hazy nebula
knotty plaza
knotty plaza
#

I guess

chrome flint
tiny tartan
#

what is difference in type.id and typeId

subtle cove
chrome flint
chrome flint
glacial widget
#
world.afterEvents.playerJoin.subscribe((join) => {
    for(const player of world.getAllPlayers()) {
        const id = join.playerId
        const name = join.playerName
        if (player.hasTag == `"rank:§a§lVIP"`){
          world.sendMessage(`A VIP member ${name} has joined`)
        } 
    }
})

can this work guys cuz tag the has this in them " "

chrome flint
#
player.hasTag("rank:§a§lVIP")
#

@glacial widget

#

also why are you iterating all players lol

#

use playerSpawn event, i dont think you can get player data with playerJoin

burnt remnant
#

Can someone tell me the difference between = and == and === cause I thought I knew but apparently not

distant tulip
sudden nest
#

Anyone using Android 13 for Minecraft bedrock scripting? How do you copy your whole BP folder to the "com.mojang" directory located in Android/data?

neat hound
# glacial widget ```js world.afterEvents.playerJoin.subscribe((join) => { for(const player of...

The (join) will have the player that joined, not need to cycle thru them all, which if you do, all VIP are going to be announced, not just the one that just logged in.

PlayerJoinAfterEvent only has playerId and playerName. Tag is not available, so if you use the playerSpawn event instead, you can check the tag of the player that joined and spawned in. Be sure to check the initialSpawn property to determine if just logged in or not, so that it is not activated from a respawn after death.
https://stirante.com/script/server/1.14.0-beta.1.21.20-preview.22/classes/PlayerSpawnAfterEvent.html.

grand heart
sudden nest
#

Ok, thanks. I'll try it later

vocal elbow
#

Hello everyone, how to decrease an item durability every ticks when it's equipped in the chest slot ?

#
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const slotChest = player.getComponent("equippable").getEquipment("Chest");
    const slotMainhand = player
      .getComponent("equippable")
      .getEquipment("Mainhand");

    let durabilityMax = slotChest.getComponent("durability").maxDurability;
    let durabilityDamage = slotChest.getComponent("durability").damage;
    let durability = durabilityMax - durabilityDamage;

    if (getEquipmentVoid(slotChest) === "minecraft:netherite_chestplate") {
      player.applyKnockback(0, 0, 0, 0.35);
      
      durabilityDamage = durabilityDamage + 1
    
      player.sendMessage(`${durability}`);
    }
  }
}, 3);``` I tried this but it doesn't work
stiff ginkgo
#

how to use .teleport?

sleek nexus
#

@stiff ginkgo

entity.teleport({x:100, y:256, z:300}, ...) // ... is teleportOptions (see second link)```

https://stirante.com/script/server/1.11.0/classes/Entity.html#teleport
https://stirante.com/script/server/1.11.0/interfaces/TeleportOptions.html
halcyon phoenix
#

what's the difference of TS and JS?

tight plume
#

How to know you're making a progress on JS:

Able to fully understand documentations are beautiful thing to ever exist

tight plume
carmine cloud
remote oyster
sudden nest
remote oyster
fiery solar
# halcyon phoenix what's the difference of TS and JS?

The point of typescript is that you always know what the type of every variable is. If you set things up right, typescript will always give you auto complete for every part of your code automatically and you never have to worry about getting undefined errors in the game because typescript can identify 99% of bugs before you even start Minecraft.

Jayly's script debugger is just a combination of typescript checking and eslint. You can easily set up VSCode to always give you that information and more.

sudden nest
remote oyster
# sudden nest Oh, okay. I was trying to copy a BP directory from my computer to "com.mojang" i...

There should be no restrictions when connected to the PC. The restrictions are limited to the framework of Android only.

When you plug your device in to your computer it should recognize the connection. By default it's charging only. On your device you select to change it from charging to file transfer. This will have your computer mount the storage drive.

Open the file manager, double click on the mounted drive related to your device, then go to Android/data/com.mojang and you should have no issues modifying that directory. When done, just make sure you properly unmount the drive or use your phone to change back to charge only to prevent file corruption/damages.

tiny tartan
#

someone already suggested this

sudden nest
#

Oh okay. Thank you for your responses. Going to try rn (2nd time), i think i was just hungry earlier that's why I am confused of what am I doing

sudden nest
remote oyster
sudden nest
#

I can only modify the existing folder/files ithink

#

Tried it earlier

sudden nest
#

Yup already did

tiny tartan
#

kinda weird cuz ima able to make files and folder in android/data

remote oyster
tiny tartan
#

13

remote oyster
# tiny tartan 13

Does it let you copy files over to Android/data? Can you show a video?

sudden nest
remote oyster
# sudden nest

I do know that Root can open the door to make it possible to bypass Scope Storage but every device is slightly different on how you approach it due to OEM's making their frameworks unique by their own standards.

glacial widget
# chrome flint no it wont
world.afterEvents.playerSpawn.subscribe((v) =>{

  let joined = v.initialSpawn
  let player = v.player

  if (player.hasTag("rank:§a§lVIP" && joined)){
world.sendMessage(`VIP member ${player.name} has joined`)
  }
})

smth like this right

sudden nest
sudden nest
pale terrace
neat hound
twilit crag
#

what will beta-1.140 change from beta-1.13.0?

amber granite
wary edge
charred dune
amber granite