#Script API General

1 messages Ā· Page 45 of 1

quick shoal
#

Bruh U at least need 2 players to test it

#

Unless bds

sterile epoch
#

since it's before you leave

fallen cape
marsh berry
#

Hey. Is there a way to script so you shoot up fireworks everywhere on a server? Say to not have as much lag that it shoots up based on where a player is?

chilly fractal
chilly fractal
#

If you mean like summon fireworks

marsh berry
#

At new Years i want to shoot up loads of fireworks in my server. But summon the fireworks only gets you the rocket with the white particals. Not the explotion?

chilly fractal
#

Oh.. well then uhh gimme a second

#

Ima search rq

shut vessel
#

Do you know what he needs to fix?

for the poison I want him to attribute it to the affected player

the damage in void is if the score 53 is hit

for the nauseous I want him to attribute it to the affected player

for resistance it is the player who hits the other player who receives the effect

world.afterEvents.entityHitEntity.subscribe((data) => {
    let {
        damagingEntity,
        hitEntity
    } = data;
    if (damagingEntity instanceof Player && hitEntity instanceof Player) {
        const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
        if (score === 50 && Math.random() < 0.10) {
            damagingEntity.dimension.spawnEntity("lightning_bolt", hitEntity.location)
        }
    }});
    world.afterEvents.entityHitEntity.subscribe((data) => {
        let {
            damagingEntity,
            hitEntity,
            player
        } = data;
    if (damagingEntity instanceof Player && hitEntity instanceof Player) {
        const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
        if (score === 49 && Math.random() < 0.10) {
            player.addEffect('resistance', 100, {amplifier: 1, showParticles: false}); //200 => 20ticks x 10
        }
    }});
    world.afterEvents.entityHitEntity.subscribe((data) => {
        let {
            damagingEntity,
            hitEntity,
        } = data;
    if (damagingEntity instanceof Player && hitEntity instanceof Player) {
        const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
        if (score === 33 && Math.random() < 0.10) {
            damagingEntity.addEffect('poison', 200, {amplifier: 1, showParticles: false}); //200 => 20ticks x 10
        }
    }});
    world.afterEvents.entityHitEntity.subscribe((data) => {
        let {
            damagingEntity,
            hitEntity
        } = data;
    if (damagingEntity instanceof Player && hitEntity instanceof Player) {
        const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
        if (score === 8 && Math.random() < 0.10) {
            damagingEntity.addEffect('nausea', 200, {amplifier: 1, showParticles: false}); //200 => 20ticks x 10
        }
    }});
    world.afterEvents.entityHitEntity.subscribe((data) => {
        let {
            damagingEntity,
            hitEntity
        } = data;
    if (damagingEntity instanceof Player && hitEntity instanceof Player) {
        const score = world.scoreboard.getObjective('kit').getScore(damagingEntity)
        if (score === 53 && Math.random() < 0.10) {
            Hurtplayer.applyDamage(1, { cause: "void",damagingEntity: entity})
        }
    }
});```
round bone
#

oh it's not, just weird indentation

coral ermine
#

can we set true/false condition to dynamic property? Like

.setDynamicProperty("test", true)

round bone
#

you can set strings, numbers, booleans (true/false) or even coordinates (Vector3 interface)

chilly fractal
#

Or undefined

#

Or null

#

Or just setting it like this:
.setDynamicProperty("bruh:bruh")

warm mason
chilly fractal
round bone
# shut vessel Do you know what he needs to fix? for the poison I want him to attribute it to ...
import { world, Player } from "@minecraft/server";

const kitObjective = world.scoreboard.getObjective("kit") || world.scoreboard.addObjective("kit");

world.afterEvents.entityHitEntity.subscribe(({ damagingEntity, hitEntity }) => {
    if (hitEntity instanceof Player && damagingEntity instanceof Player) {
        if (Math.random() >= 0.1) return;
        const playerScore = kitObjective.getScore(damagingEntity) ?? 0;

        switch (playerScore) {
            case 8:
                damagingEntity.addEffect("nausea", 200, { showParticles: false, amplifier: 1 });
                return;
    
            case 50:
                damagingEntity.dimension.spawnEntity("lightning_bolt", hitEntity.location);
                return;

            case 53:
                hitEntity.applyDamage(1, {
                    damagingEntity, cause: "void"
                });
                return;
        };
    };
});
chilly fractal
#

It has some good examples.

round bone
marsh berry
chilly fractal
shut vessel
marsh berry
#

I appreciate the time you used i now have a mode definitive answere

#

Mode = more

chilly fractal
round bone
marsh berry
#

Haha. I will get there. One day. 😁 Im just trying not to overload myself as is 😊

chilly fractal
round bone
chilly fractal
round bone
#

he should remove the Math.random if statement then test it again

#

like wrap it as a comment

round bone
#

then on the end just add these chances

shut vessel
#

no its ok i needed

chilly fractal
ocean escarp
#

Not sure if this is the best place to ask but can anyone let me know the best way to set up a scripting environment?

ocean escarp
#

Not typescript

wary edge
ocean escarp
#

And if I wanted to code fully in js?

#

My friend was streaming their work and had access to a bunch of autocomplete stuff

#

I think I might be missing some libraries

somber cedar
#

@ocean escarp

ocean escarp
#

I’ve never used npm stuff

wheat condor
chilly fractal
wheat condor
chilly fractal
chilly fractal
#

So run ```bash
pkg install nodejs

or whatever the equivalent of pkg is for your system.
chilly fractal
#

No

#

Its to make your life easier

#

If you wanna make your life easier than yes

dim tusk
#

I want to make my life suffer

#

Can I not install it?

ocean escarp
#

All I want is autocompletion. Any random math and stuff I’ll do manually

chilly fractal
chilly fractal
ocean escarp
#

Time for file bloat YAY!

ocean escarp
#

There goes having a clean workspace

chilly fractal
wheat condor
wheat condor
dim tusk
#

And luvs reading

#

That's why I luv docs... Except maths but meh

wheat condor
chilly fractal
ocean escarp
#

I’ve tried bridge

#

hate it

wheat condor
wheat condor
chilly fractal
dim tusk
ocean escarp
#

Idk it just seems clunky

dim tusk
#

I mean I prefer bridge v1

chilly fractal
#

I hate it honestly, i never used it execpt for generating manifest files, now i use my own manifest generator.

ocean escarp
#

I’ve never had to use the command prompt with coding before

wheat condor
#

command prompt?

dim tusk
#

I did use it before, but now I generate my own manifest in my own made manifest generator ( yes it supports scripts )

ocean escarp
#

isnt that where I use the npm installs?

#

Which I cannot find

chilly fractal
ocean escarp
#

I’m never doing web dev

#

never

chilly fractal
dim tusk
#

Rahh, I need to do more maths to check if the shulkerbox is openable

chilly fractal
ocean escarp
#

I’m 99% sure I have node.js

wheat condor
dim tusk
#

I mean I don't really need math in my cass but it's annoying

wheat condor
ocean escarp
#

usually I just write stuff in lua and ask people to translate…

#

lua > js

#

Any day

wheat condor
#

is even lua

dim tusk
wheat condor
#

never used them but for assetto corsa scripts

ocean escarp
#

json sucks except for data storage

wheat condor
chilly fractal
#

NodeJS > all

wheat condor
#

java is better

chilly fractal
ocean escarp
chilly fractal
#

npm version? Lol idk dont actually do that

ocean escarp
#

-# god I’m useless

dim tusk
ocean escarp
#

I hate being taught. I should just know the info automatically

dim tusk
#

And if it sucked then say that to Mojang... Because they still use it to this day

chilly fractal
wheat condor
ocean escarp
#

10.2.4?

#

is that valid?

chilly fractal
#

Idk just do

pkg update nodejs

