#Script API General

1 messages · Page 24 of 1

wary edge
#

Are you sure its not because of what I said above?

simple zodiac
#

well you have the freedom to just npm i @minecraft/server@beta

untold magnet
woven loom
gaunt salmonBOT
untold magnet
#

wait a god damn moment, after i finished termux, bridge back to work somehowbao_icon_entities

#

bridge is now working for me

woven loom
#

/s

untold magnet
#

well, now i can complete working on my project

untold magnet
#

hmm,

#

how can i remove one item from the entity inventory?
itemStack.amount - 1 or something?

untold magnet
# wary edge Yes

if (itemStack.amount >= 1) itemStack.amount - 1 this should remove the item only if the amount is 1 or higher right?

wary edge
#

Yeah

untold magnet
#

im learningbao_doggo_happy

#

somehow

simple zodiac
wary edge
#

or .amount--; as well. But you also have to consider that when it's 1, set it to undefined

untold magnet
#

all works the same right?

simple zodiac
#

itemStack.amount - 1 will not work on its own

itemStack.amount -= 1
itemStack.amount--
itemStack.amount = itemStack.amount - 1

will work the same

untold magnet
#

itemStack.amount-- will remove one item
itemStack.amount = itemStack.amount - 1

#

.amount-- is more simpler and smaller

simple zodiac
#

smaller != more readable

untold magnet
#

should i do something like new ItemStack(itemType)?

simple zodiac
#

well whats itemType

untold magnet
#

itemType will be different all time

simple zodiac
#

whats the type of itemType

untold magnet
#

like

if (itemStack.typeId === itemType) ItemStack.amount - 1
}
// aFunction(itemStack, 'minecraft:dirt')```
untold magnet
#

'minecraft:stick'

simple zodiac
#

if its a string then yes you need to do new ItemStack(itemType)

untold magnet
#

should i use new ItemStack to spawn the item?

#

alright

simple zodiac
#

you could also just pass in the item stack directly and

untold magnet
#

every time i do something my knowledge is enhanced

#

gosh,

#

z: z + 1 returns a log

#

@simple zodiac bao_block_missingtexture

#

oh, wait

#

const { x, y, z } = block.center
should be like this
const { x, y, z } = block.center()

#

my bad

#

um, how can i make the item just spawn, without throwing away?

buoyant canopy
#

is there a way to get DisplaySlotId of a scoreboard?

#

i want to test if a scoreboard is displayed on the sidebar

untold magnet
#

yasser,
how to spawnItem normally without spreading away?

#

also,
itemStack.amount - 1 isn't working

#

the item is still there

buoyant canopy
buoyant canopy
untold magnet
buoyant canopy
#

yeah

#

i wish we could do amount = 0 tho

untold magnet
buoyant canopy
#

in a variable

untold magnet
buoyant canopy
#

or directly into your slot

buoyant canopy
#

that would simplify lots of scripte

untold magnet
#

i know what u mean

untold magnet
untold magnet
#

edit it for me :>

#

bec idk where should i put that thing

buoyant canopy
#

const item = ...
and then use it wherever

untold magnet
buoyant canopy
#

what are you trying to do with it?

untold magnet
#

the item will spawn at some specific locations

#

hmmm

#

, ItemStack.setThatThing(x: x, y: y, z: z - 1)?

#

ooh wait, making it throw the item will be nicer

#

just like how the crafter block threw items, the system should throw items like it

buoyant canopy
#
block.dimension.spawnItem(new ItemStack("diamond").setVelosity({x:0,y:0,z:0}), block.location)
buoyant canopy
#

but i am not sure if that method would return the itemStack back or not so do this to be safe:

#
const diamond = new ItemStack("diamond")

diamond.setVelosity({x:0,y:0,z:0})

block.dimension.spawnItem(diamond, block.location)
untold magnet
#

setVelocity isn't showing up on bridge for some reason

buoyant canopy
#

maybe i got the name wrong, wait a second

wary edge
#

You cant set velocity on an ItemStack

buoyant canopy
#

oh yeah, you need to convert it into an entity first

untold magnet
#

uh, lets not think about making the item not spread away,

oak lynx
untold magnet
#

i gotta make it throwing like how the crafter block works

buoyant canopy
#
const diamond = 
block.dimension.spawnItem(new ItemStack("diamond"), block.location)
diamond.setVelosity({x:0,y:0,z:0})
oak lynx
#

i am not exactly sure what data driven entity event means

wary edge
#

That's all

oak lynx
#

the events can be empty in the json right?

untold magnet
#

sssoooo
how can i make the item spawn and throw it away like the crafter block?

wary edge
buoyant canopy
#

propably in the direction of the crafter

untold magnet
#

i just need the spawn item system

untold magnet
#

theres no setVelocity

untold magnet
wary edge
untold magnet
#

well, that sucks

#

also wait, how there's not setVelocity?

wary edge
untold magnet
#

wait,

#

applyKnockback or applyImpulse will work but

glacial widget
#

how do i set velocity?

untold magnet
#

the item will spawn and spread anyway

wary edge
untold magnet
#

i remember someone made me a script that will not spread the items when i spawn them

#

i didn't use that script bec i was making an ore block

buoyant canopy
#

oh yeah, i knew i got the name wrong, it's applyImpluse, applyKnockback doesn't work on item entities

buoyant canopy
#

yes

untold magnet
#

how about clearVelocity?

#

meh i dont think it will work

buoyant canopy
#

no it does

untold magnet
#

it will spawn the item without spreading right?

wary edge
#

Try it and see

untold magnet
#

oh wait

#

my bad

neat hound
#

Anyone know of any way to get biome tags of current location, or block in location or anything in location... ????

wary edge
cinder shadow
#

erm, wrong

untold magnet
neat hound
#

Need to get without building big if/case... they have MinecraftBiomeTypes... so must be a use

untold magnet
#

spawning the item normally without spreading away

wary edge
neat hound
#

Expand please

cinder shadow
#

It's a little annoying though

#

becuase that's only going to find one biome

neat hound
#

wait... I want to get the biome... not test for them

cinder shadow
#

If you want to get ALL of the biomes part of that biome, you'll need to make a loop through biomeTypes

neat hound
#

oh.. that may work... so I don't have to build it..

#

Thanks Bear

untold magnet
#

it looks pretty stupid when it throws

#

I'll make it just spawn the item

lyric kestrel
#

Ye, but it will only show logs. Any warnings or errors won't show up

buoyant canopy
wary edge
#

If we're going to go out of the scope of ScriptAPI just look at the vanilla files at that point.

buoyant canopy
#

like recreating the algorithm that decides where biomes should generate in Minecraft and use it to return the biome in a location.

lyric kestrel
#

What about the BiomeTypes class?

buoyant canopy
lyric kestrel
buoyant canopy
#

the work is already done by minecraft java players, we just can't access it

lyric kestrel
#

Ye, that's Java

buoyant canopy
#

and converting java code into js code won't be impossible

untold magnet
#

oh man,

#

bugs, issues

#

the dynamic property is setting for all of them at the same time

#

i think,

#

damn it...

#

the only way to fix that issue is by making a tag or dynamic property for each entity

#

right?

