#Script API General

1 messages · Page 17 of 1

ionic kayak
#

It’s all in one script file

knotty plaza
#

What are you trying to do in that event?

#

Maybe it is working but whats inside is the problem

ionic kayak
#

tried this @knotty plaza

knotty plaza
#

Just in case, you know that worldInitialize only runs once per world load right?

#

/reload wont make it fire again

ionic kayak
#

Ofc

#

Leaving the world every time

knotty plaza
#

Check your content log, maybe it showed up and dissapeared really fast

ionic kayak
#

Uhm figured out what was wrong

viral plaza
#

is player.getDimension() a valid method

knotty plaza
viral plaza
#

oh

valid ice
#

I mean if you wanted you could do world.getDimension(player.dimension.id)

viral plaza
#

thanks

#

Well, someone just asked if you could run a script for players in the nether so I wasn’t sure if getting their dimension was a method or not

valid ice
#

ah fair

knotty plaza
#

Instead of just transfering the money

valid ice
inland merlin
#

Hey herobrine what's up

ionic kayak
#

Should I add a delay to run in game commands using worldInitialize?

inland merlin
#

To make sure time to see it

#

If slow device

solar dagger
#

i managed to do it without chatGPT, did a lot of youtube research 😆 it did take me a while tho. And i added a little of a wave path too

meager pulsar
winter plaza
#

can you tell me or show me how to do this?

knotty plaza
#

Is your item custom or vanilla?

solar dagger
knotty plaza
#

?

#

Where do you need math?

solar dagger
knotty plaza
shut citrus
#

How ?

#

is it mc bedrock feature?

random flint
#

He has the source code in his GitHub (check his main video)

meager pulsar
burnt remnant
#

can you detect if it is raining? and if so can you detect if a player is currently standing in it

dense skiff
#

Is there a way to get all of the properties on a component? Does JS allow some syntax for this or something?

tiny tartan
#

what is launch_power replacement for projectile shoot?

untold magnet
honest spear
#

👍

west chasm
# burnt remnant can you detect if it is raining? and if so can you detect if a player is current...

Here's an example of how you could do that. Also, keep in mind, the getWeather() method on the Dimension Class is currently in Beta.

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

const overworldDimension = world.getDimension("minecraft:overworld");

system.runInterval(() => {
  const isRaining = overworldDimension.getWeather() === "Rain";

  for (const player of world.getAllPlayers()) {
    const playerDimension = player.dimension;
    const isOverworldDimension = playerDimension.id === overworldDimension.id;

    if (!isOverworldDimension) continue;

    const { x, y, z } = player.location;
    const topMostBlock = playerDimension.getTopmostBlock({ x, z });

    if (!topMostBlock) continue;

    const isStandingInRain = y > topMostBlock.y;

    if (isRaining && isStandingInRain) {
      world.sendMessage(`${player.name} is standing in Rain.`);
    }
  }
}, 0.1);
west chasm
slow walrus
#

that doesn't work lol, runInterval delay is in ticks

#

full ticks

west chasm
#

That does work.

slow walrus
#

yeah it'll do it every 1 tick

#

cause it rounds it

sleek nexus
#

It clearly runs 10 times every tick Omniac

west chasm
west chasm
modest oasis
#

guys whats wrong with my code, does world.runCommand() not valid?

server.system.run(function tick() {
    for (let player of server.world.getPlayers()) {
        managePlayerClanTags(player);
        player.nameTag = handlePlayerName(player);

        if (player.hasTag("tempestKnight")) {
            giveEffect(player, 'strength', 10, 3, true);
            giveEffect(player, 'haste', 10, 1, true);
        } else if (player.hasTag("flameOni")) {
            giveEffect(player, 'fire_resistance', 10, 255, true);
        } else if (player.hasTag("forestSpirit")) {
            giveEffect(player, 'speed', 10, 1, true);
        } else if (player.hasTag("dragonsFang")) {
            giveEffect(player, 'resistance', 10, 6, true);
            giveEffect(player, 'weakness', 10, 1, true);
            
            if (!player.hasTag("hasWings")) {
                player.addTag("hasWings");
                player.runCommandAsync(`replaceitem entity @s slot.armor.chest 0 ewings:demon_0 1 0 {"item_lock":{"mode":"lock_in_slot"},"keep_on_death":{}}`);
            }
        } else {
            if (player.hasTag("hasWings")) {
                player.removeTag("hasWings");
                player.runCommandAsync(`replaceitem entity @s slot.armor.chest 0 air`);
            }
        }
        sidebar(player);
    }


    if (server.system.currentTick % 200 === 0) {
        server.world.sendMessage("sendMessage test");
        server.world.runCommand("say runCommand test");
    }

    // Schedule the next tick
    server.system.run(tick);
});
#

nevermind i resolved it server.world.getDimension('overworld').runCommand()

shy leaf
#

whats the best event for bows

#

itemReleaseUse?

distant tulip
shy leaf
#

whats the difference between release and stop

#

is release for chargeable stuff

distant tulip
#

idk
can the charge be canceled?

shy leaf
#

shrug

burnt remnant
fading sand
#

How do i get the min and max property value of an enum property?

gaunt salmonBOT
shy leaf
#

how can i get the owner of projectile that was shot by player using bow

tiny tartan
shy leaf
#

no i need to give projectile to do smth when hit

#

wait

#

oh

#

nvm i just realized smth

#

nevermind the nevermind

#

i still need to track the owner of the projectile and store functions in there

fiery solar
shy leaf
#

ig thats the only way

#

ty

grave thistle
#

How do I stop world.beforeEvents.playerInteractWithBlock from firing repeatedly? I'm not using the preview, so I can't use isFirstEvent.

fiery solar
# shy leaf ig thats the only way

Are you trying to do a custom enchantment that can be put on a bow, or just do something for all arrows the player fires?

It might be enough to just lookup the owner in the projectileHitEntity or projectileHitBlock afterEvent

shy leaf
#

oh wait
yeah it has source property

grave thistle
#

Be cancelling the block placement using e.cancel

shy leaf
#

hmmm

#

whats the full code

#

gotta see what we can do here

grave thistle
shy leaf
grave thistle
#

Using a ladder on an already placed ladder will extend the ladder down if there is space and a solid block for the ladder to attach to

#

Like reverse scaffolding

green prairie
#

hi, why my json ui don't work on new version

shy leaf
#

hmmmmm

grave thistle
shy leaf
#

yeah

#

this is kinda off limits to me

grave thistle
#

Script works fine atm, still gotta add the item decrement function but that's all sorted ready to be imported. It's just the rapid fire activation that's a problem. Can place enough ladders from build height to bedrock layer in like 5 seconds lol

#

The isFirstEvent property just needs to become available outside of the preview

shy leaf
#

just gotta hope it enters stable

grave thistle
#

Can't see why it shouldn't. It'd fix so many issues with interactions and item usage

tiny tartan
grave thistle
solar dagger
iron jewel
#

** Glide Minigame Flashbacks intensify **

grave thistle
fiery solar
shy leaf
#

can dynamicproperty store function or code?

subtle cove
#

yes...

shy leaf
#

why am i asking this tbh

subtle cove
#

learn abt eval

shy leaf
#

yeah sorry

#

11:04 pm is kicking my brain hard

#

though

#

im scared of using eval

subtle cove
#

mhm...

shy leaf
#

cuz of its nature

#

hmmm i need a workaround

subtle cove
#

well, it depends on what variables are scopeable from where it's used

shy leaf
#

im making custom bow functionalities that can run codes for events like projectileHitEntity and projectileHitBlock

#

but im not sure what to do to store the functionalities into arrow

#

or... i could use Date.now() to sync the arrow and event without storing code into arrow

sleek nexus
#

Wait why? I feel like you might be overcomplicating it

shy leaf
#

could be

sleek nexus
#

I'm heading to bed now, but see if you can take a step back and look at the problem more broadly to try find a simpler solution

shy leaf
#

my brain is optimized at making the most complicated solution lmao

#

but yeah projectiles are kinda funky

sleek nexus
#

Yeah like getting the owner and stuff?

shy leaf
#

yeppers

#

getting the owner is ok

#

the rest of the stuff are kinda headache

sleek nexus
#