(Idk if its also a valid command lmao, btw it should update your nodejs version, not check it), for checking do:

npm -v
wheat condor
ocean escarp
#

Idk if that means it’s installed or if I’ve called something else random entirely

wheat condor
#

what

ocean escarp
#

Don’t worry

#

I’m useless

dim tusk
#

No you're NOT!

#

You just got feeded by new information

#

That you're Bain can't comprehend properly because if the speed of it

ocean escarp
#

My goal is to install as little NPMs as possible

ocean escarp
#

because json sucks ** COUGH COUGH**

#

I hate I can write out a perfect psuedo script for what I wanna do

#

but when it comes to actually making it I crumble

warm mason
ocean escarp
#

Speaking off I’m probably going to need hundreds of them

#

since my project basically redefines the whole concept of ā€œdamageā€

dim tusk
distant tulip
#

your message is sent using json

dim tusk
#

Anyways, does getBlock support float?

#

Nice....god, I need to check if there's 0.5 space above the shulker box

distant tulip
#

huh

warm mason
dim tusk
#

Shucks

ocean escarp
#

I’m also going to need a UI developer but I’ll have to learn that myself too

distant tulip
#

it return a block... idk what are you trying to do

dim tusk
#

man I'm Dead

#

Oh nvm, why I think of getBlock

ocean escarp
#

The health, armor and hunger bar are all going to be replaced

distant tulip
#

#1067869374410657962

ocean escarp
#

Not really

#

I’m just gonna hide them and create a custom health system via scripts

distant tulip
#

alr

warm mason
ocean escarp
#

I don’t think there is a way you can really. I’m bad at retaining info and refuse to use regolith

distant tulip
#

not all of us use regolith

dim tusk
#

Why is the regolith in this conversation now...

distant tulip
#

idk he seem to link it to his problem
i am saying we don't use it so he can ask whatever

ocean escarp
#

Because my friend tried to teach me scripts and it was 1 of the first things that came up

distant tulip
#

it is an optional tool

#

in fact i never used it

wary edge
#

I love regolith!!!

warm mason
#

-# šŸ‘€

chilly fractal
#

What the hell is regolith??

#

I'm on mobile so i have absolutely no idea wtf is most of the pc tools yall are using.

distant tulip
#

-# jk

chilly fractal
#

Nah why tf is the home page a copy of the bridge??

wary edge
distant tulip
#

lol

chilly fractal
#

Copying css be like

chilly fractal
warm mason
chilly fractal
distant tulip
#

addon development is

chilly fractal
distant tulip
#

let stay on topic, lol

chilly fractal
#

I want a inventoryChange event

chilly fractal
steady canopy
#

That's just javascript... Prototypes obviously save their properties and methods.

chilly fractal
distant tulip
#

seem like a packet thing to me

chilly fractal
#

(I dont wanna use bds)*

warm mason
granite badger
chilly fractal
chilly fractal
#

Too much to explain plainly...

ocean escarp
#

If when trying to install NPMs it says audited how to fix that?

chilly fractal
#

Audited means edited/updated/fixed.... (i believe lol)

ocean escarp
#

They clearly don’t exist

turbid delta
chilly fractal
ocean escarp
chilly fractal
#

Ah alright

chilly fractal
distant tulip
chilly fractal
#

Maybe add a --force if it exists... i think I'm mixing up cloudflare commands with normal npm but maybe it exists

ocean escarp
distant tulip
#

yeah

#

what did you install btw

turbid delta
#

Ima need a item Cooldown end event for real 😭

ocean escarp
distant tulip
distant tulip
chilly fractal
turbid delta
#

What I'm currently doing on a loop but it has to assume you know the item cooldown, so if you want it for several it's gonna need one if statement for each

chilly fractal
#

Like stable stable...

distant tulip
#

my bad didn't see your response

dim tusk
#
world.beforeEvents.chatSend.subscribe(ev => { 
    if (ev.message.startsWith('!testForm')) {
        ev.cancel = true;
        const args = ev.message.split(' ');
        const characters = args[1] ? parseInt(args[1], 10) : 10;

        if (characters && !isNaN(characters)) {
            system.run(async () => await testForm(ev.sender, characters));
        }
    }
});

async function testForm(player, characters = 10) {
    let bodyContent = '';
    for (let i = 0; i < characters; i++) bodyContent += String.fromCharCode(32 + (i % 95));
    let form = new ActionFormData().title('Test Form').body(bodyContent).button('Back');
    
    await forceShow(player, form);
}

async function forceShow(player, form, timeout = Infinity) {
    const startTick = system.currentTick;

    while ((system.currentTick - startTick) < timeout) {
        const response = await form.show(player);
        if (response.cancelationReason !== "UserBusy") {
            return response;
        }
    }
    throw new Error(`Timed out after ${timeout} ticks`);
}```
#

I made this stupid script to check how many characters my phone can handle in the server form

#

And it can handle below 80k characters, but higher than that closes my world

#

Scrolling is fine but opening and closing the form is the worst part it lags so bad lmao

chilly fractal
#

Ah so i can just open a 300k character form to force crash any player?

ocean escarp
#

Is there any way to grab entity components with scripts?

neat hazel
#

What's the error?
Error

[Scripting][error]-TypeError: not a function at durabilityDamage (main.js:128)
at <anonymous> (main.js:123)

Code:

mc.world.beforeEvents.playerBreakBlock.subscribe((ev) => {
  const block = ev.block
  const player = ev.player
  const hand = player.getComponent("minecraft:inventory")?.container.getItem(player.selectedSlotIndex)

  if (pickaxeBlocks.includes(block.typeId) && pickaxes.includes(hand.typeId)) {
    const damageValue = pickaxeBlocks.includes(block.typeId) ? 1: 2
`LINE 123 -->`    durabilityDamage(player, pickaxes.includes, damageValue)
  }
})

function durabilityDamage(player, item, damageValue) {
`LINE 128 -->` const durability = item.getComponent('durability');
  const enchantable = item.getComponent('enchantable');
  const unbreaking = enchantable?.getEnchantment('unbreaking')?.level ?? 0;
  
  if (Math.random() * 100 <= (100 / (unbreaking + 1))) durability.damage += damage;
}
ocean escarp
neat hazel
ocean escarp
#

Pretty much just move the function above where you’re calling it

#

so the code reads the function first

#

Custom functions usually work best at the top of a file

neat hazel
#

Thnks

ocean escarp
#

Lemme know if it works

neat hazel
neat hazel
# ocean escarp Lemme know if it works

Like this?

mc.world.beforeEvents.playerBreakBlock.subscribe((ev) => {
  const block = ev.block
  const player = ev.player
  const hand = player.getComponent("minecraft:inventory")?.container.getItem(player.selectedSlotIndex)

  if (pickaxeBlocks.includes(block.typeId) && pickaxes.includes(hand.typeId)) {
    const damageValue = pickaxeBlocks.includes(block.typeId) ? 1: 2
    durabilityDamage(player, pickaxes.includes, damageValue)
  }
function durabilityDamage(player, item, damageValue) {
  const durability = item.getComponent('durability');
  const enchantable = item.getComponent('enchantable');
  const unbreaking = enchantable?.getEnchantment('unbreaking')?.level ?? 0;
  
  if (Math.random() * 100 <= (100 / (unbreaking + 1))) durability.damage += damage;
}
})
dim tusk
neat hazel
dim tusk
# neat hazel What's the error? Error ```js [Scripting][error]-TypeError: not a function at du...
const pickaxeBlocks = ["minecraft:stone", "minecraft:iron_ore"];
const pickaxes = ["minecraft:iron_pickaxe", "minecraft:diamond_pickaxe"];

