#Script API General

1 messages · Page 43 of 1

ruby haven
#

Wait will a player die if I add the component minecraft:instant_despawn

dim tusk
#

Btw can you specify wym by replaces button like put he button back?

ruby haven
#

Okay so the smile entity kills the player it doesn't actually die cause it has the minimum health component so it will be present in the death scene the problem is after the death scene I expect the player to actually die you know where the respawn UI appears but I can't override the minimum health component so there is no way for it to work

patent tapir
#

I just had to replace ‘north’ with like 5 or something

ruby haven
dim tusk
patent tapir
#

I STILL don’t understand why you used north

#

Because the numbers work and not the words.

#

Even in /setblock

dim tusk
patent tapir
#

I thought I explained it very well

dim tusk
patent tapir
#

I just destroy it so the player can’t push it again during the animation (the logic is all put into REACHING the button, not PUSHING it)

#

And for dramatic effect

#

Anyway im gonna get some dinner

ruby haven
#

Okay instead of using entitydie how about entity hurt detect if the health of the entity is 2 it will recreate the death scene but how do I make sure that even if the damage of the smile is 100 it will still leave 2 hearts for the player?

remote oyster
meager cargo
#

Hello, I have question if there is possibility to trigger events on entity by using in entity behavior properties and control that by script?
Example: Entity has 0-1 properties if it has tag - "test0" it will change in script property to 0 and then event will be triggered and if it has "test1" tag it will trigger another event and it will be done in scripts too.

I don't want use only commands, because it must be set up for many entities on the map

meager cargo
# remote oyster That is possible.

Can you tell me/point me how I can achieve that? I've tried entity.setProperty("test:test, state);
And then in system.runInterval if entity has tag it will check player in radius like that in full script:

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

const CHECKPOINTS = [7, 10];
const SIGN_TYPE = "test:entity";

// Function to set the entity's parkour display state
function setDisplayState(entity, state) {
    entity.setProperty("parkour:display_state", state);
}

system.runInterval(() => {
    const players = world.getPlayers();

    players.forEach((player) => {
        const scoreboard = player.getScoreboard();
        let checkpoint = scoreboard.getObjective("checkpoint")?.getScore(player) || 0;

        const queryOptions = { type: SIGN_TYPE, tags: ["tag1"] };
        const nSigns = player.dimension.getEntities(queryOptions);

        nSigns .forEach((sign) => {
            const distance = player.location.distanceTo(sign.location);

            switch (checkpoint) {
                case 0:
                    if (distance <= CHECKPOINTS[0]) {
                        setDisplayState(sign, 0); // novisible
                        player.runCommand("scoreboard players set @s checkpoint 1");
                    }
                    break;

                case 1:
                    setDisplayState(sign, 1); // appear
                    player.runCommand("scoreboard players set @s checkpoint 2");
                    break;

                case 2:
                    if (distance > CHECKPOINTS[0] && distance <= CHECKPOINTS[1]) {
                        setDisplayState(sign, 2); // visible
                        player.runCommand("scoreboard players set @s checkpoint 3");
                    }
                    break;

                case 3:
                    setDisplayState(sign, 3); // disappear
                    player.runCommand("scoreboard players set @s checkpoint 0");
                    break;

                default:
                    break;
            }
        });
    });
}, 20); // Run every tick (20 ms)

crude ferry
#

how can i make a entity MOVE, not teleport, in a given direction?

bright dove
#

how do you make a custom component that ticks randomly ?

warm mason
crude ferry
#

Thanks.

bright dove
bright dove
warm mason
# bright dove like, from 5-6 ticks, execute the code

Script:

world.beforeEvents.worldInitialize.subscribe(event => {
  event.blockComponentRegistry.registerCustomComponent("wiki:tick_component", {
    onTick: (data => {
      let block = data.block
      //Code
    })
  })
})```

Block: 
```json
"minecraft:custom_components": [
  "wiki:tick_component"
],
"minecraft:tick": {
  "interval_range": [5, 6],
  "looping": true
}
crude ferry
distant tulip
#

it is applying velocity
not "move to" function

crude ferry
#

right...

#

now i get it.

distant tulip
warm mason
marsh berry
#

Hi. I cant seem to get past and issue in having with privlages in a code i have:
import { HttpRequest,HttpRequestMethod, HttpHeader, http} from '@minecraft/server-net';
import { world } from '@minecraft/server';console.log("før senddata");

export function sendDataToWebsite(data) {
const url ="https//eozghbch9kyk3aa.m.pipedream.net";
const req = new HttpRequest(url);
req.body = JSON.stringify(data);
req.method = HttpRequestMethod.Post;
req.headers = [
new HttpHeader("Content-Type", "application/json")
];
http.request(req);
}

Is there something i am missing? I have server-net in my manifest and permission file in the config folder. On my server i also went inn and changed permissions on all folders and files for my addon to read/write. I am using crafty as a server client that runs in a Docker on my server that is using unraid (so Linux).

distant tulip
crude ferry
#

I thought it is a move to function.

distant tulip
granite cape
slow walrus
meager cargo
#

Yeah, I get that 🥺 , but I'm not programmer, I'm self-learner, so still using some chatgpt to some base of code is still better than doing all by myself for now. After month of trying I can do simple mechanics like changing blocks, dtecting entities, etc. But for complex scripts or something new is hard for me

warm mason
#

And even if you don’t understand something, it’s better to come here than to an AI that writes absolutely meaningless code

#

|| By the way, how does a self-learner ask for help if he is a self-learner. It turns out that he is no longer a self-learner bao_foxxo_smug ||

meager cargo
warm mason
meager cargo
#

I managed since my first message above about detecting property of entity to make script which is running events on entity by detecting player in radius.
I wanted do it by properties from 0 to 4 in entity behavior. Script should detect if player is near then change property from 0 to 1, if it's near and stay in radius then change from 1 to 2, if player leave radius it will change to 3 property and then after it will go back to 0.

#

I made that on in scripts and triggering event with animations

#

But it's on events not on properties

warm mason
# meager cargo I managed since my first message above about detecting property of entity to mak...
system.runInterval(() => {
  for (let id of ["overworld","nether","the_end"]) {
    for (let entity of world.getDimension(id).getEntities({type: "test:entity"})) {
      let property = entity.getProperty("parkour:display_state") || 0
      if (entity.dimension.getPlayers({location: entity.location, maxDistance: 5})) {
        if (property < 2) entity.setProperty("parkour:display_state", property+1)
      } else if (property == 3) {
        entity.setProperty("parkour:display_state", 0)
      } else if (property > 0) {
        entity.setProperty("parkour:display_state", 3)
      }
    }
  }
}, 80)
meager cargo
#

Thank you very much for help!

empty yoke
#

Do dynamic properties have a creation limit?

empty yoke
# warm mason no

Thank you, I'm trying to learn, I have another question. Would it be better to save the properties on the player, or to create a system that saves every player in the game, setting properties for each one? Additionally, if I save the players in a map, will the player be removed when they leave, or will they remain in the map? Only if owner leave the world will all the variables reset, correct?

warm mason
empty yoke
warm mason
wary edge
warm mason
# wary edge

You can't trust everything that's written in the documentation.

wary edge
warm mason
remote oyster
# wary edge

It may be obsolete since they have a dedicated event, but I feel like that event is a waste of resources and would be better suited the other way. Personal opinion and thoughts.

wary edge
remote oyster
#

Correct

wary edge
#

Inclined to agree when EntityInitializationCause contains a loaded member.

remote oyster
#

I suppose raising a ticket may bring resolve.

wary edge
#

I already brought it up in the OSS and bumped my message there already. Just gotta wait to see if Navi notices.

remote oyster
dense kayak
#

Hey, with @server-net I am getting

TypeError: Native property setter [HttpRequest::method] cannot be assigned null or undefined

the doc's example says this req.method = HttpRequestMethod.Post

but mine says Post doesn't exsist its POST request.method = HttpRequestMethod.POST