Yep nice and easy, you can store it in a dynamic property on the arrow entity (unless they've changed it and it's directly accessible now). What's the other stuff you're trying to do?

#

... What does "custom bow functionalities" from above entail?

shy leaf
#

its not just one bow but a whole collection of bows

#

with abilities? i dunno im just helping with saving an addon from HCF hell

burnt remnant
#

can someone give an example of findClosestBiome

#

my brain is too small to understand the microsoft doc one

shy leaf
#

this should help you understand better

#

Note that the findClosestBiome operation can take some time to complete, so avoid using many of these calls within a particular tick.

#

just in case

sleek nexus
# shy leaf with abilities? i dunno im just helping with saving an addon from HCF hell

Well, if the event for the arrow is predictable/deterministic i.e. The same bow type fired 3 times will always make the projectile do the same thing, you could simply store a kind of id in a dynamic property on the arrow entity, and when it hits something (in the callback event), check the id and run the appropriate block of code / function

shy leaf
#

ah thats much nicer

#

ty

#

now go to bed, ya deserve it

sleek nexus
#

Haha thanks. Yeah I gotta fix my sleep schedule. Goodnight! Let me know if you have any more questions tomorrow.

burnt remnant
#

const { x, y, z } = player.location;
player.dimension.findClosestBiome(x,y,z,"minecraft:plains")

feels so off 😭

shy leaf
#

looks ok to me

#

though uh

#

the pos part should be a vector3

#
player.dimension.findClosestBiome(player.location,"minecraft:plains")```
#

this alone should be ok

burnt remnant
#

hmm okay

#

how would you input an array into it since this doesnt work

player.dimension.findClosestBiome(player.location,${snowBiomeList})```
shy leaf
#

hmmm

#

i feel like this would make the script slow

burnt remnant
#

ooo you should see the other array i have then

#

let rainBiomeList = ["ocean","deep_ocean","lukewarm_ocean","deep_lukewarm_ocean","warm_ocean","deep_warm_ocean","river","beach","cold_ocean","deep_cold_ocean","forest","flower_forest","birch_forest","birch_forest_mutated","roofed_forest","jungle","jungle_edge","bamboo_jungle","mushroom_island","swampland","plains","sunflower_plains","mangrove_swamp","lush_caves","dripstone_caves","deep_dark"]

shy leaf
#

no im saying findClosestBiome is very resource heavy

burnt remnant
#

so executing it every 30 seconds would probably be bad

shy leaf
#

if youre looking for one biome in particular then it should be alright

#

but doing that for each

#

doesnt sound great

burnt remnant
#

just trying to decern that when its raining is the biome im in gonna create snow, and if so, nothing happens, only looking for rain. and when getting the weather, Rain is, rain and snow

shy leaf
#

uh

#

findClosestBiome returns the location of the biome

#

not the type...

burnt remnant
#

what

shy leaf
#

