#Script API General

1 messages · Page 72 of 1

prisma shard
#
function hi() {
    console.log('Hello World!');
}
hi();
umbral dune
#

that it!
I will try to solve this

umbral dune
#

nvm, finnafinest's message is literally all the code does

dim tusk
#

Bloating at it's finest.

rapid nimbus
#

Hey @dim tusk

dim tusk
rapid nimbus
# dim tusk ?

Want to try the Traveler's Titles Bedrock add-on pack I created?

umbral dune
#

'-'

rapid nimbus
# dim tusk ?

If you want to try out the Traveler's Titles Bedrock add-on pack I created, I'll send you a link to the add-on in MediaFire for you to download and try out in Minecraft Bedrock.

fathom hemlock
#

why is event.cancel = true not working?

thorn flicker
fathom hemlock
#

just the wiki code:


world.afterEvents.chatSend.subscribe((eventData) => {
    const player = eventData.sender;
    switch (eventData.message) {
        case "!gmc":
            eventData.cancel = true;
            player.runCommand("gamemode c");
            break;
        case "!gms":
            eventData.cancel = true;
            player.runCommand("gamemode s");
            break;
        default:
            break;
    }
});```
fathom hemlock
#

but I can't use beforeEvents

thorn flicker
#

why

#

because its in beta

fathom hemlock
#

if I have beforeEvents

thorn flicker
#

wrap it in system.run

fathom hemlock
#

ok

thorn flicker
#

also there's a native method for changing gamemode

#

you dont need to use commands

#

player.setGameMode('creative')

fathom hemlock
#

*thxsm

#

how do I make that: player target in command, ik I can do player.runCommand(`gamemode c ${target}`), the hard part is to define target

#

oh wait I think ik

#

I did

thorn flicker
distant tulip
#

so, he just ignored what you said

thorn flicker
#

lol

unique acorn
#

he probably meant how to make another player in the world creative

distant tulip
#

possibly

thorn flicker
#
const target = world.getPlayers({name: targetName})[0]
fathom hemlock
#

yoo thx for helping me but I have a question how do make a wait function that works mit system.run

fathom hemlock
#

thats working too

#

umm I think

thorn flicker
woven loom
#

lol

valid ice
#

What can we do with pfid, given in the player join event?

#

I’ve searched a bit online and haven’t found any way to gather meaningful information from it

distant tulip
valid ice
#

:(

snow knoll
#

Could I have help with fixing this script

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


function getEntityAge(entity) {
  //const spawnTick = entity.getDynamicProperty('spawnTime');
  //return system.currentTick - spawnTick;
  const spawnTime = entity.getDynamicProperty('spawnTime');
  return Date.now() - spawnTime;
}


system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const hand = player.getComponent("equippable")
    if (player.hasTag("electric") && player.hasTag("fly")) {
      const playerLoc = player.location
      const vel = player.getVelocity();
      if (vel.x !== 0 || vel.y !== 0 || vel.z !== 0) {
        const trail = player.dimension.spawnEntity('ltng:trail', playerLoc);
trail.setDynamicProperty("spawnTime", Date.now());
        world.afterEvents.entitySpawn.subscribe((event) => {
          if (event.entity.typeId == 'ltng:trail') {
            const age = getEntityAge(trail)
            const playerRot = player.getRotation();
            const maxAge = 0.05;
            if (age <= maxAge) {
              trail.setRotation({ x: playerRot.x, y: playerRot.y });
            }
          }
        });
      }
    }
  }
});
#

The problem is in the function

distant tulip
#

what need to be fixed?

distant tulip
#

does it throw errors?

snow knoll
distant tulip
#

what error

snow knoll
#

I haven't set the spawn time dynamic property to a value

#

And don't know what value to use

snow knoll
#

Wait nevermind I mistook the error

#

The content log says that it was "unable to call function getDynamicProperty at line 7 and line 22"

prisma shard
#

hi

woven loom
#

1.18 is now final right?

prisma shard
fathom hemlock
#

so is there like a wait function for system.run

#

or tick thing

prisma shard
fathom hemlock
#

ik i need the value

prisma shard
#

You need to use async in your event

fathom hemlock
#

ooohhh

#

yea yea forgott that

fathom hemlock
# prisma shard Show full code
import { openUIBuilderMenu } from "../main.js"
import { wait } from "../functions/wait.js"

world.beforeEvents.chatSend.subscribe((eventData) => {
    const player = eventData.sender;
    switch (eventData.message) {
        case `!gmc ${player.nameTag}`:
            eventData.cancel = true;
            system.run(() => {
                player.runCommand(`gamemode c ${player.nameTag}`);
            });
            break;
        case `!gms ${player.nameTag}`:
            eventData.cancel = true;
            system.run(() => {
                player.runCommand(`gamemode s ${player.nameTag}`);
            });
            break;
        case `!gms`:
            eventData.cancel = true;
            system.run(() => {
                player.runCommand(`gamemode s`);
            });
            break;
        case `!gmc`:
            eventData.cancel = true;
            system.run(() => {
                player.runCommand(`gamemode c`);
            });
            break;
        case `!ui-builder`:
            if (!player.hasTag("admin")) return;
            eventData.cancel = true;
            await system.waitTicks()    
            system.run(() => {
        
            openUIBuilderMenu(player);
            });
            break;
        default:
            eventData.cancel = true;
            player.sendMessage(`§cUnknown command. Please use !help for a list of commands.`);
            break;
    }
});
prisma shard
fathom hemlock
#

ye

#

I forgott that

prisma shard
fathom hemlock
#

thx

drowsy scaffold
#

Anyone know if the newest hotfix fixes the desync?

prisma shard
drowsy scaffold
#

In 1.21.70, there was really bad desync with clients, especially with knockback

#

And I was wondering if it got fixed with the newest update

prisma shard
#

Okay, i see, i wonder too.
Because the issue also happens for me

#

lemme check the changelogs ig

#

Yeah i was like fixing my addon, i sprinted then hit the creeper 2 times, it flew away

#

totally drunk knockback

safe stream
#

Am I doing something wrong with this?

const form = new ModalFormData()
    .title("Rotate Entity")
    .body("Select the rotation step:")
    .slider(1, 8)
    .button1("Confirm")
    .button2("Go Back")```
It's returning a content log error
fallow minnow
safe stream
#

oh

fallow minnow
#

u can only use

slider
textfield
dropdown
toggle
or submit button

safe stream
#

Thank you!!

#

I thought it was like MessageFormData lol

fathom hemlock
#

