#Script API General

1 messages · Page 139 of 1

cold grove
#

Youre trying to test for a specific entity or just all entities? In the corners?

lean canopy
#

technically for a specific entity

#

but i also want the player to have only the ender crystals in that position

#

so i think this is better

#

cuz i already have a way to check for it once i have that array of type ids

#

actually no that would be wrong cuz i dont think its controllable how they would go into the array

#

hmm

lean canopy
#

okay actually i think thisll work now

#

i just changed it to this

#

cuz it appears to go by order they were placed into the world

#

which it's pretty unlikely you're gonna have a entity go into the spot of the ender crystal since it will explode and kill the entities near it, so the player probably will not want them to be near the reactor

#

but still if there's a better way I do wanna see other methods

on a side note, is there a way to check the state of the block using getBlock? cuz I'd like the respawn anchors to have to be fully charged, but rn it doesn't matter if they're charged or not

cold grove
# lean canopy i just changed it to this

You should keep the array and, in your other code, add a find() method

const targetEntityType= '';
const entitiesAtDirections = entityTestFunc();

entitiesAtDirections[0].find((e) => e.typeId === targetEntityType);
lean canopy
#

ooh

#

that's good to know

lean canopy
#

i meant at the spot specified

#

does that let you do that?

wary edge
#

Did you look at the doc I sent?

lean canopy
#

i saw it before when i was originally looking and it looked like it wasn't helpful to me but maybe i missed somethjng

#

yeah what am I missing? cuz this doesn't seem helpful (in this scenario)

wary edge
#

What are you missing from the query?

lean canopy
#

ok where the heck is this cuz this is not the doc you sent

#

oh nvm im stooooopid

#

😭

#

ya okay for some reason i didnt think entity query options was clickable

#

so i just thought the examples given showed off all the query options

#

oki

#

this is very good to know

lean canopy
lean canopy
lean canopy
#

ye i figured it would be that but what i mean is does it have a bunch of filters like that

wary edge
lean canopy
#

ok yeah i probably missed it the same way

wary edge
#

Why loop?

lean canopy
#

whats the difference between this site and microsoft learn btw cuz this seems way nicer and ive been looking at the microsoft learn documentation previously and just constantly been missing stuff apparently

cold grove
wary edge
#

Its already built into the query.

lean canopy
#

whats this for :o

cold grove
wary edge
cold grove
#

just the corners

#

youre right

#

didnt realize hehe

lean canopy
#

since we're on the subject of volume, is there a way to control which blocks it checks for in different parts of a blockvolume, or does it just check that the volume contains all the block types you list

wary edge
#

Make multiple volumes then?

lean canopy
#

ok thats what i thought

#

and i couldn't get it to work when I was testing it but it seems like it should be possible to check for blocks diagonally like, in an x shape? or am i thunking wrong

wary edge
#

Honestly, what are you trying to do?

lean canopy
lean canopy
#

but rn everything should at least work

#

so I just wanted to see alternate days of doing it

cold grove
lean canopy
#

but for this specific instance I'm trying to make it so that when the player clicks a block, it checks for specific blocks (and for one of my custom blocks, also checking entities, which is why i was asking here) in the first place) in a 3x3x3 area

#

my function for the blocks works fine except for checking states, which is fine bcuz only the one custom block needs to check those states

#

so i was focusing on entities here

#

once all of it is checked and if the player placed it correctly then it places a structure

lean canopy
#

so actually it might be better for me to use that method instead of getblocks filters

wise raft
#

Is there a way to check if a block is flowing_water instead of water?

wise raft
wary edge
#

Thats not flowing water.

wise raft
#

yes

#

no

wary edge
#

Thats water with liquid depth.

#

Check the block state then.

wise raft
#

alright thanks

lean canopy
#

oh also @wary edge @cold grove thank you for all your help :)

night oracle
#

What is the glyph (unicode) for the mc heart?

open urchin
last latch
#

for the love of god i cannot remember the event that was triggered once the player that joined was ready to get an actionform opened

#

does anyone know the event?

#

i cant find it either

wary edge
#

We have playerSpawn and playerJoin only.

#

What people do is have retry attempts.

last latch
#

That is weird as hell, cuz i can remember that some friend said I should use that event if I want to show a form right after join

#

it was like weirdly named

wary edge
#

An ancient technique called gaslighting.

last latch
#

i might have dementia 😢

wary edge
#

It might be worth looking at server-net then?

#

Catch some packets.

last latch
#

Good idea. Seems like a better option than bruteforcing showForm()

half ivy
#

Is there a eay to increased player swim speed

distant tulip
#

@half ivy

hazy nebula
#

can script give player yellow heart?

half ivy
#

Thankz

shut citrus
#

how to covert movement value to speed value?

#

like movement value is 0.25 but speed value is 1

crude ferry
#

I do not understand your question lol.

violet bloom
#

@crude ferry I pinging you because idk if any one else is online on here but I get this error