Returns a location of the biome, or undefined if a biome could not be found.```
burnt remnant
#

hmm couldnt i just get that location and detect if the player is standing in it

shy leaf
#

how are you getting the type of the biome the player is standing at

#

(genuinely a question)

#

((i dunno how))

shy leaf
#

im not sure if the script returns the center of the closest biome

#

or the location of the closest biome border

burnt remnant
#

well if this is how you say it is and itll give me the location of the biome, i assume i can compare that ouput with the player's current position and if its the same then idk command fire that says hi for now. but like you are saying right now idk where the number it gives me is, i might have to do a range, if the player is at least 50 blocks close

shy leaf
burnt remnant
#

if its the same logic as the locate command it wont be the center of the biome, i was flying around using it earlier and when in the biome i was firing it and it kept taking me to different spots inside the biome

#

up to 45 blocks away

#

idk this is way out of my league

shrewd wedge
#
e.itemComponentRegistry.registerCustomComponent("evo:voids_edge", {
        onUse(e) {
            const player = e.source;
            const xyz = player.location;
            const dimension = player.dimension;

            player.startItemCooldown("custom", 20);
            player.playSound("mob.enderdragon.flap");
            player.runCommandAsync("particle evo:voids_edge_particle ~~~");

            let nearbyEntities = dimension.getEntities({
                location: xyz,
                maxDistance: 10,
                excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
            });

            nearbyEntities = nearbyEntities.filter(entity => entity !== player);

            nearbyEntities.forEach(entity => {
                entity.runCommandAsync("particle ptg:voids_edge_particle ~~~")
                entity.applyKnockback(xyz.x, xyz.z, 1, 0.3);
            });
        }
    });
#

How to fix apply knock back? I want entity to be pulled to player who use sword

#

But it don't work. Player only go in positive x direct

keen thorn
#

@shrewd wedge

#
e.itemComponentRegistry.registerCustomComponent("evo:voids_edge", {
        onUse(e) {
            const player = e.source;
            const xyz = player.location;
            const dir = player.getRotation();
            const dimension = player.dimension;

            player.startItemCooldown("custom", 20);
            player.playSound("mob.enderdragon.flap");
            player.runCommandAsync("particle evo:voids_edge_particle ~~~");

            let nearbyEntities = dimension.getEntities({
                location: xyz,
                maxDistance: 10,
                excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
            });

            nearbyEntities = nearbyEntities.filter(entity => entity !== player);

            nearbyEntities.forEach(entity => {
                entity.runCommandAsync("particle ptg:voids_edge_particle ~~~")
                entity.applyKnockback(dir.x, dir.y, 1, 0.3);
            });
        }
    });
shrewd wedge
#

hey sorry I habe notification off

#

Thank you

keen thorn
#

dw

shrewd wedge
#

Hey i test and did not work

#

Entitys goes out not pull in, how to make it pull in instead

keen thorn
keen thorn
shrewd wedge
#

Ohh ok

#

ok thank you

devout dune
#

heyyyoo anyone know what im missing here?

Not able to get a translation.

const message: RawMessage = { translate: 'ts_ml.messaging.toggle_falling_stars'};

It is logging as "ts_ml.messaging.toggle_falling_stars"

open urchin
#

remove the spaces around the =

woven loom
#

anyone has an algorithm to detect tree

valid ice
# woven loom anyone has an algorithm to detect tree
for (let x = WORLD_MIN.x; x < WORLD_MAX.x; x++) {
  for (let y = WORLD_MIN.y; y < WORLD_MAX.y; y++) {
    for (let z = WORLD_MIN.z; z < WORLD_MAX.z; z++) {
      const block = world.getDimension('overworld').getBlock({x: x, y: y, z: z})
      if (!block?.isValid()) continue;
      if (block.isTree()) world.sendMessage('Found a tree!');
    }
  }
}
``` ![yessir](https://cdn.discordapp.com/emojis/1141627766220017724.webp?size=128 "yessir")
distant tulip
#

🗿

woven loom
#

wat

neat hound
#

I do... see tree? no, turn around... see tree? no. wait. maybe. yes tree over there....

valid ice
subtle cove
#

yes

grave thistle
#

i.e. the throttle lasts for 5 seconds. Player 1 places a ladder triggering the throttle but then player 2 goes to place a ladder 1 second in to the throttle's duration and it doesn't allow the ladder placement

shy leaf
#

what about storing the duration into player

#

(i actually just found out about throttling so i have no idea)

sudden nest
# valid ice ```js for (let x = WORLD_MIN.x; x < WORLD_MAX.x; x++) { for (let y = WORLD_MIN...

don't forget to use try-catch:

try {
  for (let x = WORLD_MIN.x; x < WORLD_MAX.x; x++) {
    for (let y = WORLD_MIN.y; y < WORLD_MAX.y; y++) {
      for (let z = WORLD_MIN.z; z < WORLD_MAX.z; z++) {
        const block = world.getDimension('overworld').getBlock({x: x, y: y, z: z})
        if (!block?.isValid()) continue;
        if (block.isTree()) world.sendMessage('Found a tree!');
      }
    }
  }
} catch (e) {
  throw "No tree"
}

grave thistle
# shy leaf what about storing the duration into player

I've sorted my problem now thanks to Kira. I've only just learnt about throttling and debouncing and it sounds like a cool way of adding function delays. Not only that, I've only just learnt that functions can be passed as values of a property (still learning js lol, all self taught atm with occasional help from AI when I need something explaining)

sleek nexus
#

Nice! Well done

shy leaf
#

the one im doing rn is very inefficient and i cant redo the code since i dont have access to minecraft rn

odd path
#

Can someone help me resolve a function error? I can't find the problem

shy leaf
#

the owner property in jayly's script docs doesnt mention about return so i was wondering

shy leaf
odd path
shy leaf
odd path
shy leaf
odd path
#

@shy leaf

I just can't find what is causing this bug to happen

function arrestEnemy(player) {
    const entitiesInView = player.getEntitiesFromViewDirection({ maxDistance: 4 })

    if (entitiesInView.length > 0) {
        const nearestEnemy = entitiesInView[0]
        const playerPos = player.location
        const playerRotation = player.getRotation()

        const offsetX = 1.5 * Math.sin((playerRotation.y + 90) * (Math.PI / 180))
        const offsetZ = 1.5 * Math.cos((playerRotation.y + 90) * (Math.PI / 180))
        const newX = playerPos.x + offsetX
        const newZ = playerPos.z + offsetZ
        const newY = playerPos.y

        nearestEnemy.runCommand(`tp @s ${newX} ${newY} ${newZ}`)
    }
}
shy leaf
odd path
#

nearestEnemy gives the error "not a function", but it doesn't make sense

odd path
shy leaf
#

i see the issue

odd path
#

But the problem is not what is inside the command, because when I took it out, it continued with the error

shy leaf
#

since entitiesInView returns an arrary of it, youd need to do forEach or for loop

odd path
#

This doesn't make sense to me, because in another function it doesn't generate errors, but I'll test it

shy leaf
#

try

for (const e of entitiesInView) {
    e.runCommand('say Hello World!');
}```
odd path
#

I will test

shy leaf
#

yeah

true isle
#

Is it possible to cycle through textures for for a block face with permutations that change the texture for a material instance? If that makes any sence

shy leaf
#

very possible

#

with block states

true isle
#

Yeah I tried and I'm not really getting anywhere I even had help with it but idk what I did wrong I have a thing open if anyone could help

mystic mortar
#

I know paddles for sure wouldn't work.

fiery solar
# shy leaf just to make sure, can `.owner` property on projectile component return the owne...

Yeah, owner will contain the owner if there is one (which there will be unless an arrow is spawned directly or fired by a dispenser)

https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/entityprojectilecomponent?view=minecraft-bedrock-stable

You should be able to do it without itemReleaseUse

Contents of the @minecraft/server.EntityProjectileComponent class.

shy leaf
#

now im kinda facing another issue
im storing bow's typeid into projectile's dynamic property to determine which function to fire, but im kinda worried if the dynamic property will be nullified since the projectile would be destroyed upon hit

#

i could use Map for this but i kinda want to preserve it until the projectile dies

deep quiver
shy leaf
#

thats what i did

#

well idk i havent tested it and i might be overthinking but

#

projectiles are wack

deep quiver
#

You can’t really do much if their killed before script api gets them

muted wing
#

i just shat mysel

#

f

shy leaf
shrewd wedge
#

How to remove item stack when use? I try item.amount--; but it say "cannot be less 0 greater 256" in log

#

would using clear command cause error?

deep quiver
shy leaf
#

hmmmm

deep quiver
shrewd wedge
#

But if 0 then I have none?

deep quiver
#

Ye

solar dagger
#

You do setItem(undefined)

#

Something like that

shrewd wedge
shy leaf
#

wouldnt that destroy the whole itemStack

#

unless thats what theyre trying

shrewd wedge
#

No I try to remove by 1 when use,

#

But I have one in hotbar, use and it say cannot be less 0

shy leaf
#

are you using beforeEvents for itemUse?

shrewd wedge
#

No custom component

shy leaf
#

oh

shrewd wedge
#

onUse

shy leaf
#

its hard to tell without checking the code

solar dagger
#

Does anybody know the polar Rotation? I'm trying to setup a custom path for an entity using this. I searched on YouTube, I can't seem to find anything useful for what I'm trying to do

shy leaf
#

can you post the block of the code

shrewd wedge
#
e.itemComponentRegistry.registerCustomComponent("evo:skull", {
        onUse(e) {
            const player = e.source;
            const itemStack = e.itemStack;
            const container = player.getComponent("minecraft:inventory").container;
            player.runCommandAsync("effect @s regeneration 5 1 true");
            player.runCommandAsync("effect @s absorption 5 0 true");
            player.startItemCooldown("skull", 20);
            itemStack.amount--;
            container.setItem(slot, itemStack);
        }
    });
});
shy leaf
#

now i see it

shrewd wedge
#

It say when use: "item amount cannot be less than 0"

shy leaf
#
const item = player.getComponent('equippable')?.getEquipment('Mainhand');```
#

youre trying to get the inventory instead of the item used

shrewd wedge
#

Ohh ok thank you

solar dagger
#

Can't you just use the world event for itemUse?

#

Also you can set effects to the player via addEffect

shrewd wedge
#

Yes

shrewd wedge
solar dagger
#

Literally nothing tbh

#

player.addEffect('conduit_power', 2400, {showParticles: false});

#

It's the same thing

shy leaf
shrewd wedge
#

Oh

#

ok I habe question, if I use clear command, does it clear item you are holding or is random?

solar dagger
#

Doesn't the clear CMD clear your hotbar?

shrewd wedge
#

like if I habe one item in hand, and one in inventory, does it random choose one

shy leaf
#

it clears your entire inventory unless you define which item by amount

shrewd wedge
#

I know if I only clear 1 of the item, then will it be random which it clear?

solar dagger
#

Sorry i haven't touched the cmds in years 😂

shrewd wedge
#

It's ok

shy leaf
shrewd wedge
#

no, sorry hard to explain

shrewd wedge
#

That is what I mean

shy leaf
#

for that? pretty sure it goes in this order

solar dagger
#

If you want to specify the slot you can do something like this

invComp.setItem(slotId, undefined);

shrewd wedge
#

Oh ok

#

Do you habe link to document of this? I don't see in player

solar dagger
#

It's going to be in Entity

#

Get component inventory

#

Something like that

shy leaf
#

use this as slot instead

shrewd wedge
#

Ohh ok. So I do inventory.setItem(heldItem, itemStack--;)

solar dagger
#

Uh no the undefined already removed 1

shy leaf
#

the undefined removes 1??

#

instead of clearing it?

solar dagger
#

I stand corrected

#

It clears the slot apperantly

#

So I'm assuming the whole stack

shrewd wedge
#

???

shy leaf
#

yeah since it reduces itemStack into atoms

shy leaf
shrewd wedge
#

But error was that it said the item amount can not be less 0

#

I was holding one

shy leaf
#

you didnt have slot defined, that could be the issue

shrewd wedge
#

Ok I check, thank you

solar dagger
#

Oh that's true

prisma shard
#
world.afterEvents.itemCompleteUse.subscribe((eventData) => {
    const { itemStack, source } = eventData;
    if (itemStack.typeId === "your item typeid") {
        source.runCommandAsync(`the command you want to execute`);
    };
});```
#

what do you mean by go down????

shrewd wedge
shrewd wedge
unreal cove
#

that or custom components with onConsume works too

prisma shard
prisma shard
#
function decreaseItem(itemStack, decreaseAmount) {
  itemStack.amount -= decreaseAmount;
  return itemStack;
};

  // function usage
  const inv = player.getComponent('inventory').container;
  const newItem = decreaseItem(itemStack, 1); 
  inv.setItem(player.selectedSlotIndex, newItem);
#

@shrewd wedge ^

#

i had a function for decreasing item durability, i just changed it to itemStack.amount

#

i think you wanted to decrease the amount of the item, not the item's durability...right?

#

just change the selectedSlotIndex if you dont want to do this with the hand eqquiped item

#

or wanna do with any inventory item

#

whatever

nimble schooner
#

How to set a block a sign with a specific text content?

sleek nexus
#

That page has a snippet that provides everything you need 👍

shy leaf
#

at least it works perfectly

nimble schooner
nimble schooner
nimble schooner
#

Thank you!

fallow rivet
#

playerInteractWithEntity

#

Is it possible to use this to stop a player from hitting another player?

nimble schooner
nimble schooner
#

As far as I know you can‘t do that, only with editing the player.json

fallow rivet
#
world.afterEvents.playerInteractWithEntity.subscribe(data => {
     const player = data.player;
     const entity = data.entity;

        console.warn('test')
});
#

How can you make this work?

nimble schooner
#

Idk you‘d have to ask someone who has a good overview over the documents

#

It theoretically makes sense but I don‘t know how entity and player are called in that case

nimble schooner
shy leaf
#

you can prevent damage using entity json but you cant cancel the attack

nimble schooner
#

Yeah

#

I tried to use that beforeEvent

#

But it doesn‘t cancel attack on cancel

shy leaf
#

playerInteractWithEntity is for right clicking so

nimble schooner
#

On mobile it‘s long clicking lol

fallow rivet
#

Why is this happening?

shy leaf
#

can you tell the issue

fallow rivet
#

Shouldn't it be running in 11 to 11 position?

nimble schooner
#

Do you use Android?

shy leaf
fallow rivet
nimble schooner
shy leaf
#

rip

fallow rivet
#

The phone I use has a side window feature.

#

Thanks to this I do it

fallow rivet
shy leaf
#

iphone isnt advanced tbh

nimble schooner
#

Well, it‘s faster than my Android

#

And it doesn‘t run out that fast

shy leaf
#

but coding in iOS does not go well

#

at all

nimble schooner
#

Yeah

#

Code Editor exists too

shy leaf
#

to be fair coding in mobile is frustrating but

#

all the iphone's """policy""" makes everything harder (at least in my eyes)

nimble schooner
#

I‘ve never coded on a pc

#

So for me it‘s life

#

🫠

shy leaf
#

though i do recommend getting a phone with high ram if youre getting one someday

#

so that you dont go insane

fallow rivet
fallow rivet
#

It should work in 11 to 11 coordinates but it doesn't.

summer walrus
#

try diff operators like !== or === instead of <= or >= and why are the coords duplicated

nimble schooner
#

How do I system.clearRunInterval();?

shy leaf
#

system.runInterval() returns a unique id so that you can use it

const interval = system.runInterval(() => {
    //code
});
system.clearRun(interval)```
nimble schooner
shy leaf
#

not sure if you can do that

#

keyword: not sure

#

i havent tested it

slow walrus
#

block positions are measured from the NW corner iirc

slow walrus
slow walrus
nimble schooner
#

Can the player leave before event cancel player leave?

#

Is there a player death after event?

shy leaf
nimble schooner
#

Is there a way to cancel a system.runTimeout?

shy leaf
shy leaf
slow walrus
glacial widget
#

is there a way to face a player when using the .teleport notation?

wheat condor
plush moss
#
spawnEntitiesInArea([startX, startY, startZ], [endX, endY, endZ], entitiesToSpawn, entityType);

is it posible to spawn the entity only as an adult?

glacial widget
#
player.teleport({ x: -315, y: 138, z: 36 }, 
            {
               facingLocation: targetLocationShop
            }
          );
#

however thank you

steady zinc
#

What's the difference between system.run() and system.runJob() ?

honest spear
steady zinc
#

Generator? Never heard of that xD

honest spear
steady zinc
#

I don't know that either

honest spear
#

¯_(ツ)_/¯

#

I think you don't need to know then

woven loom
#

@beta no more returns preview exp?

honest spear
woven loom
#

hm

tight plume
#

How do i get the location the entity is facing because im trying to recreate the random sheep eating grass then turning it into dirt.
I cant trust this code so much since the location could be on the side of the entity which doesn't make sense at all:

const blockEaten = dim.getBlock({
  x: entity.location.x,
  y: entity.location.y - 1,
  z: entity.location.z + 1
});
blockEaten.setPermutation(
  BlockPermutation.resolve('minecraft:dirt')
);
distant gulch
#

getPlayers is only get online player?

subtle cove
#

same with getAllPlayers, yes

distant gulch
#

cant get offline player?

subtle cove
#

no

#

do u need the name or scoreboard, or something else?

shy leaf
#

it doesnt consider lan players??

celest fable
#

is it possible to do multi threading?

subtle cove
shy leaf
#

oh

#

i had a brainfard for a second

#

i took offline as internet offline

#

☠️

distant gulch
#

but how can i get just player not name, id or something

shy leaf
#

would you like to go to dms? i can speak korean

subtle cove
#

if the player isnt offline, then its not possible to get the Player.prototype

#

but its possible to manage its ScoreboardIdentity

honest spear
#

Ya, there is no native instance for offline players, only accessible are scoreboards that are linked to entities and players
||Player.prototype is always accessible||

distant gulch
#

ty

celest fable
#

btw how do you make add method player.tell? like override the player and add method tell that basically sendMessage but with prefix

honest spear
shy leaf
#

time to have some headache

shy leaf
#

it did get the object normally

#

but now it just refuses?

remote oyster
shy leaf
#

ah yes

#

time to dive into

#

hundreds of lines of code...

remote oyster
#

Lol

sharp elbow
#

Always name your functions. Then it becomes easier to debug.

shy leaf
#

well i did

#

but

shy leaf
#

it just tells me "hey im not getting this data"

#

"over there"

sharp elbow
#

The stack trace is relatively short, so it should be easy to find a start

shy leaf
#

i ask "why", they reply with " "

sharp elbow
#

What is the anonymous function at ItemsFunctionalities/itemHandler.js on line 186? I'm betting it is an event subscription

cold grove
shy leaf
#

no parse is used

#

i dunno why cuz the event gives an object

#

and sends the object to other scripts

#

but it doesnt convert?... object

sharp elbow
#

You are sending the event object to other functions? Minecraft could be garbage collecting it before it can be used

#

Maybe it could be worthwhile making a shallow copy of the event object. Something like (e) => {const event = {...e};}

shy leaf
#

gotcha

#

i think garbage collecting is the issue here, this started once i added some codes for bows

honest spear
sharp elbow
#

No longer? I'm curious, when did that change

honest spear
#

maybe more but not sure

sharp elbow
#

Long enough that I am a bit silly for not having noticed lol

honest spear
#

@sharp elbow Not sure which update it was but this is the date of my notice
07/12/2023

#

lmao

sharp elbow
#

Ah, so about a year ago 😆

honest spear
#

yes

shy leaf
#

BUG SQUASHED

#

my statics were like

static weapon(id,eventData)```

but i forgot it was supposed to be
```js
static weapon(eventData,id)```
#

the object was kept sending to id part

granite badger
#

Stats (using the api)

wary edge
shy leaf
#

yeah

#

imma redo the code

#

id, data looks better in eyes

nimble schooner
granite badger
#

I made that

nimble schooner
#

I mean how to get the player stats

#

Those which you can view on player‘s profile

#

Or are the shown stats for your world only and counted by your system?

subtle cove
#

If its on scoreboard, then world
if dynamic property, then pack

slow walrus
#

I did not know that lmao

subtle cove
#

regardless of pack version

#

but i havent tried working two packs same uuid, but diff ver

slow walrus
#

in that case, global dynamic props would be hella nice

valid ice
#

I did it by accident the other night, and it said I applied one pack but it was actually the other one

subtle cove
#

it chooses the higher version?

valid ice
#

Both had the same version

#

I just copied over one of my packs in its entirety, removed a bunch of stuff & changed the pack name (But forgot to change the UUIDs), and said it added the new pack to the world, but all the stuff in-game was the old pack stuff.

slow walrus
#

iirc each world caches it's packs so if the version wasn't different, then it wouldn't have updated it

valid ice
#

It was a dev pack, however- and I deleted all the world BP json files & the folder for the BP.

slow walrus
#

pack path was probably still pointing to the old one

buoyant canopy
#

i wonder if an addon can access the dynamic properties of another addon?

wary edge
#

No

wanton ocean
#

No..

#

My life is ruined

buoyant canopy
#

interesting, so i don't have to worry about my addons interfering with other addons of the dp share the same name

buoyant canopy
#

that's... convenient

fallow rivet
#

I am making a claim system and I am thinking of using dynamicproperty to save the data.

#

Do you have any other advice?

valid ice
#

That works

sage portal
#

is there any event to detect when an entity shoots a projectile?

sage portal
subtle cove
#

projectile have owner property in its "projectile" component

sage portal
#

I feel like there should be a shorter route to reach this, but that sounds like it'll work, thanks.

gaunt salmonBOT
wary edge
#

@jaunty relicPlease use #debug-playground

grave thistle
#

I have a function that scans the player's hotbar for an item. How do I check if that item is a block? I'm using if (hotbarItem instanceof Block) { but it's not working

#

Is it because even though it's a block, it's still technically an item since it's in my inventory

winter plaza
#

help

#
mc.world.afterEvents.itemCompleteUse.subscribe((eventData) => {
    const { itemStack, source } = eventData;
    if (itemStack.typeId === "your item typeid") {
        source.runCommandAsync(`the command you want to execute`);
    };
});
valid ice
#

What are your imports? And did you swap the your item typeid & the command you want to execute parts for your own usage?

winter plaza
#

yes I changed

wheat condor
winter plaza
#

says it doesn't exist

valid ice
#

Can you show the actual code you are running in-game, then?

winter plaza
#

yes

#

wait a few minutes

wheat condor
shrewd wedge
#

How to make apply knock back go in direction of person who use sword

wheat condor
valid ice
#

get the user's view direction and apply that to the knockback amounts

shrewd wedge
#

Closer. So when player use sword it pull in player and entities

shrewd wedge
valid ice
#

wdym?

#

Oh, use sword, not hit with sword

shrewd wedge
#

So when player uses the sword, I want to have it pull nearby entity towards who used

#

When I use direction sometimes entity pull in wrong direction

valid ice
#

In that case, you'd need to get the x & z (and maybe y) vector between the two entities

shrewd wedge
#

I try and do player.location and use apply knock back to player who use sword x and z but it not work?

winter plaza
#

Sorry, it worked, it was another script that was giving conflict and saying it didn't exist

#

more thanks too

valid ice
# shrewd wedge How?
    const dx = otherEntity.location.x - source.location.x;
    const dy = otherEntity.location.y - source.location.y;
    const dz = otherEntity.location.z - source.location.z;
    const magnitude = Math.hypot(dx, dy, dz);
    otherEntity.applyKnockback(dx / magnitude, dz / magnitude, 1, 1);``` maybe something like the this
shrewd wedge
#

Thank you! Sorry am not good at math haha

#

I try

valid ice
#

You may need to swap the two locations- can't recall if source or otherEntity should be first.

#

(can also just chuck a negative in front of the dx & dz in the applyKnockback part too)

wheat condor
#
const kb = {};
Object.keys(player.getViewDirection()).forEach(key => {
    kb[key] = -player.getViewDirection()[key];
})
HitEntity.applyKnockback(kb.x , kb.z , 1 , kb.y)
wheat condor
valid ice
#

Wouldn't it be better to use Object.entries() instead of recalling the getViewDirection method for every direction?

shrewd wedge
#
e.itemComponentRegistry.registerCustomComponent("evo:voids_edge", {
        onUse(e) {
            const player = e.source;
            const xyz = player.location;
            const dir = player.getViewDirection();
            const dimension = player.dimension;

            player.startItemCooldown("custom", 20);
            player.playSound("mob.enderdragon.flap");
            player.runCommandAsync("particle evo:voids_edge_particle ~~~");

            let nearbyEntities = dimension.getEntities({
                location: xyz,
                maxDistance: 10,
                excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
            });

            nearbyEntities = nearbyEntities.filter(entity => entity !== player);

            nearbyEntities.forEach(entity => {
    	    const dx = entity.location.x - xyz.x;
            const dy = entity.location.y - xyz.y;
            const dz = entity.location.z - xyz.z;
            const magnitude = Math.hypot(dx, dy, dz);
            entity.applyKnockback(dx / magnitude, dz / magnitude, 1, 1); 
            
                entity.runCommandAsync("particle evo:voids_edge_particle ~~~")
            });
        }
    }); 
#

Ok this pull nearby entity?

valid ice
#

try it and see shrug

shrewd wedge
#

Ok

sage portal
#

Is there something I don't know about the percent symbol here? In any other situation, the % will work just fine, but no matter how I try to format it here, the symbol just... doesn't show up.

announced.sendMessage(`Health: ${health + "%"}`)
announced.sendMessage(`Health: ${health} + "%"`)```
valid ice
#

Try double percent symbol

#

Single is used for translation keys in certain strings, and the way the game parses it is a bit goofy

#

It's my pet peeve that single percent shows up on the item name in the inventory, but it does not in the item name when held- the one above the hotbar

wheat condor
valid ice
#

ye

wise raft
#

How can I do something if a Player uses an Item for x seconds?

shrewd wedge
#

Hey, is not work

sage portal
shrewd wedge
#

It pull entity away and up not towards

sage portal
wheat condor
shrewd wedge
#

But if player who use sword is not looking at player who got pulled, player gets pulled in other direction

wheat condor
shrewd wedge
#

It is not when hit

#

Ability used when click item

#

Custom component

wheat condor
#

🤦‍♂️🤦‍♂️

#

Wait a sec

shrewd wedge
#

It supposed to pull every entity 10 blocks towards the xyz of player who use sword but everything I try does not work

#

I don't know what I'm doing wrong, the code I use just pull entity up and away not close

wheat condor
#

This should work

fallow rivet
#
system.runInterval(()=>{
world.getPlayers().forEach(player=>{
const test1 = (player.location.x <= 13 && player.location.x >= -13) && (player.location.z <= 13 && player.location.z >= -13)
 
player.runCommand(`title @s actionbar ${test1}`)
    
})});

Shouldn't it work when x is 13 and z is 13?

chilly moth
#
import { ActionFormData } from "@minecraft/server-ui"

function Ui(player) {
const ui = new ActionFormData()
    .title("Form")
    .body("")
    .button("button1")
    .button("button2")
    .button("button3");
form.show(player).then((r) => {
    if (r.selection === 0){
         player.runCommandAsync('say a')
    }
    
}
    )
};

function CustomUi(player) {
const customUi = new ActionFormData()
    .title("Custom Form")
    .body("")
    .button("Rewards", "textures/ui/promo_holiday_gift_small")
    .button("Shop", "textures/ui/icon_deals")
    .button("Ban Tool", "textures/ui/hammer_l")
    .button("Skins", "textures/ui/icon_hangar")
    .button("Skins", "textures/ui/icon_hangar")
    .button("Skins", "textures/ui/icon_hangar")
    .button("Skins", "textures/ui/icon_hangar")
    .button("Skins", "textures/ui/icon_hangar")
    .button("Skins", "textures/ui/icon_hangar")
form.show(player).then((r) => {
    if (r.selection === 0) {
      Ui(player);
    }
  });
};

world.afterEvents.itemUse.subscribe(async (event) => {
    const { source, itemStack } = event
    switch (itemStack.typeId) {
        case "minecraft:compass": ui.show(source); break;
        case "minecraft:clock": {
            const res = await customUi.show(source);
            res.selection //This Is Number Will Be Derived From The "collection_index" property of a button in JSON UI
            world.sendMessage(`Button ${res.selection} Has Been Pressed!`)
            break
        };
    }
})```

why am I getting a reference error
gray tinsel
wheat condor
chilly moth
#

hm

gray tinsel
#

just to help avoid it getting lost mostly

#

also provide the script error

#

as in the raw error from logs

cold grove
#

Ah i see..

#

You are referencing multiple times unexistant variables

chilly moth
#

[Scripting][error]-Unhandled promise rejection: ReferenceError: 'customUi' is not defined

[Scripting][error]-Unhandled promise rejection: ReferenceError: 'ui' is not defined

#

@cold grove

cold grove
#
const ui = new ActionFormData();
//...
form.show(); // 'form'??? Where??

This is what are you doing rn

chilly moth
#

uh

#

let me try

cold grove
#

Also, you cant use local variables outside his function

remote oyster
#
import { world } from "@minecraft/server";
import { ActionFormData } from "@minecraft/server-ui";

function Ui(player) {
    const ui = new ActionFormData()
        .title("Form")
        .body("")
        .button("button1")
        .button("button2")
        .button("button3");

    ui.show(player).then((r) => { // Use 'ui' here instead of 'form'
        if (r.canceled) return;
        if (r.selection === 0) {
            player.runCommandAsync('say a');
        }
    });
}

function CustomUi(player) {
    const customUi = new ActionFormData()
        .title("Custom Form")
        .body("")
        .button("Rewards", "textures/ui/promo_holiday_gift_small")
        .button("Shop", "textures/ui/icon_deals")
        .button("Ban Tool", "textures/ui/hammer_l")
        .button("Skins", "textures/ui/icon_hangar")
        .button("Skins", "textures/ui/icon_hangar")
        .button("Skins", "textures/ui/icon_hangar")
        .button("Skins", "textures/ui/icon_hangar")
        .button("Skins", "textures/ui/icon_hangar")
        .button("Skins", "textures/ui/icon_hangar");

    customUi.show(player).then((r) => { // Use 'customUi' here instead of 'form'
        if (r.canceled) return;
        if (r.selection === 0) {
            Ui(player);
        }
        return r.selection; // Return the selected button index
    });
}

world.afterEvents.itemUse.subscribe(async (event) => {
    const { source, itemStack } = event;
    switch (itemStack.typeId) {
        case "minecraft:compass":
            Ui(source); // Changed from 'ui.show(source)' to 'Ui(source)'
            break;
        case "minecraft:clock": {
            const res = await CustomUi(source); // Changed from 'customUi.show(source)' to 'await CustomUi(source)'
            world.sendMessage(`Button ${res} Has Been Pressed!`);
            break;
        }
    }
});
chilly moth
valid ice
#

You can do if (r.canceled) return;

#

so if the form was canceled (e.g. no button selected but still closed) it'll just stop the code

chilly moth
#

where in actually?

valid ice
#
.show(player).then(r => {
if (r.canceled) return;
...
chilly moth
#

ok

remote oyster
#

Both form functions would need that.

#

I didn't include it since I didn't know what your plan was going forward.

chilly moth
#

ui.show(player).then((r) => {

if (r.canceled) return;
// Use 'ui' here instead of 'form'
if (r.selection === 0) {
player.runCommandAsync('say a');
}
});
}

#

ok

valid ice
#

hol up

#

why is it selection of undefined

remote oyster
#

I edited my response to include it

valid ice
#

does that not imply that r is undefined?

west chasm
# valid ice why is it `selection of undefined`

The reason for that is this section of code. The CustomUi function doesn't return anything.

        case "minecraft:clock": {
            const res = await CustomUi(source); // Changed from 'customUi.show(source)' to 'await CustomUi(source)'
            world.sendMessage(`Button ${res.selection} Has Been Pressed!`);
            break;
        }
remote oyster
#

That's a valid point

valid ice
#

ohh that's the problem section

west chasm
remote oyster
#

The custom UI function is incomplete anyways, so when they add more functionality to it then they can have it return as needed.

#

I modified the above to return r.selection to appease the res call in sendMessage

glacial widget
#

is there a way to add a cooldown for itemUse ?

shy leaf
glacial widget
shy leaf
#

similar to ender pearls?

glacial widget
# shy leaf similar to ender pearls?
world.afterEvents.itemCompleteUse.subscribe((r) =>{
    const {source:player, itemStack:item, useDuration:time} = r
    switch(item.typeId){
        case "minecraft:ender_pearl":
            time = 1000

        break;

        case "minecraft:enchanted_golden_apple":

        break;
    }
})
#

yh pretty much what am tryna do

shy leaf
#

isnt useDuration in ticks? let me check

glacial widget
#

ItemStack#starCooldown ?

cold grove
#

Wait hehe

#

1st check if item its in cooldow
ItemCooldownComponent#getCooldownTicksRemaining

Run and set cooldown
ItemCooldownComponent#startCooldown

shy leaf
shy leaf
#

yeah

glacial widget
shy leaf
#

nah

cold grove
shy leaf
#

getting 'cooldown' component from itemStack can do

distant tulip
#

not all items have a cooldown

shy leaf
#

yeah

#

if youre trying to make a custom cooldown via scripts, try using this

distant tulip
#

something like this can work

    if(player["coolDown"] > Date.now()) return;
    player["coolDown"] = Date.now() + 1000;
cold grove
# glacial widget should they be imported?

const cd = <ItemStack>.getComponent(ItemComponentTypes.Cooldown);

if (cd.getCooldownTicksRemaining(<player>) > 0)  return;

// Do item action

cd.startCooldown(<player>);

cold grove
shy leaf
#

whats the best way to deal with error thats thrown for executing code outside the loaded area

#

its not a big deal but the error kinda bothers me

muted wing
#

yo

#

do yall know how to call a function and have it continue even if it errors?

shy leaf
muted wing
#

im just wondering

cold grove
#

thats a bad practice... but, use try {} catch () {}

shy leaf
muted wing
#

cath

cold grove
#

mb

muted wing
distant tulip
distant tulip
#

Lol

muted wing
#

it wont continue

#

even if it errors

shy leaf
#

thats

#

something else

muted wing
#

oh

cold grove
distant tulip
#

1000 is the cooldown in ms

grave thistle
#

Is there a way to check if a held item is a block?

west chasm
shy leaf
#

how can i get the itemStack from equippable component it if the item breaks or runs out

#

cuz it returns undefined

#

i feel like i had a workaround but i kinda forgot

#

maybe i could add a beforeEvent itemUse to store the item and then give it to functions

cold grove
shy leaf
#

hmm i cant really use runInterval

cold grove
#

Huh

shy leaf
#

yeah

fiery solar
#

You could create a property lastItemType and update it any time you read the itemType for a slot

shy leaf
#

beforeEvents time

stoic ocean
#

guyy is there anyone know if i use tp command with location is ^^^0.3 so how it looklike in scripts . i meant how location like that look like in scripts
player.teleport({?})

granite badger
stoic ocean
#

.-. ukmmmmm

chilly fractal
#

Yo anyone know how to get the block placed?

#

(In the playerPlaceBlock beforeEvent)

#

I haven't touched scripting api in a while and I'm back, lots of cool things are here

#

But seems they haven't really added a method to get the block being placed

valid ice
#

permutationBeingPlaced

chilly fractal
#

The location

#

You gave me this script in 1.12.0-beta if I recall correctly

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

const faceOffset = new Map([
  [Direction.East, { x: 1, y: 0, z: 0 }], [Direction.West, { x: -1, y: 0, z: 0 }],
  [Direction.Up, { x: 0, y: 1, z: 0 }], [Direction.Down, { x: 0, y: -1, z: 0 }],
  [Direction.South, { x: 0, y: 0, z: 1 }], [Direction.North, { x: 0, y: 0, z: -1 }],
]);

world.beforeEvents.playerPlaceBlock.subscribe((data) => {
  let { player, block, face, permutationToPlace, dimension } = data, item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
  let offset = faceOffset.get(face);
  let newLocation = { x: block.location.x - offset.x, y: block.location.y - offset.y, z: block.location.z - offset.z}; // new block, but doesn't  work
});

I edited it a bit

#

So here's what I'm tryna do, I'm tryna something like the pc block picking up, when u shift break a block in creative it actually makes a random id and saves the structure name as the ID and puts the ID in the items lore, and yes I tested it, the saving part is fine I can load it using /structure load but, it doesn't seem to override the block I am placing.

#

Here's the full script:

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

const faceOffset = new Map([
  [Direction.East, { x: 1, y: 0, z: 0 }], [Direction.West, { x: -1, y: 0, z: 0 }],
  [Direction.Up, { x: 0, y: 1, z: 0 }], [Direction.Down, { x: 0, y: -1, z: 0 }],
  [Direction.South, { x: 0, y: 0, z: 1 }], [Direction.North, { x: 0, y: 0, z: -1 }],
]);

world.beforeEvents.playerPlaceBlock.subscribe((data) => {
  let { player, block, face, permutationToPlace, dimension } = data, item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
  if (!item || !item.getLore()[0] || !item.getLore()[0].startsWith('ID: ')) return;
  let offset = faceOffset.get(face);
  let newLocation = { x: block.location.x - offset.x, y: block.location.y - offset.y, z: block.location.z - offset.z};
  system.runTimeout(() => {
    let itemID = item.getLore()[0].split(' ')[1];
    player.dimension.runCommandAsync(`structure load ${itemID} ${Object.values(newLocation).reverse().join(' ')}`);
    player.dimension.runCommandAsync(`structure delete ${itemID}`);
  }, 2);
});
valid ice
#

permutationToPlace should be permutationBeingPlaced, no?

chilly fractal
#

Nah doesn't throw error

#

But sure I'll change it

valid ice
#

You aren't using it regardless, so it won't throw an error

chilly fractal
#

I didn't use it nor put it their but I decided not to mess with your script and just edit My part.

valid ice
#

Also they fixed the issue with the block in the events being the one you're placing on- no need to get the offset now, you can just use the block property from the event 👍

chilly fractal
#

So block is the block being placed?

#

(Rn)?

#

Bet

valid ice
#

Ye

#

Didn’t used to be, but it is now

chilly fractal
#

Moyang finally be putting in 50 hours a week

valid ice
#

Always have

#

That’s been changed since like, 1.21.0

chilly fractal
#

Bruh it still ain't working

#

It's still putting in the item I'm holding's block and not being overrided by the structure

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

world.beforeEvents.playerPlaceBlock.subscribe((data) => {
  let { player, block, face, dimension } = data, item = player.getComponent('inventory').container.getItem(player.selectedSlotIndex);
  if (!item || !item.getLore()[0] || !item.getLore()[0].startsWith('ID: ')) return;
  system.runTimeout(() => {
    let itemID = item.getLore()[0].split(' ')[1];
    player.dimension.runCommandAsync(`structure load ${itemID} ${Object.values(block.location).reverse().join(' ')}`);
    player.dimension.runCommandAsync(`structure delete ${itemID}`);
  }, 2);
});
#

What's possibly wrong with this script???

#

#debug-playground message

#

Complier says absolutely no problems and even for extra measures I fixed the ts thing of typing face & dimension and never using them

#

Am I supposed to use afterEvent?.. I'll use it

granite badger
#

I think you need to cancel the before event

chilly fractal
#

Really?

#

Ok

#

Doesn't work, I'll test it in a different way in a sec, I gtg rn

wheat condor
deep plank
#

Is it just me, the tameable component returns undefined in vanilla entities that can be tamed. But works perfectly on custom entities that can be tamed.

amber granite
#

._.

#

Hailo

chilly fractal
chilly fractal
#

Ima use after event

#

Maybe it'll work

wheat condor
chilly fractal
#

It works lol, not cuz of deleting the reverse. It's cuz it deletes the structure with the placing so if there is a problem with the placing the structure would get deleted anyway and so it never got deleted so I made it send a message before the if (!item || !item.... and after and the after didn't work and so I instantly knew it was a problem with the if statement and I realized the whole problem was with the || !item.getLore()[0].startsWith('ID: ') return; cuz it was supposed to be '§r§5ID: ' not 'ID: '

#

Anyway thanks for the help yall

#

Especially herobrine

craggy crater
#

How would I make it so when I put on a specific armor piece/set it would make my gamertag go away

wheat condor
craggy crater
#

Make it to where it's no longer visible

wheat condor
#

you can just give the player invisibility

#

to stop showing it

craggy crater
#

Ok

#

Then how do I make it so where when wearing a specific piece of armor walking it's like sprinting but only when they're sneaking if that makes any sense

wintry valve
wintry valve
craggy crater
#

Ooo

#

I'm actually also in that discord so maybe I'll message them

cinder shadow
#

when you set "nametag" to "" 😔

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

// Function to update player's name tag visibility
function updateNameTagVisibility(player) {
    const inventory = player.getComponent("inventory").container;
    const helmetSlot = inventory.getItem(103); // Slot 103 is the helmet slot

    if (helmetSlot && helmetSlot.typeId === "minecraft:iron_helmet") {
        // Player is wearing an iron helmet, hide the name tag
        player.nameTag = "";
    } else {
        // Player is not wearing an iron helmet, show the name tag
        player.nameTag = player.name;
    }
}

// Run the check periodically
system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        updateNameTagVisibility(player);
    }
}, 20); // Check every second (20 ticks)