hey in line 148 is smth wrong

            const updated = JSON.parse(world.getDynamicProperty('auctions') ?? '[]');
            const a = updated[index];
            if (!a) return;

            if (a.highestBidder === player.name) {
                const inv = player.getComponent("inventory")?.container;
                const playerMoneyNow = moneyObj?.getScore(player) ?? 0;

                if (playerMoneyNow >= a.highestBid) {
                    player.runCommand(`scoreboard players remove @s money ${a.highestBid}`)
                        .then(() => {
                            try {
                                inv.addItem({ typeId: a.icon, amount: a.amount });
                                player.sendMessage(`§aYou won the auction for §6${formatItemName(a.icon)} §afor §6$${a.highestBid}!`);
                            } catch (err) {
                                player.sendMessage("§cError giving item: " + err);
                            }
                            updated.splice(index, 1);
                            world.setDynamicProperty('auctions', JSON.stringify(updated));
                        });
                } else {
                    player.sendMessage("§cYou no longer have enough money to pay for your bid.");
                }
            }
        }, 100); ```

```line 147                            world.setDynamicProperty('auctions', JSON.stringify(updated));
  line 148                    });```
#

line 148 is wrong

#

cuz I changed player.runCommand(`scoreboard players remove @s money ${a.highestBid}`)

dim tusk
#

Umm, how do I get the value from the custom enums in custom commands?

timid zenith
#
world.beforeEvents.chatSend.subscribe((data) => {
  try {
    utilities.setTickTimeout(() => {
      const allPlayers = [...world.getPlayers()]
      for (const player of world.getPlayers()) {
        player.nameTag = "§7[§r" + Misterank(player) + "§7]§r " + player.name + "§r"
      }
    }, 20)
  } catch (error) {

  }
})

The mistake is in this

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

valid ice
#

What script version are you using

warped blaze
timid zenith
timid zenith
valid ice
#

What’s the error? What’s your script version?

timid zenith
valid ice
#

Is line 11 the subscribe?

#

And are you using the development behaviour pack folder

valid ice
#

That error is not from that code

timid zenith
#

In manifest 2.0.0-beta

valid ice
#

It’s saying “beforeChat” of undefined

Your code has zero mention of beforeChat

valid ice
timid zenith
valid ice
#

That’s what the error says

timid zenith
valid ice
#

The game seems to think otherwise

timid zenith
#

I was trying the before chat and chatSen

#

One I get an error and another I don't get any error but the addon doesn't work

valid ice
#

Well, the second one doesn’t exist any more

#

Do you have two index.js files in the same pack? Or what’s going on there

timid zenith
valid ice
#

Is that second one in a different pack, or…?

timid zenith
dim tusk
#

I'll just spread the param values.

#
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
  customCommandRegistry.registerEnum('coddy:team', ['Red', 'Blue', 'Green']);

  customCommandRegistry.registerCommand({
    name: 'coddy:multi',
    description: 'A command with enum, location, and number',
    permissionLevel: CommandPermissionLevel.Any,
    mandatoryParameters: [
      {
        type: CustomCommandParamType.Enum,
        name: 'coddy:team'
      },
      {
        type: CustomCommandParamType.Location,
        name: 'target_pos'
      },
      {
        type: CustomCommandParamType.Integer,
        name: 'repeat_times'
      }
    ]
  }, (origin, ...params) => {
    console.error('Raw params:', JSON.stringify(params, null, 2));
  });
});```
warped blaze
#

with the latest preview

dim tusk
warped blaze
#

oh it got added one update ago

#

mb, didn't see that

dim tusk
warped blaze
snow jungle
#
Unhandled promise rejection: Error: Failed to call function 'getComponent' due to the Entity being invalid (has the Entity been removed?).    at <anonymous>```

on a beforeEvent playerLeave?
#

Im pretty sure I still have a handle on the player before they leave?

dim tusk
#
world.beforeEvents.playerLeave.subscribe(({ player }) => {
  const { currentValue } = player.getComponent('health');

  console.error(currentValue);
});```
snow jungle
#
world.beforeEvents.playerLeave.subscribe(async (event) => {
    const playerName = event.playerName;
    const player = event.player;

    system.run(async () => {
        await player.getComponent("inventory").container.clearAll();
    });
})
snow jungle
#

?

dim tusk
dim tusk
# snow jungle ?

this triggers before player left right? Since system.run() runs teh next tick, so teh player already left you can't clear it anymore.

snow jungle
#

so whats the fix for this?

dim tusk
#

Store the ID of player in a dynamic property and use playerSpawn to clear it.

shy leaf
#

why not just use playerSpawn to clear inventory?

dim tusk
#

thank you for repeating it lol

shy leaf
#

i mean

#

it doesnt need playerLeave

#

or playerJoin works too

dim tusk
shy leaf
#

since the intention is to clear the players inventory when they join back

shy leaf
shy leaf
#

oh

#

sorry i slept late last night

dim tusk
#

Only playerName and playerId

shy leaf
#

whar

#

oh right it doesnt

#

playerSpawn it is then

#

i think you could also use WeakMap for this cuz

#

garbage collecting

shy leaf
#

just wait until i get my coffee

#

im a sleepyhead rn

dim tusk
shy leaf
#

if the player joined (using playerSpawn event), clear inventory and set a key

#

if the player respawned (check if the player has key), dont clear inventory

shy leaf
#

...does initialSpawn fire if player rejoined?

dim tusk
#

Since the world wasn't closed or stopped

#

Unlike multiplayer, local worlds or realm(?)

shy leaf
#

yeah thats why i was suggesting that

#

just to make sure

dim tusk
shy leaf
#

mhm, but tags dont remove by its own when player leaves

tropic geyser
#

what min engine version, script version and ui version are we on

fathom hemlock
#
                const inv = player.getComponent("inventory")?.container;
                const playerMoneyNow = moneyObj?.getScore(player) ?? 0;

                if (playerMoneyNow >= a.highestBid) {
                    player.runCommand(`scoreboard players remove @s money ${a.highestBid}`)
                        .then(() => {
                            try {
                                inv.addItem({ typeId: a.icon, amount: a.amount });
                                player.sendMessage(`§aYou won the auction for §6${formatItemName(a.icon)} §afor §6$${a.highestBid}!`);
                            } catch (err) {
                                player.sendMessage("§cError giving item: " + err);
                            }
                            updated.splice(index, 1);
                            world.setDynamicProperty('auctions', JSON.stringify(updated));
                        }); // line 140
                } else {
                    player.sendMessage("§cYou no longer have enough money to pay for your bid.");
                }
            }```
warped kelp
#

Is there a way to detect what item an entity is holding and run an event based on the item held?

#

By running an event, I mean a function that runs
/event to activate that event in an entity, if possible

dim tusk
dim tusk
warped kelp
#

Awh, alright. I'll just rely on component switching using timers

dim tusk
#

you can use functions files and check holding of item using hasitem={}

dim tusk
#

Just do that.

warped kelp
#

I'll check the documents

#

One more question,

How I can reduce damage recieved by an entity without using resistance, even if it is coming from an override damage attack?

dim tusk
warped kelp
#

Darn

#

Is there any resources you could point me to? If available

#

Could be using armor?

dim tusk
#

get what I meant?

warped kelp
#

Sorta, but looks math heavy

dim tusk
#

hurt -> get health -> calculate damage and current health -> give back required health

dim tusk
warped kelp
#

Ima test it out

dim tusk
warped kelp
#

... a boss :3

dim tusk
#

Nono, I meant why you need to reduce the damage?

#

Is this custom entity? If yes damage sensor already exists.

warped kelp
#

Ohh, some of the custom weapons use override damage and I don't wanna turn it into a damage checker by raising base hp of the custom entity

#

I could explain why, but I'd be rambling-

warped kelp
distant tulip
prisma shard
#
export function getArea(player) {
    const fromArea = player.getDynamicProperty("fromArea");
    const toArea = player.getDynamicProperty("toArea");

    if (fromArea && toArea) {
        const { x: fx, y: fy, z: fz } = fromArea;
        const { x: tx, y: ty, z: tz } = toArea;
        return { fx, fy, fz, tx, ty, tz };
    } else {
        return null;
    }
}

// Cannot convert to object error
const { fx, fy, fz, tx, ty, tz } = getArea(player)```
#