wary edge
untold magnet
# wary edge How are you doing this?
  const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
    for (const entity of world.getDimension(dim).getEntities()) {
      const block = entity.dimension.getBlock(entity.location);
      if (entity.typeId === 'my:entity') {```
buoyant canopy
#

you can do entity.setDynamicProperty you know?

untold magnet
untold magnet
#

if one of those entities have a specific item inside it, the script will work and set the same dynamic property for every same entity

#

uh

#

wait

#

the script works on the entity that has the item inside the slot 0

#

if there are 2 entities that have the same item at the same slot, the script will spawn the item to the first entity for some reason

#

hmmmmmbao_foxxo_doubt

cinder shadow
#

@neat hound
My bad, I don't think it gives you all the biome tags, only the main one

#

There is also overlap between biome borders

untold magnet
#

if the first entity has an item in the first slot, it will set a dynamic property of the block location that the entity is inside

#

but

#

the second entity will get a different dynamic property location

#

gosh my brain really hurts

#

fun fact, if all entities have the same item at the same slot, the script will remove the item from all entities without spawning any items

#

hmm,

#

entity.setDynamicProperty('loc', block.location)
const loc = entity.getDynamicProperty('loc')

#

how can i detect the dynamic property location?

#

likeif (loc === block.location) { ,,, }?

lyric kestrel
#

Try it

lyric kestrel
untold magnet
#

maybe tomorrow

#

im thinking now

#

gosh, guys

#

i give up

#

for now

deep quiver
deep quiver
untold magnet
#

ik,

#

even if it works, the same issue will happen

deep quiver
#

whats your issue

untold magnet
#

pretty hard to fix

#

if theres 2 entities have the same item at the same slot, the script will work on both of them if one of those entities got energy

deep quiver
#

I do see that

untold magnet
#

i think,

#

putting different tag for each one will fix it

deep quiver
#

yeah you gotta store the data somehow in a better way

untold magnet
#

its a marketplace addon, i cant make it unplayable on multiplayer

deep quiver
#

ah okay

#

so you can't even send the code

lyric kestrel
untold magnet
#

i will be one but soo later

deep quiver
#

ah so its supposed to be in marketplace

#

so you can't be sharing it

#

you will have to sign an nda sooner or later

untold magnet
#

marketplace addons can be used on realms right?

deep quiver
#

yes

untold magnet
#

if 2 players purchased the addon they can use it in the same world

deep quiver
#

only 1 needs to purchase

untold magnet
#

uh,

deep quiver
#

theres strict rules on addon stuff for market place tho

lyric kestrel
#

Ye, only the owner of the world needs it

untold magnet
#

the issue happens when u put multiple of the same block and putting the same item at the same slot on each block

#

if one block got energy, all other blocks that get energy

#

and all blocks will lose the item from that slot

#

and only one of them will actually drop only one item

#

hmmmmmm

#

if the entity got the item in that slot, it will get a tag or dynamic property, after that the script will detect if other entity have the same item at the swme slot and give it a different tag or dynamic property

#

damn....

#

damn it

#

I'll go sleep for now..

#

maybe I'll find a way tomorrow

#

if i did my freaking best and stay having the same issue or even more issues

#

I'll left it behind, and say the addon might have problems on multiplayer,

#

hopefully i dont have to do thatbao_foxxo_blank

buoyant canopy
deep quiver
buoyant canopy
#

i had an issue with stringifying coordinates, where my script works fine on a computer but breaks if run on a mobile, and reason for that was JSON.stringfy returned {z, y, x} instead of {x, y, z}

untold magnet
#

I FOUND IT

#

the handcrank system is sending energy to every single entity

#

thats why that bug happening

#

the handcrank isn't giving the block underneath energy, it's giving energy for all entities

#

i just have to make a system for the handcrank and make it give energy for the block underneath it only

#

that will fix the issue

untold magnet
#

itemStack.amount - 1 isn't working even if there are more than 1 items there

#

itemStack.amount = itemStack.amount - 1 has a log

#

itemStack.amount-- has a log

#

What else should i use?

random flint
#

Is JavaScript decorator supported now?

untold magnet
#

itemStack.maxAmount = itemStack.amount - 1;

#

??

slow walrus
prisma shard
#

s

dawn moon
#

why are my actionformdatas acting weird?

#

whenever i click a button in the actionformdata it doesnt close the form and makes me spam until it finally closes

#

I have to press one of the buttons 8-10 times before the form finally closes. I created a fresh pack with nothing but the most basic form and it still does this

light tinsel
#

Make sure to share your forms in a new Post!

#

And what version of the @minecraft/server-ui are you using?

#

If beta than issues are common

slow walrus
#

that's not a version issue, that's just some incorrect code

dawn moon
slow walrus
#

player interact with block fires multiple times, so I assume it's firing while your form is opening, so like 8 forms open instead of one

dawn moon
#

yep

#

i didnt know it fired multiple times

#

what would be the best way to deal with that? is it possible to have it only fire once?

slow walrus
#

can you try moving your form variable outside of showForm?

#

so that it's only the form.show().then part inside of the function

knotty plaza
#

If the player is still in cooldown then return

#

I think 5 ticks is enough

dawn moon
#

got it

#

thanks

digital trout
#

Is it possible to read wearable armor protection value through script?

There doesn't seem to be an item component type for in in the API

ruby haven
#

Is their a way to access the skin of your player through scripting cause I wanted to make a realistic death addon where you die and spawn another entity which takes your skin

untold magnet
#

guysbao_icon_entities

#

#1286925551550074970 ^

supple yoke
#

I love ffmpeg

gentle charm
#

One message removed from a suspended account.

ruby haven
unreal cove
#

queue_command

wheat condor
#
let items = [];
if (this.#getDataType(key)) {
    for (let i = 0; i < 256; i++) items.push(inv.getItem(i));
    for (let i = 255; i >= 0; i--) if (!items[i]) items.pop(); else break;
} else items = inv.getItem(0);

is there a better way to do this?
i wanted to delete all undefined from right till it gets an item

#

like if the array is
[ item | undefined | item | undefined | undefined ]
it needs to convert it to this:
[ item | undefined | item ]

knotty plaza
#

And start adding elements to the array once you find one item

#

At the end you can do .reverse() to the array

subtle cove
sage sparrow
#

hi there, the block component onPlayerInteract only works if you have no item on hands? it doesnt trigger if you are holding any item?

sage sparrow
#

sure? because mine only triggers with empty hands, look it is very simple: ```javascript
world.beforeEvents.worldInitialize.subscribe(eventData => {
// On Interact
eventData.blockComponentRegistry.registerCustomComponent('awp:on_interact', {
onPlayerInteract: (event) => { onBlockInteract(event.player, event.block, event.dimension, event.face, event.faceLocation) }
});
})

export function onBlockInteract(player, block, dimension, face, faceLocation) {
console.log(JSON.stringify(on block interact))
}```

sage sparrow
#

anything, like weapons, iron ingot, blocks, bone

gentle charm
cold grove
#

First screenshot

gentle charm
#

One message removed from a suspended account.

gentle charm
#

One message removed from a suspended account.

dawn moon
#

Are there any possible ways of powering a redstone lamp, piston, etc without having redstone beside them? I'm basically trying to make a redstone lamp become powered through scripting without needing to actually put a power source beside it

runic crypt
#

@distant tulip
can you check your dms ??

#

i wanna know what modules i need to import for the script

#

because the ones i added

#

dont work for sm reason idk why :(

drifting ravenBOT
#
DMs Are Not Ideal

When you ask a question via DM, you are restricting the total number of people who can help you from all potential server members to just one. Asking in the public channels is the best way to get a good, community-sourced answer to your question, allowing other observers to give their input.

While you are certainly welcome to DM with each other, please be aware it is against our rules to send unsolicited DMs requesting help.

copper lake
#

I'm not sure where to look or ask this question so asking here to find out what I need to be searching for.
I would like to create a setup script that will help me prepare a new world for classroom use. There are several steps I currently have to go through in the process. Most of it is /function commands but I generally need to make sure I do them in the right order, make sure each step complete before moving on as some steps include entity behavior pack animations, and I have to make sure that I'm in the right place before I do each step.
Can't script api help me with any of this? Or must I keep using a checklist?

buoyant canopy
#

what does this error mean?

honest spear
scenic bolt
#

Would anyone be able to explain to me how you can make loot spawn at the entity rather than 0 0 0 in a command in scripting.

For reference, my current command setup is source.dimension.runCommandAsync(‘loot spawn ~~~ loot my_loot_stuff’);

honest spear
wary edge
glacial widget
#
world.structureManager.place("start:1", player.dimension, { ...player.location, y: player.location.y + 2})
#

why do i get this error?

wheat condor
#

if you re using before events then wrap it in a system.run(()=>{})

quasi meteor
#

are there any addons for vs code ide,

copper lake
#

how can I make some one fly when I teleport them. As in I want to teleport them up in the sky and I want them to stay there and not fall down. They will be in creative mode but how to I make it so they are already flying?

uncut fjord
#

If an item has the component to not break blocks while in creative is there a way to reference the block that is hit without it being destroyed?

misty pivot
#

how do i detect whether a location/chunk is loaded?

runic crypt
#

is it possible to enchant something like a arrow with enchantments ??
like enchant an arrow with sharpness ??

runic crypt
#

oki

runic crypt
halcyon phoenix
#

how do I detect potion thrown with js? or on_hit of some sort

#

I want to make all of my throwable potion script-based but I don't know how to trigger it from the item.js

fallen cape
fallen cape
halcyon phoenix
#

THanks a lot

#

I forgot afterEvents exists

fallen cape
true isle
#

how do i detect a specific level of fortune?

runic crypt
#

any way to apply sharpness on a pickaxe using scripts ??

#

i tried using inventory editors and nbt and it works

#

so i thought there is a way of doing it using scripts ?

true isle
#

i mean you can do it with a loot table lmao i just figured that out oddly enough

halcyon phoenix
#

is getEquipment still usable? or hsould I use getEquipmentSlot instead?
getComponent('equippable')?.getEquipment('Mainhand');

uncut fjord
#

Use getComponent(“inventory”).container.getItem(player.selectedSlotIndex)

Pretty sure that’s how it goes but I could be wrong

supple yoke
#

is there like a create-script CLI or something

halcyon phoenix
#

which one?

gentle charm
#

One message removed from a suspended account.

unreal cove
gentle charm
#

One message removed from a suspended account.

#

One message removed from a suspended account.

unreal cove
#

that should fix the log error yea

gentle charm
#

One message removed from a suspended account.

gentle charm
hazy nebula
#

what's wrong with this code```js
world.afterEvents.playerInteractWithBlock.subscribe(data => {
const block = data.block;
const player = data.player;
const itemChest = block.getComponent("inventory");

for (let i = 9; i < 18; i++) {
    const item = itemChest.container.getSlot(i);
    const enchantable = item?.getComponent('enchantable');
    let enchantmentMessage = `${item.typeId}: `;

    if (enchantable) {
        const enchantments = enchantable.getEnchantments();
        if (enchantments.length > 0) {
            enchantments.forEach((enchant, index) => {
                enchantmentMessage += `id:${enchant.type.id}, lvl:${enchant.level}`;
                if (index < enchantments.length - 1) {
                    enchantmentMessage += '.';
                  }
            });
            console.error(enchantmentMessage);
        }
    }

    const itemLore = item.getLore();
    const itemName = item.name;
    const itemAmount = item.amount
    const dataMessage = `[\nid|${item.typeId}\nAmount|${itemAmount}\nname|${itemName}\nlore|${itemLore}\nenchantment|${enchantmentMessage}\n]`;
    player.sendMessage(dataMessage)
    player.playSound('random.orb');
}

});

warm drum
#

how do i change gamerule using script?

#

runCommand?

distant tulip
hazy nebula
hazy nebula
distant tulip
#

also 724 is not the typeId one

hazy nebula
#

it work

distant tulip
#

also add a check if there is item or not

dim tusk
#

hello boys and girls

distant tulip
dim tusk
#

im rusty asf :(

#

i got pretty small problem

distant tulip
#

you will get back quick
didn't take you much to learn in the first place lol

distant tulip
dim tusk
#

actually i started boring project

distant tulip
#

about?

dim tusk
#

this one dude, I can't seem find a way how to put a comma on the numbers

distant tulip
#

eww opera

dim tusk
dim tusk
#

i missed alot of updates... in this server huh

distant tulip
dim tusk
distant tulip
distant tulip
dim tusk
distant tulip
#

you mean 8,991

dim tusk
#

i want it to be = 8,991

dim tusk
#
function evaluateExpression(expression) {
    expression = expression.replace(/(^|[\s+*/()-])0+(?=\d)/g, '$1');
    try {
        let result = eval(expression.replace(/x/g, '*'));
        if (result !== undefined) {
            let formattedResult = result.toLocaleString();

            return Number.isInteger(result) ? formattedResult + '.' : formattedResult;
        } else {
            return 'Syntax ERROR';
        }
    } catch {
        return 'Syntax ERROR';
    }
}```
distant tulip
#

bruh
just stringify the number and slice it and insert the coma

dim tusk
#

i frgot how to stringify now

#

wait lemme check my memory boop

distant tulip
#

dose q js have toLocaleString

dim tusk
#

nvm

#

yey thanks again minato

dim tusk
lapis heart
distant tulip
#

try number.toLocaleString()

distant tulip
dim tusk
distant tulip
lapis heart
dim tusk
# distant tulip

that's my first idea but im confused cause sometimes it works someitmes it doesn't

#

like WTH

lapis heart
dim tusk
lapis heart
lapis heart
dim tusk
distant tulip
dim tusk
# dim tusk that's my first idea but im confused cause sometimes it works someitmes it doesn...
function evaluateExpression(expression) {
    expression = expression.replace(/(^|[\s+*/()-])0+(?=\d)/g, '$1');
    try {
        let result = eval(expression.replace(/x/g, '*'));
        if (result !== undefined) {
            let formattedResult = result.toLocaleString();

            return Number.isInteger(result) ? formattedResult + '.' : formattedResult;
        } else {
            return 'Syntax ERROR';
        }
    } catch {
        return 'Syntax ERROR';
    }
}
#

here's what i did but bruh

distant tulip
#

don't use eval bao_icon_entities

lapis heart
dim tusk
distant tulip
distant tulip
dim tusk
#

here's what I did to make to make it work lmfao... a lot of shenanigans and shits

function evaluateExpression(expression) {
    expression = expression.replace(/(^|[\s+*/()-])0+(?=\d)/g, '$1');
    try {
        let result = eval(expression.replace(/x/g, '*'));
        if (result !== undefined) {
            let resultStr = result.toString();
            let parts = resultStr.split('.');
            
            let integerPart = parts[0];
            let withCommas = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

            let formattedResult = withCommas + (parts[1] ? '.' + parts[1] : '');

            return Number.isInteger(result) ? formattedResult + '.' : formattedResult;
        } else {
            return 'Syntax ERROR';
        }
    } catch {
        return 'Syntax ERROR';
    }
}```
lapis heart
dim tusk
distant tulip
#

if anyone can input stuff to it, it can go badly if not handled

dim tusk
dim tusk
#

this is messy cause i'm lazy to format it yet but as long as it work then we got no problem there buddy

distant tulip
#

bruh.js

dim tusk
#

but yors was more organized i guess? i forgot

distant tulip
#

hmm? i meant i played around with json ui
not related

dim tusk
#

i miss a lot of people here, especially herobrine, ash, smokey, you and other people i frgot the names cause i am dyslexic have short term memory

distant tulip
dim tusk
distant tulip
#

wait there is no input text 🤦‍♂️

#

nvm

dim tusk
#

man i also miss cyberaxe

#

is he still live sometimes?

distant tulip
#

if you are using eval
don't

distant tulip
dim tusk
distant tulip
#

oh the "howdy" guy

#

yeah lol

dim tusk
#

where's the "tnt" guy

#

i wanna blow him up

distant tulip
dim tusk
#

not in a weird way

#

wait2

distant tulip
#

he changed his pfp

dim tusk
#

aww

#

ok my brain is pretty warm up

#

time to do a bit of scripting again

distant tulip
#

good luck

dim tusk
static wedge
#

custom entities have EntityEquippableComponent ?

distant tulip
static wedge
distant tulip
static wedge
distant tulip
loud brook
#

Hey guys

#

Why do onPlayerInteract work when I place a block?

#

I mean i want to place the block without it running the interacting function

wheat condor
#
world.beforeEvents.chatSend.subscribe(e => {
    function run(any, e) {
        system.run(() => any(e))
        e.cancel = true
    }
    const { sender: plr, message: msg } = e
    if (canSendSave.get(plr) && msg != ".cancel") run(saveInv, e);
    if (canSendLoad.get(plr) && msg != ".cancel") run(loadInv, e);
    if (msg == ".save") run(initSave, e);
    if (msg == ".load") run(initLoad, e);
    if (msg == ".cancel") run(cancel, e);
})

will this cancel the message only when its used to save the inv??

dawn moon
#

    const block = data.block
    if(block.typeId == "minecraft:red_concrete")
        console.warn("test")
}) ```
why does this basic code bug out when i use 1.15.0-beta?
it only runs the console.warn if i place another block on the block im trying to interact with
#

a normal interaction does nothing, but it does run if i stand farther away and interact while simultaneously placing a block down in front of me if that makes sense

shy leaf
shy leaf
# loud brook How do I cancel it?

for me, i do this

world.afterEvents.playerPlaceBlock.subscribe(({player}) => {
    player.__cancel = true;
});

world.afterEvents.playerInteractWithBlock.subscribe(({player}) => {
    if (player.__cancel == true) {
        player.__cancel = false
        return;
    }
});```
loud brook
#

Thanks!!

dawn moon
wintry bane
#

I want to place a block of wool when a chunk loads but only when a player loading that chunk has the tag "wooly_curse". Is it possible? I'm making a strange add-on with sheep-evokers

dawn moon
lone ruin
#

is it just me or is WorldInitializeBeforeEvent not working when i either use ESNext or put the await keyword in the top-level

lone ruin
#

addendum: it was the latter

celest fable
#

how do i make a class that like handler, has .open(player, callback) that when called it will show form with buttons that has customized text like literal template, i have one but it doesn't work

selectPlayerHandler.js

import { world } from "@minecraft/server"
import { ActionFormData } from "@minecraft/server-ui"

class SelectPlayer {
  constructor() {
    this.title = "Select Player"
    this.body = ""
    this.buttonText = ""
  }
  
  body(text) {
    this.body = text
  }
  
  buttonText(text) {
    this.buttonText = text
  }
  
  open(player, callback) {
    const players = world.getPlayers
    const form = new ActionFormData()
    .title(this.title)
    .body(this.body)
    players.forEach(f => form.button(this.buttonText.replace(/\{([^{}]+)\}/g, (match, key) => player[key] || '')))
    form.show(player).then(res => {
      if (res.canceled) return

      const target = players[res.selection]
      callback(player, target)
    })
  }
}

// uses
/**
const form = new SelectPlayer()
  .buttonText("{name}\n{getTags().find(f => f.startsWith('tes'))}")
  .open(player, (player, target) => {
    new ModalFormData()
    .title("SetPerm")
    .textField("permission", "tes")
    .show(player).then(res => {
      if (res.canceled) return
      
      target.sendMessage("added permission")
    })
  })
*/
shy leaf
#

so ive been lookng at geyser's source code to see how they deal with air swing for bedrock

#

and

#

they used sound event oml

#

why mojang

#

why cant you just allow us to swing air???

shy leaf
#

this just hurts to see

sharp elbow
#

Brilliant

glacial widget
#
/**
 * @param {ItemStack}
 */
world.afterEvents.entitySpawn.subscribe((e) =>{
  if(e.entity.nameTag == "§d§lStarter" && e.entity.typeId == "minecraft:item")  return e.entity.kill()

  if(e.entity.nameTag == "§d§lStarter") e.entity.kill()
})

What did i do wrong?

knotty plaza
#

The item entity nameTag is not the actual item identifier

knotty plaza
sturdy ermine
#

Hey where/when was the change log for 1.14-beta -> 1.15-beta?

sturdy ermine
#

It was just my shitty ass code lol

last latch
#

am i r3tarded, is bds broken or is the api broken?
it says that damageSource is undefined

true isle
#

How do I detect a specific level enchant?

last latch
granite badger
last latch
last latch
#

i prefer entityHurt over entityHitEntity

idle dagger
last latch
#

but damageSource is undefined for some reason, even tho it needs to be defined

#

cuz hustEntity gets hurt somehow

true isle
#

I did that but idk where to put the level for it I'm dumb lmao

lone thistle
last latch
#

i am saying that damageSource is undefined

#

damageSource needs to be defined

#

always

#

i cannot get damagingEntity because damageSource is undefined

lone thistle
#

It is always defined, it's not broken

#

If it's not damagingEntity then it's damageSource.cause

last latch
#

it says damagingEntity cannot be read of undefined

#

TypeError: cannot read property 'damagingEntity' of undefined

true isle
#

It's the api I get the error for get component (equippable) constantly and it works fine

last latch
lone thistle
true isle
#

I'm trying to detect separate levels of the enchant like fortune 1 fortune 2 and fortune 3 for 3 separate loot tables for ores

last latch
# lone thistle Send the snippet
world.afterEvents.entityHurt.subscribe(({ damageSource, hurtEntity: entity }) => {
    const { x, z } = damageSource.damagingEntity.getHeadLocation();

    entity.applyKnockback(x, z, 0, 0.356);
});```
true isle
#

I'm an idiot and don't know where to put the level of the enchant I'm trying to get only how to get the enchant itself

last latch
#

do you use bds aswell?

true isle
#

Bds?

last latch
#

i meant @lone thistle

last latch
true isle
#

Ah

lone thistle
last latch
#

1.14.0-beta

lone thistle
#

That should still work

last latch
#

yeah, should. but doesnt for me

#

and i dont know why

lone thistle
#

It could be other things, like the scripts are not reloaded

true isle
#

Done

last latch
last latch
true isle
#

I appreciate the help ::)

last latch
lone thistle
last latch
last latch
lone thistle
#

Your code is fine

#

Most likely other things

last latch
#

BRO WHAT

#

i just commented it, saved it, reloaded bds, then uncommented my snippet, saved, reloaded bds

#

and it works now

#

i dont get why

#

but it works now

#

(i change nothing in my snippet)

#

thanks for the help tho

copper lake
#

Any ideas about how to locate an Island as in the most time efficient way? Would I be able to use script to locate an ocean biome and teleport me there and then run some other script to search for an Island?

sturdy ermine
#

My code is so fuckin cooked

#

Line 2 of utils.js

import * as utils from './utils';
last latch
#

is there a event which is triggered whenever the world loads?

#

worldInitialize triggers when it reloads

#

but i want it to trigger whever world loads for the first time

wary edge
last latch
#

unless im dumb

wary edge
last latch
wary edge
last latch
granite badger
#

what's your use case?

last latch
#

i want to send a webhook, which states that the server is down/up

wary edge
#

Oh, cant you just use world before initaliziation and check if there are players? If so then it means it was using reload?

last latch
#

so the "worldLoad" event is possible, what about "worldshutdown" event

granite badger
#

There isn't one

last latch
#

by "worldshutdown" i meant doing a custom one

#

for myself

#

i will try figuring it out on my own

last latch
wary edge
last latch
wary edge
#

Im kind of confused

#

Wont the server only be online if there are players? If not this seems lile something scriptapi cant do

untold magnet
# wary edge Im kind of confused

hey smokey, can u show me the marketplace allowed and denied list? like what things that aren't allowed to be inside the marketplace addons.
sorry for pinging/replaying u

drifting ravenBOT
#
Does It Work on the Marketplace?

Not allowed

  • Anything beta
  • Anything experimental
  • Shaders
  • Guns, drugs, violence, religion etc.

Allowed
Everything that isn't shown above. Custom items for example are allowed, as long as you don't use the new experimental components.

Pretty much, if it works in a non-beta and non-experimental world it's good to be on the marketplace.

Why did I see a map using experimental features?
Some maps get special permission from Microsoft to use experimental features. These are usually free, or intended specifically to show-off the new creator-features. You are unlikely to get the same permission.

wary edge
#

This is the only publicly available list because the full list is under nda. Sorry

untold magnet
wary edge
#

🤷

untold magnet
#

he said vanilla UI like chest_ui or horse_ui aren't allowed on addons,

#

for an example, this isn't allowed on the marketplace addons,
it's allowed only on maps

#

i just wanted to make sure it's allowed or notbao_icon_entities

untold magnet
wintry bane
#

Is there a way to detect if the player is near certain coordinates?

#

like detecting if the player is near 0, 0, 0

wary edge
#

System.runInterval -> grab all entities near coordinates

wintry bane
#

Could you give an example?

narrow patio
#

What does ItemStack.prototype do?

unique dragon
#

this will return the distance

distant tulip
#

you don't need that

#

there is a distance filter

untold magnet
#

is there a limitation of dynamic properties for the single entity?

shy leaf
#

well thats more of a limitation of dynamic property in general

sudden nest
# narrow patio What does ItemStack.prototype do?

i'm not expert with js/ts, but from my perspective, it adds methods and properties to an existing class, like for example (This is probably not the best example), i want to create a new method for itemStack that checks if the current owner is not the original owner:

ItemStack.prototype.isCurrentOwnerAThief = function(){
// Your code
// Let's say parentSource property is existing (player who first owns this item), and currentSource property is existing.
return this.parentSource.id !== this.currentSource.id;
}

Mostlikely, prototypes are used to make it readable as well as make data communication be easily accessible.

I mean you can just use functions for this, but creating new methods or properties to something that makes sense is more readable imo, like for example:

player.inventory.giveItem(new ItemStack(...)) instead of giveItem(player, item). It's just personal preference to the developer on how they want to maintain their codebase, if they like suffering with OOP or just wanna do straight forward implementation with functional.

#

P.S. i'm no expert or whatnot bao_mob_t_snowgolem

random flint
true isle
#

Type '"creative"' is not assignable to type 'GameMode'. anyone else get this error ? script works like it should even with this

shy leaf
fiery solar
true isle
#

just gets the gamemode and id of a block before its broken

#

the script itself works fine though

shy leaf
#

i think its better to use getGameMode()

#

it returns enum (or string)

#

also i think you kinda did an oopsie on typeId check

true isle
#

how so ? its part of an array

shy leaf
#

isnt it supposed to be block.typeId.includes(viralia_ore)?

wary edge
#

I think it be best if you posted your full code in a post and the full content error

true isle
shy leaf
shy leaf
#
player.getGameMode() === "creative"```
fiery solar
shy leaf
#

still

velvet swallow
#

Hello, does anyone know how to get a player's experience points? Also, is there an event for a welcome message? (I'm new to scripting)