// Listen for item equip events to update immediately when helmet is equipped/unequipped
world.afterEvents.itemUseOn.subscribe((event) => {
    const player = event.source;
    if (player.typeId === "minecraft:player") {
        system.run(() => updateNameTagVisibility(player));
    }
});
shy leaf
#

ya

#

no

wintry valve
#

so this should work?

shy leaf
#

not that

wintry valve
#

oh-

shy leaf
#

well youd still need that i think

#

maybe

#

but it would require editing player.json

cinder shadow
#

no?

shy leaf
#

no???

#

what kind of sorcery did r4isen do

cinder shadow
shy leaf
#

holy

cinder shadow
#

Why would you need to edit player.json

shy leaf
#

i

#

wait you can just

#

edit the nametag right away?

#

huuuh

cinder shadow
#

nametag isn't a component

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

// Function to update player's name tag visibility
function updateNameTagVisibility(player) {
    const inventory = player.getComponent("inventory").container;
    const helmetSlot = inventory.getItem(103); // Slot 103 is the helmet slot

    if (helmetSlot && helmetSlot.typeId === "minecraft:iron_helmet") {
        // Player is wearing an iron helmet, hide the name tag
        player.nameTag = "";
    } else {
        // Player is not wearing an iron helmet, show the name tag
        player.nameTag = player.name;
    }
}