Can someone help me

#

Why does it return "cannot convert to object" error

dim tusk
#

Check if it really set the values,

#

Or just ```js
export function getArea(player) {
const fromArea = player.getDynamicProperty("fromArea") || { x: 0, y: 0, z: 0 };
const toArea = player.getDynamicProperty("toArea") || { x: 0, y: 0, z: 0 };

const { x: fx, y: fy, z: fz } = fromArea;
const { x: tx, y: ty, z: tz } = toArea;
return { fx, fy, fz, tx, ty, tz };
}```

#

And check if the dynamic property is actually a vector3

prisma shard
#

Oh

#

Thanks!!!

#

i seee

#

agh

#

idk why now it spams unloaded chunk error

dim tusk
#

getBlocks already has built-in for that. Dimension.getBlocks(volume, {}, true)

#

It's Boolean, suppress the unloaded chunk error

prisma shard
#

hmmm nah bro like i cant fix it

#

mayb its not a area problem

#

i think i did smth werid somehwherer

fathom hemlock
#

how did u guys got soo good at scriptapi?

prisma shard
prisma shard
#

And no if your talking about me, i am not good at scripting

dim tusk
fathom hemlock
#

did u guys read the scriptapi docs?

dim tusk
#

anyways, custom commands is fun wadahell...```js
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
customCommandRegistry.registerEnum('coddy:grant', ['grant', 'revoke']);
customCommandRegistry.registerEnum('coddy:scope', ['only', 'from', 'through', 'until']);

customCommandRegistry.registerCommand({
name: 'coddy:advancement',
description: 'Grants or revokes advancements',
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [
{
type: CustomCommandParamType.Enum,
name: 'coddy:grant'
},
{
type: CustomCommandParamType.PlayerSelector,
name: 'targets'
},
{
type: CustomCommandParamType.Enum,
name: 'coddy:scope'
},
{
type: CustomCommandParamType.String,
name: 'advancement'
}
],
optionalParameters: [
{
type: CustomCommandParamType.String,
name: 'criterion'
}
]
}, ({ sourceEntity }, ...params) => {
const [action, targets, scope, advancement, criterion] = params;

sourceEntity.sendMessage(`${sourceType} ${JSON.stringify(params)}`);

});
});```

prisma shard
#

Ofcourese

dim tusk
prisma shard
fathom hemlock
#

I just use the docs to seach events

prisma shard
#

And so he uses commands instead of blockVolume or fillBlocks

prisma shard
#

i will have pain if i change everything to native fill

#

hmm

#

uh

#

WHY DOES playerInterWithBLock not work for me?

#

itemUse only work for me

prisma shard
dim tusk
#

restart mc or check script version.

dim tusk
prisma shard
#

oh ok ay lemme

#

HEY IT WORKS
THANK YOU CODDY

prisma shard
#

Now how do i get the first block

#

it spams lol

hybrid island
#

yo custom cmds exist in 1.21.71?

#

or just preview

prisma shard
#

but it still returs two times

fathom hemlock
#

how do I define the inventory cuz const inv = target.getComponent('minecraft:inventory').container; is not working

dim tusk
dim tusk
dim tusk
#
const { container } = player.getComponent('inventory');

for (const slot = 0; slot < container.size; slot++) {
  const itemStack = container.getItem(slot);
  // ...
}```
prisma shard
#

it returns two times

fathom hemlock
#

okay

prisma shard
dim tusk
prisma shard
#

OH

#

okay it was my script 😂

hybrid island
dim tusk
#

The find(), firstEmptySlot(), firstItem(), contains() and reverseFind() in inventory component are very freaking useful.

fathom hemlock
#

inv ist sill not working:

    if (!inv) return target.sendMessage("§cInventory not found.");

    for (let i = 0; i < 36; i++) {
        const item = inv.getItem(i);
        if (!item) continue;

        ui.button(i, `§l§f${item.typeId}`, [`§7Amount: §e${item.amount}`], item.typeId, item.amount);
    }```
#

getComponent is not defined

dim tusk
fathom hemlock
#

oh wait let me define player

dim tusk
#

or you're getting invalid entity.

fathom hemlock
#

cuz on my auctionhouse its working

#
    if (!inv) return player.sendMessage("§cInventory not found.");

    const ui = new ChestFormData('large').title("§l§eSelect an Item to Sell");

    for (let i = 0; i < 36; i++) {
        const item = inv.getItem(i);
        if (!item) continue;

        ui.button(i, `§l§f${item.typeId}`, [`§7Amount: §e${item.amount}`], item.typeId, item.amount);
    }
dim tusk
prisma shard
#
function mainMenu(player) { 
    const form = new ActionFormData()
    .title(`Main Menu`)
    .button(`§l§5settings`)
    .button(`§l§cUndo`)
    .button(`§l§qRedo`)
    .button(`§l§1Fill`)
    .button(`§l§1Paste`)
    .button(`§l§1Create`)
    .button(`§l§1Circle`)
    .button(`§l§1Sphere`)
    form.show(player).then(result=>{
        const forms = [
            command.settings,
            command.undo,
            command.redo,
            command.fill,
            command.paste,
            command.create,
            command.circle,
            command.sphere
        ];

// why does that line return error
        forms[result.selection](player);
    })
}
dim tusk
#

Say the error.

prisma shard
#

wow chaining operator saves my life

#

i should realy do practice of using chaning operator

dim tusk
#

-# oof nvm.

prisma shard
# dim tusk what error? The dog eat the cat??
// open menu
world.afterEvents.itemUse.subscribe(e=>{
    const {source: player, itemStack} = e
    if (itemStack.typeId == "minecraft:wooden_axe") {
        let distance = 10
        if (player.getBlockFromViewDirection()) {
            let {x,y,z} = player.getBlockFromViewDirection().faceLocation 
            x += player.getBlockFromViewDirection().block.location.x
            y += player.getBlockFromViewDirection().block.location.y
            z += player.getBlockFromViewDirection().block.location.z
            const pLoc = player.getHeadLocation()
            distance = Math.sqrt(
                Math.pow(x - 0.5 - pLoc.x, 2) +
                Math.pow(y - 0.5 - pLoc.y, 2) +
                Math.pow(z - 0.5 - pLoc.z, 2)
            );
        }
        if (distance > 6) {
            mainMenu(player)
        }
    }
})````
Theissue with it is the form opening, some wrong calculations in distance or head location maybe,
because the not a function error, only happens when the player is lill far away, and looking on air, btu still form don't open, then it returns the not a function error
dim tusk
#
import { world } from "@minecraft/server";

const command = {
  settings: (player) => player.sendMessage("Opened Settings"),
  undo: (player) => player.sendMessage("Undid last action")
};

function mainMenu(player) {
  const commands = {
    'Settings': command.settings,
    'Undo': command.undo
  };

  const form = new ActionFormData().title(`Main Menu`);
  Object.keys(commands).forEach(text => form.button(text));

  form.show(player).then(result => {
    if (result.selection === undefined) return;

    const commandNames = Object.keys(commands);
    if (result.selection >= 0 && result.selection < commandNames.length) commands[commandNames[result.selection]](player);
  });
}
#

I literally created it.

#

Like wtf.

prisma shard
#

huh

dim tusk
#

I recreated it.

prisma shard
#

okay

fathom hemlock
fathom hemlock
prisma shard
dim tusk
prisma shard
#