wary edge
viscid horizon
oblique eagle
#
        x: -592,
        y: -17,
        z: -1912
    }
    portalLocation.dimension.spawnParticle('myth:void_portal_travel_particle', portalLocation)``` anyone know why this isnt working? "cannot read property 'spawnParticle' of undefined"
subtle cove
#

portalLocation is {x,y,z} object (vec3 object, specifically)

#

use entity.dimension

oblique eagle
#

entity.dimension.spawnParticle?

subtle cove
#

yeah...

#

where do u use it?

oblique eagle
#

i dont have an entity defined

#

im using this in a function

subtle cove
#

perhaps world.getDimension('overworld').spawnParticle

oblique eagle
#

it works

#

thx

subtle cove
#

np

runic crypt
#

@distant tulip
i sent you a dm can you see it ?

untold magnet
untold magnet
#

hmm

#

const deniedEntities = [ /// ];
if (entity.typeId !== deniedEntities) { ,,, };
??

#

fr I forgot

unreal cove
#
const deniedEntities = []
if (!deniedEntities.includes(entity.typeId)) {  };
fallow rivet
#

Can a code that works for the world work when there is no one there?

untold magnet
#

i somehow found a log, especially at this line
if (block?.typeId !== 'my:block') { ,,, }

#

i think this should fix it
if (block?.typeId !== 'my;block' && entity.isValid()) { ,,, }

untold magnet
#

lemme do some tests

#

only when the entity is inside unloaded chunks

shy leaf
#

slap a ? inside there and youre good to go

untold magnet
#

yah fixed

untold magnet
shy leaf
#

squash it

untold magnet
#

when the block is inside unloaded chunks it will not be detected and the entity will instantly disappear

#

if (block?.typeId !== 'my:block' && entity.isValid()) ?

#

should i add block.isValid() to it?

#

or !block.isValid()?

#

idk

cold grove
#

How are you geting the entity?

#

If the chunk is unloaded.. the entity is unloaded too..

shy leaf
#

since isValid requires you to get the entity, you should just do if (entity) or if (block)

#

isValid checks whether the target can be manipulated with scripts

untold magnet
#

should i remove entity.isValid()?

#

or adding block.isValid() with it?

shy leaf
#

idk

#

depends on what youre trying to do

distant tulip
#

combine both

untold magnet
#

so both entity and block will be detected inside the unloaded chunks

distant tulip
#

entity?.isValid()

untold magnet
#

so if (block?.typeId !== 'my:block' && entity?.isValid() && block?.isValid())

distant tulip
runic crypt
#

Okay

#

can you tell me how i can make a script in which if i look down and crouch, i sit down

distant tulip
distant tulip
# runic crypt Okay

you will have to make a variable and keep track of both states
once you reach a point without any change perform your task

untold magnet
#

i could use block.isAir but what will happen when u replace that block with something else? ( any other blocks except air )

#

testing if the entity is inside the specific block inside loaded chunks and unloaded chunks is the better way to do it

distant tulip
# runic crypt oki

example

const sit = new WeakMap()
system.runInterval(() => {
  world.getPlayers().forEach((player) => {
    if(player.isSneaking && player.getRotation().y <= 88){
      sit.set(player,(sit.get(player)??0)+1)
    } else {
      sit.set(player,0)
    }
    if(sit.get(player) >= 60){ //20*3 => 3 seconds
      //sit animation/logic
      //don't forget a way to disable it for example if(player.isJumping) sit.set(player,0)
    }
  })
});
runic crypt
#

oki imma modify it 🫡

#

thanks :D

sharp elbow
#

WeakMaps are supported in the API now?

distant tulip
#

they weren't?

sharp elbow
#

Last time I tested, no.

shy leaf
#

ive heard of Maps but WeakMaps?

distant tulip
#

used them for long time

sharp elbow
shy leaf
#

huh

#

sounds interesting but not sure if its usable in minecraft api

distant tulip
shy leaf
#

hmmmm

distant tulip
#

avoiding memory leaks

shy leaf
#

imma ask GPT about this cuz im interested

untold magnet
#

hmm, is this the best way to do it?

if (item2.typeId === 'minecraft:raw_copper') {
            if (energy === true) {
              if (copper2 === 0) entity.setDynamicProperty('copper2', 1)
              if (copper2 === 1) entity.setDynamicProperty('copper2', 2)
              if (copper2 === 2) entity.setDynamicProperty('copper2', 3)
              if (copper2 === 3) entity.setDynamicProperty('copper2', 4)
              if (copper2 === 4) entity.setDynamicProperty('copper2', 5)
              if (copper2 === 5) entity.setDynamicProperty('copper2', 6)
              if (copper2 === 6) {
                entity.setDynamicProperty('copper2', 1)
                grinder(item2, inv, 2, 'minecraft:raw_copper', block)
                world.playSound('block.grindstone.use', block.center())
              }
              entity.setDynamicProperty('energy', false)
            }
          } else entity.setDynamicProperty('copper2', 0)```or u guys have a better way? grinding system ^