[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at <anonymous> (main.js:3)

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

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

world.beforeEvents.chatSend.subscribe((data) => {
const player = data.sender;
const message = data.message;

data.cancel = true;

if (message.toLowerCase().startsWith("-me ")) {
    const actionText = message.substring(4);
    
    world.sendMessage(`${player.name} ${actionText}`);
} else {
    world.sendMessage(`${player.name}: ${message}`);
}

});

#

Why am I getting that error

#

Because it's looks fune

crude ferry
#

What version of minecraft/server are you using?

violet bloom
#

1.10.0 without -beta

crude ferry
#

chatSend is in pre-release.

#

You need Beta.

shut citrus
crude ferry
#

I only do Script and never worked much with entity components but I am very sure the "value" of the minecraft:movement cannot give you the speed at a given instant. If that's what you're asking.

stray spoke
#

I experienced a bug but unrecorded, it was when I knockback myself with wind charge while I stopped using fly

#

Then I stayed in mid air going up and down a little repeatingly

#

And then a few seconds after it continues to fall down and back to normal

#

Second bug is this, but I think this is just in bad timings of heal and death

knotty plaza
stray spoke
distant tulip
#

that bug is still here

stray spoke
#

Lol

sage portal
#

If I want File A to import a function from File B, but said function imports something from File C, do I have to import both B and C, or just B?

sage portal
#

finally some convenience, thanks

crude ferry
#

When you import even just a function from a file, the whole file runs once. So 'technically' you already import C when you import B in A.

crude ferry
stray spoke
#

idk why

#

I used some imported functions and I forgot that I haven't deleted some of my debug codes in there that auto-runs

#

But when I use something like

const DEBUG = true
export function sendLog(txt){
  if(DEBUG) console.warn(txt)
}

It says DEBUG is undeclared

crude ferry
#

You also have to export the variable DEBUG.

#

DEBUG is a variable only in your debug(whatever you named it.) file scope.

#

When I said it runs the file once. That does NOT mean all of B's variable is exposed to A.

crude ferry
stray spoke
#

I had to put the variable inside the function

crude ferry
#

Can you show how you were calling sendLog() function though?

stray spoke
#

Incase if something wrong here, here's the full example:

import "./src/event1.js" 
import "./src/event2.js" 

const DEBUG = true;
export function sendLog(txt){
  if(DEBUG) console.warn(txt)
}

in event files, I use it like:

import {sendLog} from "../index.js"

function something(){
  sendLog("Something successfully happened")
}
distant tulip
stray spoke
#

Oh yes sorry

#

I mean, still the problem

#

I just mistype it here

distant tulip
#

whats the problem

stray spoke
#

It's small issue though and it's working if I put the variable inside. It's just idk why it didn't work and says variable DEBUG is undeclared when I use the sendLog function

stray spoke
subtle cove
#

Donnt trigger the function instantly while importing

crude ferry
#

Yeah.

stray spoke
#

Ohh

crude ferry
#

The two imports on the DEBUG file are most probably causing it.

stray spoke
#

Like the timing

crude ferry
#

Function do have access to variables of their original file.

crude ferry
stray spoke
#

I get it now

#

Thanks yall

crude ferry
#

I mean is there any specific use case you had to use such an old version for lol?

woven loom
#

Does anyone have working code for camera.playAnimation?

crude glacier
#

Tbh the most interesting thing in math is matrices

digital swallow
#

Does anyone know how to actually use Potions.resolve? I can't figure it out

crude glacier
#

Potions.resolve ?

digital swallow
#

I am trying to give a potion as an ItemStack

crude glacier
#

Then write its type id

#

That s all

#

Wait sorry...

#

Use it this way
Potion.resolve("minecraft:effect_type_id" , "delevery_type")

#

Tbh , i didn't find no enums in index.ts for it

distant tulip
#
    const item = ItemStack.createPotion({ effect: 'WaterBreath', liquid: 'Regular', modifier: 'Long' })

if this is what you are looking for

digital swallow
distant tulip
#

let me double check

crude glacier
#

Not in stable

digital swallow
#

Not even in beta seemingly

crude glacier
#

Are you trying to make custom effect or use already existing one ?

digital swallow
#

existing one

distant tulip
crude glacier
#

Yeah , but it have no enums that s the problem

#

You don't know what to put in potionDeliveryType

#

As a string

digital swallow
#

apparently you use vanilla-data

distant tulip
#

there is getAllDeliveryTypes

crude glacier
#

Try using Potions.getAllDeliveryTypes()

#

Or just make generic key-word function

#

Like you give it a key word from the effect type and the delivery type

#

And you get the potion

digital swallow
#

const potion = Potions.resolve("minecraft:Healing", "Consume")
inventory.addItem(potion)

Wait this specfically works, like the first one have "minecraft:" and the 2nd one not

crude glacier
#

Yes

digital swallow
#

cool so I think my problem the whole time was I expected both to have the minecraft: prefix or not to have it

crude glacier
#

I mean they should add that i guess to make it more intuitive

digital swallow
#

Oh its listed that way on these docs too dang I can't read

crude glacier
#

like you know you can use itemStack item's type id without or without Minecraft

digital swallow
#

Thanks for the help guys

crude glacier
#

Uw

cyan basin
crude glacier
#

Guys is there a way ,to enforce breaking a black

thorn flicker
#

are you asking if there's a method for destroying a block at a location? no

#

you'll have to use the setblock command with destroy set to true

crude glacier
#

no like actual breaking

#

with particles

distant tulip
#

fill command with destroy

crude glacier
#

hmm intersting

#

what about breaking multi blocks

#

but the problem is one block is getting destroyed before the other ones

warm mason
#

not setblock

#

what's the problem with using it?

crude glacier
#

no like when breaking blocks

#

like one breaks before the other ones

warm mason
crude glacier
#

yeah but it sucks

#

is there like SOLUTION

thorn flicker
#

no

crude glacier
#

sad

thorn flicker
#

its not that big of an issue anyway

#

lol

crude glacier
thorn flicker
#

im assuming you are making a hammer

crude glacier
#

but for bigger ones the impact is not negligible

crude glacier
thorn flicker
#

oh

crude glacier
#

fuh wasted my time to know there is already a component named multiblock to solve it

crude glacier
#

no like after i finished everything ☠️

#

that s totally messed up

thorn flicker
#

damn that sucks

crude glacier
#

sucks so much

#

i need my time back ☠️

thorn flicker
#

time well spent practicing your coding skills

#

think of it that way ig

#

lol

crude glacier
#

: [

#

yeah u are right

thorn flicker
#

just be happy there's official support

crude glacier
thorn flicker
#

let the happiness overshadow your frustration

crude glacier
#

oh never mind

#

it only supports up and down

thorn flicker
#

damn

crude glacier
#

yeah then time well spent

thorn flicker
#

well you could make it hybrid...

crude glacier
#

hmmm yeah but it would be harder maybe

thorn flicker
#

hm

crude glacier
#

i mean ._.

#

i need vsync for breaking lol

thorn flicker
#

vsync?

crude glacier
#

you know when you screen generated unsynced frames

#

there is technology name vsync that fixes it

#

or gsync free sync

#

it solves the frames cut problem

thorn flicker
#

i know the technologies im just confused what it has to do with it

crude glacier
#

when u break a block

#

and it breaks before the other ones

#

i mean the one tick delat

#

lol

thorn flicker
#

well... you could cancel the break, then break it again

#

but the block will flash for like a tick

crude glacier
#

yeah it s like making new problem

#

so i will stick with what i have for now

#

smol question

#

how to make fill command dosen t drop item

cyan basin
#

when i saw you guys talking about breaking with fill command i thought you guys were talking about veinminer like this but then i saw the multiblock so i guess not

crude glacier
#

._.

crude glacier
cyan basin
#

gamerule dotiledrops false?

crude glacier
#

no using fills

#

fill command i meant

sharp elbow
#

/fill should just replace the blocks. How are you using it?

crude glacier
#

i just want particles but no item dropped

#

/fill somethingsomething destroy

cyan basin
#

either do gamerule dotiledrops false or check the block that was broken to it's item that drops within a small radius around the block and then kill it 🤷‍♂️

crude glacier
#

that s all

cyan basin
#

so kill them when broken -_-

sharp elbow
#

Could disable the game rule for a tick, I suppose

crude glacier
cyan basin
#

what's not performant about that?

wary edge
#

If only we had a BlockItemDrop event.

cyan basin
#

Do we?

wary edge
#

No, we have Entity.

crude glacier
cyan basin
#

Silly

wary edge
#

Which works for disabling certain loot.

crude glacier
#

hmmm

cyan basin
#

Or just give loot table for blocks 😉 so blocks can either drop nothing or custom items all together

crude glacier
#

Entity item drop ?

#

or EntitySpawn

wary edge
crude glacier
cyan basin
#

I'm just saying in general to this channel lol

wary edge
#

I had to disable tiledrops, check for bamboo, cactus, and then all the edge case, use loot table manager, and shebang.

thorn flicker
sharp elbow
# cyan basin what's not performant about that?

About performing one entity query on the dimension L×W×H times, looking up the item component on that entity, then checking the typeId against the block's typeId? This sounds nightmarish for performance

wary edge
#

Oh I got mixed up, I thought the vein miner was arthur's use case. Yeah, just give the block an empty loot table and use loottablemanager if you want to still utilise the engines loot table system.

thorn flicker
#

yeah, smart

cyan basin
wary edge
#

Only works for custom blocks. In this case yeah. Again, I got mixed up and thought that vanilla coal ore.

crude glacier
#

yeah np

thorn flicker
#

wish we could give spawned items the pickup delay though

wary edge
thorn flicker
#

how long is the delay anyways?

crude glacier
#

no way fill command is faster than setBlock

crude glacier
#

fill command is faster than setBlock somehow on my script

#

tbh noice cancelation using sound files and script api would be a crazy idea ☠️

crude glacier
#

Why non-marketplace add-ons aren't compatible anymore with vibrant visuals

cyan basin
subtle cove
#

"

cyan basin
#

exactly

#

iPhone stinks giving me “ lol

crude glacier
#

So i need a custom block to open storage space "inventory" when i click on it, Is it possible to do it ?

#

No way right?

naive frost
woven loom
#

Does anyone have a way to find solid blocks?

shut citrus
#

why doesn't keepVelocity in teleport method support players?

#

while clearVelocity does

shut citrus
meager zenith
#

It's still in beta

woven loom
#

Ye

cyan basin
# naive frost

If it’s the first open why make me have to hold the button first, that’s so dumb 💀

simple zodiac
cyan basin
simple zodiac
potent drift
#

Please, what is the beta version of the latest version of the manifest? Thank you.

granite badger
fallen cape
potent drift
#

Thank you 😊

deep quiver
#

I reported it to darknavi, let me see if I can find the code

#
                /**
                 * @type {import("@minecraft/server").AnimationOptions}
                 */
                const animation = {
                    totalTimeSeconds: 10,
                    animation: {
                        progressKeyFrames: [
                            {
                                alpha: 0,
                                timeSeconds: 0,
                            },
                            {
                                alpha: 1,
                                timeSeconds: 10,
                            },
                        ],
                        rotationKeyFrames: [
                        ],
                    },
                };

                for (const player of world.getAllPlayers()) {
                    const location = player.location;
                    location.x -= 3;
                    location.y += 2;

                    const spline = new LinearSpline();
                    spline.controlPoints = [location, { x: 438.0, y: 187.0, z: -714.0 }, { x: 450.0, y: 187.0, z: -714.0 }];

                    player.camera.setCamera("minecraft:free", { location: location, facingEntity: player,  });
                    player.camera.playAnimation(spline, animation);
                }
            });