hehe

dim tusk
#

Tf you don't see no redundancy 😭😭

#

Your redundancy can slow down your script and game.

prisma shard
#

ik ok ill fix

dim tusk
#

And what are you doing?

prisma shard
#

I mean,
trying update a Old WorldEdit script to 2.0.0-beta

distant tulip
#

itemUseOn

fathom hemlock
#

guysss I get error on line 11 but on line 11 is nothing

distant tulip
#

error and code

prisma shard
fathom hemlock
#

its always line 11

dim tusk
#

Checking if the block is 6 blocks ways from

prisma shard
dim tusk
distant tulip
prisma shard
fathom hemlock
distant tulip
dim tusk
#

Checking if there's 6 blcoks of air from view direction of player?

prisma shard
# distant tulip playerIneractWithBlock

playerInteractBlock is to detect interacting with block , i am detecting when the item is used in air, player cant interact with air. itemUse is the only way

fathom hemlock
#
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
import { showJobsMenu } from "./plugins/jobs.js"
import { openEditor } from "./plugins/chestui.js"


import "./essentials/chat_commands.js"
import "./plugins/invsee.js"
import "./plugins/auction_house.js"


let uiStorage = {};
const bannedPlayers = new Set();
let worldSettings = {
    welcomeMessage: "§6Welcome to the server!",
    canBreak: false,
    canPlace: false
  };
  const kits = {}; 


function saveAllUIs() {
  try {
    world.setDynamicProperty("gravel_ui_storage", JSON.stringify(uiStorage));
  } catch (e) {
    console.warn("§c[ERROR] Failed to save UI storage:", e);
  }
}

function loadAllUIs() {
  try {
    const raw = world.getDynamicProperty("gravel_ui_storage");
    if (raw) {
      uiStorage = JSON.parse(raw);
    }
  } catch (e) {
    console.warn("§c[ERROR] Failed to load UI storage:", e);
    uiStorage = {};
  }
}





system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const tag = player.getTags().find(t => t.startsWith("open:"));
    if (!tag) continue;

    const name = tag.split(":")[1];
    const ui = uiStorage[name];
    if (ui) {
      showGeneratedUI(player, ui);
    } else {
      player.sendMessage(`§cUI "${name}" not found.`);
    }
    player.removeTag(tag);
  }
}, 20);

#

just a part

prisma shard
#

:

prisma shard
#

very sus why would it return error on a empty line

fathom hemlock
#

its spamming my chat

prisma shard
# dim tusk Answer me.

I think im just disturbing you guys, the "not a function" is a lil rare errror. if it works it works lmao hehe

dim tusk
#

Spamming in chat?

prisma shard
#

I think you meant console

dim tusk
#

If I help, I will help lol

fathom hemlock
#

😭

#

I have this issue soo long

prisma shard
fathom hemlock
#

I deleted the code and its still line 11 😭

prisma shard
#

So its not a code fault

fathom hemlock
#

the logs 😭

distant tulip
fathom hemlock
#

no

distant tulip
#

you should

fathom hemlock
#

but after reload the script is changing

prisma shard
#

no

distant tulip
#

no?

fathom hemlock
#

yes

#

its changing

prisma shard
fathom hemlock
#

ohhh

distant tulip
# fathom hemlock no

the game take a copy of behavior packs if they are on behavior_packs, so changing the ones in behavior_packs change nothing

fathom hemlock
#

oh ok

prisma shard
#

i accidentaly reacted a sklull to your messege "you should" you might've thought that i am not telling him to use development pack folder lol

fathom hemlock
#

np