world.beforeEvents.playerBreakBlock.subscribe(({ block, player, itemStack }) => {
    if (pickaxeBlocks.includes(block.typeId) && pickaxes.includes(itemStack?.typeId)) {
        const damage = pickaxeBlocks.includes(block.typeId) ? 1 : 2;
        system.run(() => durability(player, itemStack, damage));
    }
});

function durability(player, itemStack, damage) {
    const durab = itemStack.getComponent("durability");
    const enchant = itemStack.getComponent("enchantable");
    const unbreaking = enchant?.getEnchantment("unbreaking")?.level ?? 0;
    const equippable = player.getComponent("equippable");

    if (Math.random() * 100 <= (100 / (unbreaking + 1))) {
        durab.damage += damage;
        equippable.setEquipment("Mainhand", itemStack);
    }
}
dense inlet
#

Anyone know how to solve this?: [Scripting] ReferenceError: Native property setter [HttpRequest::body] does not have required privileges. at <anonymous> (main.js:67)

dim tusk
dense inlet
#

thanks, I'll try that

dim tusk
ocean escarp
dim tusk
#

but it still applies to most things... the function is the exempted one

stark kestrel
#

Drag and drop doesn't exist for script api right?

stark kestrel
#

PlayerCursorInventoryComponent Class

dim tusk
stark kestrel
#

Oh

stark kestrel
dim tusk
stark kestrel
dim tusk
stark kestrel
stark kestrel
dim tusk
#

Maybe send a gif or a video of it?

stark kestrel
#

Oh yeah

#

Ofc

#

Why not

#

Lemme join a server

#

And send it

stark kestrel
#

@dim tusk

dim tusk
#

Yeah but this isn't possible with android devices

nimble schooner
#

How to turn a player name as string (for example ā€žAsquilorc ā€ž) to an actual player object in my code?

#

I know how to turn a player object to a string

#

But how to do it the other way

rigid belfry
#

Anyone have any ideas on how to fix this?

dim tusk
#

I answered you in your post

chilly fractal
dim tusk
chilly fractal
#

Basically i just guess what they want...

#

Idk what to say lol.... my eyes are paining me

#

I just woke up

#

(For context, i slept when it was 5am and now is 9am)

#

4 hours ehh?

#

I hope thats enough but at least i got some commands to work and i fixed a bit more bugs on my website..

quick shoal
dim tusk
#

No difference at all tbh...

quick shoal
dim tusk
#

Unless it's entities

quick shoal
#

No but I did not put it before then it bugged

#

Until someone tells me [0] is needed

dim tusk
#

Nvm, I don't need to test it...

quick shoal
#

?

#

It really bugged but

dim tusk
#

it still needs to check every player within that array with that name

dim tusk
warm mason
quick shoal
#

Oh I understand

#

He not add ()

#

These things are always forgotten by me too lmao

dim tusk
#

Bloating yey!

#

-# not 100% bloating but meh

chilly fractal
flat barn
chilly fractal
dim tusk
junior oracle
#

Is it possible to show a specific player's skin to other players? I know it's possible to see your own skin in a panel. But I'd like to know if it's possible to do that.

thorn flicker
#

and im not sure if you can do that in general.

#

-# probably not

chilly fractal
#

Nvm

#

Some mad ideas of mine...

stark kestrel
#

Like the person told?

dim tusk
stark kestrel
#

I'll do something for Android players later

dim tusk
#

Do you know how to do the person who told you how to do it??

stark kestrel
slow walrus
dim tusk
dim tusk
chilly fractal
#

Seems like a micro optimization to me..

slow walrus
chilly fractal
slow walrus
chilly fractal
#

I am doing this alot

#

Too much

slow walrus
#

I mean a LOT

chilly fractal
#

Yes

slow walrus
#

Like to the point that you're touching the 50ms line each tick

chilly fractal
#

I do it like ~200 calls per 30 seconds

chilly fractal
slow walrus
#

it's faster cause all the iteration is done natively instead of in the JS runtime

#

anyway even if it is a micro-optimisation, it's nicer to look at, and why not take the optimisation if you can

chilly fractal
chilly fractal
#

Really hate it

#

And also i do multiple extra parameters... i filter out some op permissions and their id and their gem... i dont think the query params would help with that would it?

chilly fractal
slow walrus
#

if you're using the id then world.getEntity(id) is even better

#

just typecast as player

chilly fractal
#

I know there are native functions, i just hate the sight of them

#

I get an urge to break my phone

#

When i see them

#

Idk why, but it is what it is

slow walrus
#

lmao what

#

your choice ig but that aint a great mindset

chilly fractal
#

I genuinely tried to use a good'ol world.getEntity() and i just... i got mad... idk i need help ig...

#

It was a week ago so yeah i might attempt to do that again...

#

I also love making my variable names as short as one or two characters at max

#

Why you may ask? The answer is... I GET A F-ing URGEEEE, im sorry but i just just.... i need help..

stark kestrel
celest abyss
#

any example to make a custom dimension using end and a mcstructure.

celest abyss
dim tusk
dim tusk
meager cargo
#
                if(r.selection === 0) {
                    if(player.hasTag("Staff")) 
                        player.runCommand(`execute if entity @s[scores={md1=1}] run dialogue open @e[tag=memory_disc_all] @s memory_disc_all_1`);
                else
                player.sendMessage({ rawtext: [{ translate: 'memory_disc.menu.locked', "with": ["\n"] }] })
                }

Heyy, how I can get rid of player.hasTag, but leave player.sendMessage when the score is not reached?

chilly fractal
#
function getScore(ent, sb) {
  let scoreboard = world.scoreboard.getObjective(sb) ?? world.scoreboard.addObjective(sb);
  return scoreboard.hasParticipant(ent) ? scoreboard.getScore(ent) : 0;
}
if (r.selection === 0) {
  if (getScore(player, "md1") === 1) player.runCommand(`dialogue open @e[tag=memory_disc_all] @s memory_disc_all_1`);
  else player.sendMessage({ rawtext: [{ translate: 'memory_disc.menu.locked', "with": ["\n"] }] })
}
meager cargo
chilly fractal
#

You're welcome.

honest spear
#

Hello scriptin' guys, and Merry Christmas!!! šŸŽ‰

nimble schooner
#

How to spawn multiple items once with spawnItem?

#

100000

warm mason
#

Just use multiple spawnItems

nimble schooner
#

Nawww

#

wait

#

Can you just add quantity to the itemStack?!

warm mason
#

Yes, from 1 to 64. But if you need more, you will have to use multiple spawnItem

honest magnet
#

can i toggle sprint for a player?

chilly fractal
#

To stop them from sprinting...

honest magnet
#

i mean to make them sprint

chilly fractal
#

You wanna make them sprint?

honest magnet
#

yep

chilly fractal
#

What the fk do you mean by "sprint". They can sprint by default...

#

Elaborate

#

Explain further

honest magnet
#

like make them run?

#

because when i use tp they lose thier sprint

chilly fractal
#

... you wanna keep their velocity?

honest magnet
#

yes

chilly fractal
#