runic crypt
#
const sitDuration = 60;
const sitMap = new WeakMap();

system.runInterval(() => {
  world.getPlayers().forEach((player) => {
    if (player.isSneaking) {
      sitMap.set(player, (sitMap.get(player) ?? 0) + 1);
    } else {
      sitMap.set(player, 0);
    }

    if (sitMap.get(player) >= sitDuration) {
      player.runCommand('');

      const jumpCheck = system.runInterval(() => {
        if (player.isJumping) {
          sitMap.set(player, 0); 
          system.clearInterval(jumpCheck);
        }
      }, 5);
    }
  });
});

@distant tulip
yes this is partly made by chatgpt

untold magnet
runic crypt
shy leaf
#

not the api

runic crypt
#

makes sense

untold magnet
distant tulip
shy leaf
#

ive fed good enough info to gpt about how i style the code so its gonna be good at explaining it in my language

untold magnet
untold magnet
sharp elbow
runic crypt
#

so is the script correct ?

#

and whats the animation of player riding a horse called ?

distant tulip
#

clearRun

shy leaf
#

asking GPT about JavaScript: ✅
asking GPT about Minecraft API: ☠️

distant tulip
#

why did you even ask it
Did you test the script

runic crypt
shy leaf
#

cuz youve fed infos about it