dim tusk
# prisma shard If you want answer, Yes
world.beforeEvents.itemUse.subscribe(({ source, itemStack }) => {
  if (source.typeId !== 'minecraft:player') return;

  const head = source.getHeadLocation();
  const view = source.getViewDirection();

  if (itemStack.typeId === 'minecraft:wooden_axe') {
    const blockRay = source.dimension.getBlockFromRay({ x: location.x, y: location.y + 0.1, z: location.z }, view, { maxDistance: 10 });
    if (!blockRay.length) return;

    const { block, faceLocation, face } = blockRay;

    const distance = Math.sqrt((faceLocation.x - head.x) ** 2 + (faceLocation.y - (head.y + 0.1)) ** 2 + (faceLocation.z - head.z) ** 2);

    if (distance > 6) {
      // ...
    }
  }
});```
or ```js
world.beforeEvents.itemUse.subscribe(({ source, itemStack }) => {
  if (source.typeId !== 'minecraft:player') return;

  const head = source.getHeadLocation();
  const view = source.getViewDirection();

  if (itemStack.typeId === 'minecraft:wooden_axe') {
    const blockRay = source.dimension.getBlockFromRay({ x: location.x, y: location.y + 0.1, z: location.z }, view, { maxDistance: 6 });
    if (blockRay.length) return;

    const { block, faceLocation, face } = blockRay;

    // ...
  }
});```
fathom hemlock
#

finally

#

I just recoded everything

prisma shard
dim tusk
#

for?

tropic geyser
# dim tusk for?

do you know how to access the equipment worn on an armor stand?

tropic geyser
# distant tulip can't what for?

its not rlly nothing specific i was just coding a circle made out of armor stands and i was seeing if you could put a helmet on all of them through the code

distant tulip
#

use commands

tropic geyser
distant tulip
#

entity.runCommand("replaceitem entity @s....")

tropic geyser
#

yeah ty

tropic geyser
distant tulip
tropic geyser
cyan basin
#

that's a bit silly that equippable doesn't work on non-players. hopefully this gets updated at some point

#

does anyone actually play preview? i made a simple homes addon using the new command registry (mainly for when it goes stable) but i don't know if anyone would actually use this at the moment.

distant tulip
cyan basin
#

fair enough

gaunt salmonBOT
warped kelp
warped kelp
#

The output can be used to run other events using more script like getModifier?

warped kelp
#

Example please? Brain not braining:(

valid ice
#

You can do whatever the heck you want with the output inside scripts

warped kelp
#

So essentially, if I use sensors inside a mob that runs events, either for movesets or mode_changer, the script could read that and run other things alongside it?

valid ice
#

Absolutely

warped kelp
#

Like, if for example the entity sensor detects a target entity far enough away, it could run an event that makes it angry, adding the component group, which then activates like.. applyImpulse to "dash" towards the target?

#

There could be more efficient ways to do this.. but maybe using timers on single component groups that cycles through?

valid ice
#

Totally possible
You could even have the entity sensor inside of scripts, using a getEntities on a consistent loop to detect close by mobs

warped kelp
#

Posibilits

#

Mind comprehends now

#

I will
Dig
In the documentation and
Cook

valid ice
#

You will have to learn javascript, just be warned 😛

warped kelp
#

I can wing it, people say I'm pretty fast at learning :3
-# only one person has said it

#

So long as the sacred texts can provide me a template, I'll try

valid ice
#

If you're willing to learn you're halfway there yessir

warped kelp
#

I guess the next simplest step forward is adding a script that applies a dash mechanic for when target entities are too far away. I'd assume that I can run a function that gives the entity resistance for immunity

valid ice
#

You can legitimately do whatever you want inside scripts*

#

* some limits apply

warped kelp
#

The deep always know where to seek, as they say.

prisma shard
#

when will mojang ever add entituHurt beforeEvent

warped kelp
#

Do you need it? I have made one for components

valid ice
#

You can mimic it with damage sensors, but having the ability inside scripts is very valuable

#

(Such as reading the amount of damage dealt and modifying it)

prisma shard
warped kelp
#

Mathematics :(

weary onyx
#

guys, how can i make my addon runs the scripts?

warped kelp
prisma shard
prisma shard
warped kelp
coral ermine
#

how to check if player started breaking block? Is it possible with
itemUseOn or entityHitBlock event

weary onyx
warped kelp
# warped kelp Yesh

Most of my addons just have a lot of json file for detecting on hit and running random functions, or just a function, and another for just removing duplicate mobs

prisma shard
prisma shard
warped kelp
#

One more thing, applyImpulse for entities, and applyKnockback for players?

prisma shard
#

applyImpulse() doesn't work for players.

warped kelp
#

Hmm. I might just use applyKnockback for all then?

prisma shard
#

but applyKnockback() also works for entities

#

but not dropped items ("minecraft:item") you got to use applyImmpulse to push them

#

there are also some cases where applyKnockback not work for entitites

warped kelp
#

I see, but since I mostly use entities, the items are fin—..

#

Darn

prisma shard
#

the items are fin-?

weary onyx
#

is this good implemented?

prisma shard
warped kelp
#

I guess I'll just have to take my chances with 3 tp commands in a function

prisma shard
prisma shard
#

entity.teleport({})

weary onyx
#

i made a little command that say hello world, but doesn't execute

warped kelp
#

I'll sleep on it

prisma shard
weary onyx
#

execute once time

prisma shard
#

Also, make sure your script version is 1.18.0 (latest stable) or 2.0.0-beta (latest beta) in manifest.json

#

if your using bridge v2, it sets @minecraft/server to 1.0.0-beta once upon creating a project, idk why

#

So you'd have to set it manually if you haven't

weary onyx
#

i see

prisma shard
#
world.afterEvents.worldInitialize.subscribe(() => {
  world.sendMessage("Hello World!")
})
weary onyx
#

i see

prisma shard
#

worldLoad if using 2.0.0-beata

weary onyx
#

a little question

#

how do i know the version of that?

prisma shard
#

you dont have to care about that

#

thats the pack version right

#

or mayb a dependency version

shy leaf
warped kelp
#

Is there a template I can use?

#

It turns out "sleeping on it" isn't so easy

prisma shard
warped kelp
#

For the dash, I mean

prisma shard
prisma shard
#

wdym dash

#

uhhh just elaborate

warped kelp
# prisma shard wdym sleeping on it

Sleeping on it to like, sleep to get a fresh mind for it.
Dash as in using applyKnockback to "dash" either from being called thru events or on use of an item/weapon

#

I have a player input someone let me kindly use so I can experiment with it

coral ermine
#

world.afterEvents.entityHitBlock.subscribe(({ damagingEntity: player, hitBlock: block }) => {
  if (!player || !block) return;
  const id = block.typeId;
  console.warn(id);
});

prisma shard
#

bcoz creative instantly breaks the block....

coral ermine
#

so there’s no way to detect it in creative?

prisma shard
#

I still didnt understand what you meant by sleeping on it/ fresh mind

prisma shard
#

Oh you just want the block

#

then use playerBreakBlock event

prisma shard
#

in entityHitBlock you'd detect if player is in survival
and in playerBreakBlock event, you;d detect if player is in creative
@coral ermine

#

Bcoz firing the event when starting to break the block could be only possibgle in survival

#

and using entityHitBlock makes no sense in creative, since creative instantly breaks block.

weary onyx
#

a little doubt

#

hmm, how do i refresh the files after i modified and saved the changes?

distant tulip
#

/reload

weary onyx
#

on bedrock, right?

distant tulip
#

uh, yeah?

prisma shard
dense sun
#
else if (message == ".suicide") {
        data.cancel = true
        return player.runCommand(`kill @s`);
    }
valid ice
#

Ok 👍

dense sun
#

it says no required permissions

dense sun
prisma shard
prisma shard
dense sun
#

would that lag the game?

prisma shard
distant tulip
#

Player.kill()

prisma shard
dense sun
#

does system,runJob help in multithreading ?

prisma shard
dense sun
#

so if i have 2 loops

#

and i dont use system.runjob

#

will it use a single CPU thread ?

prisma shard
# deep arrow Yes

system.runJob

Queues a generator to run until completion. The generator will be given a time slice each tick, and will be run until it yields or completes.

#

Bro changed his answer to Yes apple_skull THATS VERY WILD

dense sun
#

I have a loop that lags when there are more than 20 players

somber cedar
#

Script api isn't multi threaded

deep arrow
dense sun
#

if I use system.run Job for my loop , will it actually help?

prisma shard
prisma shard
# somber cedar Script api isn't multi threaded

system.runJob queues each work until completion, so it doesnt just instantly run that, and by making a stop/queue, it can somehow help in multithread like suppose you want to do antoher task at the same time

dense sun
prisma shard
#

And multithread is used here a pseudo word, like it means here to not make the game overloaded with the task, but not like the CPU multitaksing

prisma shard
somber cedar
dense sun
prisma shard
# somber cedar the process is run in slices before other sync stuff are run i think

I meant, system.runJob divide one task, you can see in the picture, it runs at first, "until" the "task" is complete. then it runs system.run, and if you can even somhow divide the task, and you wrap the task in system.run, it will run each tick, which will make the task run so slowly, runJob is to not make the game overload, and but to keep the task efficient at the same time.

prisma shard
dense sun
humble lintel
#

random question but does anyone know how to scale gui below -1

random flint
distant tulip
# prisma shard Yes

what? no
script api run single threaded, and all scripts share the main game thread

#

runJob only help with offloading heavy calculations by scheduling "jobs" to be run asynchronously to prevent blocking other scripts

random flint
fathom hemlock
#

umm

#

how do I do a scrolling effect with herobrines chestui?

#

or actionformdata

#

idk

nova flame
#

would anyone be able to help me with actionformdata in vc im poo at js

fathom hemlock
#

should work

nova flame
#

Not what i meant

unique acorn
nova flame
#

Okay ill join in 1 second

fathom hemlock
#

how do I add the player health?

dim tusk
fathom hemlock
#

its not working I don't see more healths on my health bar:

    const { damageSource, deadEntity } = event;
    const killer = damageSource?.damagingEntity;

    if (!killer || !killer.hasTag("lifesteal:on")) return;
    if (!killer.hasComponent("minecraft:health")) return;

    const health = killer.getComponent("minecraft:health");
    const currentMax = health.currentValue;

    if (currentMax < MAX_HEARTS) {
        health.setCurrentValue(currentMax + 2);
        try {
            killer.runCommand(`titleraw @s actionbar {"rawtext":[{"text":"§a+1 Heart (Lifesteal)"}]}`);
        } catch (e) {
            console.warn("runCommand error:", e);
        }
    }
});
dim tusk
#

You can't make show more heart bars without using health boost.

fathom hemlock
#

ohhh

dim tusk
#

It set current value but not max value.

fathom hemlock
gloomy wolf
#

Good evening, can someone help me with JS? I need to launch an entity in circles around another one to simulate a tornado. But I can't think of any function that would help me do that.
Sorry for the English, I'm Brazilian and I asked ChatGPT to translate this for me.

patent tapir
#

Would my script run without error with this logic, WITHOUT anything in the pack to add the player beforehand? js if (world.scoreboard.getObjective("deathCount")) if (world.scoreboard.getObjective("deathCount").getParticipants().includes(deadEntity.scoreboardIdentity)) if (deadEntity instanceof Player) world.scoreboard.getObjective("deathCount").addScore(deadEntity.scoreboardIdentity, 1)

#

I'm making a script for basic statistics, but I would like to have the option of not making the score in the first place or choosing only certain players.

dim tusk
dim tusk
#

I have read that, I was just confirming

#

The script you just gave is confusing.

patent tapir
#

Yes. I'm going for all the non-compound scoreboard criterion that Java has

#

Air, food, health, levels, xp, and armor

dim tusk
patent tapir
#

And all the kill/deaths ones

dim tusk
#

Don't be mad lol

dim tusk
patent tapir
#

I'm just asking if it would work (as in, not work but continue the code without error) if there was either no score or no player on that score, or both

dim tusk
#

no fancy BLA BLA, just directly add score.

patent tapir
dim tusk
patent tapir
#

...

#

I'M SIMPLY ASKING IF IT WOULD WORK, NOT HOW TO MAKE IT BETTER

dim tusk
#

Umm, I answered you twice tho.

#

You don't need to be mad.... Loll

patent tapir
#

You really havent

#

It's yes

#

Or no

dim tusk
#

ok mister...

#

yes.

patent tapir
#

Ok

#

Thank you

dim tusk
#

Happy? Also can't you just check it?

patent tapir
dim tusk
#

and?

patent tapir
#

Oh wait

#

It counts all deaths

#

Nevermind

#

Still no though

#

I like to have my scripts "finished" before testing

#

And so far, I can't figure out how to the get the current armor or food values of the player

#

How do I do that?

dim tusk
#

okay? Then good luck finding error root by root if you go test it thinking it actually works.

patent tapir
#

I don't understand properties or dynamic properties so unless you tell me that one of the properties of the player carries it I can't use them

dim tusk
patent tapir
dim tusk
patent tapir
#

Dang

dim tusk
patent tapir
#

I guess I'm not making armor or food stats

dim tusk
#
const dp = Entity/Player/ItemStack/World.getDynamicProperty('<name>');

Entity/Player/ItemStack/World.setDynamicProperty('<name>', <value | Boolean | String | Number | Vector3 | undefined>);```
#