// Run the check periodically
system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        updateNameTagVisibility(player);
    }
}, 20); // Check every second (20 ticks)

// Listen for item equip events to update immediately when helmet is equipped/unequipped
world.afterEvents.itemUseOn.subscribe((event) => {
    const player = event.source;
    if (player.typeId === "minecraft:player") {
        system.run(() => updateNameTagVisibility(player));
    }
});
craggy crater
#

Ok ty

wintry valve
craggy crater
#

Ya

wintry valve
craggy crater
#

Ok

wintry valve
#

maybe like increase the speed of a player while theyre sneaking?

#

so when they walk they go faster?

craggy crater
#

How would I do that

wintry valve
#

I have no idea

#

or maybe i do wait

wintry valve
# craggy crater How would I do that
import { world, Player, TicksPerSecond } from "@minecraft/server";

const sprintSpeed = 0.3; // Sprinting speed
const normalSpeed = 0.1; // Walking speed

world.events.tick.subscribe(() => {
    for (const player of world.getPlayers()) {
        if (player.isSneaking) {
            player.setMovementSpeed(sprintSpeed); // Set speed to sprinting speed when sneaking
        } else {
            player.setMovementSpeed(normalSpeed); // Reset to normal speed when not sneaking
        }
    }
});
#

just check if this works