runic crypt
#

every time

shy leaf
#

chatgpt has memory now

distant tulip
#

let me test that bao_icon_entities

runic crypt
#

what 💀

runic crypt
#

more importantly

shy leaf
#

weeks ago

runic crypt
#

how do i delete it 🙂

shy leaf
#

as a new feature

#

in settings

runic crypt
#

brb i gotta delete some stuff

shy leaf
#

didnt understand it until now

distant tulip
#

not bad but it is a simple example
cleared it memory

using mcbe scipt api
make a form that have 3 buttons
each one send a message with it index to the player when clicked

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

// Function to create and display a form with 3 buttons
function showButtonForm(player) {
    // Create a new modal form
    let form = new ModalFormData();
    
    // Add buttons to the form
    form.title("Choose a Button");
    form.button("Button 1"); // index 0
    form.button("Button 2"); // index 1
    form.button("Button 3"); // index 2
    
    // Show the form to the player
    form.show(player).then((response) => {
        // Check if form was not canceled
        if (!response.canceled) {
            let buttonIndex = response.selection;
            player.sendMessage(`You clicked button ${buttonIndex + 1}`);
        } else {
            player.sendMessage("You canceled the form.");
        }
    });
}

// Event listener to trigger form display when a player joins the world
world.events.playerJoin.subscribe((event) => {
    let player = event.player;
    showButtonForm(player);
});