This are very straightforward they're not that hard to understand

#

you can store DP in world, player, entity, and item.

patent tapir
dim tusk
patent tapir
dim tusk
patent tapir
dim tusk
#

either your lazy to find or you suck at finding.

patent tapir
dim tusk
#

Don't tell me Microsoft docs.

patent tapir
dim tusk
#

if yes just use stirante or jayly

patent tapir
dim tusk
dim tusk
#

Now I'm not surprised why you always asked for properties players/items or blocks has...

patent tapir
#

The only shit I know how to do for the most part are things Bridge can autocomplete

patent tapir
#

Bro even on pc I don't know how to properly use or install schemas and what about other behavior/resource pack stuff??

woven loom
dim tusk
#

you used Block.getMapColor()??

woven loom
#

yes and format codes

dim tusk
woven loom
#

yep 😄

dim tusk
#

You used runJob() for checking?

woven loom
#

nah for demo nope

#

i wanted to build the idea

dim tusk
woven loom
#

any good char to use as block ? rn i am using §l#

tropic geyser
#

what is the item component in item json for setting item to be enchanted as a sword eg it can have mending, unbreaking, etc

tropic geyser
#

mb

dim tusk
#

Then use char code.

woven loom
#

i hate using rps :/

#

thats why i had this idea

#

xd

wary edge
#

Video clearly using RP

woven loom
#

for addons*

cinder shadow
#

man I'm really trying my best to use the new container methods we got recently, but they all just seem so... useless

#

The one I did manage to use, isStackableWith, doesn't seem to have much of a use when you can check typeId == typeId

random flint
distant tulip
dim tusk
#

and iirc if it's unstackable it returns false...

random flint
#

What is that, unicode?

distant tulip
#

emoji

ripe dune
dim tusk
woven loom
#

is that default ?

ripe dune
woven loom
#

damn didnt knew that

#

can u share default png

ripe dune
#

oooh now i got it lol

#

that is unicode

#

as you can see

#

but i remembered something

#

wait

random flint
cinder shadow
# dim tusk isStackable is ItemStack and ItemStack....

I'm aware, but you can just do typeId == typeId. If it's unstackable it returns false, but you can also just check amount to maxAmount. Additionally, it doesn't return whether that specific itemStack is stackable, only if the item itself can be stacked, so you still have to do additional checks beyond that.

ripe dune
#

░▒▓█

#

those will not make your text unicode

thorn flicker
random flint
distant tulip
#

typeId == typeId. If it's unstackable it returns false
no

ripe dune
cinder shadow
#

so great, now you know the item can be stacked! now you have to do

