#Script API General

1 messages · Page 130 of 1

untold magnet
#

can u show me the other one u talked about? (using the button input thingy)

#

so i can do some testing with it,

dusky flicker
#

holdon

#

i got to mount my ssd

#

to have access to the files

untold magnet
#

alright

#

ill try to return false when the player gets knockback, so getting hit or being launched by an explosion will not count as a jump

dusky flicker
#

i forgot where my files are '-'

untold magnet
#

great job!

#

jk, gl finding them

dusky flicker
#

xd

#

found it

#

i was searching it on .local but it was on .var

#

'-'

#
 world.afterEvents.playerButtonInput.subscribe((ev) => {
    for (const component of components)
      if (component.affected_items.has(current))
        if (
          ev.button === InputButton.Jump &&
          ev.newButtonState === ButtonState.Pressed
        )
          component.onJump?.(ev.player);
        else if (ev.button === InputButton.Sneak) {
          if (ev.newButtonState === ButtonState.Pressed)
            component.onSneak?.(ev.player);
          else component.onStopSneak?.(ev.player);
        }
  });
if (!player.isFalling && !player.isFlying) {
      const velocity = player.getVelocity();
      const len = this.velocity_amplifier >> 1;
      velocity.x *= len;
      velocity.y ^= velocity.y;
      velocity.z *= len;
      ev.applyImpulse(velocity);
    }
untold magnet
#

currently, i did some major improvements to it, fixing most of those issues

untold magnet
untold magnet
#

now breeze-balls doesnt count as jump, any explosion that damages u and knocks u into the air doesnt count as jump, including being damaged and get a tiny bit of knockback, thats also doesnt count as a jump

#

BUT, minor knockbacks that doesnt damage u but throws u into the air by EXACTLY a block, will count as a jump.

dusky flicker
#

just from my script

#

it ain't made to be copy pasted

#

i mean, i didnt write it here with this purpose

untold magnet
untold magnet
#

i mean, what else? is there anything else that makes u go upwards against ur will?

#

i did some reseach, these things can still count as a jump:
riptide trident
fishing rod (only happens on multiplayer when one of the players decide to fish u for whatever reason)
blocking a ravager with a sheild to trigger its knockback roar and blocking that with ur shield.
landing on slime - fixed

#

ill do some more testings ig

untold magnet
#

ill give queries a shot, they might work better
nope, there are no hope, there might be some hope, ill give it a shot tho.

untold magnet
harsh robin
#

Any idea why this isn’t workin. And a work around it ```javascript
import { world } from "@minecraft/server";
world.beforeEvents.chatSend.subscribe(async (eventData) => {
if(eventData.message.includes("")) {
eventData.cancel = true
eventData.sender.runCommand("kick @s")
}
});

valid ice
#

Which part isn’t working? The kick?

harsh robin
#

Already fixed lol

dusky flicker
dusky flicker
untold magnet
untold magnet
dusky flicker
dusky flicker
#

if so i don't think i can think in anything else

untold magnet
#

u can use a shield to block the damage

#

and get knockback,

#

that kind of knockback counts as a jump,

#

and fishing rods can still pull u and counts as a jump

#

gotta play some isaac,

dusky flicker
#

i really think as you got it working, even though nlt perfect, you should keep working in other things on the addon

#

and then when you have more stuff completed

#

improve the jump system

summer cloud
#

why does this function crash my game when ran? It used to not, but recently it just started for some reason

untold magnet
#

@distant tulip show me ur button input method so i can test it out and see if it works better or worse,

distant tulip
#

It won't work with auto jump as Serty said

untold magnet
distant tulip
#

Well send it in a bit

distant tulip
#

@untold magnet

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

const jumpIntervals = new WeakMap();

world.afterEvents.playerButtonInput.subscribe(({ player, button, newButtonState }) => {
  if (button !== InputButton.Jump) return;

  if (newButtonState === ButtonState.Pressed) {
    if (jumpIntervals.has(player)) return;

    const handle = system.runInterval(() => {
      if (!player.isValid || !player.isJumping) return;

      console.log("Player is jumping");
    }, 1);

    jumpIntervals.set(player, handle);
  }

  if (newButtonState === ButtonState.Released) {
    const handle = jumpIntervals.get(player);
    if (!handle) return;

    system.clearRun(handle);
    jumpIntervals.delete(player);
  }
});
untold magnet
distant tulip
#

it does not
add a delay to the interval
there is no other way afaik

untold magnet
distant tulip
#

eh... good luck

#

btw your original version have a bug

#

return in a loop break the loop, so not multiplayer friendly
use continue

untold magnet
#
import {world, system, InputButton, ButtonState} from '@minecraft/server';

const jumpIntervals = new WeakMap();
const jumpCache = new Map();

world.afterEvents.playerButtonInput.subscribe(({player, button, newButtonState}) => {
    if (button !== InputButton.Jump) return;

    if (newButtonState === ButtonState.Pressed) {
        const handle = system.runInterval(() => {
            const vY = player?.getVelocity().y;
            const hasJumped = jumpCache.get(player?.id) ?? 0;
            const eBlock = player?.getBlockStandingOn();
            if ((player?.isOnGround || player?.isInWater) && hasJumped === 1 && (eBlock?.typeId !== 'minecraft:slime' || (eBlock?.typeId === 'minecraft:slime' && vY === 0))) jumpCache.set(player?.id, 0);
            if ((!player?.isOnGround && !player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0) {
                jumpCache.set(player?.id, 1);
                world.sendMessage('jump');
            };
        }, 1);
        jumpIntervals.set(player, handle)
    };
    if (newButtonState === ButtonState.Released) {const handle = jumpIntervals.get(player); if (!handle) return; system.clearRun(handle); jumpIntervals.delete(player)};
});;```
#

it wasnt registering the first jump

#

like it was only detecting when u jump twice, not once,

#

so i fixed that,

#

hold on,,

untold magnet
untold magnet
# distant tulip <@917785883959263293> ```js import { world, system, InputButton, ButtonState } ...

final results:

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

export const ePlayers = new Set();
const jumpIntervals = new WeakMap();
const jumpCache = new Map();

world.afterEvents.playerJoin.subscribe(({playerId}) => {ePlayers.add(playerId)});
world.afterEvents.playerLeave.subscribe(({playerId}) => {ePlayers.delete(playerId); jumpCache.delete(playerId)});

system.runInterval(async () => {
    for (const ID of ePlayers) {const player = world.getEntity(ID);
        if (!player?.isValid) return;

        const hasJumped = jumpCache.get(player?.id) ?? 0;
        const eBlock = player?.getBlockStandingOn();

        if ((player?.isOnGround || player?.isInWater) && hasJumped === 1 && (eBlock?.typeId !== 'minecraft:slime' || (eBlock?.typeId === 'minecraft:slime' && vY === 0))) jumpCache.set(player?.id, 0);
    };
});;