#

apart from the event

shy leaf
#

i guess it did learn enough from all the people

#

interesting

#

its like drawing AI but for code

distant tulip
#

it always get the events wrong

shy leaf
#

not the first time seeing .events

distant tulip
#

providing info do help

shy leaf
#

though i do think the ai couldve done js world.afterEvents.playerJoin.subscribe(({player}) => { showButtonForm(player); })

distant tulip
#

not sure what the person who made it provided to it

shy leaf
#

me neither

shy leaf
#

that

#

oh

#

right

distant tulip
#

yeah
join ui

shy leaf
#

but iirc you can just force open ui in function if the cancelation reason was "UserBusy"

#

so that the player can see the ui after loading up

distant tulip
#

yep

runic crypt
distant tulip
#

animation

shy leaf
# shy leaf so thats what garbage collecting is for
const playerStatus = new WeakMap();

function initializePlayerStatus(player) {
    const status = {
        sprintKnockbackHitUsed: false,
        sprintKnockbackValid: false,
        critSweepValid: true,
        shieldValid: false,
        mace: false,
        attackReady: false,
        lastSelectedItem: undefined,
        lastSelectedSlot: undefined,
        cooldown: 0,
        lastAttackTime: 0,
        shieldDelay: 0,
        fallDistance: 0,
    };
    playerStatus.set(player, status);
}