if(currentInventoryItemAmount + amountToAdd > currentInventoryItemMaxAmount) {
                currentInventoryItem.amount = currentInventoryItemMaxAmount;
                inventory.setItem(i, currentInventoryItem);
                amountToAdd -= (currentInventoryItemMaxAmount - currentInventoryItemAmount);         
            }```
Which you were already going to have to do
distant tulip
#

just use addItem

#

it return the left amount that didn't get added

cinder shadow
#

that doesn't behave as I believe it should be

random flint
cinder shadow
#

addItem does not, it fills into the next empty slot

random flint
#

-# Only stacks if it has the same data obviously

cinder shadow
#

If you want it to go into the available stacks, you have to search the inventory manually first

distant tulip
#

it check items before that

cinder shadow
#

It does not

distant tulip
#

...

#

let me see

valid ice
#

addItem returns the remaining ItemStack if it could not add it to the inventory in general

#

Not the slot

random flint
#

I think Koala means that addItem() will prioritize the first empty slot then an existing item of the same type

cinder shadow
#

^

#

The best solution is:

  1. Manually search through inventory for available stacks and add to those
  2. use addItem
  3. spawnItem
distant tulip
#

it does not ....wt😣

cinder shadow
#

that's essentially how /give works

cinder shadow
#

I was pretty much done fixing my function that I have left untouched for months to cover any special cases and thought I was done

#

but I'm trying to cover if someone tries to add like 2000 of something

valid ice
#

Solution: don’t

cinder shadow
#

well, I need to cover it for one of my crafting systems, I haven't exactly checked the theoretical max and whether it would ever be an issue

shy leaf
#

like, why does it keep going into my hotbar?

#

💀

distant tulip
#

give @s item 😅

cinder shadow
#

but I might as well make it flexible anyways

valid ice
#

Bad

distant tulip
#

ok

#

lol

thorn flicker
cinder shadow
distant tulip
thorn flicker
#

I misunderstood what koala said ig

distant tulip
#

i am questioning my memory now, that can't be true

thorn flicker
thorn flicker
cinder shadow
#

It did

thorn flicker
#

yeah, I misunderstood.

distant tulip
#

had to double check in game, lol

thorn flicker
#

lol

distant tulip
#

now i can sleep peacefully
-# 2 AM

random flint
#

Good night

#

I mean, Good morning

distant tulip
#

yeah, lol

#

good day to you too lol
idk your time zone

random flint
#

I'm 6 hours in the future

cinder shadow
#

welp time to see if what I did works or if I'm about to crash my game with an infinite while loop

shy leaf
#

-# especially when i accidentally mess up with nametags

cinder shadow
#

you just don't use while loops

shy leaf
#

ofc but i meant infinite loops

#

not just while loops

cinder shadow
#

an infinite loop will always crash any game at some point

shy leaf
#

man i wish watchdog was useful for this

cinder shadow
#

I don't see what watchdog would do

#

"Your game is about to crash"

#

0.1 seconds before it crashes

shy leaf
#

oh yeah fair

#

cant stop what has already happened

distant tulip
#

-# zzzz not if it is in a runJob

shy leaf
#

speaking of which

#

what does runJob do exactly

#

i never understood it

distant tulip
#

run a job

shy leaf
#

understandable

distant tulip
#

lol, give me a sec

shy leaf
#

thanks

distant tulip
#

a function under the system class that uses generator function to run a set of tasks in different times

Generator functions have something called yeild, when the runjob run the function and reach a yeild it stops the execution and resume it next time the game is free

shy leaf
#

oh so it basically gives the game a 'work' to do instead of making them to do it immediately

distant tulip
#

yeah

shy leaf
#

thats nice

distant tulip
#

it is like
normal functions: stop everything you are doing and do this now
runJob + Generator functions: Do this when you can, when ever you have free time work on it a bit

random flint
shy leaf
#

the name makes sense now

#

runJob

#

RAM as salary

distant tulip
#

we need runFromJob

#

quietJob

#

gtg now fr lol

shy leaf
#

quitJob :trolley:

#

see ya

random flint
shy leaf
#

watchdog would put them in sleep

distant tulip
#

-# auto wake up at 7 😫

cinder shadow
#

I am at peace now

viscid horizon
#

how are you all doing today

random flint
#

kaboom

solar dagger
#

is there a way to get the total of entities killed within a certain attack action?

let killCount = 0;

world.afterEvents.entityDie.subscribe(({ damageSource, deadEntity }) => {

  const dmgSource = damageSource.damagingEntity;
  const validEntityTypes = Object.keys(entityAbilities)
  const victimHealthComp = deadEntity.getComponent('minecraft:health') as EntityHealthComponent;
  if (!dmgSource || !validEntityTypes.includes(dmgSource.typeId) || !victimHealthComp) return;
  const isTamed = dmgSource.getComponent('is_tamed');

  if (!isTamed) return;
  addExperience(dmgSource, xpReward(victimHealthComp.effectiveMax) * killCount);
});
#

Or would I have to use the entityHurtEntity event to increase that value

random flint
#

Does attack action refer to the damage type dealt? Or the way they're killed?

tropic geyser
#

how do i set the lore of an item in scripting?

random flint
tropic geyser
random flint
tropic geyser
#

inv?

random flint
#

yes inventory

tropic geyser
#

alr ty

random flint
#

addItem() to add the item to the first empty slot. Automatically stack with a similar item

setItem() to override specific slot

tropic geyser
#

yeah ty again

random flint
valid ice
#

ItemStack is like a "snapshot" of the item at the time it's gotten (event fire, getItem, etc) and is not related to the inventory in any way.

tropic geyser
#

how do i get auto sugestions like if i do world. then it will show me what i can do im using vscode

random flint
#

I just search on YouTube blindly. Took me an hour.

random flint
#

Installing autocompletion (typings)

#

npm and stuff

tropic geyser
#

like "npm i @minecraft/server@latest"?

random flint
#

"Bedrock Scripting set ups guide"

tropic geyser
random flint
#

Search it on youtube

tropic geyser
#

alr ty

random flint
#

Might not get what you want. You need to improvise and search more or use different wording

solar dagger
random flint
shy leaf
#

can itemStartUse and itemStopUse desync?

#

trying to make right click hold detection but im worried if anything can go wrong

shy leaf
#

hopefully

#

cant believe i have to do ALL OF THOSE to check for shield block check

#

man only if i could use is_blocking query in scripting

dim tusk
random flint
#

Oh no, It's a disaster indeed

echo tinsel
#

Is there something like this I could use but attachables giving effects instead?

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

const helmetParticle = {
    "minecraft:diamond_helmet": "...",
    "minecraft:golden_helmet": "...",
    //...
};

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const equipment = player.getComponent("minecraft:equippable");
        if (!equipment) continue;

        const helmet = equipment.getEquipment("Head");
        if (!helmet) continue;

        const particleId = helmetParticle[helmet.typeId];
        if (!particleId) continue;

        const playerPos = player.location;
        const spawnPos = {
            x: playerPos.x,
            y: playerPos.y + 2, // spawning above the head
            z: playerPos.z
        };

        player.dimension.spawnParticle(particleId, spawnPos);
    }
}, 10); // 0.5 seconds

random flint
echo tinsel
echo tinsel
random flint
#

You can do the particle thing with only a resource pack. But applying potion effects like invisibility needs to done on the server

echo tinsel
#

What?

random flint
#

-# missread your message there

echo tinsel
#

Nevermind. I think I figured it out

random flint
#

Not edited, just new one that doesn't spawn the particle

const helmetEffect = {
    "minecraft:diamond_helmet": ["haste",{ amplifier: 2 }],
    "minecraft:golden_helmet": ["invisibility",{}],
    //...
};

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const equipment = player.getComponent("minecraft:equippable");
        if (!equipment) continue;

        const helmet = equipment.getEquipment("Head");
        if (!helmet) continue;

        const effectData = helmetEffect[helmet.typeId];
        if (!effectData) continue;

        player.addEffect(effectData[0],10,effectData[1])
    }
}, 10); // 0.5 seconds
dim tusk
#
system.runInteral(() => {
  for (const player of world.getPlayers()) {
    const equippable = player.getComponent('equippable');
    const head = equippable.getEquipment('Head');
    const location = player.location;

    if (head?.typeId === 'minecraft:netherite_helmet') {
      player.dimension.spawnParticle('', { x: location.x, y: location.y + 2, z: location.z });
      player.addEffect();
    }
  }
});```
echo tinsel
#

And head to chest

random flint
#

yes, but it's case sensitive iirc

echo tinsel
#

Thank you!
It's working!
Is there a way for me to make it where the effect particle doesn't show?

#

Is that the last "1"?

