#Script API General

1 messages · Page 27 of 1

lone thistle
#

try y + 1

last latch
#
const { dimension, location: { x, y, z } } = block;

dimension.spawnParticle("minecraft:crop_growth_emitter", { x, y: y + 1, z });
north depot
#

bao_bee_cyborg
im back

#

why 'hasTag' dont work in here?

#

itemRegistry.registerCustomComponent("aliien:on_consuming", {
onConsume: (event) => {
const item = event.itemStack;
const player = event.source;
player.sendMessage("item1");
if (item.hasTag('custom')) {
player.sendMessage("item2");
player.runCommand(say hi)

                    }
              }
              
  })
untold magnet
#

guys

#

i somehow found a log

#

how?!

#

const { x, y, z } = block?.center(); at this line

#

that happened when i left the world once

meager pulsar
#

why does this fails? js console.warn(pEquipment.getEquipment(`Mainhand`).getComponent(`minecraft:cooldown`).isCooldownCategory(`mh_soul_crystal`))

abstract cave
#

is there a way to check for charged creepers in specific

thorn flicker
#

you can detect if the minecraft:become_charged event triggers

#

then set a tag, or dynamic property on them

abstract cave
#

possible*

thorn flicker
#

in filters, you can check if it has the minecraft:is_charged component

frozen vine
#

I save the structure with the mob id and add the mob id as the item's lore

terse tide
#

Is System.waitTick the same as setTickTimeout?

subtle cove
#

undefined cant be deconstructed into x,y,z

shut citrus
#

why do not you use unsubscribe instead?

sour narwhal
#

Does anybody know why this happens?
I have my block version to 1.21.20 and it doesnt work. I have tried a couple of things and still... Any help can be usefull! TwT

shy leaf
#

that aint script API

sour narwhal
#

a

shy leaf
#

maybe try #1067876857103536159?

sour narwhal
#

right, i forgot

#

sorry

round bone
#
/** @type {boolean} */
const isOnCooldown = player.getItemCooldown("mh_soul_crystal") > 0;
full brook
#
    world.runCommandAsyc(`gamerule keepinventory true`);
});```
guys why this doesn't work
shy leaf
#

you need to get dimension

full brook
#

ok thanks

round bone
wise raft
#

How can I detect if a players interacts with an block with an empty hand?

round bone
wise raft
#

thanks

quick shoal
#

Anyones

#

How to fix this

#
import { system, world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import "./combatlogger";

world.afterEvents.playerSpawn.subscribe(evd=>{
    const player = evd.player;
system.runInterval(() => {
    system.run(() => NotPlayedDialogue(player.hasTag('NotPlayed')))
}, 15);
function NotPlayedDialogue(viewer) {
    const dialogue = new ActionFormData();
   dialogue.title('§l§a『遊玩條款』');
   dialogue.body(`§l§b嗨嗨!§f歡迎你來到了本遊戲§8【§6職業§cPVP §7v1.0§8】§f我是這張地圖的創作者——§c紅石§f。在開始前,可以的話請先仔細閱讀本圖的規則,謝謝ww§a本地圖§f的玩法十分簡單,你可以在這裡與所有玩家進行一場§b酣暢淋漓§f的§c戰鬥§f!!此外,本地圖也有商店系統,你可以從商店購買小道具!這些道具會在戰場上給予你一些特殊的能力,每個道具都可使用§e金幣§a購買,§e金幣§f可通過§c擊殺§f玩家§a獲得§f。說了那麼多,是時候來介紹§a本地圖§f的規則了:)