#

this is generated by chatgpt so i highly doubt if it works

fallow rivet
#

How can I spawn a particle between 10 0 10 and 10 0 15 with spawn particle?

warm acorn
#

there any way to route a player empty hand block interact to script yet in stable apis? i see block has an on_interact but not seeing a way to route it to a script with a coordinate etc

#

oh custom components that you register via script api, interesting

valid ice
#

tick event did exist at one point in time, so it's not inaccurate, just... behind the times.

honest spear
wintry valve
#

that thing is a menace

wheat condor
wintry valve
wheat condor
wheat condor
honest spear
#

wow, thats cool

wintry valve
#

oh wow thats actually kinda impressive

valid ice
#

chat GPT is good if you feed it the npm types and can spend time correcting its mistakes

wheat condor
cinder shadow
#

I yoted my code in there yesterday and just asked it to optimize it

#

All it really did was make const variables for things I'm calculating several times

#

and then replace block.above(1) with block.location.y + 1

valid ice
#

wild

north rapids
#

Does the script run every game tick or every millisecond?

cinder shadow
#

it's every tick

#

now if you just slapped a while(true) {} in your code, that will run as fast as possible and crash your game

north rapids
#

Lol

#

So one second would be 20 ticks right?

cinder shadow
#

yes

north rapids
#