Do ```js
player.teleport({x: 0, y: 0, z: 0}, {keepVelocity: true});

#

???

#

How is it wrong @warm mason

warm mason
warm mason
honest magnet
#

but that they still lose sprint

warm mason
#

This is the best you can do

honest magnet
#

thanks

warm mason
#

Why are you teleporting a player, maybe there is a better way than teleportation

honest magnet
#

ok?

#

how?

chilly fractal
#

So i assume it would be able to be set to true

distant tulip
#

nope

chilly fractal
#

K...

warm mason
honest magnet
#
    //fence part
    if (scoreboard.getObjective("fence").getScore(player) == 1 && player.isFalling == false && player.isJumping) {
        player.runCommand("playanimation @s animation.humanoid.fence_vault.1 move 0")
        player.runCommandAsync("execute anchored feet as @s at @s rotated ~ 0 run tp @s ^^^0.5")
        applyKnockback(player.getViewDirection().x, player.getViewDirection().z, 0.1, 0.1)
    }
warm mason
#

.....

distant tulip
warm mason
#

What is the essence of your code, why are you teleporting a player

honest magnet
#

a fence vault thing

warm mason
#

Why was a teleport needed there at all?

honest magnet
#

wait a min

warm mason
#

?????

chilly fractal
#

So they need teleport to tp the player above the fence

honest magnet
#

tp player in to the fence and push player out by knockback

chilly fractal
#

But they still want the player to be able to run

honest magnet
#

yes

distant tulip
#

just edit the movement speed when not sprinting after that action

honest magnet
#

ok i will do that

#

thanks

ocean escarp
#

How do I import effect functions?

#

Whenever I try I only get the stuff I’ve used before

warm mason
ocean escarp
#

Pretty much

#

finally figured it out

ocean escarp
#

Honestly for me it’s js syntax I think

#

I don’t know when to use each type of bracket or an array

warm mason
#

Watch training videos

ocean escarp
#

Time to spend the next 3 years rotting

warm mason
#

Or read the JS documentation

ocean escarp
#

cause that’s how long it’ll take me to understand step 1

warm mason
#

It's better to try than to say that you will spend 3 years on it

ocean escarp
#

entity.addEffect(ā€œinfiniteā€,ā€minecraft:health_boostā€, true)

#

Laugh at me

#

I know I’m 8 miles off

warm mason
ocean escarp
#

I got it backwards

#

there’s no way to test tho

#

I don’t have a server open

distant tulip
ocean escarp
#

Yeah I just saw that

#

This is literally my first time scripting in js

#

I thought at least some of my knowledge from lua would translate over

#

I’ve never done oop

distant tulip
#

we are just reading the docs and applying it, it is not that complicated for the most part

ocean escarp
#

I do love the fact that ā€œoptionsā€ is so well covered in VS

#

So much info fr

solar dagger
#

anyone know how to disable the player's left and right rotation animation?

dim tusk
solar dagger
#

Well figuring that you can edit the player's rotation i figured someone knew a way via script

distant tulip
#

disable camera controls
this disable the pitch rotation too

dim tusk
#

Bruh, I thought it was just an animation because he said rotation animation 😭

distant tulip
#

more context needed

sage portal
#

What does the "checkforblocks" in the entity teleport options do?

#

I figure it would have canceled the teleportation if the destination would teleport the entity into nonpassable blocks, but that doesn't seem to be the case after testing.

alpine nebula
#

Any way to check if block/entity is in unloaded chunk?

distant tulip
#

block/entity,isValid()

alpine nebula
#

I have a problem: script engine runs my code slow and the game interrupts.
I'm making custom explosions with 'ray' mechanic. If I switch dim.createExplosion(coords, pwr, { allowUnderwater: true }); to // rayBlock.setType('minecraft:bedrock');, it works quite fast.
Anything I can do to increase the speed of explosion spread (without decreasing their amount)?
Here is a piece of my code:

#
const processedBlocks = [];
        const onRadiusBlocks = getOnRadiusBlocks(explosionLocation, explosionMaxRadius);
        for (const blockLocation of onRadiusBlocks) { // for each on radius block
            const block = dim.getBlock(blockLocation);
            if (!block.isValid()) { continue; }
            const rayArray = createRay(explosionLocation, blockLocation);

            for (const coords of rayArray) { // for each block in ray

                let index = processedBlocks.indexOf(coords);
                if (index > -1) {
                    continue; // do not create secondary explosion there again
                }
                processedBlocks.push(coords);

                const rayBlock = dim.getBlock(coords);
                if (!rayBlock.isValid()) { continue; }


                // skip if doesn't fit in range
                const dist = calculateIntDistance(rayBlock.center(), explosionLocation);
                if ((explosionMaxRadius * secondaryExplosionsStartCoefficient > dist) || (dist > explosionMaxRadius * secondaryExplosionsStopCoefficient)) {
                    continue;
                }

                if (passBlocks.indexOf(rayBlock.typeId) < 0) { // break 'ray' if there's an obstacle
                    break;
                }

                // create secondary explosion
                const pwr = calculateExplosionRadiusByDistance(dist, secondaryExplosionsMaxPower, explosionMaxRadius, 0);
                // rayBlock.setType('minecraft:bedrock');
                dim.createExplosion(coords, pwr, { allowUnderwater: true });
            }
        }
#

|| If I load the world after watchdog stopped it, I see such lovely crater ||

alpine nebula
#

Maybe some async functions? But idk how to deal with them plus I need to wait to check if previous explosion removed an obstacle.

neat hazel
#

Is it the same thing? Can I use either one?

player.getComponent('equippable').setEquipment("Head", null);
player.getComponent('equippable').setEquipment(EquipmentSlot.Head, null);
dim tusk
slow walrus
#

I would make a post detailing what it's actually supposed to do

solar dagger
celest abyss
#

Is there any way to remove the push when an entity attacks you?

simple arch
#

Any other suggestions for my simulated player menu addon?

cold grove
quick shoal
#

I've tried it before when I wanted to make a custom kb

#

That's because knockback resistance is not supported on player

#

My suggestion is use negative values with applyknockback

quick shoal
dim tusk
#

Yeah, they're the same case of knockback_roar you can't use that component directly on the player

quick shoal
#

The best but troubled way to create a custom kB is using plugin but only work on server

dim tusk
#

Unrelated but, I bug the game with my script so bad I have a culling block/ghost block šŸ˜‚

quick shoal
warm mason
dim tusk
quick shoal
#

How about toLocaleString()?

warm mason
dim tusk
quick shoal
#

I'm interested about date

dim tusk
tidal wasp
#

can you use world.beforeEvents in 2 different scripts?

quick shoal
tidal wasp
#

ok

dull shell
#
   const getScore = (objective, target, useZero = true) => {
        try {
            const obj = world.scoreboard.getObjective(objective);
            if (typeof target == 'string') {
                return obj.getScore(obj.getParticipants().find(v => v.displayName == target));
            }
            return obj.getScore(target.scoreboard);
        } catch {
            return useZero ? 0 : NaN;
        }
    }

    function enchants(player) {
        new ActionFormData()
            .title(title)
            
            .button("§cPurchase:\n§sSharpness")
            .button("§cPurchase:\n§sSoul Steal")
            .button("§cPurchase:\n§s???")
            .button("§cPurchase:\n§s???")
            .button("§cPurchase:\n§s???")
            .button(`§l§0Back`)
            .show(player).then(r => {
                if (r.selection == 0) {
                    player.runCommandAsync("execute @s ~~~ say");   
                    }
                if (r.selection == 1) {
                    player.runCommandAsync("execute @s ~~~ say");
                }
                if (r.selection == 2) {
                    player.runCommandAsync("execute @s ~~~ say");
                }
                if (r.selection == 3) {
                    player.runCommandAsync("execute @s ~~~ say");
                }
                if (r.selection == 4) {
                    player.runCommandAsync("execute @s ~~~ say");
                }
                if (r.selection == 5) main(player)
            })
    }
})```
#