world.afterEvents.playerButtonInput.subscribe(({player, button, newButtonState}) => {
    if (button !== InputButton.Jump) return;

    if (newButtonState === ButtonState.Pressed) {
        {const hasJumped = jumpCache.get(player?.id) ?? 0; const vY = player?.getVelocity().y; if ((!player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0 && vY !== 0.15000152587890625); world.sendMessage('First Jump'); jumpCache.set(player?.id, 1)};

        const handle = system.runInterval(() => {
            const vY = player?.getVelocity().y;
            const hasJumped = jumpCache.get(player?.id) ?? 0;
            if ((!player?.isOnGround && !player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0) {
                jumpCache.set(player?.id, 1);
                world.sendMessage('Jump')
            };
        });
        jumpIntervals.set(player, handle);
    };
    if (newButtonState === ButtonState.Released) {const handle = jumpIntervals.get(player); if (!handle) return; system.clearRun(handle); jumpIntervals.delete(player)};
});;```
#

does not detect auto jump,

#

lets be real here, who tf uses auto jump in the big 2026?

untold magnet
#

it will detect some too low jumps (vY > 0 && vY < 0.02) in low TPS,

cold grove
untold magnet
#

jk

nova wraith
#
    {
          typeId: "goat:steve_kit",
          onUse: (e, world, player, item) => {
             const steve = player.dimension.spawnEntity("goat:steve", player.location);
             const tameable = steve.getComponent("minecraft:tameable");
             tameable.tame(player);
             steve.nameTag = "Steve"
          }
    },

This was working before but for some reason it's not working anymore, did they changed something?

nova wraith
marble sigil
#

Does anyone know to detect a left click or tap on mobile?
entityHitBlock works, but it's meh for mobile users. 🫠

wary edge
marble sigil
#

It's not instant

#

Like if I just tap on a block, it wouldn't fire.

untold magnet
# fair quarry Mobile users

@distant tulip update-
this tiny system works just fine, even autojump is working with it:

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

const jumpCache = new Map();

system.runInterval(() => {
    for (const ID of world.getAllPlayers()) {
        if (!player?.isValid) continue;

        const hasJumped = jumpCache.get(player?.id) ?? 0;
        const eBlock = player?.getBlockStandingOn();

        if ((player?.isOnGround || player?.isInWater) && hasJumped === 1 && (eBlock?.typeId !== 'minecraft:slime' || (eBlock?.typeId === 'minecraft:slime' && vY === 0))) jumpCache.set(player?.id, 0);
        if (player?.isJumping && (!player?.isOnGround && !player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0 && (vY > 0.15 && vY < 0.155)) {
            jumpCache.set(player?.id, 1);
            world.sendMessage('Jump')
        };
    };
});;```
untold magnet
#

vY !== 0.15000152587890625 is used to stop detecting scaffoldings

sharp elbow
#

Please don't do equality comparisons with floats like this, this is making me cry

#

Do an absolute error check, like if it is ±0.01 from 0.15

distant tulip
#

or just use player.isJumping

wary edge
#

Asking again since my last attempt works well but not perfect.

Is there a reliable way to detect player mining? My attempt utilised hitBlock, PlayerSwing and playebreak which works well. However, the issue arise when youre continuously mining thus not griggering the hitBlock.

untold magnet
dusky flicker
#

for example

#

floats dont have inifinite precision

#

so its pretty unlikely to get something with so many numbers after the '.'

untold magnet
distant tulip
#

Isn't there isClimbing? Or did my mind make that up

round bone
thorn flicker
untold magnet
untold magnet
untold magnet
#

maybe via a item cooldown or whatever

thorn flicker
#

itemReleaseUse has a useDuragtion property, you can check if its longer than the charge complete time to detect when the player releases it to lunge.

untold magnet
thorn flicker
#

umm okay

#

thought you had to charge it for that.

untold magnet
#

so ig ill have to detect if the spear is enchanted with lunge, the spear cooldown and detect if the hunger is < 6

untold magnet
thorn flicker
#

I just forgot how the spear worked

thorn flicker
#

no need to check for the cooldown neither, because you cant swing during the cooldown with it.

untold magnet
# thorn flicker no need to check for the cooldown neither, because you cant swing during the coo...

too late

            const lunge = itemStack?.getComponent('minecraft:enchantable')?.getEnchantment('lunge');
            const hasLunged = lungeCache.get(player?.id) ?? 0;

            if (itemStack?.typeId.endsWith('_spear') && lunge && hunger?.currentValue > 6) {
                const cooldown = itemStack?.getComponent('minecraft:cooldown')?.getCooldownTicksRemaining(player);
                if (cooldown !== 0 && hasLunged === 0) {
                    lungeCache.set(player?.id, 1);
                    console.warn('Lunged');
                } else if (cooldown === 0) lungeCache.set(player?.id, 0);
            } else lungeCache.set(player?.id, 0);```and it works lol
thorn flicker
untold magnet
#

yeah

thorn flicker
#

worse performance

#

consider what i suggested

untold magnet
untold magnet
thorn flicker
untold magnet
thorn flicker
#

cant you just use playerButtonInput

#

i know autojump doesnt get detected with it but what else is wrong with it

untold magnet
# thorn flicker what

basically, a core addon (more like a library mod on java) that contains all of my addons functionality, so instead of having a runInterval inside each addon, ill just have one large interval inside the core addon and it will contain all of the other addons functions.

untold magnet
#

and tbh, i did manage to modify the playerButtonInput one and force it to work just like how i wanted, but the only downside was that autojump wasnt detectable, and that button input detection has a runInterval inside of it, so it is the worse option,

thorn flicker
untold magnet
# thorn flicker why what?

button input:

system.runInterval(() => {
    for (const ID of world.getAllPlayers()) {
        if (!player?.isValid) return;

        const hasJumped = jumpCache.get(player?.id) ?? 0;
        const eBlock = player?.getBlockStandingOn();

        if ((player?.isOnGround || player?.isInWater) && hasJumped === 1 && (eBlock?.typeId !== 'minecraft:slime' || (eBlock?.typeId === 'minecraft:slime' && vY === 0))) jumpCache.set(player?.id, 0);
    };
});;

world.afterEvents.playerButtonInput.subscribe(({player, button, newButtonState}) => {
    if (button !== InputButton.Jump) return;

    if (newButtonState === ButtonState.Pressed) {
        {const hasJumped = jumpCache.get(player?.id) ?? 0; const vY = player?.getVelocity().y; if ((!player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0 && vY !== 0.15000152587890625) {world.sendMessage('First Jump'); jumpCache.set(player?.id, 1)}};

        const handle = system.runInterval(() => {
            const vY = player?.getVelocity().y;
            const hasJumped = jumpCache.get(player?.id) ?? 0;
            if ((!player?.isOnGround && !player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0) {
                jumpCache.set(player?.id, 1);
                world.sendMessage('Jump')
            };
        });
        jumpIntervals.set(player, handle);
    };
    if (newButtonState === ButtonState.Released) {const handle = jumpIntervals.get(player); if (!handle) return; system.clearRun(handle); jumpIntervals.delete(player)};
});;```
thorn flicker
#

"why fucking it"

untold magnet
#

new:

        const hasJumped = jumpCache.get(player?.id) ?? 0;
        const eBlock = player?.getBlockStandingOn();

        if ((player?.isOnGround || player?.isInWater) && hasJumped === 1 && (eBlock?.typeId !== 'minecraft:slime' || (eBlock?.typeId === 'minecraft:slime' && vY === 0))) jumpCache.set(player?.id, 0);
        if (player?.isJumping && (!player?.isOnGround && !player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0 && (vY > 0.15 && vY < 0.155)) {
            jumpCache.set(player?.id, 1);
            world.sendMessage('Jump')
        };```
thorn flicker
#

what does that even mean

untold magnet
#

which one is better?

#

both has intervals,

untold magnet
thorn flicker
#

its the way you are saying it

untold magnet
untold magnet
thorn flicker
untold magnet
#

just bec it works well, doing what i want it to do, (detects whenever the player jumps)

#

even with autojump

wary edge
untold magnet
untold magnet
# wary edge However, if the code is not optimise that would triumph over this saying.
import {world, system} from '@minecraft/server';

export const ePlayers = new Set();
const jumpCache = new Map();

world.afterEvents.playerJoin.subscribe(({playerId}) => {ePlayers.add(playerId)});
world.afterEvents.playerLeave.subscribe(({playerId}) => {ePlayers.delete(playerId); jumpCache.delete(playerId)});

system.runInterval(() => {
    for (const ID of ePlayers) {const player = world.getEntity(ID);
        if (!player?.isValid) continue;

        const hasJumped = jumpCache.get(player?.id) ?? 0;
        const eBlock = player?.getBlockStandingOn();

        if ((player?.isOnGround || player?.isInWater) && hasJumped === 1 && (eBlock?.typeId !== 'minecraft:slime' || (eBlock?.typeId === 'minecraft:slime' && vY === 0))) jumpCache.set(player?.id, 0);
        if (player?.isJumping && (!player?.isOnGround && !player?.isInWater && !player?.isClimbing) && hasJumped === 0 && vY > 0 && (vY > 0.15 && vY < 0.155)) {
            jumpCache.set(player?.id, 1);
            world.sendMessage('Jump')
        };
    };
});;```is it like bad for performance or something?
thorn flicker
#

triggering code every tick vs only when it needs to

untold magnet
thorn flicker
#

but then youll clear the interval when you no longer need it

untold magnet
#

that interval is per player, more player holding the jump button means more intervals,

wary edge
#

You're not clearing the runs.

untold magnet
#

if i did clear the runInterval, the whole addon will stop working, bec that one interval contains everything

#

ig i need to return if not used somehow

wary edge
untold magnet
#

-# maybe cuz im tired,

wary edge
#

Then take the time off to rest. Approach this later.

subtle cove
#

time for some rest then

thorn flicker
#

this is why i try not to code when tired, its more stressful lol

untold magnet
subtle cove
#

inputbutton event doesnt trigger unless the button is pressed/unpressed

thorn flicker
untold magnet
#

autojump doesnt require any button inputs

thorn flicker
#

ig the only way would be in system.runInterval like they were originally using

subtle cove
#

hmm

untold magnet
wary edge
#

What are you needing to detect jumping for?

untold magnet
#

stamina addon and possibly for other addons

subtle cove
#

would basing it off it's velocity be not a gud approach?

untold magnet
#

but, how am i going to detect the velocity when needed?

#

it has to be inside a runInterval

#

or just if (vY === 0) continue;

subtle cove
#

isOnGround checks?

untold magnet
#

so it wont run the jump detectors when the player is not jumping and has no vertical velocity

subtle cove
#

oh well, prob another complex logic

untold magnet
#

all of this struggle, is just bec mojang didnt add entityJumpAfterEvent

#

but ay, at least i did find a workaround,

#

at the cost of some performance,

#

-# its just, way way better than whatever abomination i have made in the Enhanced Mobs addon

#

that script is really unhealthy imo

thorn flicker
#

"unhealthy" lol

subtle cove
#

unhealthy indeed

untold magnet
# thorn flicker "unhealthy" lol
let count = 0;

system.runInterval(() => {
    count++;
    ['overworld','nether','the_end'].map(dim => {
        for (const entity of world.getDimension(dim).getEntities({propertyOptions:[{propertyId:'xhardercore:worker',value:'employed'}]})) {...}
    });;
});;```what could possibly go wrong?
#

those 'employed' are zombies that can place blocks, track their target and even mine blocks,

#

the average american is more healthy than this script

untold magnet
subtle cove
#

what abt /execute cmd for such and trigger scriptevent, altho idk what the performance would be like

untold magnet
#

no /execute and no scriptevent

#

i can show u the full script if u want, and tell me if its healthy or not

subtle cove
#

nah, i'd rather let u take some rest, lol

untold magnet
#

i cant

#

im downloading a game, it will be finished in an hour (probably two) bec the internet is too shitty

#

so i wont sleep anytime soon,

subtle cove
#

even power naps...

untold magnet
#

and ay, i code better while being tired, (speaking of experience)

#

i just cant understand others well while being tired,

subtle cove
#

can't disagree to that ngl

untold magnet
untold magnet
sinful portal
#

I just realized functions are objects in javascript...

#

what

#

so you can attach properties to functions

#

I now understand functional programming than OOP...

dusky flicker
sinful portal
#

do people really slap some variables inside the function object 💀

#

can be useful in react though

sinful portal
remote oyster
sinful portal
#

this can be useful to avoid classes I assume

remote oyster
# sinful portal this can be useful to avoid classes I assume

Definitely, but also personal preference as well. Some are accustomed to using classes due to their experience and background in other areas so even though functions as objects can, in many ways, be far more superior, some still use classes out of comfort and experience. So there definitely isn't anything wrong with classes in JS. Just different by nature lol.

sinful portal
#

yeah. I like OOP too very flexible for me

remote oyster
sinful portal
subtle cove
#

depends if u can remember all the logic behind, which is very hard to track when coding

remote oyster
# sinful portal The problem with this is you can only attach properties at runtime

That’s the beauty of writing code lol, understanding the strengths and weaknesses of different approaches and choosing based on the trade-offs.

When I see people debating what’s “good” or “bad,” I usually just step away. At that point, it often comes down to preference and context. There are many ways to accomplish the same goal, some may be better suited than others, but rarely is there only one “correct” way.

subtle cove
#
export const parseFirstMention = (message = "@") => {
    let rgxResult = parseFirstMention.rgx.exec(message);
    if (!rgxResult) return null;
    const lastIndex = message.search(rgxResult[0]) + rgxResult[0].length;
    return {
        name: rgxResult[2] || rgxResult[3] || "",
        message: message.slice(lastIndex).trimStart(),
    };
};
parseFirstMention.rgx = /(@(?:"([^"]+)"|(\S+)))/;
```got this rgx attached cus regex is expensive when triggered in large quantity
remote oyster
#

That's a smart idea.

#

I like it.

sinful portal
subtle cove
#

no

sinful portal
#

why not just create a variable?

#

for the rgx

subtle cove
#

it costs some performance

sinful portal
#

Mind explaining how it costs performance

#

rather than just using a constant

subtle cove
#

instantiating regex is different from instantiating number/string/boolean

sinful portal
#

mmmmm I see

#

but wouldnt the byte size be the same?

subtle cove
#

same with instantiating a function

sinful portal
#

mmm I see

subtle cove
#

size is different from performance
like RAM isnt CPU...

#

idk, its just there to lessen cpu work

sinful portal
#

not entirely sure how instantiation of functions work too lol

warm jungle
#

is it possible to play swing animation on playerInteractWithBlock?

subtle cove
#

doing ()=> {} is instantiating already, which isn't rly expensive

thorn flicker
subtle cove
thorn flicker
#

unless the block is interactable

warm jungle
thorn flicker
warm jungle
#

Nope, I'm using a custom block

thorn flicker
subtle cove
thorn flicker
#

giving it the onPlayerInteract event will make it interactable and the player will swing their arm.

warm jungle
#

ohh okaayy, Thankk youu!! I'll try it

thorn flicker
warm jungle
#

Thankss!

fallow minnow
#

how can i make my camera follow another players camera in 3rd person?

#

like a "follow" command

wise nova
#

Can I use PlayerInventoryChangeAfterEvent to detect Entity's inventory

thorn flicker
#

meaning only player.

prisma shard
#

Oh hi

#

People still doing scripting

cold grove
thorn flicker
#

lol

frosty yoke
cold grove
#

You still have a constructor, methods and properties

#

Thats how people used to make classes/object templates before they were implemented in javascript bao_ext_toldyouso bao_ext_toldyouso bao_ext_toldyouso

sinful portal
sinful portal
cold grove
#

People code as they like, it will work anyway lol

warm jungle
#

is there a best way to filter out a values in formValues?? (Modal Form) there's still a undefined on the array..

#

nvm got it

sharp elbow
honest spear
#

real

honest spear
#

TS and JS are really magical with the core concepts of prototypes, its really unique in its sense, i am not sayin its good practice to modify or manipulate but once you do then everything starts feeling magical 🙃

sharp elbow
#

I wish object prototypes were more accessible in TypeScript. TS is really not built around JS structures

honest spear
#

yea

jolly junco
#

thanks

sullen ocean
sullen ocean
#
// JavaScript
// Note that single '>' in comments is for example input.
class MyClass {
  constructor (/*args here btw*/) {
    // Code that runs when this is done:
    // > new MyClass(/*args here*/)
    // To access the instance use `this`:
    // > this.property = newValue // etc.
  }
  myMethodName (/*args*/) {
    // Invoked when an instance uses it:
    // > let ins = new MyClass();
    // > /*result = */ ins.myMethodName();
  }
  // myMethod2 and myMethod3 are used by the subclass. They are still methods fom here though.
  myMethod2 (/*args*/) {}
  myMethod3 (/*args*/) {}
  get something () {
    // A "getter" for the property named `something`. Getters accept zero arguments, but does have `this` accessible. Should return a value.
    // > console.log(theInstance.something);
  }
  set something (value) {
    // A "setter" for the property named `something`. Setters accept one (1) argument, along with implied `this` accessible. Don't return a value from here.
    // > theInstance.something = value;
  }
  // A getter can have no setter, and same the other way around. Trying to read a write-only property (w/o a getter) or trying to set a read-only property (w/o a setter) will cause an error.
  get readOnly () {
  }
  set writeOnly (value) {
  }
}

// You can also subclass. Can only have one base class but can chain it.
class MyOtherClass extends MyClass {
  constructor (/*args*/) {
    // The constructor requires invoking
    // > super(/*args here*/)
    // exactly once before you can access `this` from the subclass constructor
  }
  foo (/*args*/) {
    // You can add new methods.
  }
  myMethod2 (/*args*/) {
    // You can completely override methods.
  }
  myMethod3 (/*args*/) {
    // Also can override but still invoke from the parent class:
    // > return super.myMethod3(/*args*/);
  }
}
honest spear
sullen ocean
honest spear
#

Have you ever modified native class prototypes

sullen ocean
#

Can you have the game send to chat the result of typeof Proxy (should return a string)?

#

I'm curious if it is implemented.

honest spear
#

typeof always returns string

#

thats how the operator works

sullen ocean
#

I know that... I meant "the output of this should work if you send it to the chat... could you see if Proxy exists, please?"

#

If it does exist, it should say function.

#

I recall this because you can use Proxy to override an object's getters and setters, even to properties / methods / etc. that are not yet defined on the object.

Info I know about is from MDN: https://developer.mozilla.org/

#

If you are just overwriting specific methods, that sort of monkey-patching works (that you shown).

honest spear
#

Proxy is indeed available in MC engine

#

not sure what you want to prove tho

#

you can use proxy as you wish but keep in mind that proxy is not same object, its a wrapper on top of it

#

so if the native isntance is the raw handle, then you loose the identity of it

sullen ocean
#

Proxy (and the Reflect that is used with it) is more usable when you want to work on something like an Array:

let arr = [];
Object.getOwnPropertyNames(arr); // result: ['length']

arr.length = 5;
Object.getOwnPropertyNames(arr); // result: ['length']

arr = Array(5);
Object.getOwnPropertyNames(arr); // result: ['length']

arr = Array.from({length:5});
Object.getOwnPropertyNames(arr); // result: ['0','1','2','3','4','length']
honest spear
#

¯_(ツ)_/¯

#

i am still confused

#

what are you trying to say?

#

can i help you somehow?

sullen ocean
sullen ocean
honest spear
#

idk i don't think i have shown anything yet?

#

thats why i am confused

#

my bad

sullen ocean
#

If the task I saw earlier was just overriding specific methods of a global built-in object, using a class is overkill.

I noticed so I sent that message once I realized it.

#

The part of Proxy was just curiousity.

honest spear
#

I am missing the context sorry

#

i didn't say anything about classes afaik

sullen ocean
honest spear
#

OK and?

#

i am confused

#

can i help you somehow?

sullen ocean
#

The one you replied to.

#

That kind of use seems to be better suited for a class.

honest spear
#

sure

#

?

#

and?

#

i am sorry, but i feel like i am still missing something

#

how do i involve in that?

#

I think i didn't say anything about classes

sullen ocean
#
  • Set and Map are classes as you must use the new keyword to initialize them.
  • Error is a class but will implicity add the new keyword if called without it.
  • Date is also a class, but when called without the new keyword, it acts differently.
honest spear
#

and NaN is number btw

#

just sain

#

like you do

sullen ocean
sullen ocean
honest spear
sullen ocean
#

... never mind.

honest spear
#

i am so confused 😭 don't do that to me

sullen ocean
#

And obviously I'm bad at expressing things properly, such as replying to the wrong person / message.

honest spear
#

ahhh, i see i thought i did something wrong or whatever looks like its just a misunderstanding 👍

sullen ocean
#

My honest apologies...

honest spear
#

Good, good, don't worry, i just got confused

sullen ocean
#

The subject shift to Proxy was just my own curiousity.

honest spear
#

also do you generate some of your answers by AI?

#

nvm

sullen ocean
#

The only times I have, I always make sure to explicitly mention I did... and never once have I used it for code.

honest spear
#

anyway Proxies are really nice, but i avoid them as much as possible

sullen ocean
#

I trust AI as much as I trust back when I was a kid and my ability to hold myself on the chin-up bar (read: I don't trust it at all)

honest spear
#

its really bad for debugging

sullen ocean
#

I assume Symbol is also supported?

honest spear
#

yea

#

Symbol is like ES5 afaik

#

or ES6 idk

#

i mean BigInts were not supported for long time

#

but nowdays it has almost everthing

#

@subtle cove Do you rememeber any of environment apis that are still not available?

honest spear
distant tulip
#

Buffer and ArrayBuffer

honest spear
#

they are supported tho

#

i used them many times already

distant tulip
#

wait really?

honest spear
#

just there is not much of usecases for them

#

if we didn't got the Script API integration

#

i wish we had Uint8Array is valid DP value

honest spear
sullen ocean
#

Is there BigInt ?

distant tulip
#

yeah

honest spear
#

yea

sullen ocean
#

My bad.

distant tulip
honest spear
#

i was just messing around with globals haha

distant tulip
#

i can think of few use cases in bds but i never needed to use that

honest spear
#

python mentioned 💀

#

sounds like a crime to me

#

¯_(ツ)_/¯

#

Python is just wrong at its core, the syntax is just unacceptable

#

thats all i don't like about it

#

i don't care if its slow or whatever

#

Readability is not really that super good for python eather

#

you have to get big tabs to make it more readable except you might miss on what level of scope it is

distant tulip
#

that is really not a good way of comparing

a turtle is faster than a rabbit without legs, yeah sure

cold grove
#

How is python related to scripting api

sullen ocean
cold grove
#

You dont have to

#

I was reading it

sullen ocean
#

Too late... hopefully most of the non-JS stuff is out.

sullen ocean
# cold grove I was reading it

For Python stuff that I do know, you can ask in DMs... I'll try opening one with you (so I remember after I am done showering)

distant tulip
buoyant canopy
#

is it possible to get subtick delay?
i need to run something exactly every 3.5 ticks

honest spear
#

thats not really possible, the lowest you can make it is tick it self

#

thats how the game operates

#

i suggest doing some thing every 3 and 4 ticks

#

so at the end the interval is two times per 7 ticks

buoyant canopy
#

i tried both, 3 is too fast, 4 is too slow

honest spear
#

then combine it

#

3 once 4 next one

#

and so on

#

there is no good answer

distant tulip
#

can runJob do it somehow

honest spear
#

not really, maybe you would be able to spin the time with empty loop or whatever, but it would still run in the same tick

#

at the end its just the tick it self

buoyant canopy
honest spear
#

¯_(ツ)_/¯

#

and i am here to tell you the only few ways

#

you can also make semi-infinite loop to make the ticks slower

#

and then doing interval every 3 ticks

#

there are manyways but nothing as good as 3-4-3-4-3-4 pattern

#

there is no such a think as middle of the tick

buoyant canopy
#

alright, thank you for the help

honest spear
#

i wish there was an answer but there really is not

sharp elbow
#

What do you need to execute on a subtick? Every gameplay element operates on ticks, so subticks are not terribly relevant. If it is audiovisual, you should be using stuff on the client (key frames in animations, empty silence in sounds, durations in particles, etc.)

honest spear
#

Well said

mystic harness
#

how to set equipment a dyed leather armor?

#
const eq = player.getComponent("minecraft:equippable");
  if (!eq) return;
  const chest = new ItemStack("minecraft:leather_chestplate", 1);
  const legs = new ItemStack("minecraft:leather_leggings", 1);
  const feet = new ItemStack("minecraft:leather_boots", 1);
  const colorRGB = player.hasTag(TAG_BLUE)
    ? { red: 0, green: 0, blue: 255 }
    : { red: 255, green: 0, blue: 0 };
  const chestDye = chest.getComponent("minecraft:dyeable");
  if (chestDye) {
    chestDye.color = colorRGB;
  }
  const legsDye = legs.getComponent("minecraft:dyeable");
  if (legsDye) {
    legsDye.color = colorRGB;
  }
  const feetDye = feet.getComponent("minecraft:dyeable");
  if (feetDye) {
    feetDye.color = colorRGB;
  }
  eq.setEquipment(EquipmentSlot.Chest, chest);
  eq.setEquipment(EquipmentSlot.Legs, legs);
  eq.setEquipment(EquipmentSlot.Feet, feet);

tried this one but seems like none of them were dyed just normal leather

distant tulip
#

another useles component that don't work on vanilla items

mystic harness
#

dangit

#

any alternative to set color to leather?

thorn flicker
mystic harness
#

alr thanks

wary edge
distant tulip
#

yeah, just weird that they don't consider such cases

wary edge
ripe dune
#

hardcoded ✨🙌

sharp elbow
#

I suppose for a simple case like the following an interface would work.

interface IMyObj {
  make: string;
}

const MyObjProto: IMyObj = {
  make: "foo",
};

const obj = Object.create(MyObjProto);

console.warn(obj.make) // "foo"
#

Yet when we get deeply nested prototypes, would each successive object have to take the union of each interface in the chain?

#

Or if I want to change the type of the property make? (Or if it's a method, change its return type/signature)

sinful portal
subtle cove
subtle cove
#
const global = [
    "Object","Function","Error","EvalError","RangeError",
    "ReferenceError","SyntaxError","TypeError","URIError","InternalError",
    "AggregateError","Array","parseInt","parseFloat","isNaN","isFinite",
    "decodeURI","decodeURIComponent","encodeURI","encodeURIComponent",
    "escape","unescape","Infinity","NaN","undefined","Number","Boolean",
    "String","Math","Reflect","Symbol","eval","globalThis","BigInt",
    "Date","RegExp","JSON","Proxy","Map","Set","WeakMap","WeakSet",
    "ArrayBuffer","SharedArrayBuffer","Uint8ClampedArray","Int8Array",
    "Uint8Array","Int16Array","Uint16Array","Int32Array","Uint32Array",
    "BigInt64Array","BigUint64Array","Float32Array","Float64Array",
    "DataView","Promise","WeakRef","FinalizationRegistry",
    "console","print","Symbol.toStringTag"
];```these stuff
#

has anyone use the "FinalizationRegistry"?

marble sigil
#

WeakRef is supported??

sharp elbow
#

Ah, is FinalizationRegistry in?

sharp elbow
honest spear
#

yea

worthy comet
#

Do someone already make anti piston

#

I already make one but it's really buggy

silver agate
#

Can we save objects or arrays on dynamic properties? for example:

world.setDynamicProperty('array',[ "a", "b", "c" ])
world.setDynamicProperty('object', { "a": 1, "b": 2, "c":3 })
honest spear
#

you can use JSON to serialize the objects or arrays

silver agate
warm jungle
#

is there a efficient way to do spawnEntity? cuz without tickingManager it's just LocationOutOfBounds which is annoying and because of constantly calling world ticking manager it's causing memory leaks..

earnest meadow
warm jungle
#

I have set it's distance filter to 30-50 blocks since that's what i am doing with it but I can't find a way for it since idk if i can read simulation distance on scripts..

earnest meadow
#

If you're forced to do it that way, then you can just ignore the error by try-catch.

warm jungle
#

I forgot the error name but i never went to below bedrock😭 i thought it's the same as the chunks error lol

earnest meadow
warm jungle
#

Ohh wait

subtle cove
earnest meadow
round bone
prisma shard
#

Was there a recent event? How did you got that

thorn flicker
last latch
#

😁

silver agate
cyan basin
#

Just been trying to mess with entityItemDrop for the past half hour.. not sure what Mojang thought the use case would be for it but I think it's pretty silly that it uses items as Entity[] instead of the itemStack you dropped.

It would be nice to get a specific playerItemDrop event instead since just using system.runInterval() seemed to be the better way instead.

wary edge
#

It's also a very good use case, I add the dynamic property to the item dropped entity which then I cancel using itempickupevent if it doesnt match the id.

wary edge
#

One thing I do like about entityItemDrop it also detects loot drops.

cyan basin
#

I'm guessing that's why it's Entity[] for items then

wary edge
#

You can also do item.remove() which you can't with an ItemStack.

cyan basin
#

I just mean having playerItemDrop or something that returns just the single itemStack that the player dropped because when you do items[0] that only allows for typeId and id

wary edge
cyan basin
#

I suppose it is...

#

I tried quite a few things earlier and nothing worked but I guess out of everything I tried somehow that wasn't one of them

wary edge
#

Yeah, the item component of entities is easily forgotten. I had your reaction when I first used the event until I realised it's better to be an Entity[] instead of an ItemStack[].

cyan basin
#

I see why I couldn't get it to work now. After getting the itemStack I was attempting to set the nameTag of said itemStack which fails. I had to get the data I needed from the itemStack and then set the nameTag of items[0] instead to display it.

thorn flicker
last latch
#

I did it wdym?

thorn flicker
#

100%

#

silly me

last latch
#

Yeah. I would check out myself

#

yk

#

in case anything bad happened

#

because it was there 100%

thorn flicker
#

you are right, I must have extreme brain damage

#

you are so right

#

im going to the doctor now

last latch
#

let me know if everything is alright

#

im worried for you purple VoicDell

thorn flicker
last latch
#

Same as the first message

#

:)

#

😁

thorn flicker
#

no it couldnt have been, I swore it was spelled right

#

its happening again

#

im seeing things

last latch
#

What?

thorn flicker
last latch
#

hmm

#

or is it?

#

(vsauce music)

thorn flicker
#

lol

cold grove
#

Is CustomComponentParameters#params a string that you have to JSON.parse?

cold grove
untold magnet
#

entityHurtBeforeEvent are still in beta or will be stable in the next update?

#

cuz i will be using it to make a gravestone addon, detecting when the player take too much damage while having low health to copy the whole inventory to the gravestone entity

snow knoll
untold magnet
snow knoll
#

Good idea

distant tulip
#

Just use keep inventory
And get the items in the death event and clear them

last latch
#

OR save the inventory beforehand and cache it

untold magnet
distant tulip
#

Yeah?

untold magnet
#

maybe via world.runCommand('gamerule keepInventory true') or whatever

distant tulip
#

There is a native api for game rules

untold magnet
#

i see,

distant tulip
#

World.gameRules or something

untold magnet
#

ig ill have to do some testing

distant tulip
#

Yeah, getting the items and clearing them is fast

untold magnet
#

and no runintervals are needed

distant tulip
#

Yeah

untold magnet
#

since, why would i need one?

cyan basin
#

Finally found a use for DebugText (mainly the visibleTo feature) Torchic_Party

fallow minnow
#

key*

weary umbra
naive tinsel
#

no it doesnt

#

u can set a dimension location when you create it

weary umbra
#

Huh what, when i used it, it didnt had a dimension thing

cyan basin
cold grove
distant tulip
#

You can just conditionally add the s

marble spruce
#

In your opinion, should I use...

world.runCommand

or

runCommandAsync? because my friend said Mojang removed the Async but it works normally for me

slow walrus
#

if async works then you're on a very outdated version

#

and for most things you should be using native methods, not commands

marble spruce
#

Noice

#

Thanks

ocean escarp
#

How long does it usually take from experimental release for scripting apis to become stable?

fiery solar
cyan basin
#

At this point I think they've just forgotten about the event

cyan basin
cyan basin
#

That doesn't help... 😭

thorn flicker
#

think of a zombie, its attacking you, you are the target

#

whatever the entity is attacking is the target

cyan basin
#

Okay, there we go then.. cool.

warm mason
cyan basin
#

That's what I was wondering.

#

So it has no use case coming from the player though?

warm mason
#

would also be super duper cool if it wasn't read-only

thorn flicker
#

it used to not be

lyric kestrel
#

"The entity that will be interacted with"

thorn flicker
lyric kestrel
#

Ah

#

It's the only type of target I could find 😅

#

Ah

thorn flicker
#

different classes, different meanings

lyric kestrel
#

There

cyan basin
lyric kestrel
# lyric kestrel

Interesting, didn't know you could set the AI related behaviours in scripting

wary edge
lyric kestrel
#

Just get then?

#

Gotcha

thorn flicker
#

it says set, but that was removed

cyan basin
#

or sets 😭 why Mojang?

#

why you do dis

thorn flicker
lyric kestrel
#

Oh

thorn flicker
#

they just made it read only at some point lol

lyric kestrel
#

rip

#

Hopefully it comes back 🙏

cyan basin
lyric kestrel
#

I don't do entities, but it seemed pretty amazing to do by scripting

wary edge
thorn flicker
#

would be cool

ocean escarp
untold magnet
# cyan basin

i am using the entity.target on my enhanced mobs addon, for the minerzacks and builders, the script detect the target location and compare it with the entity location to like pile up or building a bridge,

#

and im not using any beta versions, all stable and works somehow

thorn flicker
untold magnet
#

then idk how it works

thorn flicker
#

show me the behavior manifest to the addon

untold magnet
#

also, isn't ur pfp the hollow knight guy?

untold magnet
thorn flicker
untold magnet
#

yeah i just cant remember,

#

and i cant check it out rn

#

gotta go,

thorn flicker
last latch
thorn flicker
last latch
#

ooo nice

#

welcome to the purple team serty

thorn flicker
#

with 8crafter and Venoct too

last latch
#

i feel like more people joined this event than the last time

thorn flicker
#

i dont think there were that many people actually

last latch
#

hmm, tbf i dont even know how many people were in the previous event lol

thorn flicker
last latch
harsh robin
#

@thorn flicker

thorn flicker
#

why are you pinging me lol

harsh robin
#

I pinged you*

#

Once

thorn flicker
#

uh huh

#

and what for, im asking

#

whats up

harsh robin
#

You aren’t answering my DMs

#

Oh wait wrong person

thorn flicker
#

what the hell are you talking about

thorn flicker
harsh robin
#

@late saffron

thorn flicker
#

why are you bringing it here

harsh robin
#

Why do you care?

thorn flicker
#

because I can

#

im a care-ful person

harsh robin
#

Ah

#

W

warm mason
untold magnet
untold magnet
last latch
#

the project i posted for my role was... one of its kind

#

not sure if anyone remembers my "peter griffin brainrot RP"

stone bridge
#

what cause the issue?

#

oh

last latch
stone bridge
#

i got it

#

sorry

#

but i cant get this one

warm mason
# stone bridge

TextField default value must be RawText or String, but your's is a number

stone bridge
warm mason
stone bridge
#

i fixed it temporarily in other way, that's different error from the first one

stone bridge
# stone bridge

this error is in notes, but it still has no description or something

late saffron
warm mason
granite cape
#

my first script

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

system.beforeEvents.startup.subscribe((e)=>{
  
  // docs
  // .my.id
  // .nperma.
  e.customCommandRegistry.registerCommand({
    name: "menu",
    cheatsRequired:true,
    description: "Show Menu"
  }, async (e)=>{
    const player = e?.initiator || e?.sourceEntity
    
    if (!(player instanceof Player)) return;
    
    await null;
    new ui.ActionFormData()
      .title("MENU - UI")
      .body("Hello this is menu description")
      .button("Rules")
      .button("Home")
      .show(player).then((r) => (r.selection==1?(async function LU4M4K33EF00GO7S03ESYN7AX(){return await new ui.MessageFormData().title("RULES").body("- NO NSFW\n- NO TALK\n- NO PROBLEM").button1("Close").button2("OK")})():![]
      ))
  })
})
mellow field
#

Is it possible to put multiple rawMessage strings on one lore line? Or combine them to e.g. use multiple translations after one another?

warm mason
#

like ```js
const message = {
rawtext: [
{ text: " Text" },
{ translate: "item.apple" },
{ text: " Another text" }
]
};

mellow field
civic shale
#

hello

#

anyone can help me, why in animation hold_on_last_frame dosen't work for me ?

#
    "format_version": "1.8.0",
    "animations": {
        "animation.fridge_left_door.open": {
            "loop": "hold_on_last_frame"    ,
            "animation_length": 0.6,
            "bones": {
                "door": {
                    "rotation": {
                        "0.0": {
                            "post": [-180, -180, -180],
                            "lerp_mode": "catmullrom"
                        },
                        "0.08": {
                            "post": [-180, -177.5, -180],
                            "lerp_mode": "catmullrom"
                        },
                        "0.32": {
                            "post": [-180, -132.5, -180],
                            "lerp_mode": "catmullrom"
                        },
                        "0.6": {
                            "post": [-180, -95, -180],
                            "lerp_mode": "catmullrom"

                        }
                    }
                }
            }
        },
        "animation.fridge_left_door.close": {
            "loop": "hold_on_last_frame",
            "animation_length": 0.6,
            "bones": {
                "door": {
                    "rotation": {
                        "0.0": {
                            "post": [-180, -95, -180],
                            "lerp_mode": "catmullrom"
                        },
                        "0.28": {
                            "post": [-180, -132.5, -180],
                            "lerp_mode": "catmullrom"
                        },
                        "0.52": {
                            "post": [-180, -177.5, -180],
                            "lerp_mode": "catmullrom"
                        },
                        "0.6": {
                            "post": [-180, -180, -180],
                            "lerp_mode": "catmullrom"
                        }
                    }
                }
            }
        }
    }
} ```
#
import { Fridge } from "./furniture/fridge";
world.afterEvents.itemStartUseOn.subscribe(new Fridge().fridgePlaceEventHandler.bind(new Fridge()));
world.afterEvents.playerBreakBlock.subscribe(new Fridge().destroyFridge.bind(new Fridge()));

world.afterEvents.playerInteractWithEntity.subscribe(ev=> {
    if(ev.target.typeId === "y2c:fridge_left_door" || ev.target.typeId === "y2c:fridge_right_door") {
        ev.target.playAnimation("animation.fridge_left_door.open");
        
    }
})```
#

like instead of the entity staying at its last position from the animation it gets defaulted

warm mason
warm jungle
#

ahm after the update i am getting this error "playersInWorld is not initialized at validPlayers"

let playersInWorld = [];
world.afterEvents.playerSpawn.subscribe((e) => {
    if(!e.initialSpawn) return
    if(e.player.hasTag("bot")) return;
    
    playersInWorld.push(e.player)
})

export function validPlayers()
{
    if(playersInWorld.length === 0)
        return false;

    return true;
}
#

oh wait

#

nvm i was calling something at early-execution

ocean escarp
#

Do we have a function that evaluated every tick?

#

Like tick.json for scripts

civic shale
#

guys , is Chest UI for herobrine is usable to make it as a normal chest like a fridge container ?

wary edge
civic shale
ocean escarp
wary edge
#

Yeah.

ocean escarp
#

Appreciate it

#

tho recreating an entire knockback system is going to be hard

#

Im not using an IDE atm so no way to error check yet

#
damagePrecision = 5
immunityFrames = 5

world.beforeEvents.entityHurt.subscribe((ev) => {
damageTaken = ev.damage
damageSource = ev.source 
damageTarget = ev.entity

if immunityFrames > 0 { return }

setDynamicProperty("example:health", getDynamicProperty("example:health") - (damageTaken * damagePrecision)
if getDynamicProperty("example:health") < 1 {
damageTarget.kill()
}
world.sendMessage("ouch")
ev.cancel()
})
ocean escarp
#

A bit of this is psuedocode

#

Since I forgot the exact way ppl do it

subtle cove
#

at least u got the code structured

civic shale
#
import {world } from "@minecraft/server"
let damagePrecision = 5
let immunityFrames = 5

world.beforeEvents.entityHurt.subscribe((ev) => {
const { damage , hitEntity , hurtEntity } = ev;


if (immunityFrames > 0 ) { return }

world.setDynamicProperty("example:health", world.getDynamicProperty("example:health") - (damageTaken * damagePrecision)
if (world.getDynamicProperty("example:health") < 1)
 {
hurtEntity.kill()
}
world.sendMessage("ouch")
ev.cancel()
})
ocean escarp
#

Pretty much until the max health and armor systems get exposed to scripts im just making my own system to handle it

gaunt salmonBOT
# civic shale ```js import {world } from "@minecraft/server" let damagePrecision = 5 let immun...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 6 errors:

<REPL0>.js:6:18 - error TS2339: Property 'hitEntity' does not exist on type 'EntityHurtBeforeEvent'.

6 const { damage , hitEntity , hurtEntity } = ev;
                   ~~~~~~~~~

``````ansi
<REPL0>.js:11:44 - error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

11 world.setDynamicProperty("example:health", world.getDynamicProperty("example:health") - (damageTaken * damagePrecision)
                                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
<REPL0>.js:11:90 - error TS2304: Cannot find name 'damageTaken'.

11 world.setDynamicProperty("example:health", world.getDynamicProperty("example:health") - (damageTaken * damagePrecision)
                                                                                            ~~~~~~~~~~~

``````ansi
<REPL0>.js:12:1 - error TS1005: ',' expected.

12 if (world.getDynamicProperty("example:health") < 1)
   ~~

``````ansi
<REPL0>.js:12:5 - error TS2365: Operator '<' cannot be applied to types 'string | number | boolean | Vector3' and 'number'.

12 if (world.getDynamicProperty("example:health") < 1)
       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
<REPL0>.js:17:4 - error TS2349: This expression is not callable.
  Type 'Boolean' has no call signatures.

17 ev.cancel()
      ~~~~~~

Lint Result

ESLint results:

<REPL0>.js

12:0 error Parsing error: ',' expected

ocean escarp
#

And that's what I get for not using an IDE I guess

civic shale
#

wait is there even entityHurt in stable script api ?

ocean escarp
#

AfterEvents is stable iirc

#

But I need before events

civic shale
#

what version do u use ?

ocean escarp
#

Trying to work with latest beta

#

after Events could work if it was able to ignore extra effects and only take "true" damage

civic shale
#

oh ok

ocean escarp
#

I don't feel like reverse engineering enchants, effects and armor math

#

I wish I could just grab the damage value straight from the json

#

but I would need to apply modifiers for held items and it just becomes a mess

civic shale
#

import {world} from "@minecraft/server"
world.beforeEvents.entityHurt.subscribe((ev) => {
const { damage , damageSource , hurtEntity } = ev;


if (immunityFrames > 0 ) { return }

world.setDynamicProperty("example:health", world.getDynamicProperty("example:health") - (damageTaken * damagePrecision));
if (world.getDynamicProperty("example:health") < 1)
 {
hurtEntity.kill()
}
world.sendMessage("ouch")
ev.cancel = true ;
}) ```
#

i hope that will work

ocean escarp
#

Appreciate it

#

The end goal is to extract how much damage I would have taken from any particular hit whilst ignoring all defensive bonuses

civic shale
#

i see

ocean escarp
#

I then can "remake" the damage system from scratch

#

Am I too ambitious?

civic shale
#

no

subtle cove
#

feel free to create posts whenever

sharp elbow
#

It's challenging but not impossible. You will run into difficulties with the armor calculations; armor toughness makes it piecewise

ocean escarp
#

I wanted armor to reduce by flat damage and enchants to apply a percentage after
I can give an example if needed

#

let's say a full prot 2 iron armor set + Resistance 1

Full iron: 12 defense ( -12 damage )
Prot 2: 2% per level per piece so 4% * 4 = 16%
Resistance 1 = 20%

(Damage - defense) S(enchants, effects)

S is that sigma symbol as I cant find it rn

#

Its like a really weird E

sharp elbow
#

Σ

ocean escarp
#

This yes

civic shale
#

ahh why do u need to recreate the damaging system ?

ocean escarp
#

flat damage first and then all percentages apply to get the final damage

ocean escarp
ocean escarp
#

The whole reason armor toughness got added is likely because they hit their limit already via diamond armor's protection

wary edge
#

The easiest way for a new damage system is disabling vanilla armour, enchants, tools, etc.

ocean escarp
sharp elbow
#

That may be easiest, but it is not very exciting or compatible. That's more like saying "a solution to this is not looking at the problem"

civic shale
ocean escarp
#

I think it would be easier to just backlog the numbers instead of removing every instance of vanilla numbers

sharp elbow
ocean escarp
#

I am not good at anything but commands and scripts

#

And even scripts are stretching it

#

Im just doing what I can

#

As I hate Json

civic shale
#

same

ocean escarp
sharp elbow
#

For getting toughness and armor? They are properties accessible on EntityEquippableComponent

civic shale
#

no

ocean escarp
#

hmm and this is a script or a Json thing?

#

Im still a noob at this lol

civic shale
#

script

sharp elbow
#

Scripting, that's a component you can read on players and very select mobs

#

(Reading armor and toughness on non-player entities will be its own challenge)

ocean escarp
sharp elbow
#

Surprisingly no. That component is not exposed for most entities

ocean escarp
#

So it's impossible

#

This is happened way too many times ...

sharp elbow
#

Yet the inventory is, as EntityInventoryComponent. It cannot read equipment slots, but it can read inventory slots

ocean escarp
#

Idea -> try -> impassible roadblock

#

That's my dev experience in a nutshell

#

Ideas too big for the scope of my skill

sharp elbow
#

Another idea is hardcoding the protection and toughness values for vanilla armor and measuring what armor pieces the mob has on through other means

ocean escarp
sharp elbow
#

Enchantments are another beast ... even I'm not sure how one would read enchantments on entity gear

ocean escarp
#

I guess better start learning Json then...

civic shale
ocean escarp
#

I really dont fit in here do I?

#

All y'all are super smart

civic shale
#

no and no

sharp elbow
#

Course you fit. You've just picked a tricky idea to work on

civic shale
#

yep

warm mason
civic shale
ocean escarp
warm mason
ocean escarp
#

My only other lang that I fully get is Lua

civic shale
#

welp

sharp elbow
warm mason
warm mason
warm mason
sharp elbow
#

That's a fair compromise

civic shale
ocean escarp
#

Is it possible to make custom armor unenchantable?

#

That would solve a lot tbh

ocean escarp
#

I could just implement my own take on enchants later in dev

sharp elbow
#

Aye, simply omit the component "minecraft:enchantable"—only a guarantee for armor you make though

warm mason
ocean escarp
civic shale
#

or , u can use events

ocean escarp
warm mason
sharp elbow
#

Reading enchantments is annoying, but once you have them counteracting them in the equation is rather straightforward

ocean escarp
warm mason
#

and recipes maybe

wary edge
sharp elbow
#

This is true.

ocean escarp
#

minecraft:diamond_helmet -> test:diamond_helmet

civic shale
warm mason
ocean escarp
warm mason
ocean escarp
#

Not any particular goal in mind

ocean escarp
warm mason
#
  • like, u will disable enchantments, it's not what players would like
ocean escarp
#

I don't really care much for compatibility icl
With a change as drastic as this, you gotta make sacrifices

civic shale
#

is it for only custom armor ?

#

like disabling for ur own armor

#

or all armor ?

sharp elbow
ocean escarp
#

If there were a reasonable way to do so then I'd agree but there's not

ocean escarp
civic shale
ocean escarp
#

I could just create a converter

#

I'll probably include 1 anyway for those who want to add support for the addon

civic shale
#

or u can just

#

player.getComponent(EntityComponentTypes.Inventory
)?.container.getItem(0)?.getComponent(ItemComponentTypes.Enchantable)?.removeAllEnchantments();

ocean escarp
#

Well yeah but I would also need to set everything to 0 armor points

#

Since custom system

#

I need to return raw damage

cold grove
ocean escarp
#

Wait

#

Do we have access to the armor bar in scripts?

#

And is it writable?

shy leaf
#

and read only

ocean escarp
#

Can we mo-
FUUUU-

#

Is this accurate?

#

If we can read we can reverse right?

sharp elbow
#

Seems to be when I tested it.

#

Now to apply your algebra skills!

ocean escarp
#

I am not a math major 💀

#

I can rearrange simple formula but this is not simple in the slightest

sharp elbow
#

No, and the min/max functions make this a PITA

ocean escarp
#

A what?

sharp elbow
#

Pain in the ass 😄

ocean escarp
#

Ah

#

Never seen it said that way

#

Might have to steal

sharp elbow
#

I'd treat them not as a clamp on the final value, but a clamp on how the inputs are read; that is, the effective value for defense points is capped at 20

#

Fair warning, the weapon damage input is defined in terms of itself when using armor toughness, so in that case you'll need the quadratic formula to find it

ocean escarp
#

Are you sure that is accurate btw?

sharp elbow
#

I'm about 95% confident

ocean escarp
#

I saw from some sources that bedrock armor calc is simpler or smthn

sharp elbow
#

Used to be before they added toughness, which was at a different time than Java Edition

#

AFAICT they are now (mostly) the same

#

(I used this equation with great results)

ocean escarp
#

The min and max throw so many loops into this

#

If it wasn't for stuff like the mace I could probably just use the main hand + check the damage of whatever is held

#

But then TNT and stuff too..

ocean escarp
#

@sharp elbow
I know this is frowned upon but I suck at math so asked AI about min / max for reverse engineering.
It definitely gave me something but I'm really unsure on it

#

I don't know where else to look for how to reverse it

sharp elbow
# ocean escarp The min and max throw so many loops into this

Look at it as splitting into two expressions depending on constraints in the inputs.

weapon_damage * (1 - min(20, x) / 25)

Can be split into the following:

weapon_damage * (1 - 20) / 25    {x > 20}
weapon_damage * (1 - x) / 25     {x <= 20}

(With x being shortened for brevity)

sharp elbow
#

Out of curiosity could you post its findings here?

ocean escarp
#
function reverseArmorFormula(damageTaken, armorPoints, toughness) {

    // ----- Regime 1: low damage branch -----
    // reduction = armorPoints / 5

    const possibleLow =
        damageTaken / (1 - (armorPoints / 125));

    const threshold =
        (4 / 5) * armorPoints * (2 + toughness / 4);

    if (possibleLow <= threshold) {
        return possibleLow;
    }

    // ----- Regime 2: high damage branch -----
    // reduction = armorPoints - (4 * damage) / (toughness + 8)

    const toughnessFactor = 2 + toughness / 4;

    const a = 1 / (25 * toughnessFactor);
    const b = 1 - (armorPoints / 25);
    const c = -damageTaken;

    const discriminant = b * b - 4 * a * c;

    if (discriminant < 0) {
        return null; // no physical solution
    }

    const originalDamage =
        (-b + Math.sqrt(discriminant)) / (2 * a);

    return originalDamage;
}
#

I hate math

sharp elbow
#

Well, it doesn't seem insane

ocean escarp
#

Is just solve low, if not valid solve high?

sharp elbow
#

Honestly I'm not sure, it took a slightly different approach than I would have. And I don't have the brain currently to verify

warm jungle
#

is extending classes possible here? i haven't tried it tho.. like

... extends BlockBoundingBoxUtils

shy leaf
#

but that also might work, although ive never tried it and always used prototype

warm jungle
#

Oooww okiee I'll try something

#

Thankss!!

subtle cove
warm jungle
#

Yeahh i just noticed it, but still thankss!

wicked girder
#

Anyone know how to cancel a fire aspect hit?

#

canceling in before hurt event doesnt work

#

which I assume is a bug

shy leaf
wicked girder
#

doesnt work since it needs to be ran in system

#

so it will still take a tick of damage

remote oyster
wicked girder
#

too much work lol

remote oyster
#

Oh I know. I got an entire script for it lol.

wicked girder
#

weird didnt realize wind bursts are counted as explosions

warped kelp
civic shale
#

hiro

errant stump
#

how do I play music like pigstep per script, do I use world.playMusic if then what are the disc ids?

errant stump
#

well I got smth to work by running runCommand but I would still love to hear the script version of it

#

and without any commands

olive sphinx
# ocean escarp Is this accurate?

Interesting equation. Some simple math, for some people. An equation that will take the Weapon’s Damage, Defence Points, and Armour Toughness to output a Damage value, right?

ocean escarp
olive sphinx
zinc breach
#

block.dimension.spawnEntity("minecraft:xp", block.location) I assume would work

#

you can use a for loop if you want more than one orb

lyric kestrel
wary edge
#

It's a min max function.

lyric kestrel
lyric kestrel
#

That is...

olive sphinx
#

Simple math functions in JavaScripts

cinder shadow
#

Has anyone been having issues with custom command permissions not actually working? I've added several custom commands recently all with CommandPermissionLevel.Any, but only opped players are able to use them

#

It doesn't make any sense because my other commands made a while back have the same structure and can be used by anyone

cinder shadow
#
export const friendAddCommand = {
    name: "rc:fadd",
    description: "Sends a friend request to an online player.",
    cheatsRequired: false,
    permissionLevel: CommandPermissionLevel.Any,
    mandatoryParameters: [
        {
            type: CustomCommandParamType.PlayerSelector, name: "player"
        }
    ]
}```
cinder shadow
#

Neither do I

#

this game targets me with problems

#

only difference between this and the other custom commands that do work are that they are embedded several folders down in the file path

cinder shadow
#

ah okay

remote oyster
#

OP has been an ongoing battle for year's. Riddled with issues due to the complexity of the code under the hood. Which is why I still handle permissions the old fashion way and don't bother with registered custom commands for now. Personal preference and taste until I feel more comfortable about it.

cinder shadow
#

if only I could make a dynamic Enum that updated with world players

#

oh well

warm mason
ocean escarp
zinc breach
#

how much does obfuscation impact an addons performance

remote oyster
zinc breach
zinc breach
remote oyster
#

Experience

zinc breach
remote oyster
#

Full code

zinc breach
#

theres no way bruh

#

what

remote oyster
#

Definitely

zinc breach
#

are you talking normal obfuscator.io code or things with custom obfuscators and such

remote oyster
#

The variable and function names might not be an exact match, letter for letter, but you can bet any amount of money it will be the same representation.

#

Once you read what the function does you can just use common sense to rename that function based on what it's doing.

zinc breach
remote oyster
#

It's very simple

zinc breach
#

I don't really see a point to it

remote oyster
zinc breach
#

because I'm genuinely just not processing this 😭

remote oyster
# zinc breach I don't really see a point to it

People deobfuscate for a couple of known reasons. One, your code could be suspicious and since it's not monitored from the marketplace there is a level of faith and trust they probably lack from you and your pack. The other reason will be to know how your pack works, if something about it catches their interest.

zinc breach
remote oyster
zinc breach
remote oyster
#

When people can't see the code there is a level of trust that has to be established between the developer and the user. I don't run stuff on my system in the blind from a third party I do not know.

warm mason
olive sphinx
snow knoll
#

And the resistance effect

ocean escarp
olive sphinx
snow knoll
#

Resistance removes 20% of damage taken at each incremental level

ocean escarp
snow knoll
olive sphinx
ocean escarp
#

Just feed the engine how much damage you take and then apply stuff for armor and all that
Like tbh if I was going to account for mace and spear then I would also need to tackle explosion math, arrow velocity calcs and a edge case for fall damage too

#

Why do that when I can just read the damage I would take and then adjust for player conditions like what armor they're wearing

olive sphinx
#

Then do that if you can

ocean escarp
#

Its just reversing the min / max that's the problem

#

There is an alternative but then compatibility with other addons goes down the drain

olive sphinx
ocean escarp
#

Again if I don't mind my addon being a "main" addon then there is a very easy solution

#

But that's the problem, what if people want to combine it with other addons

ocean escarp
olive sphinx
#

That would only affect Addons with custom armour, not all Addons. It would still have compatibility

ocean escarp
#

I'd probably still get complaints

olive sphinx
#

I can take a deeper look at this later if you still need help when I get home.

ocean escarp
#

Tbh I'll probably just take the less compatible option

#

Have custom armor? Not supported

keen hearth
#

Hey, im sorry to bother you all
I wanna learn Scripting ill start next week
But rn

Could someone help me out with a script that does this

  1. Makes a player immune to all damage if they have a certain tag (if they dont have the tag they can take damage just like normal)

I know its a lot, but i would really appreciate the help 🙏🏻

It would also help me under how the code works as thats how I learn most things
God bless 🙌

shell sigil
#

Is there way to get the compass direction example I use compass on a loadstone I want to know if there's a property/component on that item where it save the location

distant tulip
warm mason
keen hearth
subtle cove
last latch
#

Who thought we would live to an age where we get this

fallow minnow
#

did they fix the bug where it still does knockback or no

remote oyster
fallow minnow
thorn flicker
summer cloud
#

if i have a entity that has a equippable at slot 0, how do i set that equippable via scripting?

summer cloud
#

ok because its not setting the item

#

but if i put something in the loot table it does have a item

cold grove
#

@summer cloud the documentation says is only available for players

summer cloud
#

oh mb

#

is it possible to set for a entity?

cold grove
summer cloud
#

yea i was aware of that, ill just try out stuff

cold grove
honest spear
#

Goood

remote oyster
#

🙏

warm jungle
#

is GameTest intentionally freezes time? and disables mob spawning?

visual zephyr
#

how can I add the optional parameter on only a specific enum mandatory parameter on custom commands

visual zephyr
#

oh ok

#

thanks for the answer

warm mason
#

Who stole the messages?

obsidian coyote
#

Me, I ate them