I've debugged this on it's own and the enum returns undefined.

Imports:import { HttpRequest, HttpHeader, HttpRequestMethod, http } from '@minecraft/server-net';

#1067535608660107284 message I can see someone had the same and setting it to 1.0.0-beta fixed it for them but I am already using it

distant tulip
dense kayak
#

ah new errors, that's progression 😆 thanks

#

ayee, db insert working, that was the fix thank you PepeThanks

distant tulip
#

ur wlc

granite badger
stark kestrel
#

isnt it possible to mute errors?

wary edge
stark kestrel
# wary edge What do you mean?

like i made a systemfor block breaking keeps throwing a error that dynamic property not found bla bla error in hand, cuz its meant to only be in a pickaxe

#

if i break with hand ^ i get error, if with pickaxe i dont

wary edge
#

Then you need to set up a guard clause.

#

if(empty hand) return;

stark kestrel
#

thanks!

#

appreciate that

wheat condor
marsh berry
#

Does anyone know what can cause this error?

marsh berry
#

The text over the error is the test to see if its a valid string

#

Omg. And i was just reading about that today. Gises. A new error. But at least im one stepp forward. Thanks for the hint!

gentle hemlock
#

Can someone help :)

meager cargo
#

Can someone help me with script for detecting if player is on ground?
I have this:

function isPlayerOnGround(player) {
    const pos = player.location;
    const yPosInt = Math.floor(pos.y);

    if (pos.y - yPosInt > 0.1) {
        return false;
    }

    const blockBelow = player.dimension.getBlock({ x: pos.x, y: yPosInt - 1.5, z: pos.z });
    return blockBelow && blockBelow.typeId !== "minecraft:air";
}
jolly citrus
#

do I need to take any extra measures to be able to use typescript for my script files? will it work without anything extra

meager cargo
#

wow, xd then, thanks a lot!

meager cargo
thorn flicker
meager cargo
#

Question from another topic, do you guys use any of obfuscating tools? Or do you have any idea of creating good one for js and json files? Is this common to use them?

thorn flicker
meager cargo
#

I have one for js, it's not bad and not best. But for json files I've tried looking for, many times but without succeed.

deep yew
#

yeah JSON just uses unicode and stuff and is easily decoded with just console.log

wheat condor
#

obfuscating is trash and since javascript is a garbage language it does not compile

deep yew
#

whatever that's supposed to mean

jolly citrus
#

is there any other way to hide the "Has Customised Properties" text on items with dynamic properties other than lang files?

open urchin
jolly citrus
#

does it do anything else than specifically hide this text?

open urchin
#

it hides the itemlock triangle and text

jolly citrus
thorn flicker
#

doesnt it hide lore aswell?

jolly citrus
#

that's amazing how have I never heard about this before

jolly citrus
#

definitely does not

thorn flicker
#

good

distant tulip
#

using get block from a ray that aimed at the edge of a block make the ray go through it, is there any work around for this problem?

dim tusk
#

If ever someone needs it but I'm now sure if it's really a "solution" but just use getBlockFromRay() instead of getBlockFromViewDirection()

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const head = player.getHeadLocation();
        const block = player.dimension.getBlockFromRay({ x: head.x, y: head.y + 0.1, z: head.z }, player.getViewDirection(), { maxDistance: 10, includePassableBlocks: true });
        console.error(block?.block.typeId, JSON.stringify(block?.block.location))
    }
});```
#

For those who would ask why add 0.1, the y-axis in head location doesn't align in the players view that's why I added it

#

-# and I feel like I'm kinda late to this problem LMAO

patent tapir
#

Why is it that when the conditions are filled for me to get weakness, it toggles very quickly between “0” and “event timer index invalid” in the effect duration in-game?

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

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    if (world.scoreboard.getObjective("killStales").getScore(player.scoreboardIdentity) > 0) world.scoreboard.getObjective("killStales").addScore(player.scoreboardIdentity, -1)
  }
}, 200)

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    if (world.scoreboard.getObjective("killStales").getScore(player.scoreboardIdentity) > 5) player.addEffect("weakness", 3, { showParticles: false, amplifier: (world.scoreboard.getObjective("killStales").getScore(player.scoreboardIdentity) - 6) })
  }
})

world.afterEvents.entityDie.subscribe((eventData) => {
  if (eventData.deadEntity instanceof Player && eventData.damageSource.damagingEntity instanceof Player) { world.scoreboard.getObjective("killStales").addScore(eventData.damageSource.damagingEntity.scoreboardIdentity, 1) }
})```
solar dagger
#

how can i set the camera to face the player from above?

unique acorn
#

can dynamicProperties store an array list?

solar dagger
unique acorn
#

thanks

distant tulip
patent tapir
#

I have to use player.runCommand() instead

#

And that’s really slow apparently

valid ice
#

Problem is that it works but has the weird index thingy, yeah?

#

Make it run once a second instead of every tick

#

Can also check the status of the applied effect, and only add it when the duration is getting low (or does not match the scoreboard value) instead of applying it every single tick

patent tapir
#

I saw you coddy

patent tapir
#

Is changing how often it happens really going to change anything?

valid ice
#

it’s worth a shot- see if increasing it to once per second does anything ¯_(ツ)_/¯

past blaze
#

Note that duration is in ticks and not seconds

patent tapir
#

Right now there’s also another file that has a similar idea

#
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    const hasteLevel = world.scoreboard.getObjective("hasteLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("hasteLevel").getScore(player.scoreboardIdentity) : 0
    const strengthLevel = world.scoreboard.getObjective("strengthLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("strengthLevel").getScore(player.scoreboardIdentity) : 0
    const speedLevel = world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) : 0
    const saturationLevel = world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("saturationLevel").getScore(player.scoreboardIdentity) : 0
    const fireResLevel = world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("fireResLevel").getScore(player.scoreboardIdentity) : 0
    if (hasteLevel > 0 && player.getEffects().includes("haste") == false) {
      player.runCommand(`effect @s haste infinite ${hasteLevel - 1} true`)
    }
    if (strengthLevel > 0 && player.getEffects().includes("strength") == false) {
      player.runCommand(`effect @s strength infinite ${strengthLevel - 1} true`)
    }
    if (speedLevel > 0 && player.getEffects().includes("speed") == false) {
      player.runCommand(`effect @s speed infinite ${speedLevel - 1} true`)
    }
    if (saturationLevel > 0 && player.getEffects().includes("saturation") == false) {
      player.runCommand(`effect @s saturation infinite ${saturationLevel - 1} true`)
    }
    if (fireResLevel > 0 && player.getEffects().includes("fire_resistance") == false) {
      player.runCommand(`effect @s fire_resistance infinite ${fireResLevel - 1} true`)
    }
  }
})```
patent tapir
past blaze
#

Just making sure 👍

patent tapir
#

But the ascendantEffects file is also causing a lot of lag

#

And I’m not entirely sure how to use all the api player.addEffects function correctly

dim tusk
patent tapir
dim tusk
patent tapir
#

Of course I did that.

#

Oh.

dim tusk
patent tapir
#

Now I realize what you want me to do.

dim tusk
#

What I'm saying is instead of player.getEffects().includes('haste') === false you can just !player.getEffect('haste')

patent tapir
#

Yeah yeh

dim tusk
patent tapir
#

My issue is the player.runCommand

#

Not the if/else

#

If I do player.addEffect() well, it doesn’t like the duration for some reason

dim tusk
patent tapir
#

But I set the duration to like 1 or something and it also doesn’t like it

#

It gives the effect and immediately cancels it and in the effect time it goes from 0 > “event timer index invalid” in less than 1/5 of a second

wary edge
patent tapir
#

Gah

#

I’m dumb

wary edge
#

Simple mistake I've made numerous times.

dim tusk
patent tapir
#

I didn’t realize .addEffect() used ticks

patent tapir
distant tulip
#

quick question, what dose duration return if we used getEffect in infinite effect?

patent tapir
dim tusk
patent tapir
#

I thought they were two different syntaxes by the way you said it

dim tusk
patent tapir
#

Well sure I guess you could make an argument that I didn’t know that dividing TO something wasn’t a syntax.

dim tusk
#

the value you want to set in duration is seconds right? Just divide the value by 20 since 20 ticks is 1 second in real life

patent tapir
#

Not divide.

dim tusk
#

Yeah your right lmao

patent tapir
#

I’ll just do 20 for one second, thank you

#

I’ve worked with command blocks for a lot longer before starting to do addons

#

I know how to work with ticks

patent tapir
#

Aw, what made that so easy to tell? 🗿

dim tusk
patent tapir
#

Uh-huh

patent tapir
# dim tusk

And the message that you chose to screenshot is just so funny to me

dim tusk
#

Or 200k I forgor

patent tapir
#

How do you even get the data of a certain effect/???????///??///???/

dense kayak
dim tusk
patent tapir
dim tusk
# patent tapir Yea
const effect = player.getEffect('haste');
effect.duration;
effect.amplifier;```
patent tapir
#