以下是§a本圖§f的規則:
-不要使用§c外掛§f(這樣會破壞遊戲平衡
-不要罵人(保持友好
-不要刷屏
-不要惡意使用bug(及時報告管理員可得§e獎勵
§f最後,點擊下面的§b按鈕§f來加入§a遊戲§f!!`);
   dialogue.button('§l§b點擊這裡§a加入§e遊戲§b!!', 'textures/ui/icon_deals');
   dialogue.show(viewer).then(({ selection, canceled }) => {
        if (canceled) return;
        if (selection === 0)
         {evd.player.runCommandAsync('tag @s add Played'),evd.player.runCommandAsync('playsound random.toast @s'),system.runTimeout(()=>{evd.player.runCommandAsync('replaceitem entity @s slot.hotbar 4 compass 1 0')},35);}
   })
}
})
#

I need to show the form for player who has tag 'NotPlayed'

#

But it always have issue

shy leaf
#

theres no "viewer"

shy leaf
#

hasTag doesnt return Player

unique dragon
#
if (player.hasTag('NotPlayed')) {
  NotPlayedDialogue(player)
}
warm mason
#
world.afterEvents.playerSpawn.subscribe(evd => {
  const player = evd.player;
  if (player.hasTag("NotPlayed")) system.runTimeout(() => { NotPlayedDialogue(player) }, 60)
})```
unique dragon
shy leaf
#

since player spawns first and then join

unique dragon
#

that won't stop if it was working xd

round bone
warm mason
unique dragon
#

uh

#

that's not the issue

round bone
#
const forceShow = async (player, form) => {
    while (true) {
        const resultData = await form.show(player);
        if (resultData.cancelationReason !== "UserBusy") return resultData;
    }:
};
round bone
#

oh

#

what a spaghetti code xd

shy leaf
#

very spaghetti

#

creepypasta even

warm mason
#
import { system, world, ItemStack } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";
import "./combatlogger";

world.afterEvents.playerSpawn.subscribe(evd => {
  const player = evd.player;
  if (player.hasTag("NotPlayed")) system.runTimeout(() => { NotPlayedDialogue(player) }, 200)
})

async function NotPlayedDialogue(viewer) {
  const dialogue = new ActionFormData();
  dialogue.title('§l§a『遊玩條款』');
  dialogue.body(`§l§b嗨嗨!§f歡迎你來到了本遊戲§8【§6職業§cPVP §7v1.0§8】§f我是這張地圖的創作者——§c紅石§f。在開始前,可以的話請先仔細閱讀本圖的規則,謝謝ww§a本地圖§f的玩法十分簡單,你可以在這裡與所有玩家進行一場§b酣暢淋漓§f的§c戰鬥§f!!此外,本地圖也有商店系統,你可以從商店購買小道具!這些道具會在戰場上給予你一些特殊的能力,每個道具都可使用§e金幣§a購買,§e金幣§f可通過§c擊殺§f玩家§a獲得§f。說了那麼多,是時候來介紹§a本地圖§f的規則了:)
以下是§a本圖§f的規則:
-不要使用§c外掛§f(這樣會破壞遊戲平衡
-不要罵人(保持友好
-不要刷屏
-不要惡意使用bug(及時報告管理員可得§e獎勵
§f最後,點擊下面的§b按鈕§f來加入§a遊戲§f!!`);
  dialogue.button('§l§b點擊這裡§a加入§e遊戲§b!!', 'textures/ui/icon_deals');
  dialogue.show(viewer).then(({ selection, canceled }) => {
    if (canceled) NotPlayedDialogue(viewer)
    if (selection === 0) {
      viewer.addTag("Played")
      viewer.removeTag("NotPlayed")
      viewer.runCommandAsync('playsound random.toast @s')
      viewer.getComponent("minecraft:inventory").container.setItem(4, new ItemStack("compass"))
    }
  })
}
halcyon phoenix
#

hey, to the people here is it possible to create a chest? or imitate it? im trrying to make a custom chest with special sprinkles on it

halcyon phoenix
#

Thanks

shy leaf
#

which is better when it comes to repeating stuff, system.runInterval() or system.run() that runs function?

shy leaf
#

can i ask why

#

just curious

warm mason
#

run is intended for deferred execution so that no problems arise, and runInterval is for repeating code, and there is also a delay and there is no need to reinvent the wheel

shy leaf
#

hmmmm so run has at least one tick delay right

#

(or can have a tick delay)

warm mason
shy leaf
#

just testing

warm mason
# shy leaf just testing

I even have a function for interval

function interval(func, speed, loop, onStop = undefined) {
  let interval = system.runInterval(() => {
    try {
      func()
      
      loop--
      if (loop <= 0) {
        system.clearRun(interval)
        if (onStop != undefined) {
          onStop()
        }
      }
    } catch (e) {
      system.clearRun(interval)
      console.warn("Interval error: " + e)
    }
  }, speed)
  return interval
}```
shy leaf
#

looks great

glacial widget
#
for (let i = 0; i < inventory.size; i++) {
    const invItem = inventory.getItem(i);

    if (invItem && invItem.nameTag.startsWith("§l§aVIP Kit")) {
      if (invItem.amount > 1) {
        invItem.amount -= 1;
        inventory.setItem(i, invItem);
      } else {
        inventory.setItem(i, null);
      }
      player.dimension.getBlock(block).setType("minecraft:air");
      break;
    }
  }

You cant use startsWith?

glacial widget
unique dragon
distant tulip
glacial widget
# shy leaf you... can

how bro i got a error with this statment

invItem && invItem.nameTag.startsWith("§l§aVIP Kit")
glacial widget
shy leaf
#

why not just use dynamic property for the check

#

using nametag for item check seems very prone to breaking

#

also there could be a typo

#

and its case sensitive too

distant tulip
glacial widget
halcyon phoenix
#

how do you setblock again on a location?

#

can somebody lead me to the docs of that?

full brook
#

is there any way to apply knockback downwards? (-vertical)

source.applyKnockback(view.x, view.z, 0, -4);

not work

warm mason
full brook
shy leaf
#

does knockbacking upward work

full brook
#

work

shy leaf
#

and you sure theres nothing below the target

full brook
#

yes

shy leaf
#

post the code

full brook
#

it doesnt work on player?

shy leaf
#

it should work on player

full brook
#

oh

#

it works lol

#

thanks

warm mason
#

...

full brook
#

btw, Is there a method for players to stay in air for a while without using teleport?

glacial widget
#

How do i check the data id of a item?

world.afterEvents.itemUse.subscribe((ev) =>{
  const item = ev.itemStack
  const player = ev.source
  
  if(item){
    player.sendMessage(`${item.typeId}`)
  }
})
warm mason
full brook
#

can i know how?

warm mason
glacial widget
#

man i need the data type for a potion

warm mason
#

if you need potions you can try using the createPotion method and the "mineraft:potion" component

halcyon phoenix
#

how to use debugger in #debug-playground

shy leaf
#

and use apps, then select debug scripts

halcyon phoenix
#

ohhh I thought it was commands

#

thanks

quick shoal
#

runtimeOut cant repeat

#

Wait

thin steeple
#

runInterval is repeating

quick shoal
#

The canceled will show again?

quick shoal
#

@warm mason I think u did the effect I wanted

#

Because if cancel the form will show again right?

#

I will test it later ,thanks

idle dagger
#

How to check if it’s not player first spawn using

world.afterEvents.playerSpawn.subscribe?

warm mason
#
world.afterEvents.playerSpawn.subscribe(data => {
  if (data.initialSpawn) return;
  // Code here (if player respawned from death)
})
hushed ravine
#
server.world.afterEvents.worldInitialize.subscribe(() => {
  for (const p of server.world.getAllPlayers()) {
    setTask(p);
  }
  server.system.run(() => {
    try {
      server.world
        .getDimension(MinecraftDimensionTypes.Overworld)
        .runCommand("/tickingarea add circle 0 0 0 4 true_spawn true");
    } catch (e) { }
  });
  server.system.runJob(gameLoop());
});
#
import { GameMode, world } from "@minecraft/server";
import { isGameStarted } from "..";

let playersLeft = 0;

export function getPlayersLeft() {
  return playersLeft;
}

export function* gameLoop() {
  while (true) {
    if (isGameStarted()) {
      playersLeft = world.getPlayers({ gameMode: GameMode.survival }).length;
    }

    yield;
  }
}
#

This seems to slow down the game

#

When I remove the add-on, the world/server runs fine

random flint
#

I think you want to use system.runInterval instead of system.runJob

#

system.runInterval will give you the consistency than system.runJob

#

But I think it depends on what "isGameStarted" even does.

hushed ravine
#

It really just returns a boolean value

#
export function isGameStarted() {
  return gameStarted;
}
nocturne berry
#

How do you detect the name tag of an entity?

warm mason
wary edge
#

Is there not a player.isWalking? What's a sollution

warm mason
wary edge
bright torrent
#

Is there a method of generating a map item with pixels set to colors dynamically? Only generating map art then teleporting player?

#

I want to generate small 2D images at runtime. What's the best way?

#

I figured I'd start by trying with maps. I had some success with particle effects. I'm sure there are some cool methods to do this?

neon brook
#

So i'm fairly new to this scripting thing but can anyone help me out why i can't run this command but it works with any other minecraft commands, only fill command seems to not work. It is ticking custom component for a block.

#

i tried with functions cuz it didn't work like this fill ~-1 ~ ~ ~-1 ~ ~ sp:small_celestite_bud ["minecraft:block_face"="west"] replace air

#

but functions with fill command also don't work

#

other commands work like "time set night" for example works fine only "fill" seems to not

cinder shadow
#

oh wait, I just did !player.isSprinting, !player.isSneaking, !player.isGliding, then isMoving, which is

            const isMoving = MathRound(player.getVelocity().x) != 0 || MathRound(player.getVelocity().y) != 0 || MathRound(player.getVelocity().z) != 0;
``` @wary edge
#

pretty sure that's everything? Kinda just looking at my stamina system rn

thin steeple
warm mason
oblique heath
cinder shadow
#

I have no idea

#

I'll need to check lol

#

Not at my pc

wary edge
wary edge
unique dragon
# neon brook So i'm fairly new to this scripting thing but can anyone help me out why i can't...

the dimension is running the command, so check if your using "~", the blocks are gonna be placed there: x: -1, y: 0, z: -1

Solution:

const { dimension, location: loc } = block;
const offset = { x: loc.x - 1, y: loc.y, z: loc.z - 1 };
const checkBlock = dimension.getBlock(offset);
const perm = block.permutation.getState("minecraft:block_face");
if (checkBlock?.typeId === 'sp:small_celestite_bud' && perm === "west") {
  dimension.setBlockType(loc, 'air');
}
crude bridge
#

#1292588668627718155

ruby haven
#

I've seen addons where they summon a Minecraft block and that Minecraft block takes the texture of the ground so example if the texture of the ground is dirt it will summon a block of dirt, does that work through scripting?

oblique heath
#

minecraft developers please add a player swing event 🫠

distant tulip
drowsy scaffold
#

How do I store a method? I have objects that I made for a Daily Reward System that look like this:

,
        cookedChicken:{
            weight: 100,
            quantity: 24,
            slots:1,
            displayName: "Cooked Chicken",
            description: "Some Free Food!",
            icon: "textures/items/chicken_cooked",
            method: ((p,q) => cookedChicken(p,q))
        },

But I can't get the method property to store alongside the rest of the stringified object. Is there a means to do this that I'm just not aware of? If there isn't, is there a way to get the object back?

random flint
#

oh stringifying function?

#

nah

#

Just stringify the data, then process it with premade function

#

Or... you can do function.toString() then use eval or smt

drowsy scaffold
#

ah I see, okay

#

thank you!

magic shard
#

is system.run read only?

lone thistle
chrome flint
#

does setting dynamic property requires priveledges?

#

like can i set dynamic property before the player leaves?

#
world.beforeEvents.playerLeave.subscribe(({player}) => {
  const date = new Date()  
  const leaveDate = date.toISOString()
  player.setDynamicProperty("last_seen",leaveDate)
})
unique dragon
#

u should try

chrome flint
#

how tho, i don't have other devices to test player leave

valid ice
#

Dynamic property set does not need privileges, and you can set before player leave.

chrome flint
#

okay thank you

oblique heath
#

EntityHitBlockAfterEvent is an inaccurate name i feel

#

that event is more like when you start the process of mining

magic shard
# lone thistle No

oh. Cuz i'm trying to get a projectile to have an owner of the player shooting it and it's not setting the value.

// itemStartUse event
const bullet = player.dimension.spawnEntity(projectile, player.getHeadLocation());
const projComp = bullet.getComponent("projectile");
system.run(() => {
  projComp.owner = player;
})```
this is being taken care of with the `itemStartUse` event.
tawny jungle
#

Why do I keep getting an error that says: TypeError: 'Head' is read-only.

import { Block, BlockPermutation, Direction, EntityComponentTypes, EquipmentSlot, Player, world, system } from "@minecraft/server";

    system.run(() => {

        const headSlot = Player.getEquipment(EquipmentSlot.Head = "Head");
        world.sendMessage(headSlot);

    })```
thorn flicker
#

the code is wrong

#

just have the string "Head" or EquipmentSlot.Head.

unique dragon
#

lmao

thorn flicker
#

wait

#

I just noticed

#

lmao

unique dragon
#

xd

thorn flicker
#

hes not getting the equippable component

unique dragon
#
import { system, world } from "@minecraft/server"; 

system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    const equipment = player.getComponent("equippable").getEquipmentSlot("Head");
    player.sendMessage(equipment?.typeId);
  }
});
#