#

maybe I did it wrong tho, I just ended up doing manual animating

woven loom
cold grove
#

Microslop did it again

frozen vine
#

How do I make the server UI options save when I log out and log back into the world? Is it possible?

frozen vine
cold shoal
#

Is it possible to rename a boss bar using .nameTag? Can't make it work

last latch
#

Only using the name tag works

cold shoal
#

oof, that's unfortunate

knotty plaza
#

But the animation isn't working

subtle cove
woven loom
gaunt salmonBOT
jolly citrus
#

so is this still valid or no

  "dependencies": [
    {
      "module_name": "@minecraft/server",
      "version": "beta"
    },
    {
      "module_name": "@minecraft/server-ui",
      "version": "beta"
    }
  ]
woven loom
#

Yes

cyan basin
#

Can we use "beta" for format versions yet or is that not in stable/preview yet?

lyric kestrel
#

Ah, just found out that if entity.setProperty and entity.getProperty are used in the same tick of system.run that it doesn't output the updated property with getProperty.

lyric kestrel
#

Yeah, I realise that now 😅

#

I've been at it for the last half hour wondering why it wasn't logging the correct property value lol

sullen grotto
#

For some reason this code removes landing particles entirely. Is there a way to fix it? Should I report it to Mojira?

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

world.beforeEvents.entityHurt.subscribe((event) => {
  event.cancel =
    event.damageSource.cause == EntityDamageCause.fall &&
    event.hurtEntity.getBlockStandingOn()?.typeId == "minecraft:hay_block";
});
#

According to the docs, damage in EntityHurtBeforeEvent is not read-only. Can I possibly try changing this value to 0 to remove damage?

sullen grotto
empty tulip
#

How can I summon a Lightning Bolt when a player dies? Especially if they have a tag like "skywars"?

cyan basin
# empty tulip How can I summon a Lightning Bolt when a player dies? Especially if they have a ...
import { world } from '@minecraft/server';

world.afterEvents.entityDie.subscribe((event) => {
    const { deadEntity } = event;

    if (deadEntity.typeId !== 'minecraft:player') return;
    if (!deadEntity.hasTag('skywars')) return;

    deadEntity.dimension.spawnEntity('minecraft:lightning_bolt', deadEntity.location);
});```
You can try this, I'm not sure if the location would be valid still, especially if you have instant respawn on.
half ivy
#

How would do i detect if a certain item has been clicked

frozen vine
#

Is there any way for me to see the current weather?

late ore
#

i tried using this script for the bulletdamage but nothing happens

frozen vine
late ore
#

i'll give the entity code:

frozen vine
# late ore

Try using the new experimental custom projectile option.

frozen vine
#

Perhaps this new experiment will solve the problem, but I'm not sure.

late ore
midnight crane
#

I'm trying to remove the durability but it won't work

    if (item.typeId === "bizarrecraft:stand_arrow" && !player.isSneaking && cooldown.cooldownTicks == 100 && cooldown.getCooldownTicksRemaining(player) == 0) {
        player.runCommand('function stand_arrow')
        durability.damage(1)
        cooldown.startCooldown(player)
    }
valid ice
#

Are you setting the item back to the player once it gets damaged?

violet bloom
#

I made this Anticheat for people to use its a Anticheat to detect hacks, exploits and even lumine proxy bots but idk if they did the lumine proxy bots detection right and also when I not using hacks it detects me as using hacks is there any way to make it not detect regular players only hackers.

-# Note: I making a post thing for this

grave halo
#

How could i get the coordinates of a player using the script api?

violet bloom
#

I using the new slash cmds api

grave halo
#

uh

grave halo
violet bloom
#

The getting any coordinates of any player

grave halo
#

oh sure

#

you can send it here

violet bloom
#

I testing the code to see if it works first

grave halo
#

ok

violet bloom
#

@grave halo I adding some notes for you

violet bloom
#

I do it to teach new people

grave halo
grave halo
violet bloom
grave halo
midnight crane
shy leaf
shy leaf
# midnight crane deplete

then you need to get the durability damage, add the amount of durability damage you want to apply, set it back, and then set equipment back

durabilityComp.damage = Math.min(
    durabilityComp.damage + durabilityModifier,
    durabilityComp.maxDurability
);
equippableComp.setEquipment(EquipmentSlot.Mainhand, itemStack);

_ _

midnight crane
#

Okay thanks

violet bloom
# grave halo oooh
import { 
    world, 
    system, 
    Player, 
    CommandPermissionLevel, 
    CustomCommandParamType, 
    CustomCommandStatus 
} from "@minecraft/server";

system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
    customCommandRegistry.registerCommand(
        {
            name: "utils:coords",
            description: "Get the coordinates of a specific player.",
            permissionLevel: CommandPermissionLevel.Any,
            cheatsRequired: false,
            mandatoryParameters: [
                {
                    name: "target",
                    type: CustomCommandParamType.PlayerSelector,
                },
            ],
        },
        (origin, [target]) => {  // Destructure directly as `target`, not `players`
            // Safety check to ensure target is valid
            if (!target) {
                return {
                    status: CustomCommandStatus.Failure,
                    message: "No player found.",
                };
            }

            const { x, y, z } = target.location;

            // Format coordinates
            const posX = Math.floor(x);
            const posY = Math.floor(y);
            const posZ = Math.floor(z);

            const response = `§a${target.name} §f- Coords: §b${posX}, ${posY}, ${posZ}`;

            // Send message to the command sender
            const sender = origin.initiator ?? origin.sourceEntity;
            if (sender instanceof Player) {
                sender.sendMessage(response);
            }

            return {
                status: CustomCommandStatus.Success,
                message: response,
            };
        }
    );
});
#

There

#

@grave halo you can change the any to Admin so only admins that are op can use cmd

keen dust
#
import { 
    world, 
    system, 
    Player, 
    CommandPermissionLevel, 
    CustomCommandParamType, 
    CustomCommandStatus 
} from "@minecraft/server";

system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
    customCommandRegistry.registerCommand(
        {
            name: "utils:coords",
            description: "Get the coordinates of a specific player.",
            permissionLevel: CommandPermissionLevel.Operator,
            cheatsRequired: false,
            mandatoryParameters: [
                {
                    name: "target",
                    type: CustomCommandParamType.PlayerSelector,
                },
            ],
        },
        (origin, [target]) => {  // Destructure directly as `target`, not `players`
            // Safety check to ensure target is valid
            if (!target) {
                return {
                    status: CustomCommandStatus.Failure,
                    message: "No player found.",
                };
            }

            const { x, y, z } = target.location;

            // Format coordinates
            const posX = Math.floor(x);
            const posY = Math.floor(y);
            const posZ = Math.floor(z);

            const response = `§a${target.name} §f- Coords: §b${posX}, ${posY}, ${posZ}`;

            // Send message to the command sender
            const sender = origin.initiator ?? origin.sourceEntity;
            if (sender instanceof Player) {
                sender.sendMessage(response);
            }

            return {
                status: CustomCommandStatus.Success,
                message: response,
            };
        }
    );
});```
keen dust
#