Huh

dim tusk
#

Wym "huh"? It's obvious already

#
const effect = player.getEffect('haste');

console.error(effect.amplifier, effect.duration); // returns the amplifier and duration of effect, returns 'undefined' if effect doesn't exist on entity```
viscid horizon
#

is there any methods for reloading the world using scripts

patent tapir
dim tusk
#

iirc someone said you can do it with vscode

dim tusk
#

Use find()

#

Or whatever

patent tapir
#

Would source.removeEffect() remove ALL effects if not specified?

dim tusk
#

Just use getEffects(), get all effects and you said y'know how to use it so it would be easy for you

patent tapir
#

Ok then would this work? js for (const effect of source.getEffects) { source.removeEffect(effect) }

patent tapir
#

I could also do source.runCommand(“effect @s clear”)

patent tapir
dim tusk
#

Damn, I felt kinda nvm...

patent tapir
# wary edge Yep.

Apparently not
[Scripting][error]-TypeError: value is not iterable at <anonymous> (betterButtonTp.js:323)

wary edge
patent tapir
#

Oh I’m dumb

wary edge
#

Minor oversight.

remote oyster
#

I've made that mistake before.

tight plume
#

how do i define that a variable is instance of for example Player class so i could get the autocompletions? Without using TS?

sharp elbow
#

You could either use JSDoc or use type guards.

import {Player} from '@minecraft/server';

/**
 * @param {Player} player
 */
function affectPlayer(player) {
  // parameter 'player' should give autocompletions for Player
}
import {Player} from '@minecraft/server';

function affectPlayer(player) {
  if(!(player instanceof Player)) return;
  // parameter 'player' should give autocompletions for Player
}
unique dragon
#

💀

#

TS is life

tight plume
wary edge
valid ice
#

tsc --watch go brrr

unique dragon
#

yea

#

good config

patent tapir
#

WHY DIDN’T I SEE THAT 🤦

#

Now I don’t have to use runCommand for inventory stuff

jolly citrus
#

am i the only one whose game starts doing a long flashback of everything that happened whilst i was gone if i go afk for a long time in my worlds with scripts at like 3-5fps

patent tapir
#

Am I doing this right? I’m giving anybody who kills the ender dragon ONE dragon egg js killer.getComponent("inventory").container.addItem({ amount: 1, typeId: "minecraft:dragon_egg" })

#

Or do I have to do something like js killer.getComponent("inventory").container.addItem(new ItemStack = { typeId: "minecraft:dragon_egg", amount: 1 })

warm mason
patent tapir
#

thanks then

jolly citrus
#

how do i send a message to all players in an array

jolly citrus
#

is my question

#

what are you questioning

tight plume
#

players that are in an array?

jolly citrus
jolly citrus
#

Player[]

#

without loop

#

it will be too inefficient that way

tight plume
jolly citrus
#

an array..

#

do you know what an array is..

#

["apple","banana","mango"]

tight plume
#

yes but in order to run methods on multiple players, you need loops

jolly citrus
#

each player in the array should be sent a specific message

jolly citrus
#

for sending messages

tight plume
#

there is but its more inefficient than using a loop

#

so just use loops

jolly citrus
#

ok

jolly citrus
#

can i check if a spawned mob was spawned from a spawner?

distant gulch
#

How do I track the speed in which a player is moving?

#

I want to runan applyKnockback horizontal strength based on their speed

jolly citrus
distant gulch
jolly citrus
#

prototype is used to display the methods available for a class

#

idk what the actual technical definition of it is but like

#

outside of an actual Player object you cant do Player.getVelocity() it has to be Player.prototype.getVelocity()

#

In programming, inheritance refers to passing down characteristics from a parent to a child so that a new piece of code can reuse and build upon the features of an existing one. JavaScript implements inheritance by using objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype and acts as the final link in this prototype chain. It is possible to mutate any member of the prototype chain or even swap out the prototype at runtime, so concepts like static dispatching do not exist in JavaScript.

#

something lik ethis

distant gulch
jolly citrus
#

just dont care about it it means the same thing as calling method getVelocity() on an actual target that you have

distant gulch
#

I wasn't sure that getVelocity got speed too, I assumed it was direction of movement

#

thanks!

#

alr

jolly citrus
#

idk how but theres def a formula just look it up

#

it returns Vector3 meaning it gives you the speed they are moving at in each direction

#

if you move 45 degrees away from south you will move like at speed |x| = 0.5 and |z| = 0.5 i think

distant gulch
#

Ah

#

I see

#

that's strange

distant gulch
jolly citrus
#

better than just 'straightforwardly' returning theactual speed bc that speed can't be really reversed back to a 3-dimensional format

#

maybe with viewdirection you could but idk im not good at math

distant gulch
#

alright, thanks so much!

burnt remnant
#

lets say this code is being executed from a block using custom components and on player interact and i wanted to detect every block, then if any of those match X block, i can change them to something else for each block in a 10x10x10 radius, would i have to make a line of code detecting every block all 1000, or can it be done easier like in one swoop.

#

so pretty much can i interact with my custom block and it changes all cobblestone around it in a 10x10x10 radius to netherrack in less than 1000 lines of code

#

wait im so dumb i can use a replace command no one look at me

dim tusk
#

Quick question can you add enchaments in items in the constructor? Like the new ItemStack()

chilly fractal
#

You are gonna require lots of logic tho.

#

I can send you my code (if you want)

#

You are gonna need to have some kind of filtering and checking position and spawn cause, but using a spawn egg near a spawner will also work like the mob spawner spawning mobs, (the cause you should be detecting is "Spawned" and you should probably make a weakMap and in the beforeEvent of itemUseOn if it's within the Radius of a spawner then y'know? Some logic to stop the entitySpawn event from falsely detecting..)

chilly fractal
dim tusk
chilly fractal
dim tusk
chilly fractal
#

Lol

slow walrus
#

or magnitude

#

which would be sqrt(x*x + y*y + z*z)

distant gulch
#

system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const currentLoc = player.location;
system.runTimeout(() => {
const newLoc = player.location;
const deltaX = newLoc.x - currentLoc.x;
const deltaY = newLoc.y - currentLoc.y;
const deltaZ = newLoc.z - currentLoc.z;
var speed = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2) + Math.pow(deltaZ, 2));
player.onScreenDisplay.setActionBar(Speed - X: ${Math.floor((newLoc.x - currentLoc.x) * 100)}, Z: ${Math.floor((newLoc.z - currentLoc.z) * 100)}\n${Math.floor(speed * 100)})
}, 2)
}
})

slow walrus
#

mmm that delta stuff is redundant lol

#

just use getVelocity

distant gulch
#

well yes

#

it is

#

but I got speed from finding where u were a couple ticks ago

#

what would be the equation to do the exact same thing with velocity?

#