as soon as i remove ```js
.textField(§u(${getScore('Money', player.nameTag)}))

round bone
#

you can directly obtain non-player's participants

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

const getScore = (participant, objective) => {
    try {
        return world.scoreboard.getObjective(objective).getScore(participant) ?? 0;
    } catch {};
    return 0;
};
dull shell
#

and that should make it work?

dull shell
round bone
slow walrus
round bone
hushed ravine
#

How would I go about creating a world border using blocks? I've got a border block with no collision already. Now I just need to figure out how to actually create the border itself without replacing blocks

chilly fractal
#

Best approach in my book:

system.runInterval(() => {
  system.runJob(function* () {
    let plrs = world.getPlayers();
    for (let i = 0; i < plrs.length; i++) {
      let player = plrs[i];
      isInBorder(player) ? saveLoc(player) : player.teleport(savedLocs.get(player.id) ?? {x: Math.min(player.location.x, world.getBorder(player).x-20), y: Math.min(player.location.y, world.getBorder(player).y-20), z: Math.min(player.location.z, world.getBorder(player).z-20)});
    }
  }());
}, 20);
#

There is more, wait

#
function saveLoc(player) {
  savedLocs.set(player.id, player.location);
}

function isInBorder(player) {
  return Object.keys(world.getBorder(player)).every(k => Math.abs(player.location[k]) < world.getBorder(player)[k]);
}
#

Done? Nah.

#
let savedLocs = new Map();
World.prototype.getBorder = function(player) {
  return generalDB.get('worldBorder') !== undefined ? generalDB.get('worldBorder')[player.dimension.id] : addon.worldBorder[player.dimension.id];
}
#

Now edit the world prototype function however you want, but make sure it returns a vector3 with the border values

#

Like it returns a good'ol:

{x: 0, y: 1, z: 2}
amber granite
#

What s new with script api ?

rigid meadow
#

is there way to basically give infinite amount of blocks?

#

i treid to give 255 blocks but whenever they place a block, it just becomes 64

wary edge
rigid meadow
#

oh alr

hushed ravine
#

I have these border blocks

#

Basically, I want to do something similar to the world border in Java edition

#

If there's any other way to do it other than just using blocks, that would be cool to know

#

Also, you can go past the border

#

Hence why the block has no collision box

chilly fractal
#

Ehem

#

The way i told ya

#

And visualize the border using a giant particle or a certain amount of vanilla particles when a player gets close to the border

hushed ravine
hushed ravine
chilly fractal
chilly fractal
dull shell
chilly fractal
hushed ravine
hushed ravine
chilly fractal
chilly fractal
warm mason
#

If I did this I would use blocks

chilly fractal
hushed ravine
warm mason
chilly fractal
chilly fractal
hushed ravine
#

I might not go with the blocks approach since that would require all chunks to be ticking (not really possible in Bedrock)

chilly fractal
chilly fractal
hushed ravine
chilly fractal
#

I do not know, but i believe not, as it is one particle, not many redstone particles.

dull shell
#

is it possible to display a score in the buttons?

#

or only textboxs above

dull shell
warm mason
#
.button("Text\n" + world.scoreboard.getObjective('money').getScore(player))
dull shell
#

oooh thank you! I was putting in the wrong thing 😭

`(${getScore('Money', player.nameTag)})````
#

thats what i had before

mystic bluff
#

How to change the direction of a player

thorn flicker
round bone
dull shell
round bone
#

btw are you sure that you should use player.nameTag instead just player?

dull shell
#

i mean really it cant break that much

#

i usually just make projects for myself and maybe some friends to play

round bone
#

it does not break when player has space in their name?

dull shell
#

no I do

round bone
#

I experienced smth like this a long time ago when I was using scoreboard as a db

dull shell
dull shell
round bone
#

maybe

wary edge
#

What's the standard bundler people use here for ScriptAPI?

dull shell
#

what happened?
I changed this
js .button("§sSharpness\n§a$" + world.scoreboard.getObjective('SharpnessPrice').getScore(player))
to this
js .button("", "§sSharpness \n§a$" + world.scoreboard.getObjective('SharpnessPrice').getScore(player))

#

can I add a image onto these?

warm mason
dull shell
#

ooo thank you!

slim forum
#

I dont wanna use applyImpulse, because is very very fast

#

And applyKnockback dont work on entities

warm mason
#

What entity do you want to push?

slim forum
#

A shooting star

#

I want to push it down

warm mason
#

Show the json code

slim forum
#

Ok

#
{
  "format_version": "1.13.0",
  "minecraft:entity": {
    "description": {
      "identifier": "hyentity:shooting_star",
      "is_spawnable": false,
      "is_summonable": true,
      "is_experimental": false,
      "runtime_identifier": "minecraft:thrown_trident"
    },
    "component_groups": {
      "despawn": {
        "minecraft:instant_despawn": {}
      }
    },
    "components": {
      "minecraft:type_family": {
        "family": ["shooting_star", "from_space"]
      },
      "minecraft:collision_box": {
        "width": 0,
        "height": 0
      },
      "minecraft:projectile": {
        "power": 3,
        "gravity": 0,
        "uncertainty_base": 16,
        "uncertainty_multiplier": 4,
        "anchor": 1,
        "should_bounce": false,
        "offset": [0, 0, 0]
      },
      "minecraft:damage_sensor": {
        "triggers": [
          {
            "cause": "all",
            "deals_damage": false
          }
        ]
      },
      "minecraft:physics": {},
      "minecraft:pushable": {
        "is_pushable": false,
        "is_pushable_by_piston": true
      },
      "minecraft:conditional_bandwidth_optimization": {
        "default_values": {
          "max_optimized_distance": 80.0,
          "max_dropped_ticks": 7,
          "use_motion_prediction_hints": true
        }
      }
    },
    "events": {
      "despawn": {
        "sequence": [
          {
            "add": {
              "component_groups": ["despawn"]
            }
          }
        ]
      }
    }
  }
}
warm mason
#

Do you need to throw it at some angle or just straight down?

slim forum
#

Hmmmm

#

I will try

warm mason
#

I didn't even answer anything

slim forum
#

Oh

#

Yeah, I wanna throw it down

#

Sorry, ADHD

warm mason
#

Just increase the gravity value

slim forum
#

Like real shooting stars

warm mason
#

ok...

slim forum
#

Using applyImpulse, is really fast

slim forum
sterile epoch
#

will the player leave before event work for everyone except the host?

#

if so I can use it

slim forum
#

Use this

#

-4294967295 is host id

sterile epoch
#

wait player IDs aren't random?

#

I thought it was a UUID or smthn lol

#

ok thanks

slim forum
#

No lol

warm mason
slim forum
sterile epoch
#

is it the same on realms?

sterile epoch
#

because technically the realm owner isn't the host

slim forum
sterile epoch
#

I'll test it when I get home since I have a realm

shut vessel
#

who know how to mixt 2 player.json ?

#

or keep 2 of them

mystic bluff
#

Is there something like force hit?
i've got a reach check system that works but people has to click for it to work

chilly fractal
#

Animation controllers are your best bet

tidal wasp
#

how would i tell if the player strips a log?

remote oyster
# shut vessel who know how to mixt 2 player.json ?

Use a tool to "diff" the two. Figure out the difference between them. Decide which one you want to keep and which behavior pack it came from. Then strategically move the differentiated code from the other file over to it.

Once completed, and done successfully, you will delete the other file. It's no longer needed and the behavior pack it came from will no longer require it.

Your newly merged file can go back into the behavior pack where that file originated from.

From this point the behavior pack now lacking the file will be dependent on the behavior pack with the file containing the merged code.

Install both in your world and profit.

|| Takes practice. You will probably mess it up a couple of times. Even Veterans who are familiar with doing this can slip up and make mistakes so don't assume you are incapable. Practice it. ||

dense skiff
#

Is there a way to pass information from a resource pack to the script api?

keen laurel
#

Is the easiest way to get progress of an item use event to store it in a hashmap when u start / finish or is there some way to get progress on it

dim tusk
#

Then store in a WeakMap a time then compare the after events

keen laurel
round bone
celest abyss
#

How can I detect when it is raining and the player is not taking cover?

round bone
#

but if it's raining, you can get top most block and check if player's Y is under if

dim tusk
round bone
#
const { x, y, z ] = player.location;
const isUnder = (player.dimension.getTopmostBlock({ x: Math.floor(x), z: Math.floor(z) })?.y ?? -64) - 1 > y;
round bone
#