Ok tysm

valid ice
#

e.g. if you break 50 blocks in one second, block break would then fire 50 times

prisma shard
#

does clearVelocity work on players

unique dragon
#

nah

prisma shard
#

oho

#

bruh momentt

unique dragon
#

try with knockback

#

or use inputpermission

prisma shard
#

inputpermissiion?

#

what is that

unique dragon
#

if it's that you want

woven loom
valid ice
#

Al Gore Rhythms!!?!!???!!

solar dagger
#

Any good method of resuming a custom path system after the player joins the world again?

fast wind
honest spear
wary edge
fast wind
#

yes

honest spear
#

any errors?

#

Oh i see

fast wind
#

The player.getComponent('minecraft:inventory').container.getItem(player.selectedSlotIndex).getDynamicProperty('balance') is just to replace item because it didn't seem to work

honest spear
#

you have to save that item back, bc itemstack is abstract instance

#

basicly do this steps

  • getItem
  • set properties
  • put item back
fast wind
#

Oh

#

Thanks

#

So wait do I do the .getItem on the player's hand?

#

nvm I fixed it

slim spear
#

Did you ever get it to work? i'm having issues

hushed ravine
#

It's a library you have to bundle in your script

slim spear
#

do i have to import another module?

slim spear
#

i don't use other scripts often, just mainly @minecraft/server and ui