but all in the same tick

#

instead of running multiple ticks

#

does pythagorean work with that too?

slow walrus
#

you velocity is delta-pos over delta-time

distant gulch
#

Rlly all I want is to be able to track the players speed

slow walrus
#

velocity is just a vector

distant gulch
#

So it would just be

slow walrus
#

and your "speed" is just the magnitude of your velocity

#

speed is velocity without a direction

#

so you just replace deltaX etc with velocity.x etc

distant gulch
#

I see

slow walrus
#

in you speed calc

#

also use let instead of var

distant gulch
#

And I wouldnt even need a timeout that way

#

dope

distant gulch
#

I switched to const

slow walrus
#

even better

distant gulch
#

but ye I didnt like var

#

Alr, well thanks so much!

#

its minecraft js

slow walrus
#

var hoists the variable into the global scope so it's generally not great to use

distant gulch
#

not regylar js

#

yeah

#

alr

#

well ima go work on this

#

thanks

slow walrus
#

np 👍

autumn seal
#

does not have required privileges

autumn seal
#

👍

autumn seal
#

avoiding using /setblock command but now theres a slight delay between breaking and particles/sound

jolly citrus
#

i was wondering if there was a native way for it but i guess not

sage sparrow
#

hi there, do someone know if it is possible to use spawnParticles in a way the particle understand it is attached to the player?
for instance, I have a custom particle that have this:json "minecraft:emitter_local_space": { "position": true, "rotation": true, "velocity": false },So when this particle is executed from a animation it takes in consideration the head and looking direction of the mob.
but when executed from API, there is no way to tell the particle what entity/player this particle belongs to?

jolly citrus
#

can I set the lore of an itemstack without tick privileges somehow

chilly fractal
#

Nope

#

You can however save the data to a map and the next tick set the item's lore and delete the item. (Using some kind of indexing like the slot it's in, the container it's in, the Player's Inventory container it's in, date it has been saved, idk anything to index it.).

jolly citrus
#

its ok tho ill just make sure i only call it w privileges

chilly fractal
#

I said "index" it with any of these suggestions, if you need to set it's lore even if you don't have the required privileges currently.

chilly fractal
jolly citrus
#

thx for the suggestion tho

chilly fractal
#

You could just store it in a variable and do whatever you wanna do and then set lore on the next tick from that variable but idk if that works

jolly citrus
chilly fractal
#

Why exactly?

jolly citrus
chilly fractal
#

💀

jolly citrus
#

it's not that big of a deal anymore, later in my function I will have to add this stack to a player's container anyway so i'll just move some parts around

chilly fractal
#

Bruh

chilly fractal
#

Group the variables in one line

jolly citrus
#

no i don't need it anymore, the privilege stuff isn't a concern anymore

chilly fractal
#

For example:

const baller1 = "baller1";
const baller2 = "baller2";

Is now:

const baller1 = "baller1", baller2 = "baller2";
jolly citrus
#

ik

chilly fractal
#

Well then..... WHY not use it?

jolly citrus
#

because I don't need to

#

i've said that twice now sry

#

it's not of any concern to have tick privileges anymore, I moved some stuff around and everything is perfectly fine now

chilly fractal
#

Alright then ig...

jolly citrus
#

is it possible to open the crafting menu for a player

jolly citrus
warm mason
#

no

jolly citrus
#

what's the difference between world.getPlayers() & world.getAllPlayers()

distant tulip
#

none

jolly citrus
#

why do we have two then

#

except that getAllPlayers doesnt have entityqueryoptions

#

or playerquery idk what its called

distant tulip
#

no idea

distant tulip
jolly citrus
#

wdym

#

getAllPlayers does not

distant tulip
#

i thought you said "except that getAllPlayers have entityqueryoptions"

jolly citrus
#

oh

dim tusk
#

Their functions no differ from each other... Both of them return an array of players

#

Unless I'm wrong

distant tulip
#

i use getEntities some times, sense entityqueryoptions in getPlayers don't support some stuff

open urchin
#

They might have added getAllPlayers first and then added getPlayers since it wouldn't make sense to have a filter on a function that should return all players

dim tusk
#

is there a way to accurately get the loot dropped by the block?

#

What I'm thinking of is before events of playerBreakBlock -> entitySpawn

#

The only unreliable part is when the item is tp with command blocks or another shit that changes location, it might not work

jolly citrus
#

like if somebody dropped an item close to it

jolly citrus
dim tusk
jolly citrus
#

only on afterEvent

#

but i'm not sure

dim tusk
jolly citrus
#

there is no beforeEvent of entityspawn

#

nvm