@tawny jungle

random flint
tawny jungle
#

thanks guys

random flint
#

...And getEquipmentSlot() —> getEquipment()

ItemStack Class is simpler to work with than goofy inconsistent ContainerSlot Class

tawny jungle
#

my real issue being

#

i dont know how any of this works

#

but thank you, i will continue to learn 🫠

tawny jungle
valid ice
#

getEquipmentSlot returns a container slot, which represents the physical “slot” in the entity/player inventory
getEquipment returns an ItemStack, which represents an item, and an item alone- it kinda grabs a snapshot of the item in the slot when called, so any changes to it won’t show up on the item in the inventory.

unique dragon
#

ah yes

oblique heath
#

you'd think we'd be able to modify the itemstack directly...

valid ice
#

S’ what container slot is for

#

You can also create ItemStack references that don’t actually exist anywhere in the world, and only are a thing in your code.

#

Item stack doesn’t have to be tied to a slot- spawn item, for instance, or entity component item stack.

#

Why the two locations? You only need one

#

The third parameter for the particle is molang variable stuff

static nebula
valid ice
#

Also you can just pass in location to the second parameter, you don’t have to destructure it the way you did 👍

valid ice
#

If you wish to add/subtract, then yeah you need to destructure, but just as-is you don’t have to.

tawny jungle
#

also is there a way to make so that this doesn't show an infinite number of responses

warm mason
#

🤦‍♂️

#

"->" mean "replace"

crude bridge
tawny jungle
#

ah

#

silly me

#

i couldn't see that the formatting stopped at the arrow

tawny jungle
#

thanks

hushed ravine
tawny jungle
#

what am I doing wrong to get this to set my helmet slot to the item im holding? Im not getting any errors, just nothing

    const itemStack = data.itemStack;
    const player = data.source;
    system.run(() => {
        for (const player of world.getAllPlayers()) {
            const equipment = player.getComponent("equippable").getEquipment("Head");
            const reach = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: 1 })?.block;
            if (((equipment?.typeId??"") === "") && !((reach?.typeId??""))) player.getComponent("equippable").setEquipment("Head", itemStack);
        }
    })```
subtle cove
#

const player = data.source

tawny jungle
#

ah

#

thats my bad

#

i forgot to include that in the snippet

#

i do already have that

#

i added it

subtle cove
#

Don't use getPlayers

tawny jungle
#

what do i replace it with??

subtle cove
#

Use the player from data, not from getPlayers

#

getPlayers is @a

tawny jungle
#

i see

#

wait im confused, am I replacing world.getAllPlayers() with just player?

subtle cove
#

Yes

#

The event already have player as source who triggered the event

tawny jungle
#

its saying player is not initialized

#

as for (const player of player) {...

shy leaf
#

uh

#

i think you can just remove that for...

tawny jungle
#

as in just this? or perhaps keeping the const?

    const itemStack = data.itemStack;
    const player = data.source;
    system.run(() => {
            const equipment = player.getComponent("equippable").getEquipment("Head");
            const reach = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: 1 })?.block;
            if (((equipment?.typeId??"") === "") && !((reach?.typeId??""))) player.getComponent("equippable").setEquipment("Head", itemStack);
}```
#

this seems to have the same issue of no errors and nonfunctional

random flint
#

especially that bottom one

round bone
#
world.beforeEvents.itemUseOn.subscribe(function (data) {
    const itemStack = data.itemStack;
    const player = data.source;
    system.run(() => {
        const equipment = player.getComponent("equippable").getEquipment("Head");
        const reach = player.getBlockFromViewDirection({ includeLiquidBlocks: false, includePassableBlocks: true, maxDistance: 1 })?.block;
        if (((equipment?.typeId??"") === "") && !((reach?.typeId??""))) player.getComponent("equippable").setEquipment("Head", itemStack);
    });
});
random flint
rapid sail
#

script for placing a block above a player when holding an item?

#

i've been trying to make a script where if a player holds an item in its mainhand it will place a block above the player like glowstone but no luck

round bone
#
import { world, system } from "@minecraft/server";

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const item = player.getComponent("minecraft:equippable")?.getEquipment("Mainhand");
        if (item?.typeId !== "your_item_id") continue;

        const { x, y, z } = player.location;
        player.dimension.setBlockType({ x: Math.floor(x), y: Math.floor(y) + 2, z: Math.floor(z) }, "your_block_id");
    };
}, 1);
rapid sail
#

I'll try that out ty i was using equipment slot

rapid sail
#

will the block be centered? or offset? just asking?

warm mason
#

you can use the .center() and bottomCenter() methods to get locations like { x: 1.5, y: 1.5, z: 1.5 } and { x: 1.5, y: 1, z: 1.5 }

buoyant canopy
#

every time i open a json file in vscode i have to set the format to jsonc manually, how to make it automatic?

solar dagger
buoyant canopy
buoyant canopy
wary edge
solar dagger
#

I don't see a channel for VSCode

rugged tinsel
#

would that go under #add-ons or #off-topic ?

solar dagger
#

Probably

tawny jungle
tawny jungle
#

but thanks

scarlet lynx
#

Getting back into scripting.. Can som1 let me know why this won't work?

const scores = [
    "ach-time",
    "ach-ks",
    "ach-kills",
    "ach-deaths",
    "ach-eW",
    "ach-blocks",
    "ach-crates",
    "ach-pres",
    "claimedTier",
    "exp",
    "deaths",
    "kills",
    "Money",
    "sec",
    "min",
    "hour",
    "day",
    "ks",
    "Bounty",
    "CT",
    "kd",
    "Koth",
    "afkTimer",
    "Prestige",
    "Staff",
    "blocks",
    "crates",
    "Particle",
    "Particles",
    "BPTier",
    "DonoTokens",
    "NColor",
    "CColor",
    "eventsWon",
    "freeClaimedTier",
    "PremClaimedTier",
    "BubsClaimedTier"
].forEach((scores), world.scoreboard.addObjective(scores))
round bone
#

.forEach((objective) => world.scoreboard.addObjective(objective));

scarlet lynx
#

ty

round bone
#

but put this in try catch block

scarlet lynx
#

I forgot the =>

#

I got back

#

tyvm sir

#

it worked

round bone
#

if objective exists and you are trying to add it, you gonna end up getting an error

scarlet lynx
#

ye ik

#

ty

round bone
#

👌

#

js arrow functions if you need topic

rapid sail
warm drum
#

guys!

#

do u know how custom chest is made?

#

it looks like tile entity

#

like if i made the entity hitbox to cover the block then player can interact and open its inventory

#

but then player cant break it

scarlet lynx
#

inventory thing I believe inside of a entity

halcyon phoenix
#

what does it mean by previlages

unique dragon
valid ice
#

Before events cannot modify the world

unique dragon
#