I hope, IT will work

potent drift
crude glacier
#

._.

subtle cove
violet bloom
grave halo
violet bloom
#

I don't why it says it two times

#

But other than that it still works

grave halo
grave halo
violet bloom
#

@grave halo that's an easy fix people can do

fallen cape
#

How to control how far the camera is from the player when using "follow_orbit"?

steep hamlet
#

is there any example for assigning a value to a resource side variable with playAnimation and changing it afterwards through a controller or pre-animation?
in my test it worked making a variable true but it didnt work changing it afterwards inside another controller.

#

or are there any better alternatives for script-client communication?

sly currentBOT
#
caliiengalleta

Is there a way to fly like elytras using scripts?

stray spoke
# sly current

There's a way to bounce off the player but not to activate flying

#
I love codeboxes
shut citrus
#

anyone know why doesn't it bounce sometimes?

stray spoke
#

Is there bds forks that supports arm64

#

architecture

twilit sky
stray spoke
#

Thanks a lot

#

I'll review this first

crude ferry
stray spoke
#

Tho it exists on the website

twilit sky
# stray spoke

Does it work with Docker?

docker pull --platform linux/amd64 endstone/endstone

Then

docker run \
--platform linux/amd64 \
-p 19132:19132 \
-it \
-v ${PWD}:/home/endstone/bedrock_server \
--name endstone-server \
endstone/endstone
round bone
buoyant canopy
#

is getGeneratedStructures actually going to be released in 2.7.0?

drifting ravenBOT
snow knoll
#

⬆️

rotund coral
#

can.........I........... dm..........you?????😨

jolly citrus
#

is there some debugging tool i can use to find out which part in my scripts is causing a hang

ripe shale
#

Could someone help me? How can I make an action trigger when I hit the air (swing without hitting anything)? Could you give me an example? Thanks!

tidal terrace
#

However, it does not work for mobile users.

random flint
# tidal terrace However, it does not work for mobile users.

The event works on mobile, you just have to map the left click of a mouse input to something like the volume button, then you can swing your arm on air.

The problem is with the vanilla touchscreen attack button, it doesn't allow you to punch the air.
-# TLDR; You're correct but I yapp anyway

snow knoll
crude glacier
#

Guys need smol help

crude ferry
crude glacier
#

Can you help ? @crude ferry

#

So , basically you know when a witch finishes drinking potion, is there an event for that to detect it ?

crude ferry
crude glacier
#

How

crude ferry
#

afterEvents.effectAdd

crude glacier
#

Hmm does it work with entities?

#
  • how to check for regeneration potion
crude ferry
#

Yes.

crude glacier
crude ferry
crude glacier
#

Hmmm

#

What ? ☠️

#

No i mean how to check when an entity drinks the regeneration

#

Potion