dim tusk
jolly citrus
dim tusk
# jolly citrus show an example idk what ur implying
world.beforeEvents.playerBreakBlock.subscribe(({ block, player }) => {
   system.run(() => {
      const spawn = world.afterEvents.entitySpawb.subscribe(({ entity }) => {
         if (entity.hasComponent('item')) {}
      });
   });
});```
jolly citrus
#

i never knew you could do this waow

dim tusk
#

It's just a snippet no big deal

warm mason
jolly citrus
#

@dim tusk another way is, if you have the time for it, re-write the item dropping functionality of mc and disable vanilla tile drops

jolly citrus
#

not the best practice probably though

dim tusk
distant tulip
#

that is a weird way of using events

jolly citrus
#

i never knew that was a thing

wary edge
dim tusk
jolly citrus
#

idk if disabling tile drops disables container stuff though

dim tusk
#

But anyways back to the problem... Yes it will work but if the item is tp'd, not anymore

distant tulip
#

i definitely have some weird lines in my scripts too

#

the amount of time gone in re-coding some of my scripts ↗↗

#

i guess that what happen when you start learning a new api and using it in the same time

dim tusk
#

My weakness on scripts is the auto formatting of the software

#

They make my script long 😭

distant tulip
#

make your own
lol

dim tusk
warm mason
distant tulip
#

just make it not auto format?

dim tusk
distant tulip
warm mason
dim tusk
dim tusk
distant tulip
#

wait... you switched from notpad++? @dim tusk

dim tusk
distant tulip
#

lol, good for u

dim tusk
#

y'know what's funny? When handling json my hand will automatically select notepad++ but if scripts it's vscode now

distant tulip
#

me using windows notepad

marsh berry
dim tusk
wary edge
chilly fractal
#

Formatters? More like deformatters for me.

#

Formatted code looks weird to me and deformatted single lined code is very easy for me to understand tbh..

wary edge
#

Preferences.

dim tusk
jolly citrus
#

I have begun this new semi bad habit of separating different 'groups' of variables from each other with empty lines

#

actually before I judge whether it is bad or not I need somebody else's opinion

#

i do it a lot

#

and it maybe doubles my line count or so

#

example

valid ice
#

It's fine, honestly

#

Makes it more readable

open urchin
#

the capitalisation is what's confusing me

jolly citrus
weary umbra
#

did you guys know that you can save ItemStack with dynamicproperty?

weary umbra
# jolly citrus Omg!!!!

thats how I made my trading system. I saved the itemstack from the items that have been selected

dim tusk
weary umbra
#

thats why I was impressed

spark topaz
#

Does anyone have a guideline or known working example of using a ticking area for world.getDimension().getBlock(), I have it "working" but it is a little unreliable. Just want to see if anyone has a better implementation

dim tusk
#

But I get what you mean

weary umbra
dim tusk
spark topaz
dim tusk
#

It's been out since 1.20.60

#

Later than that setting dp only works on entities and player

spark topaz
dim tusk
weary umbra
distant tulip
#

how?

dim tusk
#

Stop playing with him mannn

weary umbra
#

let trades = JSON.parse(world.getDynamicProperty("trading"));
let item = inv.getItem(selection);
trades[player.name].items.push(item);
world.setDynamicProperty("trading", JSON.stringify(trades))

dim tusk
weary umbra
warm mason
dim tusk
dim tusk
distant tulip
distant tulip
dim tusk
weary umbra
warm mason
distant tulip
#

coddy turned into a bad trained ai model fr

distant tulip
dim tusk
#

If you use an object yes it can be possible but using dp? No sorry

patent tapir
dim tusk
patent tapir
#

Just out of morbid curiosity

patent tapir
#

Well ok then

#

Nice and simple answer

#

I like that

distant tulip
#

lol, we can't dynamically change the entity components

patent tapir
distant tulip
#

"dynamically"

warm mason
patent tapir
#

So you could probably, theoretically, set each component to a single component group and hook it up to an AI API

fiery solar
#

The only thing you can do is send entity events. Your entity JSON needs to define the component groups already.

patent tapir
#

But that would be REALLY hard to do

warm mason
distant tulip
#

maybe if you turned every component to its own component group

patent tapir
dim tusk
#

-# and Yes I'm annoying asf

jolly citrus
#

with the way he has it set up rn

#

i’m unsure how i never knew you could use itemstack but it does seem to work for him

distant tulip
dim tusk
jolly citrus
#

oh wait nvm i realized he stringifies it

dim tusk
patent tapir
#

:/

#

Also the addon would be MASSIVE at that point

distant tulip
#

try and see, i guess

dim tusk
jolly citrus
patent tapir
#

Or a simple environment detector

patent tapir
chilly fractal
dim tusk
patent tapir
#

Well then, off-topic to what I was just talking about, is there a way to easily return a very large array in string form?

You will definitely think I’m stupid, but hear me out, when you print an array it returns the objects as “item1”,“item2”,“item3”, I would at least like to space the results apart and remove the string quotes (there might not actually be string quotes and I’m misremembering but you get the idea)

gusty bramble
#

Is there a way to fill a container with an item if you specified the coords of that container? I was thinking about running the in game replaceitem command 27 times but that seemed stupid

dim tusk
jolly citrus
patent tapir
distant tulip
#

yeah

patent tapir
#

I’m insane then

#

Thanks

dim tusk
#

just use runtInterval 🤷

distant tulip
dim tusk
#

Ohh, my god my head hurts rn... I'm like ai but 50% worse

dim tusk
#

Also it's normal... Can you give me the snippet of the code? I wanna read it

#

Pls don't do that 😭... You're calling it multiple times when you can put it in the variable

gusty bramble
#

That’s not possible for what I’m doing

distant tulip
# gusty bramble Is there a way to fill a container with an item if you specified the coords of t...
import { system, world} from "@minecraft/server";

function fillContainer (location, itemType, dimension){
    const block = dimension.getBlock(location);
    if (!block) return
    const container = block.getComponent("minecraft:inventory");
    const inventory = container.container;
    for (let i = 0; i < inventory.size; i++) {
        const item = new ItemStack(MinecraftItemTypes[itemType]);
        inventory.setItem(i, item);
    }
};

//for testing

system.afterEvents.scriptEventReceive.subscribe((event)=>{
    if(event.id !== "test:fill") return
    fillContainer ({x:0,y:-60,z:0}, "minecraft:stick", event.sourceEntity.dimension)
})
jolly citrus
#

In late 2022

#

never after that have I attempted to stringify an itemstack

dim tusk
#

You're not that dumb...

distant tulip
#

don't worry about it

dim tusk
#

How can I call you this..... I forgot it nvm then

jolly citrus
#

it’s just bad practice to call for the exact same thing multiple times

#

Doesn’t make a difference, the variable will be a reference to the container

dim tusk
# jolly citrus No as i said i did it many versions ago

Stringifying an ItemStack and attor in object and see the values using console.error will return empty array but if you use it on addItem or spawnItem things that accept ItemStack it spawns the item with 1:1 copy of the item

jolly citrus
#

It wastes performance to get it multiple times

#

yes but you can save the container in a variable

dim tusk
#

He's right, when calling multiple function just store it on variable it helps readability and performance

jolly citrus
#
const container = world.getDimension("overworld").getBlock({ x: 0, y: 0, z: 0 }).getComponent("inventory").container;
for (const slots of container.size) {
    container.addItem(new ItemStack())
}```
#

this is what I meant

#

there’s probably a syntax error i made it inside of dc

#

but u get the idea

distant tulip
#

@patent tapir
you aren't even using slots variable there btw

jolly citrus
#

slots is a number

dim tusk
#
const block = world.getDimension().getBlock();
const inventory = block?.getComponent('inventory')?.container;

for (let i = 0; i < inventory.size; i++) {
   const item = inventory.getItem(i);
}```
distant tulip
#

-# ok

dim tusk
#

DONT BE FUCKIN MADDD AND DONT YELL

jolly citrus
#

What does this mean

dim tusk
jolly citrus
#

That’s my question

#

You’re probably getting the error because ur attempting to re-define the value of slots

dim tusk
jolly citrus
#

right

jolly citrus
#

yes because you can’t loop by a number

dim tusk
#

Because it's wrong?

#

it's a number not an array...

jolly citrus
#

use for (let i = 0; i < x; i++) to loop x amount of times

dim tusk
#

for of gets list of objects inside of array and for loop generate number from value a to value b depends adding or subtracting or whatever

distant tulip
#

welcome to JavaScript basics

jolly citrus
#

we aren’t bullying you we’re just correcting you and attempting to help

dim tusk
#

You assume we bullied you?

#

WELCOME TO THE INTERNET BUDDY

#

And WELCOME TO THE BASICS OF JS
-# as what Minato said

#

Just calm down... Three of us are just helping you as much as we can... No one is bullying you, we're just correcting you.. simple mistakes okay?

distant tulip
#

uhh

#

his messages gone

dim tusk
#

Nvm, he left I think?

#

Oh wow

#

You deleted it or the mods did?

distant tulip
#

we are pointing out your mistakes so you learn from them, otherwise what is the point

dim tusk
#

I don't want to say it....but you're kinda overreacting sometimes

distant tulip
#

alr, have a great day

jolly citrus
#

You can also stop responding if you feel that you got the response that you needed

dim tusk
patent tapir
dim tusk
#

I mean it's not really rude but you're just trying to imply that you're done or everything is set or fixed already

distant tulip
dim tusk
#

I will probably feel asleep while I'm working with my things lol

distant tulip
#

lol

#

i mean you didn't really do anything bad

dim tusk
#

Nah you good...

#

Everything's good, I mean it's not good my cat died but it's good that I'm still alive...

#

Yeah, as long as you didn't do anything controversial that might trigger people or communities? You're fine

distant tulip
#

🤨

steady canopy
#

when i place a custom block that has an item version the onBeforePlayerPlace custom comp event doesnt fire and the beforeEvents.playerPlayerBlock either???

#

is this normal

#

how can be fixed?

wary edge
#

Since its the item placing the block.

steady canopy
#

damn

#

but itemUseOn doesnt work either

#

which is weird

#

i need to modify the permutation to place depending on certain conditions

#

what event should i use in that case?

wary edge
#

After event or before?

steady canopy
#

before

wary edge
#

Try after.

#

If that doesnt work, then you judt cant use item blocks.

steady canopy
#

actually it works but theres still a problem and it's this event does give me the block where this custom block should be placed

#

so

#

it's worse than doing beforeOnPlayerPlace

#

damn

steady canopy
distant tulip
#

code?

wary edge
steady canopy
# distant tulip code?
use.cancel = true
        system.runInterval(() => block.setPermutation(BlockPermutation.resolve('c:beacon', { 'c:level': level })))
steady canopy
#

im very bad with Vector related stuff tbh

#

how do i calculate where to offset this block?

distant tulip
#

what event you are using for the placing

steady canopy
#

itemUseon

#

before

distant tulip
#
let {face,block} = event
switch(face){
    case"Down" : block = block.below(); break;
    case"Up"   : block = block.above(); break;
    case"East" : block = block.west(); break;
    case"North": block = block.south(); break;
    case"South": block = block.north(); break;
    case"West" : block = block.east(); break;
}
steady canopy
distant tulip
#

yeah
don't forget to check for air block

steady canopy
distant tulip
#

you don't want it to replace blocks it is not supposed to replace

#

let say player interacted with this face

#

the block returned is the fence above

steady canopy
#

ohh yeah

#

i think im doing something wrong

distant tulip
#

hmm?

steady canopy
#

wait

steady canopy
#

it works sometimes and sometimes it doesn't

distant tulip
#

huh

#

maybe i sent the wrong order

#

can you try all the block sides?
also log the blockface to console @steady canopy

#
switch(face){
    case"Down" : block = block.below(); break;
    case"Up"   : block = block.above(); break;
    case"East" : block = block.east(); break;
    case"North": block = block.north(); break;
    case"South": block = block.south(); break;
    case"West" : block = block.west(); break;
}

this should work

#

idk why i was using them reversed

steady canopy
dim tusk
#

Wadahell is tyring??

sharp elbow
#

Sounds like a cool Castlevania weapon name

dim tusk
#

shing shing clang clang

#

It's still funny to me that they misspelled a simple word

bright dove
#

how do you get a player armor using scripts

chilly fractal
#

player.getComponent('equippable').getEquipment('Head');

#

player.getComponent('equippable').getEquipment('Chest');

#

player.getComponent('equippable').getEquipment('Legs');

#

player.getComponent('equippable').getEquipment('Feet'); (nothing diddy related)

#

player.getComponent('equippable').getEquipment('Offhand');

#

player.getComponent('equippable').getEquipment('Mainhand');

ruby haven
#

Is there a way to prevent a player from joining a world?

subtle cove
ruby haven
#

I want to add to tag to the player that way I can check if it has the tag then I will prevent it from joining

subtle cove
#

A Bedrock Server file...

wary edge
ruby haven
subtle cove
#

Nope

#

Using server-net mudule is complikated

bright dove
#

like this ?

#

function applyOnNetherite(player, vector) {
  const head = player.getComponent('equippable').getEquipment('Head')?.typeId;
  const chest = player.getComponent('equippable').getEquipment('Chest')?.typeId;
  const legs = player.getComponent('equippable').getEquipment('Legs')?.typeId;
  const feet = player.getComponent('equippable').getEquipment('Feet')?.typeId;

  const isNetheriteHead = head === 'minecraft:netherite_helmet';
  const isNetheriteChest = chest === 'minecraft:netherite_chestplate';
  const isNetheriteLegs = legs === 'minecraft:netherite_leggings';
  const isNetheriteFeet = feet === 'minecraft:netherite_boots';

  const allNetherite = isNetheriteHead && isNetheriteChest && isNetheriteLegs && isNetheriteFeet;```