hushed ravine
slim spear
#

i installed the npm stuff for it

#

that's all i've done so far

hushed ravine
#

Unlike the other @minecraft libraries, @minecraft/math doesn't just contain types. It also contains actual scripts inside of it

honest spear
hushed ravine
honest spear
#

¯_(ツ)_/¯

#

but ya

hushed ravine
honest spear
hushed ravine
honest spear
#

thats the different and also reason why you can't import it by default

#

it doesn't exist in MC

woven loom
#

thats utility pkg

hushed ravine
#

Yeah, I know that

#

If I want to use an NPM package, I have to bundle it along with my scripts

woven loom
#

it provides util funcs to use

slim spear
#

i was js needing it for the distance calculations

hushed ravine
slim spear
#

ah

#

makes since

subtle cove
#

||ChatGPT translators|| 3348vinnypain

shy leaf
#

||its just that some people depend way too much on it like how they leave their assignment to AIs||

deep garden
#

This is true, chatgpt has helped my understanding of JavaScript a lot, but it does get some stuff wrong though. That being said, its usually easy to pick out what is wrong

cinder shadow
#

I've been using chat GPT to help me with a few concepts

true isle
#

can anyone tell me whats wrong with this. its just supposed to change the permutation by using an item and its not changeing it at all

true isle
gaunt salmonBOT
#

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 0 errors.

Lint Result

ESLint results:

shades.js

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

true isle
#

shit oops

shut citrus
#

Hi script team, any plan to add cancel these events:
~onAttack
~onBucket
~onDamaged
~onDeath
~onTriggered
~onExplode
~onInteract
~onTargeted
~onTeleport
~onShoot
~onCameraSet
~onItemUse
~onConsume

worn sphinx
#

Is there a way that when you press any button the amount will show and increase when you press the second button the amount will increase? Does anyone know how?

Code:

function openForm2(player, tien, values = []) {
    let text = ''
    const form = new ActionFormData();
    form.title("§m§i§n§e§fMINES")
    form.body(`${tien}`)
    
    for (let i = 0; i < 25; i++) {
        if (!values[i]) values[i] = "gray";
        if (!values[i]) text = "???";
    }
    values.forEach((value) => { 
        form.button(text, `textures/blocks/glass_${value}`)
    })
    form.button("§c§l§a§mAbc")
    form.show(player).then(rs => {
        if (rs.selection <= 24) {
            if(abc[rs.selection] == "O") {
                win++
                if (win === countO) {
                  player.sendMessage(`Bạn đã win`)
                  ResetOX()
                } else {
                    values[rs.selection] = "green"
                    openForm2(player, values)
                }
            } else {
                player.sendMessage(`Lose\n\n${result}`)
                ResetOX()
            }
        }
    })
}
wheat condor
worn sphinx
#

Yea

wheat condor
worn sphinx
#

I want it to increase the amount when the button is pressed

wheat condor
#

and what amount you want to increase?

worn sphinx
wheat condor
worn sphinx
wheat condor
worn sphinx
wheat condor
worn sphinx
prisma shard
#

is that what you mean

worn sphinx
#

That's right

prisma shard
#

ded

shy leaf
slim spear
#

bruh these docs are outdated

#

blockTypeRegistery => blockComponentRegistry

remote oyster
cinder shadow
#

can you... add colors?

#

like if I had #fbff00 and #ff0000 can they be combined to get the mix of the two colors?

wary edge
cinder shadow
#

myself? no thanks

wary edge
#

Well...by that i mean you need to implement it yourself. MC doesnt have any

cinder shadow
#

I'm not even sure if this is really worth doing lol

wary edge
#

Whatcha trying to do?

cinder shadow
#

my fan blocks work with my potion soaked sponges to give everything in the same fan column the effects of all of the potion sponges below it

#

and so my options were
a. have the fan particles inherit the color from the topmost block in the column
b. combine all the colors from the sponges in the column

distant tulip
#

don't particles use rgba

cinder shadow
#

changing/setting the color isn't my problem

distant tulip
#

this is how the the beacon beam dose that

cinder shadow
#

what in the world

distant tulip
#

something like this?

function mixColors(colorsArray) {
    let colorsAmount = colorsArray.length - 1;
    let result = [0, 0, 0];
    for (let i = 0; i <= colorsAmount; i++) {
        let w = Math.pow(2, i - 1);
        result[0] += w*colorsArray[i][0];
        result[1] += w*colorsArray[i][1];
        result[2] += w*colorsArray[i][2];
    }
    return [
        Math.round(result[0]/Math.pow(2,colorsAmount)),
        Math.round(result[1]/Math.pow(2,colorsAmount)),
        Math.round(result[2]/Math.pow(2,colorsAmount))
    ]
}
cinder shadow
#

damn, particle documentation is also wrong lol

#

it shows examples saying you can pretty use any format for "color"

#

but they only work in terms of 0 - 1

rapid sail
#

can entitys use precise interactions?

distant tulip
#

no

rapid sail
#

that would be cool though

shrewd wedge
#
e.itemComponentRegistry.registerCustomComponent("evo:bone_crusher", {
        onUse(e) {
            const player = e.source;
            const xyz = player.location;
            const dimension = player.dimension;
            player.startItemCooldown("custom", 20);
            let nearbyEntities = dimension.getEntities({
                location: xyz,
                maxDistance: 10,
                excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
            });

            nearbyEntities = nearbyEntities.filter(entity => entity !== player);
            nearbyEntities.forEach(entity => {   	 
            	entity.addTag("evo:bone_crusher");
                entity.playSound("use.bone_block");
            });
        }
    });

Why did it say "not a function" when I try add tag?

open urchin
shrewd wedge
#

Oh that only player, haha sorry

#

Thank you

#
        const player = e.source;
        const xyz = player.location;
        const dimension = player.dimension;

        player.startItemCooldown("custom", 20);
        player.playSound("mob.enderdragon.flap");
        player.runCommandAsync("particle evo:voids_edge_particle ~~~");

        let nearbyEntities = dimension.getEntities({
            location: xyz,
            maxDistance: 10,
            excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
        });

        nearbyEntities = nearbyEntities.filter(entity => entity !== player);

        nearbyEntities.forEach(entity => {
            const dx = xyz.x - entity.location.x;
            const dz = xyz.z - entity.location.z;

            const length = Math.sqrt(dx ** 2 + dz ** 2);
            const dx2 = dx / length;
            const dz2 = dz / length;

            entity.applyKnockback(
                -dx,
                -dz,
                3,
                1
            );
            
            entity.runCommandAsync("particle evo:voids_edge_particle ~~~");
        });
    }
});

Does anyone know why entity still get pushed back instead of pull to entity who use sword?

slim spear
cinder shadow
#

yeah

slim spear
#
map.setFloat("variable.colorR", num / 255)```
cinder shadow
#

I know lol

#

The particle documentation is always incorrect

slim spear
#

💀

cinder shadow
# distant tulip something like this? ```js function mixColors(colorsArray) { let colorsAmoun...

ended up with this ```js
function getColor(blocks) {
if (blocks.length == 0) return { r: 1, g: 1, b: 1 };

const color = blocks.reduce((acc, block) => {
    const potion = potions.find(p => p.id === block[0]);
    acc.r += potion.color.r;
    acc.g += potion.color.g;
    acc.b += potion.color.b;
    return acc;
}, { r: 0, g: 0, b: 0 });

color.r /= blocks.length;
color.g /= blocks.length;
color.b /= blocks.length;

return color

}``` Idk what kinda junk is being done with that glass and beacon color, but you really just need to find the average

#

chatGPT taught me what .reduce was 😔