export function getPlayerStatus(player) {
    if (!playerStatus.has(player)) {
        initializePlayerStatus(player);
    }
    return playerStatus.get(player);
}```
#

new knowledge acquired

untold magnet
shy leaf
runic crypt
#

in js player.runCommandAsync(`playanimation @p <animation name>`)

#

what do i put in <animation name> ??

#

@distant tulip

thorn flicker
#
player.playAnimation('animation_name')
#

there's a native method

distant tulip
#

make your own animation

runic crypt
distant tulip
runic crypt
#

yes sir 🫡

rugged tinsel
#

geometry.humanoid.custom
is the more accurate geo

#

pretty sure that's the one players are based off of

distant tulip
#

this one?

thorn flicker
#

also bruh, you really used chatgpt...

runic crypt
#

you know fillipino language ?

runic crypt
thorn flicker
#

no

runic crypt
#

aw man ok np

runic crypt
#

now what do i do ?

#

like put it in a resource pack ?

#
   "sit": "animation.gwim.sit"
#

i added this in player.json

#

at the end of the animations

cold grove
runic crypt
#

oh yea good point sorry :(

hazy nebula
#

@distant tulip can you give me file save player ender chest inventory addon file!

distant tulip
#

huh?
you mean the ender chest inspector

gaunt salmonBOT
#

Please select an option you have problem with

hazy nebula
quick shoal
#

Anyone can help of the litter code issue?

#

About of dynamic properties

#
import "./index";
import { world, Player, system } from "@minecraft/server";

world.afterEvents.entityHitEntity.subscribe((eventData) => {
    if (!eventData.hitEntity.hasTag('ffa_sumo')) return;
eventData.hitEntity.setDynamicProperty(
  "last_hit_by",
  eventData.damagingEntity.id
);
eventData.hitEntity.setDynamicProperty(
  "last_hit_by",
  JSON.stringify(eventData.damagingEntity)
);
console.warn(eventData.hitEntity.getDynamicProperty("last_hit_by"));
})

world.afterEvents.entityDie.subscribe(({ deadEntity }) => {
    const LastHitEntity = world.getEntity(deadEntity.getDynamicProperty('last_hit_by') ? JSON.parse (deadEntity.getDynamicProperty('last_hit_by') : null);
    const die = deadEntity
    die.runCommandAsync("scoreboard players add @s deaths 1");
    die.removeTag('InGame');
    die.runCommandAsync('clear @s');
    system.runTimeout(()=>{die.runCommandAsync('replaceitem entity @s[tag=!NotPlayed] slot.hotbar 4 compass 1 0')},35);
    LastHitEntity.runCommandAsync("scoreboard players add @s kills 1");   
    LastHitEntity.runCommandAsync("playsound random.explode @s");
    LastHitEntity.dimension.spawnParticle("minecraft:huge_explosion_emitter",LastHitEntity.location)
    world.sendMessage({
  rawtext: [
    { text: `§l§7${LastHitEntity.name}§c擊殺了` },
    { text: `§l§7${die.name}` }]});
})
gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 5 errors:

<REPL0>.js:18:102 - error TS2345: Argument of type 'string | number | boolean | Vector3' is not assignable to parameter of type 'string'.
  Type 'number' is not assignable to type 'string'.

18     const LastHitEntity = world.getEntity(deadEntity.getDynamicProperty('last_hit_by') ? JSON.parse (deadEntity.getDynamicProperty('last_hit_by') : null);
                                                                                                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
<REPL0>.js:18:147 - error TS1005: ',' expected.

18     const LastHitEntity = world.getEntity(deadEntity.getDynamicProperty('last_hit_by') ? JSON.parse (deadEntity.getDynamicProperty('last_hit_by') : null);
                                                                                                                                                     ~

``````ansi
<REPL0>.js:18:154 - error TS1005: ':' expected.

18     const LastHitEntity = world.getEntity(deadEntity.getDynamicProperty('last_hit_by') ? JSON.parse (deadEntity.getDynamicProperty('last_hit_by') : null);
                                                                                                                                                            ~

``````ansi
<REPL0>.js:29:34 - error TS2339: Property 'name' does not exist on type 'Entity'.

29     { text: `§l§7${LastHitEntity.name}§c擊殺了` },
                                    ~~~~

``````ansi
<REPL0>.js:30:24 - error TS2339: Property 'name' does not exist on type 'Entity'.

30     { text: `§l§7${die.name}` }]});
                          ~~~~

Lint Result

ESLint results:

<REPL0>.js

18:146 error Parsing error: ',' expected

unique yoke
#

// Define the blocks that should be regenerated
const regenBlocks = [
  "minecraft:dirt",
  "minecraft:stone",
  "minecraft:coal_ore",
  // Add more block types as needed
];

// Define the regeneration delay (in seconds)
const regenDelay = 10;

// Listen for the 'BlockBreak' event
events.listen('BlockBreak', (event) => {
  // Get the broken block's location and type
  const blockLoc = event.block.location;
  const blockType = event.block.type;

  // Check if the broken block is in the regeneration list
  if (regenBlocks.includes(blockType)) {
    // Schedule a regeneration task for the block
    setTimeout(() => {
      // Get the block's current state
      const currentState = world.getBlock(blockLoc);

      // If the block is still air, regenerate it
      if (currentState.type === "minecraft:air") {
        world.setBlock(blockLoc, blockType);
      }
    }, regenDelay * 1000); // Convert seconds to milliseconds
  }
});```
hazy nebula
oblique heath
distant tulip
gaunt salmonBOT
#

Please select an option you have problem with

#

Uptime: 1 hours, 40 minutes, 16 seconds
Latency: 108 ms

quick shoal
#
import "./index";
import { world, Player, system } from "@minecraft/server";

world.afterEvents.entityHitEntity.subscribe((eventData) => {
    if (!eventData.hitEntity.hasTag('ffa_sumo')) return;
eventData.hitEntity.setDynamicProperty(
  "last_hit_by",
  eventData.damagingEntity.id
);
eventData.hitEntity.setDynamicProperty(
  "last_hit_by",
  JSON.stringify(eventData.damagingEntity)
);
console.warn(eventData.hitEntity.getDynamicProperty("last_hit_by"));
})

world.afterEvents.entityDie.subscribe(({ deadEntity }) => {
    const LastHitEntity = world.getEntity(JSON.parse (deadEntity.getDynamicProperty('last_hit_by') ?? "{}"));
    const die = deadEntity
    die.runCommandAsync("scoreboard players add @s deaths 1");
    die.removeTag('InGame');
    die.runCommandAsync('clear @s');
    system.runTimeout(()=>{die.runCommandAsync('replaceitem entity @s[tag=!NotPlayed] slot.hotbar 4 compass 1 0')},35);
    LastHitEntity.runCommandAsync("scoreboard players add @s kills 1");   
    LastHitEntity.runCommandAsync("playsound random.explode @s");
    LastHitEntity.dimension.spawnParticle("minecraft:huge_explosion_emitter",LastHitEntity.location)
    world.sendMessage({
  rawtext: [
    { text: `§l§7${LastHitEntity.name}§c擊殺了` },
    { text: `§l§7${die.name}` }]});
})
#

Anyone pls help me fix the bug

gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 3 errors:

<REPL0>.js:18:55 - error TS2345: Argument of type 'string | number | boolean | Vector3' is not assignable to parameter of type 'string'.
  Type 'number' is not assignable to type 'string'.

18     const LastHitEntity = world.getEntity(JSON.parse (deadEntity.getDynamicProperty('last_hit_by') ?? "{}"));
                                                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
<REPL0>.js:29:34 - error TS2339: Property 'name' does not exist on type 'Entity'.

29     { text: `§l§7${LastHitEntity.name}§c擊殺了` },
                                    ~~~~

``````ansi
<REPL0>.js:30:24 - error TS2339: Property 'name' does not exist on type 'Entity'.

30     { text: `§l§7${die.name}` }]});
                          ~~~~

Lint Result

ESLint results:

<REPL0>.js

2:17 error 'Player' is defined but never used @typescript-eslint/no-unused-vars

20:5 warning The /scoreboard command can be replaced by the functionality in Scoreboard/ScoreboardObjective in the @minecraft/server. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/scoreboard for more information. minecraft-linting/avoid-unnecessary-command

22:5 warning The /clear command can be fully replaced with the Container.clearAll api in the @minecraft/server module. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/container#clearall for more information. minecraft-linting/avoid-unnecessary-command

23:28 warning The /replaceitem command can be replaced by the functionality in Container/ContainerSlot in the @minecraft/server. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/container for more information. minecraft-linting/avoid-unnecessary-command