wary edge
#

Yeah.

bright dove
bright dove
subtle cove
#

cough cough

#
function hasNetheriteArmor(player) {
    const eq = player.getComponent("equippable");
    return !["Head", "Chest", "Legs", "Feet"].find(slot => !eq.getEquipment(slot)?.typeId.includes("netherite")) 
} ```
bright dove
#

Thanks

dim tusk
#

anyways, quick question is there's a way to get the id of the owner of the projectile?

bright dove
#
function applyOnNetherite(player, vector) {
  const head = player.getComponent('equippable').getEquipment('Head')?.typeId;
  const chest = player.getComponent('equippable').getEquipment('Chest')?.typeId;
  const legs = player.getComponent('equippable').getEquipment('Legs')?.typeId;
  const feet = player.getComponent('equippable').getEquipment('Feet')?.typeId;

  const isNetheriteHead = head === 'minecraft:netherite_helmet';
  const isNetheriteChest = chest === 'minecraft:netherite_chestplate';
  const isNetheriteLegs = legs === 'minecraft:netherite_leggings';
  const isNetheriteFeet = feet === 'minecraft:netherite_boots';

  const allNetherite = isNetheriteHead && isNetheriteChest && isNetheriteLegs && isNetheriteFeet;

  // Calculate knockback power
  let knockbackPower = 1; 
  if (allNetherite) {
      knockbackPower *= 1.4; 
  } else {
      knockbackPower *= 1.1; 
  }

  // Apply knockback with adjusted power
  const adjustedVector = {
      x: vector.x * knockbackPower,
      y: vector.y * knockbackPower,
      z: vector.z * knockbackPower
  };

  applyImpulseAsKnockback(player, adjustedVector);
}

export class Velocity```
subtle cove
#

thats, long blush1

bright dove
#

Yeah, for a reason

#

notice the "export class Velocity"

#

I am doing something something

subtle cove
#

entity.getComponent("projectile")?.owner?.id

#

Need more docs review huh

bright dove
dim tusk
#

fuckin hell

#

im stupid

#

it works i just turned off my console log

#

OHHH MY GODDDD

bright dove
#

the gist is

#

there is no applyImpulse for player

dim tusk
bright dove
#

and netherite

subtle cove
# bright dove ```js function applyOnNetherite(player, vector) { const head = player.getCompo...
function hasNetheriteArmor(player) {
    const eq = player.getComponent("equippable");
    return !["Head", "Chest", "Legs", "Feet"].find(slot => !eq.getEquipment(slot)?.typeId.includes("netherite")) 
}

function applyOnNetherite(player, vector) {
    const kbPow = hasNetheriteArmor(player) ? 1.4 : 1.1;
    setVelocity(player, vector, kbPow) 
}

function setVelocity(entity, vector, str = { x: 1, y: 1, z: 1 }) {
  const x = vector.x *= str.x ?? str;
  const y = vector.y *= str.y ?? str;
  const z = vector.z *= str.z ?? str;
  const horizontal = Math.sqrt(x * x + z * z) * 2.0;
  const vertical = y < 0.0 ? 0.5 * y : y;
  entity.applyKnockback(x, z, horizontal, vertical);
}

dim tusk
subtle cove
#

@bright dove there

#

-# coughs on fone code

abstract cave
#

How do i add an enchantment to an item using scripts