dim tusk
#
const armor = {
  'minecraft:netherite_helmet': {
    particle: 'minecraft:redstone_wire_dust_particle',
    effects: [
      { 'minecraft:speed': { amplifier: 0, showParticles: false, duration: 100 } },
      { 'minecraft:blindness': { amplifier: 255, showParticles: true, duration: 100 } }
    ]
  }
};

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const equippable = player.getComponent('equippable');
    const location = player.location;

    for (const slot of ['Head', 'Chest', 'Legs', 'Feet']) {
      const equipped = equippable.getEquipment(slot);
      const config = equipped && armor[equipped?.typeId];

      if (config) {
        for (const effectObj of config.effects) for (const [effectId, options] of Object.entries(effectObj)) {
          const { duration = 20, ...rest } = options;
          player.addEffect(effectId, duration, rest);
        }

        player.dimension.spawnParticle(config.particle, {  x: location.x,  y: location.y + 2, z: location.z  });
      }
    }
  }
});```
#

I am weird. Wtf.

echo tinsel
#

Just watching it change trying to learn 🤣 👀

dim tusk
#

Just check how I add IDs with effects duration, amplifier, visibility and particle name.

echo tinsel
#

Thank you;

random flint
prisma shard
random flint
prisma shard
#

weren't you a TNT before-

random flint
#

Yesn't

dim tusk
#

I was redstone block before.

prisma shard
#

Yeah lol

dim tusk
#

perfect match... We would explode out of happiness.

#

Kaboosh.

echo tinsel
#

Perhaps I need to ask here, as help that I've gotten else where has not worked.

I am having issues with custom armor stand made through block bench.

They refuse to place facing forward. And when adding the axis aligned component all it does is shake, same happens if I add the blocked component.

Is it possible to script that it can only be placed in 8 directions or that it auto aligns when placed? This has been drying me insane for the past 2 weeks.

#

The one that is not shaking is how it is without axis aligned or blocked. Other is with

#

That is just a default armor stand appearance, armor stand behavior entity created through block bench

#

I was told it shakes because of the runtime_identifier but removing that makes it not act like an armor stand anymore

dim tusk
random flint
#

probably need to see the json
#1067869022273667152

true bramble
#

yall just reached 100k msgs on this forum bru

#

like dang

#

i saw it live

random flint
true bramble
#

oh

#

well

echo tinsel
dim tusk
#

What was that?

#

iirc you tagged me here.

echo tinsel
#

Sorry. I tagged saying that was the only way I could show the json currently being on mobile and didn't have access to the file

glacial widget
#

Am i a dumbie head

flat barn
#

this new movement correction is so annoying

#

If you run, jump and hit someone, you get moved backwards

distant tulip
#

for every action there is an equal and opposite reaction bao_ext_toldyouso

dim tusk
distant tulip
#

huh

dim tusk
#

I made the namespace / lol

distant tulip
#

that looks illegal

dim tusk
#

Don't worry it doesn't work, I already expected it since // is already invalid.

distant tulip
#

try §: lol

dim tusk
#

the namespace is annoying shucks

dim tusk
distant tulip
#

try escaping it too \:

#

not expecting any result, just curious

open urchin
#

can you use \0 as a namespace

dim tusk
flat barn
dim tusk
#

The preview is broki, if you're in textbox, it shows 7 otherwise it would show f

dim tusk
flat barn
dim tusk
#

hmm.

dim tusk
flat barn
#

is it preview or not

distant tulip
#

it is

dim tusk
flat barn
distant tulip
#

huh, weird

dim tusk
#

broki broki

#

Wait, I'm doing the \

distant tulip
#

double it in case

#

so it is escaped

dim tusk
#

I mean, you cna use it...

distant tulip
#

alr, was hoping it brake something

#

lol

dim tusk
#

Using / namespace still registers the command since it exists tho you can't use it since in general // is invalid.

fathom hemlock
#

how do I cancel event from a entity like villager

random flint
#

What kind? trading with them?

fathom hemlock
#

yes

#

event.cancel is not working

prisma shard
#

show error

fathom hemlock
#

there are no errors

wary edge
prisma shard
prisma shard
fathom hemlock
#

okay

fathom hemlock
prisma shard
# fathom hemlock

Just do console.warn() on after each line, and see which line doesn't execute

#

Then you'll know what line has the problem

fathom hemlock
#

okay

#

oh that return was wrong

prisma shard
#

Uh

#

Isnt entity.name a thing?

#

I am not getting .name in typings

fathom hemlock
#

error

shy leaf
#

only for player

prisma shard
#

oooo

prisma shard
#

guys which color is bettter

#

just a example

#

ok

random flint
#

I usually go with mostly red and yellow for highlights for warning message

prisma shard
#

but thats not really a warning apple_skull

#

not antthing like YOUR COMPUTER HAS A VIRUS womanalert

random flint
#

I thought a combat tag was a warning since most punished you after relogging

distant tulip
#

it is a notification
the highlight of the message is the name so it should be with a color that stand out better then the info itself

prisma shard
# distant tulip it is a notification the highlight of the message is the name so it should be wi...
world.afterEvents.entityHitEntity.subscribe(({ hitEntity, damagingEntity }) => {
    if (!damagingEntity?.hasTag("ws:combat") && (damagingEntity?.typeId === "minecraft:player" && hitEntity?.typeId === "minecraft:player")) {
        damagingEntity.addTag("ws:combat");
        damagingEntity.sendMessage(`§eYou are in combat with§r §6${hitEntity.name}!`);
        hitEntity.addTag("ws:combat");
        hitEntity.sendMessage(`§eYou are in combat with§r §6${damagingEntity.name}!`);
        system.waitTicks(6000).then(() => {
            damagingEntity.removeTag("ws:combat");
            hitEntity.removeTag("ws:combat");
            hitEntity.sendMessage(`§eYou are not anymore in combat!§r`);
            damagingEntity.sendMessage(`§eYou are not anymore in combat!§r`);
        })
    }
})

#

is this code right

#

I dont have minecraft to test :p im srorry

distant tulip
#

damagingEntity.sendMessage this throw error iirc

#

need player instance

prisma shard
# distant tulip need player instance
world.afterEvents.entityHitEntity.subscribe(({ hitEntity, damagingEntity }) => {
    if (!damagingEntity?.hasTag("ws:combat") && (damagingEntity instanceof Player && hitEntity instanceof Player)) {
        damagingEntity.addTag("ws:combat");
        damagingEntity.sendMessage(`§eYou are in combat with§r §6${hitEntity.name}!`);
        hitEntity.addTag("ws:combat");
        hitEntity.sendMessage(`§eYou are in combat with§r §6${damagingEntity.name}!`);
        system.waitTicks(6000).then(() => {
            damagingEntity.removeTag("ws:combat");
            hitEntity.removeTag("ws:combat");
            hitEntity.sendMessage(`§eYou are not anymore in combat!§r`);
            damagingEntity.sendMessage(`§eYou are not anymore in combat!§r`);
        })
    }
})

#

u mean this

#

?

prisma shard
gaunt salmonBOT
fathom hemlock
#

can somone tell what this error mean

random flint
fathom hemlock
#

ohh

#

oh yea runCommand

#
    const player = event.player;
    const entity = event.target;
    console.warn("test")
    if (!player || !entity) return;
    console.warn("test1")
    const command = entity.getDynamicProperty("command");
    console.warn("test2")
    event.cancel = true;
    console.warn("test3")
    system.run(() => {
    player.runCommand(`${command}`).then(() => {
        player.sendMessage(`§a✔ Command executed: §r${command}`);
    }).catch(() => {
        player.sendMessage(`§c✖ Failed to run command: §r${command}`);
    });
    })
});
#

what is wrong here

#

command is undefined but why

random flint
fathom hemlock
#

btw I get the message

random flint
#

Just do if (!command) return; and it'll hide the error 💀 but not fix the problem

fathom hemlock
#

yes

#

I want to fix the problem

#

and I see every second a new error

valid ice
#

What’s line 61

random flint
#

from the error commandSyntaxError I guess its the runCommand

fathom hemlock
valid ice
#

Console warn the dynamic property that you’re getting

#

Make sure it’s what you expect

random flint
valid ice
#

Yeah

fathom hemlock
valid ice
#

Run command does not return a promise

fathom hemlock
#

sometimes the command not found idk why

random flint
fathom hemlock
#

ohhh

#

yea I change runCommandAsync to runCommand

valid ice
#

It doesn’t directly translate