crude ferry
#
world.afterEvents.effectAdd.subscribe((event) => {
    const { entity, effect } = event;
    if (entity.typeId === "minecraft:witch") {
        if (WITCH_POTIONS.includes(effect.typeId)) {
            console.warn(`Witch finished drinking. Effect: ${effect.typeId}`);
        }
    }
});```

You can do something like this where WITCH_POTION is an array of every potion witch drinks.
crude glacier
#

Oh ☠️ thx very much

#
  • can i use it to trigger a custom event in json right ?
#

Yes

#

"events" : {
"Custom:event" : {"add component" }
}

#

No i just want to wire js with json ☠️

crude glacier
#

Oh thx you saved me much time

crude ferry
#

entity.triggerEvent()

glacial widget
#

Is it better to use world.afterEvents.entitySpawn.subscribe for Clearing items or should i stick to using functions in my tick.json that kills them. For example starter kit

random flint
crude glacier
#

Does someone know why my entity stops holding here crossbow back when i add "minecraft:drink_potion" behaviour, is there any fix using js and events , or something i did wrong in the behaviour file ?

dapper smelt
ocean escarp
#

Is there a way to make damage cancel eating?

meager zenith
# ocean escarp Is there a way to make damage cancel eating?

Detect both player taking damage and player eating food ( so world.beforeEvent.itemUse) and when it takes damage give the player a tag and also use system.runTimeout to remove that tag after a 1 tick, and with world.beforeEvent.itemUse, detect the tag and do event.cancel = true, so in this case you will not use event.isFirstInstance I think it's called?

ocean escarp
#

Wouldn't this only cancel the start of eating?

#

Never used system.runTimeout

#

No clue what it does lol

snow knoll
meager zenith
ocean escarp
#

Ah

#

Also does itemUse fire the entire time an item is being used or only the beginning?

meager zenith
ocean escarp
#

making it be canceled

#

It's for a combat system I plan to make

meager zenith
meager zenith
ocean escarp
meager zenith
#

Let me check smth

meager zenith
ocean escarp
#

that's my problem

#

Is there a startedEating callback?

meager zenith
#

No

ocean escarp
#

I was hoping to use the on start and on finish to hold a var

distant tulip
#

iirc food items do trigger itemStartUse

#

and item use

#

so just use that

#

and there is a consume event iirc

crude glacier
#

@distant tulip man can you hilp me

distant tulip
#

with?

crude glacier
#

With this : "Does someone know why my entity stops holding here crossbow back when i add "minecraft:drink_potion" behaviour, is there any fix using js and events , or something i did wrong in the behaviour file ?"

#

It is a pillager like entity

ocean escarp
distant tulip
distant tulip
distant tulip
#

i would assume so, both thing require eqipment. potion or crossbow

open urchin
#

I assume when the entity is drinking a potion it replaces its held item with that potion

ocean escarp
crude glacier
distant tulip
#

remove the component then try

crude glacier
#

Same

distant tulip
#

well... not sure then

#

share your code?

crude glacier
#

The entity.json ?

#

Yes np

distant tulip
#

add this to a component group

crude glacier
#

Add 1hat

distant tulip
#

?

crude glacier
#

world.afterEvents.effectAdd.subscribe((e) => {
console.log("h");
world.sendMessage("jksjqmkledqjs")
});

#

do i combine it with effectAdd event to trigger it and activate ranged mode ?

distant tulip
#

yeah, if we can't trigger events from that component

crude glacier
#

Hmm thank you then

dapper smelt
crude glacier
#

yes

dapper smelt
#

I don't know, I've always used .warn

#

🐬

shut citrus
#
const Vec3 = new Vetor3();
static function 1() {
const dirX = 1, dirY = 2, dirZ =3;
Vec3.set(dirX, dirY, dirZ);
}
static function 2() {
const dirX = 4, dirY = 5, dirZ =6;
Vec3.set(dirX, dirY, dirZ);
}

I have codes above, does it confict eachother?

remote oyster
#

Correct me if I'm wrong but can you define a function as a number in JavaScript? I've personally never done that before 👀

shut citrus
#

ok

#

that's just an example

#

so I gonna create a lot of new Vector3() class

#

for each function

remote oyster
# shut citrus so I gonna create a lot of new Vector3() class

If you don't want to return Vec3 and/or overwrite it since it's currently global then yes, your best option is to create a new instance within each function. Just know that it's only available within the scope of that function so you will have to return the variable if you wish to access it outside the function.

#
function f() {
  const v = new Vector3();
  return v;
}
const a = f();
const b = f();
a !== b // true (different instances)

With this logic you can just call f() in your other functions that need it to create a new instance of Vector3 and they won't interfere with each other as it creates a new object in memory each time, and return v just passes a reference to that specific object, not a shared one.

ocean escarp
#

How does "or" work in if conditions again?

#

I want to check if a damageType is 1 of 2 things

#

Im a bit rusty

snow knoll
ocean escarp
#

can I do like

if (damageType == "fireTick" or "magic") {}
#

I really hope I don't have to write the check twice

#
if (damageType == "a") or (damageType == "b") {}
#

I doubt I can run it through some kind of array

#

Just want to compact this a little

snow knoll
ocean escarp
#

Ohh

#

Never seen that used before somehow

snow knoll
#

Bruh

ocean escarp
#

Im rusty, ill and running on empty

#

So this should work?

#

Also poison is magic damage right?

#

Or is it its own type

snow knoll
wary edge
#

You can verify yourself by logging what the damage cause is by poisoning yourself.

ocean escarp
#

I keep forgetting I can do that

#

I'm still tryna get good with functions

#

I can do em in Lua but js is still a bit iffy to me

#

I think I fixed it

#

I'm so lost.. it's treating all damage as 0.5

#

The else isnt running

wary edge
#

damageType == 'fireTick' || damageType == 'magic'

sharp elbow
#

Logical OR operator a || b will first evaluate a, and if a is falsy then it evaluates b.

ocean escarp
#

Oh

sharp elbow
#

In an if-condition, this essentially means it will first evaluate a for being truthy and continue if so, then try evaluating b likewise

ocean escarp
#

I feel like a dumbass

sharp elbow
#

Sometimes that's the first step to true learning 🙂

ocean escarp
#

Im reteaching myself scripting after a long break

sharp elbow
#

Also curious that you're using a property on the function clampMin itself. I'd sooner expect it to return a variable. This makes the function more "pure" (without side-effects)

function clampMin(damage, damageType) {
  let finalDamage = damage;
  // ...
  return finalDamage;
}
#

Or heck, you could probably just return the parameter damage

ocean escarp
#

I would return damage but then it gets confused with my already existing const

#

I thought annotation via
function.variable
Made more sense

sharp elbow
#

It shouldn't, since the scope of your function is isolated. Any reference to damage as a parameter/variable/whatever will refer to the damage parameter you defined in the function

#
const damage = 5;

function clampMin(damage, damageType) {
  // Entirely separate reference than the "damage" on the first line
  damage = 3;
  return damage;
}

console.warn(damage) // 5
console.warn(clampMin(100)) // 3
ocean escarp
#

Where is the 100 coming from?

sharp elbow
#

Just some arbitrary number, it doesn't matter since I have clampMin reassigning the value anyway, for the sake of a simpler example

ocean escarp
#

I guess coming from Lua, func.var just makes more sense to me

#

It's easy to backtrack

#

Because what if I'm returning more than 1 value?

sharp elbow
#

But it also mutates data on the function; you could, in theory, read the value of the property var on the function outside the function. As the old adage goes, "in Javascript, everything's an Object"

ocean escarp
#

like
{3, "hello"}
?

warm mason
sharp elbow
#
function myFunc() {
  myFunc.var = "hi";
  return myFunc.var;
}

console.warn(myFunc.var)  // undefined
console.warn(myFunc())    // "hi"
// State is now mutated, I can read this on the function
console.warn(myFunc.var)  // "hi"
shy leaf
ocean escarp
sharp elbow
#

Agreed, this is exactly what you are doing now

ocean escarp
#

Wait no, I'm so lost at both atp

#

maybe I shouldn't be coding while ill

#

Less brainpower to go around

warm mason
#
sharp elbow
# ocean escarp like {3, "hello"} ?

Kinda. You could return an object literal:

function multipleReturn() {
  return {
    a: 1,
    b: 2
  };
}

const foo = multipleReturn();
// foo is an object; we can pull values from it
console.warn(foo.a)  // 1
console.warn(foo.b)  // 2
ocean escarp
#

I can tell it would work

#

Oh wait...

#

I think I get it now

#

Nvm?

#

I don't know anymore

#

Im trying to put it into context of my code

shy leaf
#

when in doubt, take a rest

ocean escarp
warm mason
shy leaf
#

overworking while ill doesnt help much

ocean escarp
#

I'm returning early just so it doesn't chat spam

sharp elbow
ocean escarp
#

I usually comment that out

warm mason
sharp elbow
# ocean escarp

I see, you are deliberately using the mutated function state in a further assignment. Indeed, if you did the one change I am suggesting, it would break your code

ocean escarp
#

So you're saying instead of running the function standalone that I should ev.damage.clampMin()
?

#

These are foreign concepts to me ok, im good at simple javascript not embedded functions

warm mason
ocean escarp
#

Ok so . something() means method

#

Ill get there slowly

#

I've never heard of the term "mutating the function"

#

Or whatever it was

#

This was never a thing when I did Lua

#

So it's taking me a bit to understand

sharp elbow
#

Here's a more full example of the refactor I am suggesting:

world.beforeEvents.entityHurt.subscribe((ev) => {
  // Changing declaration to mutable
  let damage = ev.damage;
  const source = ev.damageSource;
  const damageType = ev.damageSource.cause;

  // applyArmor() commenting because implementation is missing

  // Reassigning the value to the returned value of the function!
  // Passing "damage" as an argument to the function
  damage = clampMin(damage, damageType);

  ev.damage = damage;
  return world.sendMessage(/* ... */)
});

function clampMin(damage, damageType) {
  if (damage <= 1) {
    if (damageType == "fireTick" || damageType == "magic") {
      damage = 0.5;
    } else {
      damage = 1;
    }
  }
  // We've modified 'damage', so let's return 'damage'
  // Nothing changes outside of this function, so this function is 'pure'
  return damage;
}
sharp elbow
ocean escarp
#

Oh.. I feel very stupid now

sharp elbow
#

Don't, I didn't fully examine your use-case

ocean escarp
#

No this is on me

#

I should do more research

sharp elbow
#

What you were doing was not wrong per se, just unconventional for typical JavaScript

ocean escarp
#

Is there any reason that it's not

Let damage = function(a,b)

I've had it ingrained in my brain that variable declarations need a prefix

sharp elbow
#

Variables need to be declared the first time they are used within a scope. Thereafter they exist in that scope, and depending on how you declared it, you can reassign the value for that variable

ocean escarp
#

I really should just go back and relearn js huh?
Im making so many beginner mistakes

sharp elbow
#

What's bad is my explanation is not actually consistent, just convention. Indeed, you can redeclare variables if you declared them with var:

function foo() {
  // This is perfectly fine, no errors
  var a = 1;
  var a = 2;
  return a;  // 2
}
#

But the same doesn't apply if you declare variables with let 🙃 That nets you a runtime error

sharp elbow
#

Like, you could write it as: let damage = clampMin(ev.damage, ev.damageSource):

ocean escarp
#

Ok so this should be good?

#

(Watch me fail again)

shy leaf
#

i also had that phase

ocean escarp
#

Trying to get better with optimization

#

The only reason that applyArmor is empty rn is I don't actually have an armor to test with

sharp elbow
#

This could almost work. You declared damage as a constant, so reassignments will throw an error. Change const to let on line 4 and it should work

ocean escarp
#

Is it worth just using let as a default? It'll be a bit less optimized but will solve so many headaches early on

#

Working code before clean code

sharp elbow
#

Yea, nothing wrong with that. const and let share very similar rules, just that one is writable and the other is not

jolly citrus
#

and regardless you can change it to another type later

ocean escarp
#

Yeah thats my thought process. use let, make it work, change to const and see if it breaks

#

If not keep it

#

If yes change it back

jolly citrus
#

there's no issue with using let for everything at your stage imo

sharp elbow
#

I like to think of const as a form of self-commenting code. "This variable is not intended to change"

jolly citrus
#

yea

#

i didnt start using const until i switched to TS

ocean escarp
#

My brain sees const as "does not change" but yet its used in a callback with variable outcomes

#

So it's a little confusing at times

jolly citrus
#

changing here means mutating

shy leaf
#

tbh i think ive rarely used let recently

jolly citrus
#

but when a callback returns the value it's been initialized to be that very value

#

it doesnt change later

#

by itself

ocean escarp
#

Oh so const means
"For this function's iteration, this value is fixed and does not change contexts"

jolly citrus
ocean escarp
jolly citrus
#

oh

sharp elbow
ocean escarp
#

You can hyperlink in discord messages now?

jolly citrus
#

youve been able to for quite a while

#

lol

ocean escarp
#

The more you know

sharp elbow
#

Yup; [text to hyperlink](URL to link to)

jolly citrus
#

select some text then paste a link

jolly citrus
ocean escarp
#

Good to know

distant tulip
sharp elbow
#

It does, I just like having more control. Especially since I prefer disabling the embeds, which I do with angled brackets (<URL>), and pasting over text means I have to navigate back and add them in more tediously

distant tulip
#

ah, yeah

jolly citrus
#

when im debugging scripts where do i see the table of how long each function took to run

ocean escarp
#

Native property setter cannot be assigned null?

#

Where is it getting null from

#

Is it because 1 of my functions isn't returning?

#

Ok yeah that was it

#

I like formatting stuff

#

Nested functions are a thing in Js right?

jolly citrus
ocean escarp
#

Cause to apply armor I would need to getArmorValue()

jolly citrus
#

why would they not be

ocean escarp
#

Im writing a custom armor system that'll be used for all future custom armors (I plan to replace all the originals eventually)

#

Tho there isn't really much I can do until I create custom armor

sharp elbow
#

They exist, but know that it means JavaScript must re-declare the function each time the parent function is called. It would be more performant to move the code out if possible

ocean escarp
#

It sucks we haven't got an eating callback

#

It's just minecraft:food right?

jolly citrus
#

not for eating specifically but item interaction end

#

i forgot the exact name but it should be in the docs it's an afterevent

ocean escarp
#

Im trying to add a tag while the player is eating so I can cancel it if hit

open urchin
#

for players eating, the itemStart/StopUse events would work

ocean escarp
#

But is there an event I can even cancel to stop the action midway?

#

I don't think there is an "itemUsing"

shut citrus
ocean escarp
#

How would I even check if a component exists?

#

I know you can grab the data of a component

#

I remember seeing something similar to this

#

But idk the exact formatting of it

remote oyster
ocean escarp
#

Apparently golden carrots are not food

open urchin
#

the food component only exists for data-driven items, for most vanilla items you'll need to check that the item either has the minecraft:is_food tag or that its identifier is minecraft:glow_berries (glow berries don't have the food tag for some reason)

ocean escarp
#

Thanks

ocean escarp
#

Now I just have to figure out how to cancel itemuse mid use

subtle cove
#

perhaps try this ;-;

ocean escarp
#

I would need to save all the itemstack data no?

subtle cove
#

the itemStack itself is already the cloned one

snow knoll
ocean escarp
#

Well yeah but itemUse only fires once at the beginning

#

If it was a constant event while use was being held it would be way easier to cancel

subtle cove
ocean escarp
#

Yeah this won't let me cancel it

#

I might have a way

#

But it depends if I can access something

#

No luck

subtle cove
#

change the source.selectedSlotIndex = s ? s-1 : s+1 then change it back if u want

#
world.afterEvents.itemStartUse.subscribe((e) => {
    const s = e.source.selectedSlotIndex;
    e.source.selectedSlotIndex = s ? s - 1 : s + 1;
    system.runTimeout(() => (e.source.selectedSlotIndex = s), 2);
});```
#