bright dove
#


 export function applyImpulseAsKnockback(entity, vector) {
  const { x, y, z } = vector;
  const horizontalStrength = Math.sqrt(x * x + z * z);
  const verticalStrength = y; // Vertical strength directly corresponds to the y-component

  // Normalize horizontal direction if there is any horizontal movement
  const directionX = horizontalStrength !== 0 ? x / horizontalStrength : 0;
  const directionZ = horizontalStrength !== 0 ? z / horizontalStrength : 0;

  entity.applyKnockback(
      directionX,
      directionZ,
      horizontalStrength,
      verticalStrength
  );
}```
bright dove
jolly citrus
#

why do the enchantments not get sorted by color?

    /**
     * @param {ItemStack} itemStack 
     */
    static updateLore(itemStack) {
        const properties = {
            enchantmentSlots: itemStack.getDynamicProperty("enchantmentSlots"),
            usedEnchantmentSlots: itemStack.getDynamicProperty("usedEnchantmentSlots"),
            enchantments: JSON.parse(itemStack.getDynamicProperty("enchantments")),
            whitescrolled: itemStack.getDynamicProperty("whitescrolled"),
            nameTag: itemStack.getDynamicProperty("nameTag")
        }
        if (!Object.values(properties).includes(undefined)) {
            itemStack.nameTag = properties.nameTag
            if (properties.enchantments.length > 0) {
                properties.enchantments.sort((a, b) => {
                    const rarityA = Rarities[EnchantmentUtils.getRarity(a.name)].color;
                    const rarityB = Rarities[EnchantmentUtils.getRarity(b.name)].color;
                
                    return RarityOrder.indexOf(rarityA) - RarityOrder.indexOf(rarityB);
                });

                let nameString = `${properties.nameTag}`
                if (properties.usedEnchantmentSlots >= 5) {
                    nameString += ` §l§d[§r§b${properties.usedEnchantmentSlots}§l§d]§r`
                }
                const enchantmentString = properties.enchantments.map(enchantment => `\n${Rarities[EnchantmentUtils.getRarity(enchantment.name)].Color}${enchantment.name} ${convertToRoman(enchantment.level)}`).join("")
                const finalNameTag = nameString + enchantmentString

                itemStack.nameTag = finalNameTag
            }
            const availableSlots = properties.enchantmentSlots - properties.usedEnchantmentSlots
            let lore = [
                ` `,
                `§r§6${properties.enchantmentSlots - properties.usedEnchantmentSlots} slot${("s".repeat(Math.abs(availableSlots - 1))).charAt(0)}`
            ];
            if (properties.whitescrolled) lore.push(`§r§f§lPROTECTED`)

            itemStack.setLore(lore)

            return itemStack;
        }
    }
const RarityOrder = ["§5","§4","§d","§e","§b","§7"]

export const Rarities = {
    "Basic": {
        Tier: 1,
        Color: "§7"
    },
    "Uncommon": {
        Tier: 2,
        Color: "§a"
    },
    "Elite": {
        Tier: 3,
        Color: "§b"
    },
    "Legendary": {
        Tier: 4,
        Color: "§d"
    },
    "Spiritual": {
        Tier: 5,
        Color: "§4"
    },
    "Ancient": {
        Tier: 6,
        Color: "§5"
    }
}
#

fixed it it was all because of a capitalization error

#

wow

tiny tartan
#

it is ok to reveal/show entity id in public? like there is an item when used it will teleport entity to player, so to remember which entity it is i am using entity id in lore

valid ice
#

Totally fine, players cannot get any valuable information from it.

You could hide it on lore using something like:
'§' + id.split('').join('§') and then parse it by removing all section symbols later on

tiny tartan
#

Thnx

dim tusk
#

Does item frames and painting triggers the playerPlaceBlock?

alpine nebula
#

I'm making some custom explosions. I need to summon an entity that later explodes with some power calculated in script. What is the easiest way to do it?

dim tusk
#

Tbh, why would I ask here even if I could just do it? 🤷

chilly fractal
#

I mean I don't think they don't trigger as they are treated as entities

dim tusk
#

But anyways I don't need it anymore.

chilly fractal
#

But the item frame is treated as a block in bedrock I believe

dim tusk
#

Idk but I feel like I'm late to this but getting the ItemStack of before and after in itemUse don't make sense to me

#

I was trying to check if the item decreased it's amount

chilly fractal
#

Bruh lol

dim tusk
#

But when I do a log their amount is the fuckin same

chilly fractal
#

It ain't happened yet

chilly fractal
#

Entity events

#

Do some molang magic with whatever property the entity has and set that property in script api & trigger event

dim tusk
# chilly fractal Yeah cuz it's still beforeEvent

That shouldn't be... Yes it didn't happen but after it already happens, and the item is used... I'm using ender pearl for example so the amount of before should be higher than the after but it's not ..

#

I had no choice but to use equippable components and get the amount there :(

chilly fractal
chilly fractal
dim tusk
# slow walrus send the code
world.beforeEvents.itemUse.subscribe(({ source, itemStack }) => {
   console.error('Before:', itemStack.amount);
});

world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
   console.error('After:', itemStack.amount);
});```
#

That's it

chilly fractal
slow walrus
#

oh wait

#

actually

#

maybe not

slow walrus
#

since its and enderpearl

#

though

#

hmm

#

that still doesn't make sense

dim tusk
dim tusk
dim tusk
distant tulip
#

the item decreasing is probably delayed
use timeout to test how much it is delayed

dim tusk
dim tusk
distant tulip
#

well, the callback is getting the ItemStack before the decrease or something

subtle cove
#

aint no ContainerSlot, so thats why

#

thats just what ItemStack is

dim tusk
subtle cove
#

-# next update there's gon be usedItem

distant tulip
#

hopefully

dim tusk
#

I'll be using an equippable component in the meantime

#

sigh

sage hamlet
#

Does the crafter not have an inventory component?

if so what does it have since I cannot find anything about that I want to fill a crafter using script

warm mason
sage hamlet
distant tulip
warm mason
distant tulip
#

let me test it with the api

#

inventory component don't work but replaceitem command dose @warm mason @sage hamlet

#

keep in mind it dose work even if the slot is disabled

warm mason
distant tulip
#

crafter is a block

meager cargo
#

Hello, is it possible to make "moving" structure by scripts? Which will run on x line to left or right and also remove blocks behind?

warm mason
wheat condor
warm mason
meager cargo
wheat condor
warm mason
wheat condor
#

like if you press D to move left it moves on your left not in a costant axis of the world

warm mason
#

I think I'll do it when I have nothing else to do

steady canopy
#

is there any way to get entities that are out of simulation distance?

#

for example i wanna check how many entities are in a chunk starting from y -59 to 320

#

but when i get like 40-50 blocks far it stops getting these entities

#

or maybe that isnt it. it could be because the entities are despawning after im far enough

#

does this have any way to fix?

wheat condor
# steady canopy does this have any way to fix?

When it’s out of ticking distance the entity isn’t even loaded, you can’t detect it,

You can do a ticking area (not recommended)

Or just when you re about to stop ticking the chunk you count the entities and save it as the chunk index

jolly citrus
#

I'm trying to make a custom event system, but the cancelling part doesn't work properly:

import { world, Player } from '@minecraft/server';
import { Frozen } from './addons';

export class CustomHitEvent {
    /**
     * 
     * @param {Player} hitPlayer 
     * @param {Player} damagingPlayer 
     * @param {Number} damage 
     * @param {ItemStack} itemStack
     */
    constructor(hitPlayer, damagingPlayer, damage, itemStack) {
        this.hitPlayer = hitPlayer;
        this.damagingPlayer = damagingPlayer;
        this.damage = damage;
        this.itemStack = itemStack;
    }
}
export class CustomHitEventSignal {
    constructor() {
        this.listeners = [];
    }

    /**
     * 
     * @param {Function} listener - The callback function to subscribe to the event
     */
    subscribe(listener) {
        this.listeners.push(listener);
    }

    /**
     * Emit the event to all subscribers
     * @param {CustomHitEvent} event - The event to emit
     * @returns {boolean} - Returns true if the event was not canceled
     */
    emit(event) {
        for (const listener of this.listeners) {
            listener(event);
            Frozen.Info("event.cancel:", event.cancel)
            if (event.cancel === true) {
                return true;
            }
        }
        return false;
    }
}

export class CustomEvents {
    static CustomHitEvent = new CustomHitEventSignal();

    /**
     * Emit the custom hit event
     * @param {CustomHitEventSignal} signal - The signal to emit the event
     * @param {CustomHitEvent} event - The event to emit
     */
    static emit(signal, event) {
        return signal.emit(event);
    }
}

I can cancel the event like shown below, but not inside of a callback like I want to. how can i achieve that?

CustomEvents.CustomHitEvent.subscribe((event) => {

    event.cancel = true; // This works
    
    Object.entries(Enchantments).forEach(([key, value]) => {
        if (value.onEvent?.name === event.constructor.name) {
            if (!(event.itemStack && ItemUtils.getItemType(event.itemStack).length > 0)) return;

            const Enchant = EnchantmentUtils.getEnchantments(event.itemStack).find(enchantment => enchantment.name === key);
            if (Enchant) {
                value.Callback(event, Enchant);
            }
        }
    })
});
        /**
        * @param {CustomHitEvent} event
        * @param {Enchantment} enchantmentInfo
        */
        Callback: (event, enchantmentInfo) => {
            const { damagingPlayer, hitPlayer, damage, itemStack } = event;

            event.cancel = true; // Does not work

            if (itemStack) {
                const P = (0.06 / 3)*enchantmentInfo.level
                const duration = 60
                if (Math.random() < P) {
                    hitPlayer.addEffect("minecraft:slowness",duration,{ amplifier: 0, showParticles: true})
                }
            }
        }