24:5 warning The /scoreboard command can be replaced by the functionality in Scoreboard/ScoreboardObjective in the @minecraft/server. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/scoreboard for more information. minecraft-linting/avoid-unnecessary-command

quick shoal
#

No I just ask for help

#

Can u help me just fix the first error?

#

I'm anxious with it

last latch
last latch
#

thanks for the help tho

fiery solar
# last latch i can detect when the server is going to start (using date and the last tick, bu...

There's no distinction between running /reload and performing the initial startup from the script API's point of view.

If you're running it yourself you could build a wrapper for BDS that could report the uptime and query that with an HTTP request.

Or you could save the current time in a dynamic property every few seconds, then when the worldInitializeAfterEvent is called check that last time and try to determine based on that if it was a reload or not

distant tulip
#

isn't there a way too just ping the server and see?

last latch
#

there is also a way; use a modloader and implement webhooks directly in the api :yay:

runic crypt
#

@distant tulip
i need your help
can you hop on Minecraft ??

distant tulip
#

sure

distant tulip
#

@runic crypt

runic crypt
#

wait 2 min imma be on

runic crypt
#

whats your ign ?

#

add me OpGamer2208

distant tulip
runic crypt
#

ok

#

sending invite

#

@distant tulip you on ?

pale terrace
#

hmm why?

#

Doesn't it just change the unit? both methods return angles

distant tulip
runic crypt
valid ice
runic crypt
pale terrace
distant tulip
runic crypt
valid ice
#

Naturally derived, angles are an arbitrary division.

granite badger
#

try tan(pi/2)

runic crypt
#

@distant tulip ill make new world

pale terrace
pale terrace
granite badger
#

also, Math.sin, Math.cos etc in js params use radians btw

valid ice
runic crypt
#

@distant tulip
join now

pale terrace
valid ice
#

Degrees are 100% easier to math with

#

Yet the natural state of things is radians 👍

runic crypt
#

@distant tulip
nvr mind imma go sleep, will try tomorrow ok ?
also pls see your dms

pale terrace
valid ice
#

Don’t even get me started 😛

hazy nebula
#
world.beforeEvents.chatSend.subscribe(data => {``` in version 1.21.20 what is it
pale terrace
hazy nebula
hazy nebula
unreal cove
lethal crystal
#

Does had a way to test when the player is using a specified item in his hand open a ui?

hazy nebula
pale terrace
unreal cove
lavish iron
#

can i ask a question here?, about scripts

pale terrace
pale terrace
hazy nebula
lavish iron
#

i have this:
.getComponent(EntityComponentTypes.Health).currentValue;
Is there a way that instead of being the current life, it is the maximum life?

lethal crystal
unreal cove
hazy nebula
hazy nebula
#

[Scripting][error]-TypeError: cannot read property 'container' of undefined at <anonymous>

pale terrace
unreal cove
lethal crystal
lethal crystal
#

health.setCurrentValue is to increase the player life?

last latch
terse tide
#

how i can make when a have a specific tag, when a click a block this turns into another block

#

Hi

#

Anyone

nocturne berry
#

Does anyone know how to detect an interaction on a block with an empty hand?

oblique eagle
#

is "isOnGround" broken?

keen folio
pale terrace
oblique heath
#

Has anyone attempted to do structure generation with scripts?

lyric kestrel
#

And a few others I can't remember the names of

slow walrus
wise raft
#

Is there a way to damage a Item without playing the "item change" animation?

honest spear
lyric kestrel
# wise raft Is there a way to damage a Item without playing the "item change" animation?
import { world } from '@minecraft/server'

world.afterEvents.playerBreakBlock.subscribe((data) => {
    const { player, itemStackAfterBreak: item } = data
    const inv = player.getComponent('inventory').container
    const durability = item.getComponent('durability')

    if (item && durability) {
        if (durability.maxDurability < durability.damage) {
            durability.damage = 1;
            inv.setItem(player.selectedSlot, item);
        }
        else if ((durability.maxDurability - durability.damage) == 0) {
            inv.setItem(player.selectedSlot);
        }
        else {
            durability.damage += 1;
            inv.setItem(player.selectedSlot, item);
        }
    }
})```
#

i think that doesn't do the animation. Haven't used it in a while, so not entirely sure xD

wise raft
#

I mean when I use the Item

nocturne berry
hardy tusk
deep quiver
#

Ye it wasnt that long ago

#

I made mine like a year ago, but it was worse

#

It was just basic genereation

#

I have a newer on, but the issue is that the blending between biomes is horrible

gaunt flare
pale terrace
honest spear
honest spear
honest spear
slow walrus
#

time flies

honest spear
#

yes

honest spear
cold shoal
#

Is it possible to spawn a particle then rotate it dynamically with scripting?

honest spear
cold shoal
#

Or maybe spawn a particle everytime I need to change teh rotation?

honest spear
#

you can only set initial molang variables

cold shoal
honest spear
#

well you still can do a lot of things via Molang Variable Maps

cold shoal
#

Will read abt that. I'm so noob at particles. Thanks!

honest spear
cold shoal
#

It's like a straight line particle that connects 2 locations. Kinda like how the ender dragon heals. I'm still starting to read more about particles so I'm not even sure if I'm in the right track

honest spear
#

Check #add-ons and ask there about particles

subtle cove
#

Can spawned particles change direction mid-animation?

honest spear
honest spear
cold shoal
sage sparrow
#

hi there, what is the difference between world.afterEvents.itemReleaseUse and world.afterEvents.itemStopUse?

honest spear
sage sparrow
#

but on the descript both look like doing exactly same thing, no? I mean... even the properties of it are identical

shy leaf
sage sparrow
#

🙂

#

just wondering which one would be better to use, dunno if there is any advantage over other

distant tulip
honest spear
#

like i send releaseItem doesn't fire for all items

subtle cove
#

charge a trident,
throw - release & stopUse
change itemslot - stopUse

honest spear
#

afaik

subtle cove
#

the molang obj can change anytime, however

#

reusable

distant tulip
#

yeah i know that much
animations are client side
maybe that can
or local rotation and controlling the anchor

honest spear
#

¯_(ツ)_/¯

distant tulip
#

🤷‍♂️

hardy tusk
#

But time really did fly

honest spear
#

😅

supple yoke
#

using deprecated features feels so wrong lol

#

yet so good

#

it makes me so uncomfortable lol

#

the autocomplete and the linter is screaming at me to not use it.

misty pivot
#

how do i get the lore of a dropped item?

distant tulip
prisma shard
# valid ice

seeing this i remember about angle/360 * 2πr,
and
angle/360 * πr^2

valid ice
#

First one

prisma shard
prisma shard
valid ice
#

The conversion from rad to angle? Yes

#

The second formula is for area of a sector

near siren
#

Is there a way to get when a projectile hits an entity if the projectile does no dmg?

distant tulip
wheat condor
#

How do i get the typeId of an item when its dropped?

#

becouse entity.typeid returns minecraft:item

distant tulip
wheat condor
near siren
untold magnet
#

hmm

untold magnet
#

how can i use "can_be_siphoned_from" and make it take items from one slot only?

#

maybe i dont have to use that

near siren
untold magnet
distant tulip
distant tulip
untold magnet
#

i think its possible using scripts

#

by making a system that will detect items from that specific slot and drop them at the block center only if there's a hopper under it

distant tulip
#

ok?
but don't use can_be_siphoned_from with that

untold magnet
#

yah i will not use it

obsidian coyote
deep quiver
wintry bane
#

Will it be possible to store objects and arrays in dynamic properties?