how did I miss this xD

#

xD

dim tusk
#

I was like... Wtf?

#

But it's beta

round bone
#
const { x, y, z ] = player.location;
const isUnder = (player.dimension.getTopmostBlock({ x: Math.floor(x), z: Math.floor(z) })?.y ?? -64) - 1 > y;

if (isUnder && player.dimension.getWeather() === "Rain") {
    // ur code
};
round bone
dim tusk
round bone
dim tusk
round bone
#

but that's only my opinion, I might be wrong

round bone
dim tusk
round bone
#

it would be pretty nice to see slash commands in add-ons

#

I am not making entire proxy or using software written on-top BDS just to have slash commands

dim tusk
#

Definitely but I also kinda understand why it's not really implemented yet

round bone
#

they have a bit more important things to add

#

that's why we don't have ender chest component, so we have to use hasitem selector

dim tusk
#

They added 3 good things but others too but this is my favorite... Custom categories and the getMovementVector(), more inputpermission options

round bone
#

or they're waiting for christmas to make it their gift to developers

dim tusk
#

Or things to disable

round bone
#

but tbh slash commands are really nice to have

#

why I would type !entire-command-name when I can just /entir and then enter tab

dim tusk
round bone
#

in Russia, they're celebreating christmas on 7 January

dim tusk
round bone
#

Russia moment

dim tusk
round bone
#

fixed

#

technically I should be writing update to my API right now instead hanging out on this Discord xD

dim tusk
#

Ohh yeah, getBlockFromRay() and getBlockFromViewDirection() kind have difference

#

in the getBlockFromViewDirection has limits when you look at the certain angle of the block it passes through the block you're looking at compared to the getBlockFromRay but y'know what's funny they almost have the same functionality we just specified the direction like wtf

round bone
#

I have not used them yet tbh

dim tusk
#
cosnt blockFromView = player.getBlockFromViewDirection({ maxDistance: 20 })?.block;

const head = player.getHeadLocation();
const blockFromRay = player.dimension.getBlockFromRay({ x: head.x, y: head.y + 0.1, z: head.z }, player.getViewDirection(), { maxDistance: 20 })?.block;```
#

They don't have a difference, on paper but in game? They do

dim tusk
round bone
remote oyster
#

I keep seeing people say "add slash commands." However, slashes are just another form of a prefix before the actual command. We're able to create commands using various prefixes, so I don't quite understand what some of you mean when I come in here and read "add slash commands." Lol.

acoustic basin
#

guys, is there a way i could split this id, in such way, that i only have 'araucaria'? 'v360:araucaria_log'

#

basically, i have the same custom component for several logs, and i need to get just that first part of the id, so like, split v360 and log, and only have araucaria, so i could later use it in my script as for example v360:decay_${logType}_leaves, and that {logType} is the, welp, log type

#

i hope i didnt confuse

slow walrus
#

also just better UX

tight plume
#

relying on chatSend also introduces performance problems

remote oyster
remote oyster
# slow walrus proper parameter definitions, closing chat, etc.

Already possible to include proper parameter definitions so long as you wrote your code with these things in mind, minus the ability to close chat, but I'm pretty confident they could extend to include that capability. The question is when and will they.

I think what you and others may be really implying here is not so much the ability to introduce "slash commands" since I believe that is not the proper term being sought out in this context, but instead "Command Auto Completion". That terminology makes a lot more sense here.

tight plume
# remote oyster **???** Please show code to demonstrate.

For example, showing a form, it requires a player to close the chat in-order to open the form meaning we have to loop everytime. Another way is to just create a expiration time or some sort but i don't really think it's that better of an option in terms of UX, we should have a way to send command and then quickly close the chat.

Also on auto-completions as said earlier. If i were to say it, i wouldn't consider sendChat as a viable option in terms of custom commands, it's just some clever way people made to create "custom commands". There should be another event that focuses on slash commands only.

remote oyster
#

That doesn't answer the question regarding poor performance. You mentioned looping to close chat but your statement is more generic than that so it's particularly not on subject with my statement, but the impact on performance while listening to close chat is minimal at best, unless the logic being implemented is trash (which I have seen some rather rough logic being used for it).

You still haven't provided any code to demonstrate general use case of chatSend being a problem with performance.

warm mason
#

If you don't display the form for 300 players at the same time, there won't be any performance problems. (There will be problems only because of 300 players)

tight plume
remote oyster
tight plume
#

No i won't, you can search them yourself in this server. It's all the same method anyways, check user busy then run a loop..

ocean escarp
#

Can scripts grab the ā€œminecraft:attack_damageā€ attribute

remote oyster
warm mason
#

You made up a problem, didn't give us the code for that problem, and are telling us to look for a problem that doesn't exist.

ocean escarp
#

What would be the workaround?

#

cause I really don’t wanna have to make a table

warm mason
#

You can create the entity you need, make it hit another entity, find out the damage through the entityHurt event and save it. But it’s better to just duplicate the damage values ​​in the scripts

tight plume
tight plume
remote oyster
#

The purpose of demonstrating it isn’t to engage in a competition, but to provide evidence and validate the data. More importantly, it ensures that others who are unfamiliar and come here seeking information can access reliable feedback.

tight plume
#

Logic? If-statement and a loop in a function, how further would you able to simplify that?

If sending out information is what we are doing here then what is your first premise even about? You engaged at something controversial and we tried proving you wrong by giving out simple concepts but you just said they might implement those capabilities later on. You quite literally prove the first's guy by showing what are the holes with sendChat.

warm mason
#

And there is no loop used here

tight plume
#

There is and you haven't even noticed it

warm mason
tight plume
warm mason
#

In this case, there is a gap between code execution, unlike a loop, and this will not cause a server crash

distant tulip
#

show form is async

#

it is recommended to add a delay anyway

warm mason
#

Therefore, you need to run hundreds of such loops to cause lag.

tight plume
#

Anyways read up to the top of the message, it still falls. We've said the problem on relying on it, you've quite literally proven my point on how ridiculous it is and not comparable to a fully supported slash command implementation

warm mason
#

It's easy to make the number of function calls unlimited, you just have to add 2-3 lines of code

#

And I didn't say anything about "custom commands"

wary edge
wary edge
chilly fractal
#

Damn there is some heat that happened here

#

What'd i miss?

distant tulip
wary edge
#

And, remind me, does chatSend detect command blocks and othwr means of executing commands?

distant tulip
#

nope

wary edge
#

So then it isn't as versatile as proper commands therefore we do need support for it.

distant tulip
distant tulip
#

if they do anyway

acoustic basin
#

guys, y does it throw me error of unsupported out of bounds value?
block.dimension.spawnItem(new ItemStack('v360:blueberries', Math.random(2, 3)), block.center())

#

for Math.random()

#

argument 1 is invalid, and argument bounds in [1, 255]

round bone
acoustic basin
acoustic basin
acoustic basin
glacial widget
#

Is there a way stop when players click a item and then drop it but the item doesn't clear?

round bone
remote oyster
remote oyster
#

The main purpose anybody here wants out of it is solely for auto completion. So let's call it what it is.

wary edge
remote oyster
# wary edge And I don't believe that. There is also the issue that using / is the defacto co...

People aren't asking support to use the string /. They are asking for support for the sake of auto completion. Because when you use the native method built in the application for slash commands you get auto completion in return which makes for a convenient and logical experience to be had. Anyone saying they want support to use the string / in and of itself is either lying or arrogant and not being honest with themselves.

remote oyster
# wary edge Ok, now address my other issues.

Unless someone contributes code to guide the discussion meaningfully, there’s no need to continue the conversation. Without evidence to weigh and steer the discussion in a constructive direction, a conversation based solely on disagreements offers no opportunity for learning or growth.

round bone
wary edge
remote oyster
round bone
wary edge
round bone
#

they have more features than regular ones (just chat message)

remote oyster
#

I'm stepping away since this is fruitless.

wary edge
remote oyster
#

When you go back and read the conversations previously had in here about wanting support for slash commands, majority of the time it is not based on support for a specific string but primarily for support having auto completion because of the benefits and convenience it offers.

round bone
remote oyster
#

Agreed

round bone
#

you have information about arguments while typing it

remote oyster
#

Indeed and that brings a level of convenience that many would appreciate.

round bone
#

it's better for accessibility

#

and makes them different from chat messages

wary edge
remote oyster
# wary edge Sure, whatever. You spend more time in here than me. I do rarely see the convos ...

And I don't disagree with this statement either. I'm personally ok not having auto completion. My only point when bringing it up was the terminology being used by the majority when they wanted to express such support. Slash commands and auto completions are really different concepts when you look at it more in depth and that is all I was trying to point out before I got flanked lol.

round bone
#

but if you just want to implement smth, don't care about scale just use /scriptevent

wary edge
#

But would you rather
/scriptevent dev:debug blocks
Or
/dev:debug blocks

round bone
wary edge
#

Im saying, using workarounds sucks.

round bone
wary edge
#

As a buge HCF user and having to suffer from the previous management of HCF, having to rely on workarounds for 4 bloody years is a terrible UX. I do not wish the same for ScriptAPI nor future ApIs.

open urchin
#

I don't like the term custom "slash" commands since there is only one type of command that exists. The / is used to specify that something is a command where it might not be (ACs where it could be an event name, chat where it could be a message). Commands themselves do not include a slash. If it doesn't start with a slash, it's not being treated as a command, so there is no reason for it to have autocompletions.

round bone
#

I don't know really why they're skipping this feature that much tbh

#

this would probably make chatSend a stable event

past blaze
#

sending chat and running commands are two different actions

round bone
#

why would I have to handle them inside ChatSendBeforeEvent

past blaze
round bone
#

oh yeah

#

tbh I'm forgetting to swipe it when I'm not adding question marks to the end of my questions xD

celest abyss
#

world.afterEvents.itemUse.subscribe(ev => {
if (ev.itemStack.typeId !== 'minecraft:diamond') return; player.nameTag = 'Test'

** Does this work? **

warm mason
#

And it won't work, since you specify the name after return.

warm mason
#
world.afterEvents.itemUse.subscribe(ev => {
  if (ev.itemStack.typeId !== 'minecraft:diamond') return; 
  ev.source.nameTag = 'Test'
})
distant tulip
warm mason
turbid delta
#

can item stack be compared with other item stacks

chilly fractal
#

Yessir (not natively and not using "===" nor "==", but rather with a function of your own)

#

Here is my function:

distant tulip
#

isStackableWith

chilly fractal
#
function isEqualArr(arr1, arr2) {
  if (arr1.length !== arr2.length) return false;
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) return false;
  }
  return true;
}

function compareItems(item1, item2) { // TODO: make component comparing, finish the world border first tho.
  let props = ['typeId', 'amount', 'nameTag', 'keepOnDeath', 'maxAmount', 'lockMode', 'isStackable'];
  for (let i = 0; i < props.length; i++) {
    if (item1[props[i]] !== item2[props[i]]) return false;
  }
  
  if (item1.getDynamicPropertyTotalByteCount() !== getDynamicPropertyTotalByteCount()) return false;
  if (!isEqualArr(item1.getTags(), item2.getTags())) return false;
  if (!isEqualArr(item1.getLore(), item2.getLore())) return false;
  if (!isEqualArr(item1.getCanPlaceOn(), item2.getCanPlaceOn())) return false;
  if (!isEqualArr(item1.getCanDestroy(), item2.getCanDestroy())) return false;
  if (!isEqualArr(item1.getDynamicPropertyIds(), item2.getDynamicPropertyIds())) return false;
  return true;
}
chilly fractal
shut vessel
valid ice
#

Nop

#

One file would take priority and the other would be completely ignored

shut vessel
#

okay

warm mason
valid ice
#

I get no errors when I have that file in my game shrug

valid ice
#

huh?

shut vessel
#

oh

#

and this ?

#

i want to mixt thems

#

but i dont know how i can do it

shut vessel
turbid delta
#

I'm trying to make my own inventoryChange event with server-net but I don't have a way to find out which item stack changed

#

If only item stacks had a unique id crying

warm mason
#

Use this, store the previous rows of items in a variable and compare with the current row in a loop. For example ```js
if (stringifyItem(oldItem) != stringifyItem(item)) {
// The item has changed
}