wary edge
naive tinsel
#

what is the difference between world.getAllPlayers and world.getPlayers?

open urchin
#

getPlayers supports an entity filter as an argument

warm mason
naive tinsel
#

ok thx

meager cargo
#

Can someone help me with moving structure? In post are all details

distant tulip
wary edge
#

I'm so confused...does playerInteractWithEntity not trigger with an empty hand?

rugged tinsel
#

might be something weird with before/after

wary edge
#

Will try that.

rugged tinsel
#

it might be a case of the after event only firing if there's a valid interaction, like breeding or something

wary edge
#

An FYI, it will work with empty hand if the entity has:

                "minecraft:interact": {
                    "interactions": [
                        {
                            "on_interact": {}
                        }
                    ]
                },
rugged tinsel
#

so then yeah, it needs a valid interaction

wary edge
#

Testing beforeEvent now 👍

#

Can confirm Majestik, beforeEvent will fire regardless.

rugged tinsel
#

nice

#

when in doubt, beforeEvent

gaunt salmonBOT
distant gulch
#

Guys, wich npm module do i need to download (or vscode extension) so it will show me the diff. things i can add to the manifest

granite badger
#

wdym by different things?

distant gulch
patent tapir
#

Why isn’t this working? It’s expecting a number but I don’t know how to turn command[2] into a number if it can be one.

#

if (command[0] === "pay") {
    const sendTo = world.getAllPlayers().find(nm => nm.name.toString().toLowerCase() === command[1].toString().toLowerCase())
    if (sendTo) {
        if (command[2](typeof Number)) {
            system.run(() => {
                world.scoreboard.getObjective("coins").addScore(sender.scoreboardIdentity, command[2])                                        
world.scoreboard.getObjective("coins").addScore(sendTo.scoreboardIdentity, command[2])
                                        sender.sendMessage(`§iSent ${command[2]} coins to ${sendTo.name}.`)
            })
        } else {
            system.run(() => {
                                        sender.sendMessage(`§cInvalid integer.`)
            })
        }
    } else {
        system.run(() => {
                                sender.sendMessage(`§cNo player found by the name of '${command[1]}'.`)
        })
    }
}```
#
const command = data.message.trim().substring(1).toLowerCase().split(" ")```
#

Idk why my code spaghettified itself when i sent it but ok

distant tulip
patent tapir
#

Thanks but if it’s always a string how do I do the scoreboard thing??

distant tulip
#

Number('1')

patent tapir
#

I also forgot I left the typeOf Number thing in there

patent tapir
#

OH

#

So I just do Number(command[2])

distant tulip
distant tulip
patent tapir
#

so js if (Number(command[2]) > 0) {}

#

But if it’s not a number it’ll throw an error

#

Oh

#

Wait

jolly citrus
#

before comparing it with 0

distant tulip
#

also command[2] is never a number, it is always a string
use isNaN to check

patent tapir
#

I can just do ?.valueOf() > 0

#

Right?

#
if (Number(command[2])?.valueOf() > 0) {}```
distant tulip
#

**isNaN **

patent tapir
#

Fine

#

I’ll do it

jolly citrus
#

As long as you check if it’s not a number 1st

patent tapir
jolly citrus
#

If the 1st condition doesn’t pass it shouldn’t attempt the 2nd I think …

patent tapir
#
if(Number(command[0]).isNaN()) {
    if(Number(command[0]) > 0) {}
}```
#

Riiight?

#

I guess that gives me more opportunity to tell players what they did wrong with the command

jolly citrus
jolly citrus
patent tapir
jolly citrus
distant tulip
patent tapir
#

I’ve done it before with scoreboards

#

It doesn’t work

jolly citrus
jolly citrus
distant tulip
patent tapir
#

Fine

jolly citrus
#

i thought if any condition fails then the rest will not be checked for

patent tapir
# distant tulip how did you write it

Oh come on, idk! I deleted the code already because it doesn’t work! Do you expect me to just stash away any bad code I’ve written?? (I can’t remember things well at all.)

jolly citrus
#

mahbe I misunderstood what you meant

distant tulip
jolly citrus
patent tapir
jolly citrus
#

if (true && false && Entity.prototype.applyDamage(10)) for example, applyDamage will never run right

thorn flicker
patent tapir
# thorn flicker rewrite it real quick?
if (world.scoreboard.getObjective(“strength”).getScore(player.scoreboardIdentity) != undefined && world.scoreboard.getObjective(“strength”).getScore(player.scoreboardIdentity) > 0) {}
#

Certainly didn’t work the first time.

#

So I deleted it and never used it again.

thorn flicker
patent tapir
#

Or something along those lines.

thorn flicker
jolly citrus
#

i think

patent tapir
jolly citrus
#

i don’t work with scoreboard

patent tapir
#

The score exists.

#

The player just doesn’t have a score for it.

#

Whoops, I meant to write .getObjective not .getScore

distant tulip
#

@jolly citrus

patent tapir
#

Fixed

jolly citrus
#

nice to know this

#

i always assumed it worked this way but wasn’t sure

thorn flicker
patent tapir
#

Well it certainly doesn’t work that way for scoreboards, so i just assumed it didnt work that way for every other thing you can logic

#

Because WHY would logic work differently for different terms.

distant tulip
jolly citrus
#

is it possible to remove an effect specifically with infinite duration from a player? I want to create some custom enchantments that grant the player permanent effects, but do not want these to override their possible past potion effects

#

e.g. player first drinks speed 1 for 3 min, then equips boots with speed 2 enchantment and removes them, usign removeEffect("speed") they’d no longer have their 3 minutes of speed 1 yes?

distant tulip
#

store past effects and re-add them later

autumn seal
#

You could probably store their current effects before giving them the infinite one then apply it again after the infinite one is removed

jolly citrus
distant tulip
#

nah

jolly citrus
#

I thoughr about that as I was writing the question but i was skeptical about how reliable it could be

#

But players can have multiple effects with different amplifiers at once yes?

autumn seal
#

Multiple of the same one?

jolly citrus
#

if you have speed 2 and get a burst of speed 3 your speed 2 will come back after speed 3 ends I’m pretty sure

thorn flicker
#

the amplifiers override eachother, no?

distant tulip
#

just store all infos amplifiers and duration

autumn seal
#

I was under the impression you could not have the same effect with different amplifiers

jolly citrus
#

I thought of the opposite but am now doubting my memory

distant tulip
#

wait dose it override or is there some kinda of priority

jolly citrus
autumn seal
#

If it does override you have to decide if you want to implement logic to tick down the stored effect while the infinite one is applied or if you want it to keep the same duration the player had prior to getting the infinite duration version

thorn flicker
#

maybe the minecraft wiki answers this question.

jolly citrus
#

i think the duration of all the effects also progress as you have a higher amplifier

#

if i have speed for 5 min then speed 3 for 1 min i would end up with speed for 4 min after speed 3 ends

#

i think

distant tulip
jolly citrus
#

oh

#

wait

#

but will the lower effects come back after one with a higher amplifier ends or not thouguh

autumn seal
#

It appears not

jolly citrus
#

oh ..

sharp elbow
#

/effect @p speed 30 1 true
/effect @p speed 20 2 true
Player receives speed III for 20 seconds, after 20 seconds they have no speed

patent tapir
#

Why???

thorn flicker
#

wall of script

#

nice

#

jumpscare

jolly citrus
#

what is line 166

patent tapir
#

Oh wait I’m dumb

jolly citrus
#

vommand[2] isn’t a number

#

when ur setting the score

patent tapir
#

Yeah ignore that sorry

#

I forgot about the actual adding of the score

jolly citrus
#

all good

distant tulip
#

you do delete your messages a lot tho
that make the conversations pointless for future readers

dense skiff
#

Is there a script method to check how many tickingareas are active in a world?

#

Don't want to use loader entities cause I only want one chunk loaded

thorn flicker
#

there isn't even a method to create a ticking area yet with the api.