for before events, use system

random flint
#

await system.waitTicks(1)

oblique heath
#

just spent an hour wasting my time trying to figure out why my itemstack wasn't saving a dynmic property i was setting

#

then i remembered i can't directly modify itemstacks

oblique heath
#

because i have to set the item each time this actually sucks...

random flint
#

ContainerSlot dynamic property

oblique heath
#

maybe

#

litteraly no difference from just using setItem

#

its no good for my use case

random flint
#

it directly reference to the slot

#

so all changes is automatically applied to that item

oblique heath
#

yeah

#

but that doesn't help me

#

i am trying to store a timer value

#

basically it makes the item unusable and it it constantly plays that animation when you collect an item

#

no good for me

random flint
#

Then use the cooldown component

oblique heath
#

the timer is for a sound

#

not using the item

#

i'm just going to store on the entity because i don't see another good simple way

random flint
#

store it on the player

oblique heath
#

yeah thats what im saying

warm mason
oblique heath
#

hm?

warm mason
#

do you need to store a dynamic property in an item?

oblique heath
#

yes

#

but it will constantly modify the value of that property which i realized is bad

#

because it will make the item unusable

#

and trigger some stupid pick up animation

warm mason
#

dynamic properties of items work only if its maximum quantity is 1

oblique heath
#

i'm aware

#

but what does that have to do with it

warm mason
#

Do you need to change the property every tick?

oblique heath
#

it's a timer

#

so yes

#

it just stores a timer value

#

but what ever, i am just going to store it on the entity who has the item

warm mason
#

why do you need to change the timer every tick? its nameTag will be visible and there will be something like "05:11"?

oblique heath
warm mason
#

wouldn't it be better for you to use the actionbar?

oblique heath
#

?

warm mason
#

for example, when you take an item in your hand, you are shown "05:11" using the actionbar, and in the item itself, only the start time in ticks is stored.

oblique heath
#

i play a sound and set the timer to 50 if the timer is 0

#

then tick down every tick

#

i don't know what action bar has to do with this

warm mason
#

Why do you need to change the item every tick?

oblique heath
#

i was storing the timer there for item specific timers

#

but i found issues with that

#

and for my use case its not super needed

#

if items in the inventory had a unique runtime ids i could probably handle this in a map or something but what ever to give each one a unique timer

#

since this information only needs to persist per session

warm mason
#

you need to pick up the timer and it would show you the time, and for this you want to use the nameTag of the item. I suggest you write the current game tick there at the very beginning of the timer's operation and when you pick it up, the time is displayed to you through the actionbar (according to the formula: system.currentTick - the recorded tick)

oblique heath
#

what does it matter if it won't be per unique instance of that item

warm mason
#

On game start:

item.setDynamicProperty("startTick", system.currentTick)
let tick = item.getDynamicProperty("startTick")
player.onScreenDisplay.setActionbar("Time: " + (system.currentTick - tick))
oblique heath
#

oh i see

warm mason
#

What is a "unique copy" of an item?

oblique heath
#

every item is different

#

thats all

warm mason
#

so why is it needed?

oblique heath
#

its irrelevant

#

i already realized i don't want to store any on the item

#

in this case a timer for playing some sound

oblique heath
warm mason
oblique heath
#

no

#

you just don't understand what i am saying

warm mason
#

Well then think for yourself

fading sand
#

How do i get the current slot id and save it so i can set an item with setEquipment there later?

pliant kite
#

where to get Minecraft Bedrock Edition actual entities.json? Not outdated

full brook
#

will structure voids be removed?

distant tulip
warm drum
#

is there a way to lock item inside chest?

#

It can still be moved from chest to player inventory

ruby haven
#

I know this is not a question for this branch but is netherite hard to find or make in Minecraft cause I made a difficult game and I want to consider the use of netherite in crafting recipe

#

I never played survival on Minecraft since they released netherite armor so I don't really know

random flint
pliant kite
#

@deep plank check dm

fading sand
#

How do i get the current slot id and save it so i can set an item with setEquipment there later?

wheat condor
fading sand
supple yoke
#

while and for loops are the worst

#

haven't worked with them in a long long time

#

it's basically recursion but worse

fading sand
#

?

supple yoke
#

while and for loops are dumb

#

actually for loops (when it is use to repeat thing n times) is fine

wary edge
wheat condor
supple yoke
# wary edge What?

with recursion you can actually use it to structure and name your code but while loops in particular just make every more nested for basically no reason

wary edge
#

That is a complaint sure

fading sand
supple yoke
#

yeah I'm complaining because I have to use them

#

actually no, I'm just using them because I just want to have the knowledge of how to use them effectively just in case

wheat condor
supple yoke
#

also performance

#

I'm doing assemblyscript stuff

fading sand
wheat condor
#

but the map should be defined out of the run or the function that gets repeated

fading sand
#

Ah ye, but its all inside one function so i wouldnt even need the map i think

#

Its basically the function and inside the timed command

#

We use var for variables which shouldnt auto redefine themselves right?

wheat condor
fading sand
wheat condor
fading sand
#

Maybe i still use map than

fading sand
#

Its an run interval

#

*system.run

wheat condor
fading sand
#

So that means it wouldnt matter if i use variable or map?

#

Right?

wheat condor
fading sand
#

Its kinda to long to send all but wait

supple yoke
wheat condor
supple yoke
#

may I ask why would you not use a normal object?

#

const map = {}

wheat condor
supple yoke
#
map[key] = somethingElse
console.log(map[key]) //logs somethingElse
#

yeah you add the new key in it

wheat condor
fiery solar
supple yoke
#

valid

wheat condor
supple yoke
#

also I read, it also have a bunch of other benefits and also more descriptive for types

#

very cool

#

you have convinced me

#

looks a little dangerous with apis tho but for Minecraft is kind of cool

copper lake
#

can scripts access scores on entities other than players?

thorn flicker
#

yes

nocturne berry
#

How to decrease the stacked item in an entity's inventory?

terse spindle
#

So currently I am trying to program that the Item called lb:paper_clip can open a thing called lb:loot_box in like a few chances and every chance used removes 1 paper clip from the inventory and when opened the loot box the loot box changes block states and for some reason this code I am working doesn't do shit

#
const PAPER_CLIP_ID = "lb:paper_clip";

world.beforeEvents.itemUseOn.subscribe(event => {
    const player = event.source;
    const blockLocation = event.block.location
    const block = player.dimension.getBlock(blockLocation)

    if (block && block.typeId === LOOT_BOX_ID) {


        const inventory = player.getComponent("minecraft:inventory").typeId
        const heldItem = inventory

        if (heldItem === PAPER_CLIP_ID) {
            player.getComponent("minecraft:inventory").container.removeItem(heldItem);

            if (Math.random() < 0.5) { // 50% chance to open
                const newBlockState = block.setPermutation(
                    Blocks.get(LOOT_BOX_ID).createDefaultBlockPermutation().withState("lb:opened", true)
                );
                player.dimension.runCommand(`setblock ${blockLocation.x} ${blockLocation.y} ${blockLocation.z} ${LOOT_BOX_ID} [opened=true]`);
                player.sendMessage("The loot box has been opened!");
            } else {
                player.dimension.runCommand(`particle minecraft:happy_villager ${blockLocation.x} ${blockLocation.y} ${blockLocation.z}`);
                player.sendMessage("The paper clip didn't work. Try again!");
            }
        } else {
            player.sendMessage("You need a paper clip to open the loot box.");
        }
    }
})```
cinder shadow
#

any errors?

cinder shadow
#

the inventory itself doesn't have a type Id

#

and you aren't getting the held item anywhere

#

tbf, you don't need to get the item from the inventory at all. This event comes with the itemStack of the item being used already

thin steeple
cinder shadow
#

he's not trying to do either of those

subtle cove
sturdy ermine
#

No this can't be....

#

it's evolving

subtle cove
#
import { world, BlockPermutation } from "@minecraft/server";

const LOOT_BOX_ID = "lb:loot_box";
const PAPER_CLIP_ID = "lb:paper_clip";

world.beforeEvents.itemUseOn.subscribe(async event => {
    const player = event.source;
    const block = event.block
    if (block.typeId === LOOT_BOX_ID) {


        const heldItem = event.itemStack

        if (heldItem.typeId === PAPER_CLIP_ID) {
            await (event.itemStack = null);

            if (Math.random() < 0.5) { // 50% chance to open
                block.setPermutation(
                BlockPermutation.resolve(LOOT_BOX_ID).withState("lb:opened", true)
                );
                player.sendMessage("The loot box has been opened!");
            } else {
                player.dimension.runCommand(`particle minecraft:happy_villager ${block.x + 0.5} ${block.y + 0.5} ${block.z + 0.5}`);
                player.sendMessage("The paper worked. Congratulations!");
            }
        } else {
            player.sendMessage("You need a paper clip to open the loot box.");
        }
    }
})```@terse spindle
thin steeple
oblique heath
#