turbid delta
#

in a loop šŸ’€

warm mason
turbid delta
#

Unfortunately not

warm mason
#

Well, that's all. You can check the inventory of one player every tick and there will be no lags

turbid delta
#

Do dynamic properties work on stackable items now?

warm mason
#

Why do you need dynamic properties? You will still need to check this in a loop

turbid delta
#

Could probably make items have their own unique ids but that would be a lot of memory for dynamic properties

distant tulip
#

dynamic properties are not stored in memory

#

unless the value is cached

turbid delta
#

storage i mean

#

or whatever they work with the behavior pack manifest uuid

warm mason
#

in unicode, 1 character is encoded in 2 bytes, let's say you use 32 characters. You will need quite a lot of such items so that the weight of dynamic properties exceeds the weight of at least one chunk

distant tulip
#

just cache the previous inv items and compare them

warm mason
distant tulip
#

yeah
he seem to not want to do it that way
but it is better than any alternative

chilly fractal
#

Set each char with a § before it to hide it

warm mason
chilly fractal
#

So?

#

Set lore in each item

warm mason
#

Items will not stack due to different lore

chilly fractal
#

Compare them then

#

Using isStackableWith before hand

distant tulip
#

newly picked items...
it will be a mess

dim tusk
#

Nah, not a good idea....

turbid delta
chilly fractal
#

You are gonna have to setup multiple events and parsing. But hey, the result is great i guess..

#

I personally do this and it aint laggy

#

But yall do you

#

Ima do me.

turbid delta
warm mason
chilly fractal
#

They asked if they could have unique ids for the items. And i suggested the exact request they wanted. But, optimally, id use serty's approach if i am checking for invs and stuff, but in my case, i am literally making my own block pick up from java. So yes i need the items not to stack.

dim tusk
#

There's no 100% accurate way to detect drop and pick up even if you find a way there's definitely a limit or bug

#

if that's what you are guys talking about ( I'm out of topic )

turbid delta
#

You probably can with some obscure packet logging

dim tusk
distant tulip
#

or using other entity inventory as cache

warm mason
chilly fractal
#

Or using structure blocks (saving in memory or disk, disk is storage and memory is memory)

dim tusk
#

that's why I left them first...

chilly fractal
#

There are so many options

dim tusk
#

I'm too lazy to find a solution for that, I would like to rest first...

dim tusk
chilly fractal
distant tulip
chilly fractal
chilly fractal
#

Elaborate.

turbid delta
distant tulip
chilly fractal
dim tusk
#

Im gaslighting myself here lmao

#

Don't take it serious

warm mason
turbid delta
#

I already am logging when player has item stack change to reduce the loops I do

#

I just dont know how to compare the player inventory item stacks to deduce what changed šŸ˜‚