or move it to an empty one, or transfer the item

crude ferry
#

If you mean what I think you do,
You can by:

Number.prototype.double = function() {
  return this * 2;
}```
#

Then you can do console.log((5).double());

lethal lichen
#

i think they meant a function identifier being a number

#

functions themselves can't since the grammar doesn't accept it, but with methods you could do that

#

e.g.

class A {
    1() {}
}
new A()[1]();

internally it gets inferred as a string property of the object, so it's valid

lyric kestrel
#

I thought they meant

function 1(){
  return 1

}```
lethal lichen
#

wouldn't be valid :p

lyric kestrel
#

ik

ocean escarp
#

There isn't really better alternative, unless changing the slot contents for a single gametick doesnt cause a flicker

remote oyster
ocean escarp
#

is this a real thing?

#

target.selectedSlot.itemStack

warm mason
#

You should check the documentation before using properties or methods of API classes

#

or install the server module

ocean escarp
#

The problem im not trying to grab this value from the event data as the thing I'm triggering it on usually doesn't care about itemStack

#

Im just not sure how the grab the itemStack outside of event data

warm mason
ocean escarp
#

Oh.. well I sure feel stupidn

thorn flicker
ocean escarp
#

I just assumed that since selectedSlotIndex existed that the data would too in a similar variable