we need a pickup time property in EntityItemComponent 😦

terse spindle
tawny jungle
#

is there a way to call a const into a runcommand method?

thorn flicker
tawny jungle
#

nice

#

thanks

tawny jungle
#

how can i select any of the block ids in an array?

#

in other words, if the objects in the main hand match any of the objects in a constant array, run this. How can i make it detect for any of the items in that array?

tawny jungle
#

nvm

#

figured it out

oblique heath
#

im making a custom bow using scripting

#

is it possible to make the projectile (in this case an arrow) not hurt me when I initially shoot it?

#

the arrows the vanilla bow shoots will never hurt me

#

even if they spawn behind my head or in my body depending on rotation

shy leaf
oblique heath
#

yes but i don't want to use that

shy leaf
#

well, try setting the projectile owner

oblique heath
#

good idea

#

ok that worked

#

also im not using the shooter component because i don't want to be restricted by what ever it has

#

i already have the base logic for my bow done either way

tawny jungle
#

how do i make an item decrement stack after being placed with scripts

tawny jungle
#

?

subtle cove
#

Wdym by "being placed with scripts"

tawny jungle
#

my block is placed and the rotations are managed through a script event, but when its placed it automatically sets back to the number it was already at

#

itll disappear for a moment but then reappear in my hand

#

itll still place though

subtle cove
#

Aight, make a post abt it blobshrug

tawny jungle
#

bingo bango bongo

tawny jungle
#

nvm

#

figured it out

terse spindle
oblique heath
#

I'm trying to play the bow animation with player.playAnimation but it only lasts for a frame

#

but if it call it constantly it makes the player flicker

#

any ideas?

subtle cove
# terse spindle I spammed it….

oof, mb. the itemstack there wasnt assignable

world.beforeEvents.itemUseOn.subscribe(async event => {
    const player = event.source;
    const block = event.block
    if (block.typeId === LOOT_BOX_ID) {

        const heldItem = event.itemStack

        if (heldItem.typeId === PAPER_CLIP_ID) {
            await null;
            if (heldItem.amount === 1) player.getComponent("equippable").setEquipment("Mainhand")
            else {
                heldItem.amount--
                player.getComponent("equippable").setEquipment("Mainhand", heldItem)
            }
            if (Math.random() < 0.5) { // 50% chance to open
                block.setPermutation(
                    BlockPermutation.resolve(LOOT_BOX_ID).withState("lb:opened", true)
                );
                player.sendMessage("The loot box has been opened!");
            } else {
                player.dimension.runCommand(`particle minecraft:happy_villager ${block.x + 0.5} ${block.y + 0.5} ${block.z + 0.5}`);
                player.sendMessage("The paper didn't work. Try again!");
            }
        } else {
            player.sendMessage("You need a paper clip to open the loot box.");
        }
    }
})
#
player.getComponent("equippable").setEquipment("Mainhand",
    heldItem.amount === 1 ? undefined : heldItem.amount-- && heldItem
)
halcyon phoenix
halcyon phoenix
subtle cove
halcyon phoenix
#

wait it didn't say that it was read only

subtle cove
#

exactly where...

halcyon phoenix
#

😠

normal aurora
#

Any freelance devs?

subtle cove
# halcyon phoenix 😠

mb, i didnt mean to upset u
but for the most part, changing an (entity, block, item, etc.)'s identity to exist during a beforeEvent isn't likely an option, so most part is moved onto the followed gametick to occur via system.run

supple yoke
#

sigh

#

finally got my mock of the hopcroft karp (very wacky name) algorithm implemented

#

with my weird way of storing data done

#

I feel like I'm dying

subtle cove
#

keep dying then

#

nah, u can cooldown PENGnwn

supple yoke
#

ty, I probably need that lol

quasi meteor
#

how can I reach DynamicProperties for my minecraft world? Are there any software?

supple yoke
#

I think it is stored in the level.dat

#

not sure where tho but you can probably ctrl-f in there

#

to find it

quasi meteor
#

like this ->>

#

is any nbt editor works?

subtle cove
#

u wana edit that by...

#

idk if anyone tried editing that specific data via raw world/db files,
but the UUID is the BP uuid that can change it with scripts

supple yoke
quasi meteor
#

I want to see variables that stored in dynamicproperties actually

#

I tried to use debugger but it wasn't work for me,

subtle cove
#

what kind of variables?

#

script related or no

quasi meteor
#

I want to see the variables that I will save with the script

subtle cove
#

world.sendMessage, console.warn, log...

subtle cove
quasi meteor
#

I want access my package's dynamicProperties, this screenshot is from Universal Minecraft Editor but it is paid,

supple yoke
#

I thought I was another pack dynamic props

quasi meteor
#

oh thanks

subtle cove
#

in manifest.json, use that uuid
then in scripts/main.js

import { world } from "@minecraft/server"

const props = world.getDynamicPropertyIds()
console.warn(JSON.stringify(props))
console.warn(JSON.stringify(props.reduce((a, property) => {
    a[property] = world.getDynamicProperty(property)
    return a
}, {})))
quasi meteor
#

OHHH YOU ARE AWESOME DUDE

#

I am trying to learn

#

thank you guys

subtle cove
idle dagger
#

How to disable player fly?

warm mason
idle dagger
#

I need to make player fall if he flying and ability got disabled

distant tulip
copper lake
#

how do I get entity id? I have the following target but when I try to const targetId = target.Id I'm getting undefined.

  const targets = player.dimension.getEntities({
    type: "eduelfie:home",
    scoreOptions: [{ objective: 'home', maxScore: s, minScore: s }]
  });
const target = targets[0];
valid ice
#

Id or id?

copper lake
#

oh let me check

#

ThankYOU. I've been beating my head against this trying to figure out what I did wrong!

#

can I edit the button text on a modalform and if so, what is the syntax?

valid ice
#

The submit button?

copper lake
#

yea, is it possible to change the submit button?

keen thorn
#

is it possible to chnage player model?

copper lake
thin steeple
#
.submitButton("text")
copper lake
thin steeple
oblique heath
#

is there way to access an entity's ticks since alive value?

copper lake
tawny jungle
#

how can I make a sound play 1 block in front of me

somber echo
#

Player.dimension.playSound

#

________________________
How can I spawn particles in an unloaded chunk via script?

#

It is possible with runCommand but it doesn't work as I need

oblique heath
#

why would you want to do this anyways

#

no one will see it

somber echo
cinder shadow
#

That still won't show it for the player

#

Your best bet is making something that will always be visible to the player

#

And move towards that marker as they get closer to it

somber echo
abstract cave
#

Is there a way to cancel fall damage for a specific player

lone thistle
fallow minnow
#

whats the latest version of MC?

fallow minnow
somber echo
#

There is no native way to load the chunk right? Do you think the best way would be to use an entity to load the chunk to avoid using tickinarea and then kill it?

fallow minnow
#

so at the end of the day ur still using a ticking area

somber echo
serene radish
#

is there a 50 file limit for scripting?

#

for some reason the moment i made the 51st file, that file didnt register

serene radish
#