chilly fractal
turbid delta
#
beforeEvents.packetReceive.subscribe((packet) => {
    const { packetSize, sender: player } = packet;
    const inventory = player.getComponent("minecraft:inventory").container;
    const equipment = player.getComponent("minecraft:equippable");

    // Scan the inventory for all item stacks and save them to an array
    const playerItemStacks = [ player.getComponent("minecraft:cursor_inventory").item ];
    for (const slot of ["Head", "Chest", "Legs", "Feet", "Offhand"])
        playerItemStacks.push(equipment.getEquipment(slot));
    for (let i = 0; i < inventory.size; i++)
        playerItemStacks.push(inventory.getItem(i));
    const playerInventory = playerItemStacks.filter(item => item);
    // Save the item stacks into memory on the player if not undefined
    player.inventory ??= playerInventory;

    // Find which item stacks were removed or added and log them into the webhook
    for (const itemStack of playerInventory)
        if (!player.inventory.includes(itemStack)) inventoryTransactions.push(
            `(+) ${player.name} ${itemStack.amount}x ${itemStack.typeId} [${stringifyLocation(player.location)}]`);
    for (const itemStack of player.inventory)
        if (!playerInventory.includes(itemStack)) inventoryTransactions.push(
            `(-) ${player.name} ${itemStack.amount}x ${itemStack.typeId} [${stringifyLocation(player.location)}]`);

    // Save the new inventory for future logs
    player.inventory = playerInventory;
}, { monitoredPacketIds: [ "ItemStackRequestPacket" ] });

function stringifyLocation(location) {
    const { x, y, z } = location;
    return `${Math.round(x)}, ${Math.round(y)}, ${Math.round(z)}`;
}

const inventoryTransactions = [];
system.runInterval(() => {
    if (inventoryTransactions.length === 0) return;
    postWebhook("INVENTORY", inventoryTransactions.join("\n"));
    inventoryTransactions.length = 0;
}, 50);
#

The include statements don't work for obvious reasons

#

I'm not doing anything much besides trying to log them for now

chilly fractal
#

So what is stopping you from checking if the item is like the one cached?

dim tusk
#

You're storing the ItemStack in a variable?

turbid delta
chilly fractal
#

Sigh

#

Not that

#

I meant

#

Literally comparing them

turbid delta
#

thats big O^n operation

#

very slow

chilly fractal
#

Their amount, typeId, lore, enchants, componets, canPlaceOn, canDestroyOn, lockMode, keepOnDeath

dim tusk
#

you can't just compare ItemStack directly you need to grab it's data specifically...

dim tusk
chilly fractal
distant tulip
turbid delta
#

I already know that I was just showing the code to what I was doing with packets

dim tusk
chilly fractal
dim tusk
#

Ohh btw, dyeable component doesn't work on vanilla items iirc.. only in custom ones

#

Unless they fixed it? I dunno

warm mason
wary edge
turbid delta
# chilly fractal So, WHAT IS STOPPING YOU? (Sorry for caps, but really, what is the problem?)

Lets say I do that. First of all im going have to iterate through the current inventory and the inventory cache, and compare if each items are the same. Thats a nested for loop and thus a big O^n operation. Slow as fuck. But lets ignore that. If I compare the item stacks with all the data, its going to return true most the time anyways because my items don't have much defining features from one another, the only thign that is different would be their typeIds and amounts. every other property is always going to be the same. So its going to be super slow and going to return true for items in the cache it shouldnt be.

turbid delta
#

Or I guess I could map out the item datas into an array and see if its included in there so its not O^n, but still my second problem is still an issue.

chilly fractal
#

If you got a better approach, please go ahead, tell me. I am willing to listen.

turbid delta
#

Its not really important for me I'm just trying to log what items someone is adding or removing into their inventory for the sake of it

chilly fractal
#

Then limit the checks.

warm mason
#

-# I would write the code for you, but I'm lazy, I went to eatšŸ˜‹

chilly fractal
#

If there are no enchants on an item, check if the cached has enchants, if yes, return early. (They are different)

chilly fractal
dim tusk
#

I mean, unknown is correct tho... If checking is slow asf for you then limit check only checks typeid amount and name tag...

#

As if you have other choices since js is limited to mc rn...

distant gulch
#

Is it possible to run two things at once for example:
A block with two properties:

  • hitbox1
  • hitbox2
    And both are in different positions is it possible to use something that makes them both enabled at once?
    For example I was thinking switching between both on the same tick but idk if it will work prolly not idk
#

I've used this tactic in multiple game engines and they work but I'm not sure about Minecraft

distant gulch
distant tulip
#

dude trying to hack the system and male stair like block

chilly fractal
distant gulch
chilly fractal
#

Wait hol up. You want two blocks in the same place?

distant gulch
#

Not two blocks

#

Two hitboxes

distant gulch
#

The concept is to switch between both fast enough to create an interactive illusion that it's one hitbox

#

I've used It for years in most game engines like Roblox and unity

chilly fractal
#

Just so we are on the same page, by hitbox, what exactly do you mean?
An area a player can hit?
An outline?
What exactly do you mean?

distant gulch
#

Collision

chilly fractal
#

Ah so you can do this.

#

So you are gonna need two of the same block with different collision values and then do this:

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

function switchCollision(loc) {
  let oldBlock = world.getDimension.getBlock(loc);
  oldBlock.setType("namespace:cool_block2");
  oldBlock.setPermutation(BlockPermutation.resolve("namespace:cool_block2"));
}
switchCollision({x: 0, y: 0, z: 0});
#

So you can edit the function and all, its just an example

#

I'm just really tired so thats why i was typing slow, sorry.

distant gulch
#

It's all good

#

I've never used functions before

#

Well custom ones

#

On Minecraft

chilly fractal
#

Ah well, everyone has been there, good luck on your journey and i should probably get some sleep... i haven't slept more than (24) hours in the past 5 days... (if you are wondering it is somewhere around 4 & 5 hours per day)

steady canopy
#

just do what they say, having two loops won't crash ur server, the lag would be just small.

#

And if you don't like that just wait for better packet reading Apis.

turbid delta
#

for (loop) {
for (loop) {
}
}

is big O^n

steady canopy
#

😱

turbid delta
#

mb i meant O^2

#

im so slow

#

😭

keen laurel
#

it's not O(n^2) though

#

you're only looping through the inventory once, checking another inventory at the same time. You don't check each slot for each item

steady canopy
#

^

#

that's why i asked him if he actually knew about that notation lol

dim tusk
#

Ohh my god.

turbid delta
#

i was just overthinking it

dim tusk
#

no I guess? We still need to use a runtime identifier of snowball, arrow or whatever

#

so just use a runtime identifier it's just one line

#

Why?

#

ask smokey, I think he's experienced using throwable components on items...

#

HUUUUH?! is this a marketplace contents or some sort?

thorn flicker
#

should not mention him lol

dim tusk
thorn flicker
#

im assuming it will be

wary edge
#

We could have always done that. Your issue is just projectiles trajectory/velocity in general. As for that, no not really. Custom Projectiles still heavily rely on runtime identifiers and unfortunately, it does not seem that Mojang is putting any effort into removing them as it isnt their focus currently.

winter plaza
#
export let Jutsus = {
  "fire_ball": {
    damage: 30,
    range: 1,
    knock: true
  },
  "phoenix_flower": {
    damage: 7,
    range: 1,
    knock: false
}
export function projetil(entity, player) {
  if (entity.typeId != "wesl3y:jutsu_projetil") return;
  const jutsuName = entity.getProperty("wesl3y:jutsu");
  const teste = jutsuName ? Jutsus[jutsuName] : null;
  console.warn(`Propriedade: ${jutsuName}, Damage: ${teste.damage}, Range: ${teste.range}`);
}
#

what's wrong?

dim tusk
#

the object is invalid too

#

You missed one }

export let Jutsus = {
  "fire_ball": {
    damage: 30,
    range: 1,
    knock: true
  },
  "phoenix_flower": {
    damage: 7,
    range: 1,
    knock: false
  }
};
turbid delta
#

How much better memory wise do you think it would be to use item components for onUse events as opposed to a normal item Use event

distant gulch
#

So with Script API Custom Item Components how do I make an item clickable? With blocks there's a custom component option that enables clicking how do I do the same with an item?

wary edge
distant gulch
wary edge