warm mason
ocean escarp
#

I need to save this data as im going to have to reconstruct this itemStack

#

Im not a big fan of the slot change implementation to force the cancellation of the eating action

#

So I'm going to remove the item and then reconstruct it

#

If there was a simpler way I'd use it trust me

honest spear
#
for(let i of 256)
  console.log(i);
lethal lichen
#

yeah but numbers don't have iterators

honest spear
lethal lichen
#

i mean yeah, just override the prototype, i meant by default

honest spear
#

Yes sir!!

#

anyway

#

I get more of funny stuff thats possible

#

let me dig up that specific JS snippets i test ppl with lol

ocean escarp
#

Am I blind or does itemStack not have a remove method?

honest spear
# lethal lichen i mean yeah, just override the prototype, i meant by default
  1. Implement a function named range that can be used in the following expression:
    for (let i in range(10)) console.log(i);
    Your goal is to ensure the function produces the expected output of numbers from 0 to 9.

Bonus: Try to achieve this without allocating O(n) keys in objects or array elements.

  1. Implement a class or function named ExampleClass that enables the following code to work as expected:
const object = new ExampleClass(); 
object.onLoad += logHello; 
object.trigger(); 
object.onLoad -= logHello; 
object.trigger();
function logHello() {
      console.log("Hello World");  
} 

Your goal is to allow event handling for onLoad, where logHello can be added and removed dynamically. Ensure that calling trigger() executes the currently assigned event handlers.

#

the first one is pretty easy

ocean escarp
#

@thorn flicker apologies for the ping but I'm looking at jayly's docs but there doesn't seem to be a remove method for itemStacks?

thorn flicker
#

its optional

#

if left blank, it'll replace it with nothing

ocean escarp
#

I left it blank and it threw an error

thorn flicker
ocean escarp
#

No errors but it's not doing anything either

#

Maybe I just ditch this feature

wary edge
#

setEquipment(slot, undefined)

thorn flicker
ocean escarp
#

Worth a shot at least

#

typeError: not a function

#

At least it's a new error

distant tulip
#

you are calling the function on the target, not the component

thorn flicker
#

oh shit

ocean escarp
#

Am I stupid??

#

Genuinely

random flint
#

yesn't

distant tulip
#

nah, it happens

thorn flicker
#

I wouldn't say that

ocean escarp
#

so
target.getComponent(). setEquipment()

thorn flicker
#

yes

distant tulip
#

save the component to a variable so you are not calling it two times

ocean escarp
#

It'll still be 2 lines regardless

#

The definition takes 1 line

thorn flicker
#

either way storing it in a variable would make the code look cleaner

#

imo

random flint
#