nvm, just the worst brain fart a man could have

oblique heath
#

relatable

supple yoke
#

peak 2am code quality.

#

(probably) works. I think.

prisma shard
supple yoke
#

me too my friend lol

prisma shard
#

is it

supple yoke
#

no but it is barely Minecraft related

#

it's for turning an image into fill commands

#

using the least amount of fills

dense skiff
#

Where is the best place to report script api bugs?

small cloak
abstract cave
distant tulip
# abstract cave How do i do that in player.json
      "minecraft:damage_sensor": {
        "triggers": [
          {
            "on_damage": {
              "filters": [
                {
                  "all_of": [
                    {
                      "test": "has_tag",
                      "value": "no_fall_damage"
                    },
                    {
                      "test": "has_damage",
                      "value": "fall"
                    }
                  ]
                }
              ]
            },
            "deals_damage": false
          }
        ]
      },
abstract cave
#

😮

#

thanks

fading sand
quick shoal
#

Anyone here

#

?

#

Plz help for code

#

I just wanna ask a question

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

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const health = player.getComponent("minecraft:health");
        if (health) {
        const ls = "▎".repeat(currentHealth);
        const rs = "▎".repeat(maxHealth - currentHealth);
            player.nameTag = `§l§d${player.name}\n§l§a${ls}§c${rs}`;
        }
    }
});
#

Does this code will display visual health on player?

#

This is the code I rewrote using Jaylay API to make it more visual

#

But I'm not sure if it will work because the debugger is offline.

fiery solar
wheat condor
# fading sand Is it same with setEquipment?

this works ONLY FOR PLAYERS

//set: void, sets the ItemStack to a eq slot
player.getComponent("equippable").setEquipment("equipment slot", ItemStack);

//get: ItemStack
const item = player.getComponent("equippable").getEquipment("eqipment slot");
quick shoal
#
import { system, world } from "@minecraft/server";

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const health = player.getComponent("minecraft:health");
        if (health) {
        const ls = "▎".repeat(health.currentHealth);
        const rs = "▎".repeat(health.defaultValue - health.currentValue);
            player.nameTag = `§l§d${player.name}\n§l§a${ls}+§c${rs}`;
        }
    }
});
#

Is this correct?

wheat condor
#
world.afterEvents.itemCompleteUse.subscribe(e => {
    const { itemStack, source } = e
    const food = itemStack.getComponent("food")
    if (!food) return;
    console.warn("eat")
})

what am i doing wrong getting food component returns undefined

drifting cobalt
#

is it possible to detect if the armor has been trimmed?

#

oh its impossible

warm mason
warm mason
#

I tried to make code execution when a person eats, but it didn't work with vanilla items (it was version 1.21.2). Apparently it's still like that now. If you look at the original "addon" mine, there will be either ancient json or there won't be any at all. From this we can conclude that everything works differently in vanilla

shy leaf
#

hmmmmm

warm mason
#

I have long been familiar with their love to do everything, but half through json and the other half through c++

idle dagger
#

how to change player display nickname?

#

that in the top of head

fallen cape
stark kestrel
#

How would u detect block broken not by player but an entity or a explosion?

idle dagger
stark kestrel
abstract cave
#

i want to make my block do stuff so long as it exists, do i use world after events or...

wary edge
warm mason
#

I remember the "tick" component is disabled after a restart or moving away from the block and in order for it to work you need to install the block again

exotic raptor
#

I could easily make a better combat if I had a script that got the damage of a held item.

Anybody got any leads? Like, at all?

thorn flicker
exotic raptor
thorn flicker
#

set a dynamic property on the item of what that damage value is maybe

warm mason
thorn flicker
#

right.

#

they just need to add the item damage component class in the api.

warm mason
#

and maybe someone will think of this... but it’s unlikely that the second feature I came up with)

thorn flicker
#

it would make sense for it to be added.

exotic raptor
#

There HAS to be a way to do this.

exotic raptor
#

🙏

#

I intended for that to look terrifying but eh

warm mason
exotic raptor
thorn flicker
exotic raptor
#

Not my first rodeo with the damage system.

warm mason
# exotic raptor So what does it do?

In Minecraft, armor is limited to 20 and then it doesn’t work very well. In my system it has an unlimited value and the damage is also affected by the type of damage and I’m thinking of adding a couple more dependencies

exotic raptor
warm mason
#

Well, you can try to use the gametest module, spawn a simulated player there, give him a sword in his hands and make a blow from his face, then add the damage to the dynamic property of the world

exotic raptor
#

🦅 I will come back to this, I am interested

terse spindle
warm mason
terse spindle
#

and I also wanna make it to where it doesn't work on loot boxes that are already open but for some reason it just does it

terse spindle
warm mason
# terse spindle yeah ofc

The mega ingenious corporation Mojang made one bug in which clicking on a block with the mouse counts several times. You need to create a variable in which the click tick is recorded, and if the tick coincides with the current one, then do not execute the code

#

I have a function for this..

#
let denyMap = {}
function deny(player, cause) {
  let data = denyMap[player.name] || {}
  if (cause == "all") {
    data.every = system.currentTick + 1
  } else {
    if (data.every >= system.currentTick) return true
    if (data[cause] >= system.currentTick) return true
    data[cause] = system.currentTick + 1
  }
  denyMap[player.name] = data
}```
#

it should be used like this:

if (deny(player, "lootChestOpen")) return
// Code here
terse spindle
#

Oh, I see, gotcha

warm mason
#

it returns true if this player had an event with such a reason in the next 2 ticks

terse spindle
#

Ah

warm mason
#

|| There are so many hidden bugs in this industry, the fixes for which are found in some roundabout way... it feels so strange ||

terse spindle
#

tysm

abstract cave
#

erm, how do i make custom commands

abstract cave
thorn flicker
#

in before Events, you can cancel the event.

#

this is good in custom commands because you can cancel the message from sending.

abstract cave
thorn flicker
#

theres an example from here

abstract cave
distant tulip
#
world.beforeEvents.chatSend.subscribe((event)=>{
    const {message, sender, targets} = event
    if(message == "!hello"){
      sender.sendMessage("hi")
      event.cancel = true
    }
    
})
abstract cave
#
[Scripting][error]-Unhandled promise rejection: TypeError: cannot read property 'subscribe' of undefined

[Scripting][error]-Unhandled promise rejection: TypeError: cannot read property 'subscribe' of undefined

[Scripting][error]-Plugin [Superhero Plus - 1.0.0] - [main.js] ran with error: [TypeError: cannot read property 'subscribe' of undefined    at <anonymous> (commands.js:3)
]

Why is it doing this

valid ice
#

Chat event is beta scripts only

abstract cave
valid ice
#

Because it's not stable...?

abstract cave
#

welp, so much for not using experiments

cinder shadow
#

the before event has a property isFirstEvent that was added recently

bright torrent
#

Anyway to do 2D graphics at runtime? With a map? Particle effects?

shrewd wedge
#

How am I to test who own world

warm mason
shut citrus
#

how to get entity fieldofview(angle) ?

warm mason
tawny jungle
#

is it possible to, upon clicking on a block, spawn an entity at that block's position then automatically make the player who clicked on it a rider of that entity?

shy leaf
tawny jungle
#

Thanks bro

merry sparrow
#

what happened to getRedstonePower for blocks, its still referenced in examples in the server module but it seems to been removed in 1.14.0

warm mason
quick shoal
#

When the debugger will fix?

bitter stone
#

I have no idea why I never asked this, but what alternatives can be used to extend the Player class? Because since it's a private class, it cannot be extended.

bitter stone
#

Of course not. Its constructor is private.

balmy mason
#

It's definitely possible

bitter stone
#

(I'm using a work computer, so I can't download anything. This is purely for scripting practice and development planning. I'm just on my lunch break.)

distant tulip
#

just import player class and extended it as you like

balmy mason
#

You can use Object.defineProperties on Player.prototype

#

And just assign methods to the prototype as well

bitter stone
#

But what if I need to have an API for something like character creation for a player? Such as their RP name, age, species, faction, element, etc.

balmy mason
#

I think it's best to use the player ID property then

#

Since it's totally unique

#

Just store it as a private property in your class

bitter stone
#

I have honestly never heard of Object.defineProperties nor Player.prototype before.

balmy mason
#

That would be for adding new properties and methods to the player class

#

I think I misunderstood your goal

bitter stone
#

But then again, if it's a server (which is what I'm planning), then it's going to be difficult for me to figure out how to make this work without a way to extend the Player class.

#

I'm planning on making a server that's kinda like an Origins-esque MMORPG-style server.

balmy mason
bitter stone
#

I...

#

I have a basic JavaScript/TypeScript understanding, but I have no idea how someone could use the player ID property.

#

I'm trying to learn how classes work, but I have no idea how to use the player ID in the class, let alone the two methods you mentioned earlier.

oblique heath
#

because making a new class won't help you with that

bitter stone
#

Then again, I don't want to create an entire script file which only consists of functions that constantly ask for the specific player target.

granite badger
#

use dynamic properties

bitter stone
#

I'm doing that. It's just the repetitiveness of the functions for getting and setting those dynamic properties that I have an issue with.

tawny jungle
steady canopy
#

is there any way to get the item thats being placed in playerPlaceBlock after or before events?

#

i tried with before event .getItemStack and it gives me an item with no data.

#

using permutationBeingPlaced

cinder shadow
#

You'll need to store it in an array with the current blockID/attributed tag and the associated item Id

#

oh wait

cinder shadow
steady canopy
#

nope

#

but i just discovered i can get the itemstack by using equippable component in the before event lmao

#

it makes sense

cinder shadow
#

ahh, yeah

steady canopy
#

since its a before event its still in your hand, its not placed

#

i got it working lucklily

#

thanks for trying tho

#

❤️

#

idk how i didnt think about that before lol

rapid sail
#

script to put a block in the offhand slot?

halcyon phoenix
quick shoal
#

Guys what's the best mobile coding app

#

I need that coding app not ad , autocomple

thorn flicker
pale terrace
#

its possible to detect when a player is operator?

oblique heath
#

there is an isOp method in player

#

but its in beta

mystic mortar
#
import { world, EquipmentSlot } from "@minecraft/server";

world.afterEvents.itemUseOn.subscribe((event) => {
    const player = event.source;
    const blockHit = event.block; // Access the block hit from event
    const mainHandItem = player.getComponent("minecraft:equippable").getEquipmentSlot(EquipmentSlot.Mainhand);

    // Check if the item in the main hand is a lodestone compass
    if (mainHandItem && mainHandItem.typeId === "minecraft:lodestone_compass") {
        // Check if the block hit is a lodestone block
        if (blockHit && blockHit.typeId === "minecraft:lodestone") {
            // Get coordinates of the lodestone block
            const x = Math.floor(blockHit.location.x);
            const y = Math.floor(blockHit.location.y);
            const z = Math.floor(blockHit.location.z);
            const lodestoneCoords = `Lodestone: ${x} ${y} ${z}`;

            // Set the new lore on the lodestone compass
            let currentLore = mainHandItem.getLore();
            currentLore.push(lodestoneCoords);
            mainHandItem.setLore(currentLore);

            // Update the inventory to reflect the new lore without deleting the item
            const inventory = player.getComponent("minecraft:inventory").container;
            inventory.setItem(player.selectedSlotIndex, mainHandItem);

            // Inform the player that the lore has been set
            player.onScreenDisplay.setActionBar("Lore set on lodestone compass!");
        }
    }
});```

Why is this deleting my item?!!
balmy mason
mystic mortar
runic crypt
#

Anyway to make something like backup respawn points with spawn protection ?
like you can set multiple spawn points (like by right clicking on bed) and if one bed is broken then the sevond spawn point is used ?
And there is a 5x5 area around the spawn point where there is spawn protection (using runcommandasync)

#

if anyone can help pls ping me ?

supple yoke
#

huh I wonder

#

do you guys test your BP?

#

with like gametest

#

but tbh I don't feel like many people here test anything lol

dim tusk
#

hello

supple yoke
#

hello

dim tusk
#

quick question is the before events of the playerInteractWithBlock still only works in beta version of script?

shy leaf
#

also yeah i do test BPs, cuz it would fall apart if i dont

shy leaf
#

i mean in a structure

dim tusk
supple yoke
#

by test, I mean like actual unit e2e testing.

shy leaf
dim tusk
supple yoke
#

like what they do at mojang

dim tusk
shy leaf
#

but im saying 98% of people in mcpedl dont test their addon at all

dim tusk
shy leaf
#

theyre not even aware of content logs

#

like when i download an addon from there

#

and test it with content logs on

dim tusk
#

off been awhile since i touch dicsord i didn't notice the forward button

shy leaf
#

i get at least a log

dim tusk
#

then i'll fix it myself

shy leaf
supple yoke
shy leaf
#

its just not labelled as beta

dim tusk
shy leaf
#

well it p much does the same so

supple yoke
#

I think y'all don't understand what I mean by "tests"

shy leaf
#

we didnt sorry

#

😔

supple yoke
#

welp ig not

dim tusk
shy leaf
dim tusk
shy leaf
#

oop

#

sorry

dim tusk
#

i get cringed with my bio lmao

idle dagger
#

how to check if message is equal to not startsWith?

if (message.startsWith("-ad")) {

dim tusk
thorn flicker
#

you can check if it equals false or just use the NOT operator (what coddy is suggesting)

idle dagger
idle dagger
thorn flicker
#

?

idle dagger
#

nvm I found out how to do it

hybrid island
#
        let staff = world.scoreboard.getObjective(`staff`).getScore(player)
#

whats the issue?

subtle cove
#

staff obj doesn not exist

#

initialize the objective 1st

hybrid island
#

Im dumb

subtle cove
#

const obj = getObj(o) ?? addObj(o)

honest spear
#

Did someone said he wants to understand classes???

#

:)

honest spear
#

This is OverTakes method that does a prototype manipulation

supple yoke
#

how are you incrementing your varibles

#

oh forgot pre increment without space

#

oops

warm mason
#

i -= -1

supple yoke
#

wow that's something

wise raft
#

How can I set the mainhand item from a custom entity? entity.getComponent(Minecraft.EntityComponentTypes.Equippable) returns undefined

honest spear
supple yoke
#

so there's no case where you need to use them instead of the others

honest spear
#

not really, pre-increment, increments first and returns later, after-increment, returns current value and after that increments variable value

supple yoke
#

yes I know, but why are you incrementing in a expression

#

couldn't you spare just one line?

honest spear
#

i don't understand

supple yoke
#

sorry I'm a little tired

honest spear
#

same

#

well only same behavior has these two

++i;
i += 1;
supple yoke
#

so my point is, you shouldn't modify a variable inside another expression

honest spear
#

depending on its result

honest spear
#

wait does really some one uses the space between the (i and ++)

supple yoke
#

yes I do makes the variable name a little bit clearer

honest spear
#

Doesn't feels like JS developer lmao

#

you have to be 100% typescript guy, fr

#

JS is not build to be clean and readable

supple yoke
#

ig but js isn't build for server and someone have to make node js

#

as a wise man said, "the only use case for JavaScript is to build thing that it isn't supposed to"

honest spear
#

ya, JS is incredible language but pain to manage your projects in

#

thats why somany sites are actually running generated JS not written by man

supple yoke
#