Fewer API call is more performance (especially when you're doing it on a runInterval)

ocean escarp
#

Let me see if it works first then I'll change it

thorn flicker
#

you already have the equippable component stored

#

just make another variable for the item

ocean escarp
#

I just hope my system in general will work smoothly

distant tulip
thorn flicker
ocean escarp
#

Yup it disappears

distant tulip
random flint
thorn flicker
ocean escarp
#

If I re-add it in the same tick it would just continue to eat no?

thorn flicker
#

get rid of the getEquipment and make a new variable

#

what I mean is, its already in the variable

ocean escarp
#

Im trying to cancel the eat action as smoothly as possible

#

Hotbar slot switching looked odd

thorn flicker
#

im not saying it returns the equippable class

ocean escarp
#

Im hoping removing and re-adding the item will be cleaner

thorn flicker
#
const equip = target.getComponent('equippable')
const item = equip.getEquipment('Mainhand')

equip.setEquipment('Mainhand')
distant tulip
#
let damageType = ev.damageSource.cause

damage = applyArmor(damage, damageType)
damage = clampMin(damage, damageType)

ev.damage = damage

system.run(() => {
    if (target.hasTag("verarc:is_eating")) {
        let slot = target.selectedSlotIndex
        const equippable = target.getComponent("equippable")
        let itemInfo = equippable.getEquipment("Mainhand")
        // world.sendMessage(itemInfo.toString())
        equippable.setEquipment("Mainhand", undefined)

        return
    }

    slot = slot ? slot - 1 : slot + 1

    system.run(() => {
        target.selectedSlotIndex = slot
        system.run(() => {
            target.selectedSlotIndex = slot + 1
        })
    })
})
thorn flicker
ocean escarp
#

Anything past return was an old method

#

I wish itemUse fired constantly while held

distant tulip
ocean escarp
#

Would make this 10x easier

thorn flicker
#

sure.

distant tulip
ocean escarp
wary edge
#

itemStartUse?

ocean escarp
lethal lichen
#

2nd one is a bit tough, maybe i could do some symbol stuff

wary edge
#

itemStartUse->logic->itemStopUse->stop logic

thorn flicker
#

yeah im currently doing this for my full auto weapon.

honest spear
ocean escarp
#

I've got a variable for whether or not they are eating

honest spear
ocean escarp
#

That much is done but you can't cancel a var

lethal lichen
ocean escarp
#

It's supposed to be taking any kind of damage interrupts eating

#

but there isn't an event I can cancel to stop the eating action midway

#

Hence why I'm trying hacky solutions

lethal lichen
honest spear
lethal lichen
#

i'm guessing it's without generators then

honest spear
#

yea pretty much

ocean escarp
#

Wait this comes with its own set of problems

#

It can accidentally delete items if you switch slots on the same tick as you take damage

#

Maybe the hotbar switch was better..

#

I cant think of any other actions that could cause a player to stop eating

#

Well I can think of 1 but I don't think scripts can touch it

#

Nevermind

lethal lichen
gaunt salmonBOT
sharp elbow
#

Generators would be ideal for this though. Not sure why this is a for in question and not a for of question.

sharp elbow
gaunt salmonBOT
sharp elbow
#

A more appropriate place for getting bot output would be #bot-usage @viral osprey

lethal lichen
#

i'm reading through the for...in spec but doesn't seem like anything will help

ocean escarp
#

Sprunkles could you help me out with a slight alteration to my code?

sharp elbow
#

Sure. Assume I have read none of the chat history for two hours

ocean escarp
#

This current part after the return handles switching hotbar slots to an adjacent 1, however I want to randomise the direction if not on either of the edges

#

ignore the 2nd system.run

#

That was to test if it looked good snapping back

#

(it didn't)

sharp elbow
#

I would write a function for the modulo operation. This lets you perform division on two numbers, then take the remainder.

function mod(a, b) {
  return ((a % b) + b) % b;
}

// ... inside your event
{
  // Pick either -1 or 1
  const direction = Math.sign(Math.random() - 0.5);
  // Divide the slot index by 9, take the remainder
  // number in range of 0..8, perfectly valid for hotbar slots
  slot = mod(slot + direction, 9)
}
ocean escarp
#

Im trying to understand how this works logically

#

A modulo of a / b is this not rather complex for picking 1 or -1?

sharp elbow
#

Well, for picking -1 or 1 is on a step handled separately. That's what the expression Math.sign(Math.random() - 0.5) does

#

We're rolling a random number in the range (0, 1], subtracting 0.5 to make the range (-0.5, 0.5], then taking the sign of that number. It's a nearly perfect 50/50 split between -1 and 1 (with an infinitesimally small chance of returning 0)

#

The modulo operation is being used here so the slot that we pick stays within the bounds of 0..8 (for slots 1..9)

ocean escarp
#

isnt there a function to randomly pick from an enum?

sharp elbow
#

From an enum; can you elaborate? That could mean a number of different things

ocean escarp
#

An enum is a collection of set values you can choose from no? Or maybe my illness is clouding my memory

sharp elbow
#

I agree on that definition, but there are several different implementations for enums. Most nefarious of all being a TypeScript enum

ocean escarp
#

Im only familiar with the standard definition

#

I'm still tryna figure out what

slot = slot ? slot - 1 : slot + 1

Actually does

#

Well I know what but not how

sharp elbow
#

What it does plainly might not follow what you expect. If slot is truthy (in the case of numbers, a non-0 value), then we return slot - 1, or otherwise slot + 1

ocean escarp
#

ah so that means 1+ always goes down and 0 always goes up

#

slot is just the indexId in this scenario which I guess does make sense

sharp elbow
#
function assignSlot(slot) {
  return slot ? slot - 1 : slot + 1;
}

assignSlot(0)   // 1
assignSlot(1)   // 0
assignSlot(2)   // 1
assignSlot(3)   // 2
// Negative numbers are also truthy
assignSlot(-1)  // -2
ocean escarp
#

so I guess I can replace slot + 1 with slot + math.round(randInt(-1, 1)) or equivalent unless slot = 8

sharp elbow
#

If slot == 8, then it's possible it assigns to 9, which would be out of range. Similarly, if slot == 0, then it's possible it assigns to -1, which is also out of range

ocean escarp
#

0 wouldn't work cause of truthy no?

#

I might have the equation on the wrong end

sharp elbow
#

Ah, you meant if you replaced only the false condition in the ternary, I misread. Then yeah, I suppose it would

ocean escarp
#
if (slot = 8) {
slot = slot - 1
return 
}
slot = slot ? slot - math.round(rand(-1, 1)) : slot + 1
ocean escarp
sharp elbow
#

If you're having the player's slot change, wrapping is a natural consequence, no? If I scroll past slot 9, I end up on slot 1; that's not unexpected, at least to me

ocean escarp
ocean escarp
sharp elbow
#

Fair

ocean escarp
#

I need an alternative to round that will always round away from 0

#

0.002 -> 1
-0.31 -> -1

sharp elbow
#

I'd probably write it this way then:

if (slot == 8) {
  slot = slot - 1;
}
else {
  const push = Math.sign(Math.random() - 0.5) || 1;
  slot = slot ? slot + push : slot + 1;
}
ocean escarp
#

Can you explain math.sign to me? never used it and I would like to understand what I write

sharp elbow
#

Yup. The sign function returns the signed value of a number:

  • If < 0, return -1
  • If > 0, return 1
  • If 0, depends (some implementations return 0, some 1)
ocean escarp
#

Oh so like exactly the function I was looking for

sharp elbow
#

Quite nice, eh? haha

ocean escarp
#

How many dp does math.random go to?

sharp elbow
#

Sorry, DP?

ocean escarp
#

Decimal places

sharp elbow
#

Ah. Well numbers in JavaScript are 64-bit floating point values; that might not have an exact answer, since that depends on how close to 0 the resulting number is. But it has a fair amount of precision in that range

ocean escarp
#

Just was wondering the chances on rolling exactly 0

sharp elbow
#

Really, really, really small. Infinitesimally small

ocean escarp
#

This also handles for that edge case right?

#

Imagine if I gave them a diamond for being that ungodly lucky lol

sharp elbow
#

Aye, if it does roll 0 for whatever reason, my example uses the OR operator to evaluate it to another value.

As a simpler example, Math.random() || 0.5 will return a random number in the range [0, 1], with any 0 rolls turning to 0.5

ocean escarp
#

Well I appreciate the help

#

This should finally be a functioning cancel system

#

Yep it works

#

Eating gets cancelled by taking damage

#

And it actually is a tiny bit punishing

#

What's is the and operator again?

#

I need to exclude 2 damage types

#

It's just && right?

sharp elbow
#

Yup, a && b

ocean escarp
#

Ty

#

Cause I don't think fire / poison should prevent gapple usage

sharp elbow
#

Maybe starvation damage too

ocean escarp
#

Honestly thanks for the catch there

#

Maybe I should just create an array

#

Cause wither is it's own damage type too

sharp elbow
#

You definitely could. Though it would be good to delcare the array outside of the function, so the game isn't building a new one every time you or any other entity takes damage

ocean escarp
#

I have no clue what to call these

#

1 is all types that don't cancel eating and the other is all types that get a reduced damage floor

#

Actually tbh they're probably the same

sharp elbow
#

When in doubt, super long variable names: eating_cancel_ignored_damage_types

ocean escarp
#

special_damage_types

sharp elbow
#

And if you're still unsure about the name, you could always add a docstring above it, so you know what it is used for

ocean escarp
#

True

#

I think this is good

#

Now I gotta figure out how to implement this

#

If the damage type is not in the list. Cancel eat

sharp elbow
#

Any solution would involve iterating the array. You have many different solutions at your disposal for that; probably the simplest is using the includes() method.

ocean escarp
#

if array.includes(damageType) ?

sharp elbow
#

Yup, pretty much

ocean escarp
#

So I gotta flip it

#

I don't think js has unless?

sharp elbow
#

Can you give an example?

ocean escarp
#

unless (conditions) {}

sharp elbow
#

I suppose you could use logical negation. if (!condition) {}

ocean escarp
#

I think that should work?

sharp elbow
#

Aye; if it is any of those damage types, then the condition fails

ocean escarp
#

Well I've ran into a bug

#

Sometimes the slot changes but not visibility on the hotbar

sharp elbow
#

Hm. I'm guessing it's a client–server desync

ocean escarp
#

I am using system.run instead of system.runTimeout(code, 2)

#

That don't look like a gap

crude ferry
#

Identifier cannot start with a digit.
Even:

function 1add () {

}```isn't valid.
stray spoke
#

I guess just add a prototype to Number class

#

Tho it works on all numbers

#

Nvm it didn't work

crude ferry
#

It does work lol?

#

Did you use an arrow function? They do not have this. (At least, they do not have this of their own.)

subtle cove
#

we discussing cursed js... bao_panda_munching

crude ferry
#

Oh well.

shut citrus
#

how to get blocks break duration or detect how soft blocks are?

cerulean cliff
#

can we not translate the result message of custom commands?

shy leaf
#

if you just directly use translation key

#

well, at least thats how it is with description

subtle cove
#

tried this, and it works js return { status: CustomCommandStatus.Failure, message: `${origin.sourceEntity.name} failed to %gui.confirm` }

cerulean cliff
#

oh well

#

time to put yet another thing onto the weirdo list

shy leaf
#

you register a custom command at the start of world(server) which cant be changed later on

cerulean cliff
#

the client gets a raw message that it translates itself

shy leaf
cerulean cliff
#

yeah

#

oh well