(fyi. yes, I does use ts because I can't stand js anymore)

honest spear
#

but JS is actually very interesting language after all, its just crazy what things you can do, and it actually creates new programming concepts cus its just another language that you can't compare to others

supple yoke
#

yeah it's one of the most used programming languages today after all.

supple yoke
honest spear
# supple yoke

Well JS really small languages and there is no much to talk about, the big book looks like whole ECMAScript specification

#

lmao

loud brook
#

hi guys, sorry for interupting
how do i detect an entity's target?

honest spear
supple yoke
loud brook
loud brook
supple yoke
#

I'm not sure but I think you can't because performace

loud brook
#

look, the warden has multiple targets(players,zombies etc), how do i detect if the warden wants to kill a player not any other mob

distant tulip
loud brook
#

I am using world.afterEvents.dataDrivenEntityTrigger

distant tulip
#

hmm
send your code

loud brook
#
world.afterEvents.dataDrivenEntityTrigger.subscribe((event)=>{
let mob = event.entity;
switch(event.eventId){
     case("bd:roar"):{
        if(mob.typeId.startsWith("secret:noneofyourbusiness")){
            mob.runCommandAsync('/tag ' + mob.target +' add bd:chased')
            console.warn(mob.target)
        }
    };
}
})
#

||@distant tulip ||

#

it returns undefined

distant tulip
#

what event are you using to fire that

#

from the entity part

loud brook
#

do i use timeout?

distant tulip
#

try

loud brook
#

ok going to try it rq

distant tulip
#

but you can just use filters property on "minecraft:on_target_acquired" component

loud brook
#

timeout didn't work

distant tulip
deft prism
#

how to use module server admin

thin steeple
shrewd wedge
#
dimensions.forEach(d => {  	
  let dims = world.getDimension(d);
  items = dims.getEntities({ type: "minecraft:item" });
  })
  
  items.forEach(itemEntity => {
    const itemComponent = itemEntity.getComponent("item");
    let itemId = itemComponent.itemStack.typeId;
    itemId.startsWith("minecraft:") ? itemId.slice(10); : false;
#

Why is this not work?

#

Is not removing Minecraft: from item

sharp elbow
#

You are slicing it properly, but nothing is being done with the result. forEach simply calls a function on every entry in the array, and does not return anything.

#

Sounds like you want items.map()

#
const flatItems = items.map(itemEntity => {
  const itemComponent = itemEntity.getComponent("item");
  let itemId = itemComponent.itemStack.typeId;
  return itemId.startsWith("minecraft") ? itemId.slice(10) : itemId;
});
#

Then you act on flatItems. It's worth noting that you cannot (or at least, should not be trying to) change the actual item IDs onto the item entities like that. At best it won't do anything productive

shrewd wedge
#

Thank you :)

loud brook
shrewd wedge
#

How am I detect if entity is on fire

winged gull
#

getComponent('minecraft:onfire')

tawny jungle
#

Why might I be getting this error upon adding .setRotation()? It wasn't doing this before I added it

    initEvent.blockComponentRegistry.registerCustomComponent("custom:block", {
        onPlayerInteract: (event) => {
            const { player, block, dimension, face, faceLocation } = event;
            const miniBlockEntitySpawn = {
                x: block.center().x,
                y: block.center().y-0.4,
                z: block.center().z
            };
            const blockEntity = block.dimension.spawnEntity("sci:block_mount", miniBlockEntitySpawn).setRotation(player.getRotation());
            blockEntity.getComponent('rideable').addRider(player);
        }
    })
});```

`[Scripting][error]-TypeError: cannot read property 'getComponent' of undefined   at <anonymous> (main.js:360)`
winged gull
#

because setRotation returns void

#

you need to move it to be separate

#

like blockEntity.setRotation

tawny jungle
#

i see

#

that worked

#

thanks 👍

loud brook
#

Guys, I once again ask how do I detect an entity's target?

#
world.afterEvents.dataDrivenEntityTrigger.subscribe((event)=>{
let mob = event.entity;
switch(event.eventId){
     case("bd:roar"):{
        if(mob.typeId.startsWith("secret:noneofyourbusiness")){
            mob.runCommandAsync('/tag ' + mob.target +' add bd:chased')
            console.warn(mob.target)
        }
    };
}
})
#

I tried .target but it didn't work

#

it prints undefined

clear pendant
#

is it possible to execute GET requests to get some data from a website?

tawny jungle
#

how could I obtain blockFace data in a custom block component?

    initEvent.blockComponentRegistry.registerCustomComponent("sci:mBMountSpawn", {
        onPlayerInteract: (event) => {
            const { player, block } = event;
            const blockFace = data.blockFace;
            }
        }
    });
});```

i need the direction to summon a specific entity depending on that direction
tawny jungle
# distant tulip data?

yeah, like world.beforeEvents.itemUse.subscribe(async function (data) { allows for data.blockFace

#

apologies for the incorrect terminology

distant tulip
#

you did get it
const blockFace = data.blockFace;

tawny jungle
#

but in the first snippet i can't call data

#

as a parameter

distant tulip
copper lake
# thin steeple use 1.3.0

I'm working in education so version is still 1.21.05 and working in stable server ui is only 1.1.0 as far as I know.

thin steeple
#

.submitButton either got added to 1.2.0 or 1.30

thorn flicker
#

pretty sure it was 1.3.0

thin steeple
thorn flicker
#

🤷‍♂️

thin steeple
#

json ui still exists..

tawny jungle
thin steeple
thorn flicker
#

nope

thin steeple
#

me neither, but thats when .submitButton got added to preview

#

@copper lake if submitButton doesnt work for you, make an rp with a folder called "ui" inside. then add this file.
if you change the source property name for both long forms to your form title it should be a custom submit button for that form.

copper lake
#

@thin steeple working with stable because the average teacher isn't able to access experimental toggles on school managed devices.

dense skiff
#

For those of you familiar with translation & RawMessage, how are you supposed to build a message such as this using RawMessages?
this.description and helpEntry.description are both RawMessage types in this example.

toRawMessage() {
        let output = `§2${this.command.getUsage()}§8 - ${this.description}`;
        for (let helpEntry of this.command.getHelpEntries()) {
            output += `\n  §7> §2${Command.prefix}${helpEntry.usage} §8- ${helpEntry.description}`;
        }
        return output;
    }
thin steeple
#

anyone know if its possible to delete a dynamic property?
i have unused ones on a player i wanna remove and there's not really a method

dense skiff
#

try setting them to undefined

thin steeple
#

alr

quick shoal
thorn flicker
halcyon phoenix
#

is it possible to do block-display entities?

loud brook
shrewd wedge
#
function replaceItems(player) {
if (!player.isValid()) return;
  try {
  const replaceableItems = ["minecraft:torch", "minecraft:soul_torch", "minecraft:lantern", "minecraft:soul_lantern"];
  const customItems = {
    "minecraft:torch": "evo:torch",
    "minecraft:soul_torch": "evo:soul_torch",
    "minecraft:lantern": "evo:lantern",
    "minecraft:soul_lantern": "evo:soul_lantern"
  };
  
  const inventoryComponent = player.getComponent("minecraft:inventory");
  if (!inventoryComponent) return;
  const inventory = inventoryComponent.container;

  for (let i = 0; i < inventory.size; i++) {
    let itemStack = inventory.getItem(i);
    if (itemStack && replaceableItems.includes(itemStack.typeId)) {
      let newItemId = customItems[itemStack.typeId];
      if (newItemId) {
        let newItemStack = new ItemStack(newItemId, itemStack.amount);
        inventory.setItem(i, newItemStack);
      }
    }
  }
} catch (error) {
  console.warn("Error:", error);
  }
}
#

This crash game, please help

#

When I drop the items, my game close

#

Here is video showing. When the other testing account drop torch it crash game immediately

#

Only for that account though

#
[Scripting][error]-TypeError: cannot read property 'container' of undefined    at replaceItems (index.js:95)
    at <anonymous> (index.js:142)
    at forEach (native)
    at <anonymous> (index.js:143)

That is error

#

Please somebody help

halcyon phoenix
#

is it possible to make entities undespawnable with script?

wise raft
#

How can I set the item type from an item entity?

hardy tusk
#

Cant

#

Spawn a new one

hybrid island
#

how to get all entites in a specific radius from the player (not commands like i need to get entity variable)

prisma shard
#

what was the command for getting script api npm list

#

i damn forgor

granite badger
#

/docs info...?

prisma shard
#

ohh thx

prisma shard
#

the command isn't usable there

#

the bot is unavailable in #bot-usage