#Script API General

1 messages Β· Page 9 of 1

wary edge
#

Well, when you spread misinformation and unhelpful stuff then yes, It concerns me

turbid oriole
#

Use an event that evaluates a state prior to the mount interaction and to compensate use a system.run to evaluate a verification of the player entity above of the mountable entity on the next tick. He does it in a messy way with the line I mentioned.

#

What he does not know is that he can use an event that evaluates the state afterwards and that when executing system.run from an event it is not executed in a tick later but in the same tick.

#

I read it directly in the official documentation. I think it was in the gameplay loop section.

#

:b speak.

#

Is my information useful? Admin.

dusky cipher
#

b/c ngl they’re kinda annoying to navigate

remote oyster
turbid oriole
wary edge
unique dragon
inland merlin
#

wow, just explored a few things.

man o man... never going back to js, just coding with typescript is too nice to have

inland merlin
#

ty btw, never knew how handy it was

fiery solar
wary edge
#

What the hell dude?

slim spear
#

|| as number ||

inland merlin
remote oyster
inland merlin
#

th

#

thx

#

yeah. parameter types for sure game changer,

using tsc --watch

#

getting tired of /reload

wary edge
inland merlin
#

yes, just less type errors

inland merlin
#

sorry for confusion lol

fiery solar
# inland merlin getting tired of /reload

I have a setup that automatically compiles typescript, bundles the code using esbuild and runs /reload every time you save.

I can post it in the next few days if people would use it. I just want to clean it up a bit and add documentation.

inland merlin
solar dagger
#

Thank you, this fixed my problem πŸ™‚

#

@wary edge i got it, thanks for helping out πŸ™‚

wary edge
#

Nice

runic crypt
#

can anyone tell me how to detect if player left clicks/right clicks a specific item ?
like i can name the item/add a tag to myself, then i clcik the item and a command is run ?

neat hound
#

JS Question Class Constructor
should it be only for the parameters => properties or should it also initialize anything that any of the parameters is related to or do the other properties outside of the constructor get initialized at the same time or if they are listed before the constructor?

chrome flint
solar dagger
runic crypt
#

{
"format_version": 2,
"header": {
"name": "Right Click Detection + Custom Click Sounds",
"description": "By TheGwimWeeper",
"uuid": "a936efa2-b925-9169-48f8-807ea620a0a1",
"version": [1, 1, 1],
"min_engine_version": [1, 17, 0]
},
"modules": [
{
"type": "data",
"uuid": "d90c1e39-57a1-9488-85e7-ac0a25c50e37",
"version": "1.0.0-beta"
},
{
"type": "script",
"language": "javascript",
"uuid": "0e365d5e-2fd5-d020-9d06-0de152d6a95b",
"version": "1.0.0-beta",
"entry": "scripts/index.js"
}
],
"metadata": {
"authors": ["TheGwimWeeper"]
},
"dependencies": [
{
"module_name": "@minecraft/server",
"version": "1.1.0-beta"
}
]
}

#

can someone add the subpacks line to this please ?

runic crypt
runic crypt
solar dagger
#

Server version is wrong

#

Should be 1.12.0

runic crypt
#

can you fix it and add the subpacks line if possible ?

chrome flint
#
"subpacks": [
        {
            "folder_name": "subpack_1",
            "name": "First Subpack",
            "memory_tier": 0
        },
        {
            "folder_name": "subpack_2",
            "name": "Second Subpack",
            "memory_tier": 1
        }
    ]
runic crypt
chrome flint
runic crypt
#

i tried it but it didnt work

chrome flint
# runic crypt i tried it but it didnt work

example manifest with subpack:

{
    "format_version": 2,
    "header": {
        "name": "Pack Name",
        "description": "Pack Description",
        "uuid": "2fc2dd6f-86cb-4370-af70-21490a1ae471",
        "version": [1, 0, 0],
        "min_engine_version": [1, 13, 0]
    },
    "modules": [
        {
            "type": "resources",
            "uuid": "f6821b4a-1854-44fc-a8a4-0c2847ffda46",
            "version": [1, 0, 0]
        }
    ],
    "subpacks": [
        {
            "folder_name": "subpack_1",
            "name": "First Subpack",
            "memory_tier": 0
        },
        {
            "folder_name": "subpack_2",
            "name": "Second Subpack",
            "memory_tier": 1
        }
    ]
}

runic crypt
chrome flint
neat hound
# valid ice https://tenor.com/view/confused-gif-1732757131465405760

Did I confuse you? LOL... I have this constructorJS constructor(location, qty = 0) { this.startLocation = location; this.blockTypes = Object.keys(MinecraftBlockTypes) .map((k, i) => { return { index: i, key: k, typeId: MinecraftBlockTypes[ k ], name: MinecraftBlockTypes[ k ].split(':')[ 1 ], isAir: false, isLiquid: false, isSolid: true, hasTag: false, tags: [], xyz: { x: 0, y: 0, z: 0 }, y_offset: MinecraftBlockTypes[ k ].includes('cactus') ? 1 : 0, defaultState: {} /* button: facing_direction */ }; }); this.maxBlocks = qty === 0 ? this.blockTypes.length : qty; } //end constructor and I do not think blockTypes belongs in there... but max Blocks needs it to be complete.

chrome flint
#

experiencing is the best way of learning

runic crypt
valid ice
neat hound
#

or it be static

#

?

#

in the class

#

the base part

valid ice
#

It definitely can- there's a reason people say to define function calls outside of other function calls..

  1. bad practice
  2. looks terrible
  3. performance
#

Same deal for constants as you have there

#

Some cannot be avoided

neat hound
valid ice
#

Like, defining functions within functions

neat hound
#

wait, then what does in a class

valid ice
#

Say, a getScore() within a blockBreak call

#

same-ish deal to what you have-but the blockBreak is your function method, and your getScore is the constant

#

Something like that would definitely be better in a outside constant.

neat hound
#

I thought the whole point of the class was to bundle it all together... maybe just same file is good enough

valid ice
#

I have global constant calls in my class definitions shrug

grave thistle
#

How would I check if a block was broken with a pickaxe with a certain enchantment (stable)?

neat hound
#

outside file?

#

so not portable

neat hound
runic crypt
runic crypt
# grave thistle How would I check if a block was broken with a pickaxe with a certain enchantmen...

This addon detects when a player breaks a block and then adds +1 score to their mined scoreboard.
This addon can be used to make level up minigames where players have to mine certain amount of blocks to level up.
Made By TheGwimWeeper.
#minecraft #minecrafttutorial

β–Ά Play video
valid ice
#

It's just imports from a global constants file I have, nothing special

shy leaf
#

what is the best way to keep player's modified movement component during a specified time without it being reset to sprinting

#

runInterval sounds horrifying so im trying to stay away from it

#

unless its the only way

#

nvm ig it is the only way

grave thistle
granite badger
#

getComponent is stable. Stable typings don’t have a map on what class it returns based on specific parameters so it returns nothing. You have to use TS or jsdoc to set return type

grave thistle
#

How would I do that using js.

granite badger
#
/**
 * @type {_______}
 */
const component = item.getComponent()
grave thistle
#

Lol I'm lost. I've had a long break from scripting and addon making.

prisma shard
#

how can i describe a code using comments?

#

i dont know how to use those @param etc

#

those make the code pretty,

#

so i wanted to use them, to describe my code

#

but i dont know, how to

neat hound
#

Part of is is also the settings I changed in vscode and it annotates in TS for me.

grave thistle
#

Think I need to take a refresher, still confused lol. Why did they have to make it confusing.

neat hound
#

It is not that.. it is that there are a lot of tools.. search for what you need, you will find it.

runic crypt
#

guys how do i make it so that a command is executed when player right click a diamond named test ?

neat hound
runic crypt
#

can you tell me how ?
im a bit new to the item part

#

@neat hound

neat hound
runic crypt
neat hound
runic crypt
#

imma try it out

neat hound
#

some pages have sample code, you have to open them up

runic crypt
#

itemUse: ItemUseBeforeEventSignal

#

i gotta use this ?

#

wait ill send a zip file

#

this is what im working on

#

@neat hound
how do i implement the item use into it ?

#

import { world } from "@minecraft/server";
world.afterEvents.playerBreakBlock.subscribe((data) => {
let { player, block, brokenBlockPermutation } = data;

player.runCommand("/scoreboard players add @s mined 1")

})

#

can i modify this code somehow ?

#

like add itemUse: ItemUseBeforeEventSignal into it ?

#

can you tell how ?

neat hound
#

Well I am confused... you want to know if they broke a block with a diamond named test... but you asked about a right click... those are 2 different things

#

left click hits and breaks.... right click interacts

runic crypt
#

it detects when i block is broken

#

how do i modify it so that it detects player right-clicking a diamond

neat hound
#

no, you sent beforeItemUse and UseOn

#

the stuff I just told you to look up

#

This is what you sent.... nothing about blocks

#

use your code to display the nametag of the item to the screen so you know if you can get it.... for breaking block, it can also give you the itemused to break the block, so in that code you can test for the same thing....

and bedtime for me.... good luck

valid ice
#

real

neat hound
#

Now I sleep, nite folks

grave thistle
#

I'm using bridge. Still can't get the detect silk touch script working...

amber granite
#

Need help

valid ice
#

Don’t we all

amber granite
#

It s not philosophy time πŸ’€

#

Ok when i m trying to
world.scoreboard.getObjective

#

He told me u can't read getObjective of undefined

#

Even after i wrote :
world?.scoreboard?.getObjective?.(objective)

random flint
#

or any similar variable with the name world

#

Or actually, confirm where the error comes from

amber granite
#

Thefe is no

cold grove
#

Maybe you cursor typed getObjective on another place

#

I think this is not possible an asignation like this

import * as mc from...... 
const world = mc.world
world.scoreboard = .....
#

But maybe(????

remote oyster
# amber granite Even after i wrote : world?.scoreboard?.getObjective?.(objective)
/**
 * Returns the score of a player in the specified scoreboard objective.
 * @param {string} objective - Scoreboard objective.
 * @param {Player} player - The player object.
 * @returns {number} The player's score or 0 if not found.
 */
function getScore(objective: string, player: Player): number {
    try {
        return world.scoreboard.getObjective(objective).getScore(player.scoreboardIdentity);
    } catch (error) {
        return 0;
    }
}

/**
 * Sets a player's score.
 * @param {Player} target - The player object.
 * @param {string} objective - Scoreboard objective.
 * @param {number} amount - The number to set it to.
 * @param {boolean} stack - If true, it will be added instead of set. Default false.
 * @returns {number} The score it was set to.
 */
function setScore(target: Player, objective: string, amount: number, stack: boolean = false): number {
    const scoreObj = world.scoreboard.getObjective(objective);
    if (scoreObj) {
        const isParticipant = !!scoreObj.getParticipants().some((participant) => participant.id === target.scoreboardIdentity.id);
        if (!isParticipant) {
            target.runCommand(`scoreboard players add @s ${objective} 0`);
        }
        const score = isParticipant ? scoreObj.getScore(target.scoreboardIdentity) : 0;
        const result = stack ? score + amount : amount;
        scoreObj.setScore(target.scoreboardIdentity, result);
        return result;
    } else {
        return 0;
    }
}
fast lark
#

const score = getScore(player, "money");

#

why getscore is not defined

naive tinsel
#

ok so im doing skyblock island loading and saving

#

and when im loading the island it lags the game quite a bit

#

currently i have a 128x128 island.

#

and im using 4 structure blocks, (each at 64x64) to load the island

#

in the image there are 16 32x32 structure blocks

#

if i change the loading to use the 32x32 structures, would this create less lag?

#

and introduce priotity loading by loadint the 4 chunks in the centre and then the outside ones.

#

or split it up even more into 32 structure blocks at 16x16 each

#

idk, i just need a way to load efficiently without killing the server.

remote oyster
# fast lark why getscore is not defined

If the function is not local in the same script where you are calling the function then it means you have it in another script, or you don't have the function at all. If it's in another script you need to export it, then import it to the script where you call the function.

shy leaf
#

is it possible to make the player to do swing animation when using a custom item

#

not on specific blocks but use in general

amber granite
#

How can i show scoreboard with number beside it ?

sudden nest
#

Why was the all in EnchantmentSlot removed? And there's still no Mace EnchantmentSlot Enums yet in the latest apibao_doggo_sad

prisma shard
#

scripting not the best option to play animation

#

u can do it with json

shy leaf
fiery solar
remote oyster
sudden nest
#

okay, not really big of a deal for the devs ithink, but yeah. i'll try to report it later. thanks

crude ferry
#
import { world } from '@minecraft/server';
import { ActionFormData } from '@minecraft/server-ui';

console.warn("Hello.")

const custom_form = new ActionFormData()
custom_form.title("Map Viewer");
custom_form.body(" ");
custom_form.button("Base")

const meow_form = new ActionFormData()
custom_form.title("Meow Viewer");
custom_form.body(" ");
custom_form.button("Cat")

const ae = world.afterEvents;

ae.itemStartUseOn.subscribe((e) => {
    const item = e.itemStack;
    const src = e.source;
    console.warn(item);
    if(item.typeId == "stick") {
        custom_form.show(src);
    } else if(item.typeId == "clock") {
        meow_form.show(src)
    }
})```Why it doesn't show the forms? πŸ‘€
#

Ignore the console.warn, I made them just to test if the script is even running.

fast lark
shy leaf
#

try itemUse?

crude ferry
#

Oh, lemme try.

grand heart
crude ferry
#

I'm sorry.

crude ferry
shy leaf
#

then the form is most likely wrong

crude ferry
#

Whot-

#

How can the form be wrong lol?

shy leaf
#

shrug!

grand heart
#

try adding .then(f => if (f.canceled) console.warn("here 1"))

shy leaf
#

let me give you an example but its a modal form

#
function dcConfig(player) {
    let form = new ModalFormData()
    .title("Dungeons Combat Settings")
    .toggle("Toggle Mod\n(You can use compass to open this menu.)", player.getDynamicProperty("dc_state"))
    .slider("Camera Distance", 15, 30, 1, player.getDynamicProperty("dc_camdist"))
    .slider("Camera Position", 1, 4, 1, player.getDynamicProperty("dc_campos"))
    .slider("Camera Lerp", 10, 50, 5, player.getDynamicProperty("dc_camlerp"));  
    form.show(player).then((response) => {
        const { canceled, formValues, cancelationReason } = response;
        if (response && canceled && cancelationReason === "UserBusy") {
            dcConfig(player);
            return;
        }
        if (canceled) return;
        player.setDynamicProperty("dc_state",formValues[0])
        player.setDynamicProperty("dc_camdist",formValues[1])
        player.setDynamicProperty("dc_campos",formValues[2])
        player.setDynamicProperty("dc_camlerp",formValues[3])
        if (player.getDynamicProperty("dc_state") == true) {
            setcamera(player)
        } else {
            clearcamera(player)
        }
    })
    }```

this is how i did
crude ferry
grand heart
dusky cipher
crude ferry
#

Now time to beg for json ui help lol 😭

#

I'mma figure out something.

amber granite
#

U know json ui is the final boss

crude ferry
#

Fr fr.

abstract cave
#

would there be any reasom for someone to have more than one js file in theire manifest stuff

amber granite
#

? More than one ?

abstract cave
#

just asking

abstract cave
# shy leaf no

then must your script file be named index.js or main.js

#

or can you change the name

shy leaf
#

also no

#

i mean

#

you can change the name

amber granite
#

U can change it to whatever u want

#

Even emoji

shy leaf
#

why emoji

#

πŸ’€

amber granite
#

Idk

prisma shard
#

hi

#

haha

remote oyster
#

Also, if you scroll above where you first mentioned the function there is some code regarding that function name which you could use to accomplish your goal.

#

It's written with TS in mind so you would need to clean it up slightly

glacial widget
#

is it worth learning json ui or paying someone to do it for me?

amber granite
#

It is worth it to learn js

shy leaf
#

id say

#

90% yes

#

half of 90% is "learning something is great"

#

the other half is "i can make something ive dreamed of in minecraft"

crude ferry
shy leaf
#

json ui sounds really worth learning considering there are only few who knows it

#

but

#

idk if it pays well

#

i couldnt even start learning json ui because of how tedius it is

distant tulip
shy leaf
#

yeah but like the learning progress counteracts it to me tbh

#

im just waiting for ore ui to be a thing

distant tulip
#

same πŸ€·β€β™‚οΈ

valid ice
#

JSON UI is rewarding if you are good at it and know what you're doing

#

It sucks cuz you have to relog into the test world, and the miniscule changes to offsets & whatnot are annoying as hell

shy leaf
#

yeah thats the major thing

#

its like

#

making visual blindfolded

#

and then everytime you finish making, you take the blindfold off

valid ice
#

I would kill for a live JSON UI web editor tbh

shy leaf
#

omg that would be a game changer

#

in a literal sense too

amber granite
#

We need to wait until someone made it

amber granite
#

If u want to be phycopath then learn

#
  • they gonna change it
#

With ore ui

#

So

pallid portal
#

[mini rant]

Just "love" it when you look up a component in the massive list of script components. Just to read an ambiguous piece of text and nothing about how this component would supposedly be written in the script...

context.
This, does help explain what the component would use, but not how it would look as written.
https://stirante.com/script/server/1.11.0/classes/PlayerInteractWithBlockAfterEvent.html#block

It is almost like it could use an example of how the code would look like.

Just like how json files were documented in wikis and they had their code either explained out in full, or have an example to use as a reference.
Which helped a lot for someone learning from scratch.
Like this for example:
https://learn.microsoft.com/en-us/minecraft/creator/reference/content/blockreference/examples/blockjsonfilestructure?view=minecraft-bedrock-stable

The former gives this detached piece of information folks may not know how to apply to a string of code.
The latter is a bit easier to apply like modules without needing to somehow know that "void" means this, or that "arg:" means that something else can be put in its place.

Something like a format guide would help a lot at this rate.

abstract cave
#

it explains

pallid portal
#

Thanks. I'll try. πŸ₯²

crude ferry
#

Fuck i can't.

#

I'm too bad ;(

prisma shard
#

loll

abstract cave
glacial widget
#
function keys(player){
  const commmonkey = world.scoreboard.getObjective("ckey").getScores
  const rarekey = world.scoreboard.getObjective("rkey").getScores
  const epickey = world.scoreboard.getObjective("ekey").getScores


  const keys = new ActionFormData()
      .title("your crate keys")
      .body(`you have\n ${commmonkey} common keys\n ${rarekey} rare keys\n ${epickey} epic keys`)
      .button("back")
      keys.show(player).then(d => {
        if (d.selection === 0) {
          main(player)
        }
    });
}
``` How do i define getScores?
amber granite
#

Get score defined by addScore

glacial widget
crude ferry
crude ferry
#

πŸ˜‚

pallid portal
#

It honestly feels like a portion of fledgling addon writers have migrated to this section of the script abyss, and those able to write scripts have to deal with clueless folks asking the same questions in roughly the same way.

Which is a bit funny to see, but on a serious note makes me feel bad for bothering folks on where to learn and how it works.
Sorry folks XD

valid ice
#

Comes with the territory, I'm afraid πŸ˜›

abstract cave
distant tulip
#

we all been there (still are)

valid ice
#

Most people don't mind others asking questions, as long as the asker is making a conscious effort to learn themselves.

glacial widget
shy leaf
#

its surprising how fast a human can learn something if they are focused in it

#

like how i got to this

#

in a month

amber granite
glacial widget
shy leaf
#

and i still have the command block badge lol

abstract cave
valid ice
abstract cave
#

now its all coming to me

crude ferry
#

I started learning script API without knowing js πŸ˜‚
I learnt js to make addons but i never made addons.

amber granite
valid ice
#

Was going for Lego Movie

glacial widget
amber granite
#

Jk i m not

glacial widget
shy leaf
distant tulip
abstract cave
neat hound
# pallid portal [mini rant] Just *"love"* it when you look up a component in the massive list o...

Both Jayly and Stirante have done a lot of work to provide the help they provide with those API websites. I personally have Jayly's open 24/7.

They do it out of love for the game and for the knowledge. Jayly has added a lot of examples to his, but not to every thing. It is not his job, he does not get paid to do it.

That said, you can find lots of examples in this discord if you search on the key words. If you are not finding what you need, there is a whole community here to help and Jayly is active in this discord., Stirante in the OSS discord.

amber granite
valid ice
#

The examples on their websites are ripped straight from the types

distant tulip
#

bookmarked

crude ferry
neat hound
distant tulip
glacial widget
amber granite
abstract cave
amber granite
#

?

glacial widget
#

lol

amber granite
#

Wth πŸ’€

amber granite
glacial widget
glacial widget
valid ice
distant tulip
crude ferry
#

lol.

neat hound
#

I do not see adds anymore... I forgot about those... I wanted to ask him, can I just join or something and pay.... but they have not bothered me lately, so not sure if still there

valid ice
abstract cave
#

i ve never seen ads and I don't use adblocker

neat hound
#

or my blockers are doing their job

valid ice
neat hound
#

maybe after the 100th look up, you get no ads... LOL

abstract cave
valid ice
#

ah

crude ferry
#

There are ads.

amber granite
#

Maybe he scammed the companies πŸ’€

#

And get paid but never put an ad in it

crude ferry
#

Lmao.

distant tulip
#

i am getting a blank white area instead

crude ferry
abstract cave
neat hound
crude ferry
#

βœ… Jayly has been sentenced to 5 years in prison.

neat hound
#

He has a perma get out of jail free card with me....

abstract cave
crude ferry
#

Anything for you Jayly πŸ™

abstract cave
neat hound
abstract cave
#

should be at least a month

amber granite
crude ferry
#

I'll share it with all of my fingers.

abstract cave
abstract cave
crude ferry
#

πŸ˜‚

amber granite
#

I ll share with every molecule in my body

abstract cave
amber granite
#

Flash ?

abstract cave
crude ferry
#

Whot-

abstract cave
neat hound
#

okay when a real q uestion comes... stop all the nonsense....

valid ice
#

Script updates wahoo

crude ferry
#

Yay!

amber granite
valid ice
#

#1268596457536229437

crude ferry
#

Yayay!

abstract cave
#

more tools

crude ferry
#

Lmao.

shy leaf
# valid ice

hmmmm my tiny brain cant think of uses for this

amber granite
#

Interaction button ?

valid ice
amber granite
crude ferry
#

Nice!

amber granite
#

Ahh its preview day

crude ferry
#

I don't do much script API but yay anyways.

shy leaf
#

but well

#

it could be useful someday

#

and prevent my hair from being pulled out

abstract cave
neat hound
#

PlayerInteractWithBlockBeforeEvent Added property readonly isFirstEvent: boolean to beta. This value will be true if the event was triggered on players initial interaction button press and false if triggered on holding the interaction button

#

YES

valid ice
#

yes

crude ferry
shy leaf
#

idk if ore UI is getting released soon

crude ferry
shy leaf
#

we are kinda just waiting for it

crude ferry
#

I'm better at D.js then Minecraft script api.

crude ferry
abstract cave
amber granite
#

Uses html

#

So

remote oyster
naive tinsel
#

whats the best way to load a 128x200x128 structure? πŸ’€

amber granite
#

πŸ’€

#

I don't know if game support structure that s more than 64

#

X64x64

naive tinsel
#

well yes

amber granite
#

So u gotta devide it by 4

naive tinsel
#

buut it lags hella when it loads in

#

soo divide by 4 again

#

?

distant tulip
#

the height is more than 64 block

amber granite
#

Then devide it more

#

And add timeout

distant tulip
abstract cave
abstract cave
amber granite
#

What are crypts ?

abstract cave
abstract cave
#

why isn't it showing?

amber granite
#

?

abstract cave
amber granite
#

Thx

amber granite
#

Try with

#

Minecraft pot

valid ice
#

Decorated pot

#

you can

#

Block.getComponent('inventory')

twilit crag
#

is it normal to get ms spikes of ~140 the first time almost any event subscription is used?

#

for example, if i have subscribed to the entitydie event, the first time a mob dies i get an ms spike of like 120ms and then all next entities that die die smoothly

distant tulip
amber granite
#

Maybe ur device is low end device

twilit crag
#

very

#

can barely play multiplayer

amber granite
#

Yeah , it happens to low-end

#

U have no solution

twilit crag
#

yea i think i shouldve mentioned that

#

it's ok it only happens the first time an entity dies for example

noble lagoon
#

Does anyone know the reason for the error?

amber granite
#

beforeEvents is read-only

amber granite
#

Use afterEvents if u won't need event.cancel

valid ice
#

(If that link works for you)

amber granite
#

Or use
system.run(()=> {
//Ur code
})

noble lagoon
#

thx

remote oyster
distant tulip
#

"say my name"

amber granite
distant tulip
#

πŸ—Ώ

naive tinsel
#

how do i measure tps?

amber granite
#

Ticks per second?

fallow minnow
#

yes

naive tinsel
thorn ocean
#

Any idea on how to use system.runJob()?

amber granite
#

Hey i have question

noble lagoon
distant tulip
remote oyster
# naive tinsel how do i measure tps?
import { system, world } from "@minecraft/server";

// Variables to keep track of ticks and time
let tickCount = 0;
let lastTime = Date.now();
let tps = 0;
let tpsValues = [];
const intervalSeconds = 5; // Interval to calculate TPS
const intervalsToAverage = 12; // Number of intervals to average over (e.g., 12 intervals * 5 seconds = 1 minute)

// Function to calculate TPS
function calculateTPS() {
    const currentTime = Date.now();
    const elapsedTime = (currentTime - lastTime) / 1000; // Convert milliseconds to seconds

    // Calculate TPS
    tps = tickCount / elapsedTime;

    // Store the TPS value
    tpsValues.push(tps);
    if (tpsValues.length > intervalsToAverage) {
        tpsValues.shift(); // Remove the oldest TPS value to maintain the average window size
    }

    // Calculate the average TPS
    const totalTPS = tpsValues.reduce((sum, value) => sum + value, 0);
    const averageTPS = totalTPS / tpsValues.length;

    // Print TPS and average TPS to console (or use for other purposes)
    console.log(`TPS: ${tps.toFixed(2)}, Average TPS: ${averageTPS.toFixed(2)}`);

    // Reset counters
    tickCount = 0;
    lastTime = currentTime;
}

// Function to increment the tick count
function incrementTickCount() {
    tickCount++;
}

// Initialize world events and set up the TPS calculator
world.afterEvents.worldInitialize.subscribe(() => {
    // Set an interval to increment the tick count every tick
    system.runInterval(incrementTickCount, 1); // 1 tick interval

    // Set an interval to calculate TPS every intervalSeconds * 20 ticks
    system.runInterval(calculateTPS, intervalSeconds * 20); // 20 ticks per second
});

One of many ways to do it. This script will calculate and display the TPS every 5 seconds but the TPS being shown is the average TPS over the last 1 minute. Basically the first minute will be a process to determine your average and every 5 seconds after that will essentially be your average that's maintained. Make sense? πŸ€ͺ

amber granite
#

How will that give u Correct tps ?

remote oyster
# amber granite How will that give u Correct tps ?

Considering latency, ping, hardware, etc, it will be extremely difficult to get an accurate read on TPS. Given the variables which can be problematic to some and maybe not so much to others, you don't have many options.

sudden nest
#

Issss Minecraft Diagnostic available in the latest stable????

wary edge
sudden nest
#

Oh okay, i was hyped to try it bao_bee_sad

#

Profiler is meh

amber granite
#

Can i make a block go from right to left like sand block

grand heart
grand heart
#

How to prevent baby horse from spawning via
dimension.spawnEntity("horse", location)?

crude ferry
amber granite
#

Using Entity Spawn event and extra checks

fiery solar
twilit crag
#

No

#

My laptop just belongs to the dumpster probably

abstract cave
#

how do I summon an entity using scripts

#

like making it shoot a projectile

ionic kayak
#

Is there a test for block equivalent for scripts that returns the block id of a block at a specific location?

cinder shadow
#

Dimension.getBlock(block location).typeId or something like that, I'm not at home to confirm

remote oyster
#
import { world, Dimension } from "@minecraft/server";

const player = world.getPlayers()[0];

const block = Dimension.prototype.getBlock.call(player.dimension, player.location).typeId;
console.warn(block);
#

@ionic kayak

#

Adjust location as needed.

#

It can throw if the block is unreachable.

grand heart
#

how to access horse equipment
(how to saddle the horse using script)

random flint
grand heart
random flint
#

maybe

grand heart
#

wtf

fair quarry
#

Why doesn't kick works? Like I'm using player.runCommand(kick @s) and it just don't kick

#

And world.getdimenson.runcommand too

ionic kayak
remote oyster
#

What did you try?

ionic kayak
#

Experimenting using one of my projects @remote oyster

#

Made a whole new code

remote oyster
#

Show the code.

ionic kayak
#

Actually let me try something real quick

random flint
#

you're supposed to do world.getDimension() not importing the Dimension class

remote oyster
remote oyster
random flint
random flint
remote oyster
random flint
#

Interesting knowledge from you, i might test it later

remote oyster
random flint
remote oyster
#

Ah, I see.

#

Valid.

#

However, given my experience, the kick command tends to run into permission issues unless called from world.

random flint
#

If I remember correctly, you cannot use selector argument on /kick command. Only player names

valid ice
#

yes

remote oyster
#

That is also true.

remote oyster
random flint
#

I think calling runCommand() from the Entity class ignores the target permission.

remote oyster
#

I know that calling it from the Player Class would sometimes result in a failure when kicking a player, due to permission issues, and logging it via try/catch logic helped to recognize that problem some time ago. So the solution found to help work around that was the example I shared above, albeit being redundant.

random flint
#

I see... well thanks for the knowledge. I'm gona test it later

remote oyster
#

I knew what the exact reason was back then. I've forgotten now. It's plausible I made a note on it in the commit, back then lol.

fair quarry
remote oyster
#

Welcome

somber echo
#

Any idea about how to detect air with getBlockFromRay?

getBlockFromRay({ x: x, y: y, z: z },{ x: 0, y: -1, z: 0 },{ includeTypes: ['minecraft:air'], includePassableBlocks: true }```I try this but dont work
random flint
#

then its air

woven loom
#

ahh i accidently removed the "summon baby hose" post which was resolved already, this happend for the first time in years sorry to the owner whoever posted that

somber echo
woven loom
#

what's new in interact event

wary edge
woven loom
#

but what's new

wary edge
#

Read the changelogs?

#

Like...self explanatory

woven loom
#

yeah saw that now

shy leaf
#

can entityHitBlock check for air?

#

using 1.12.0-beta btw

valid ice
#

nay

shy leaf
#

then uh how do i check for attack

#

tryna do weapon swing sounds

valid ice
#

on air? That's the neat part, you don't

shy leaf
#

but but

#

what about other events

valid ice
#

Can detect on block & entity, that's it

shy leaf
#

and does the entityHitBlock fire only if the player hits a block

#

not even some sort of

#

returning undefined block or anything?

#

god

#

damnit

shy leaf
#

only if i could check for v.attack_time in scripts

#

thanks for telling

shy leaf
#

how do i reset all the items' cooldown at once?

round bone
cold shoal
#

Is it a bad idea to run a replacing item script with no delay? It basically replaces certain items in every players inventory with another item. I can make it so that it will only run for creative players (since the item I'm talking about is only obtainable in creative).

round bone
twilit crag
# wary edge

What does only triggered on successful interaction in playerInteractWithEntity mean? No longer possible to make an item useable on every mob without modifying every mob?

Edit: sorry for crossposting, ended up asking the same thing in #1268601041063247955

hazy nebula
#

Is there a way to fill an area where the game won't load?

wheat condor
remote oyster
#
import { system, world, Player, ItemStack, ItemTypes, GameMode, EntityQueryOptions } from "@minecraft/server";

const specificItem = "minecraft:stone";  // Replace with the specific item identifier you want to check for
const replacementItem = "minecraft:diamond";  // Replace with the replacement item identifier

async function checkAndReplaceItems() {
  const queryOptions: EntityQueryOptions = {
    gameMode: GameMode.creative
  };
  
  const players = world.getPlayers(queryOptions);
  
  for (const player of players) {
    const inventory = player.getComponent("minecraft:inventory").container;
    const size = inventory.size;
    
    for (let i = 0; i < size; i++) {
      const item = inventory.getItem(i);
      if (item && item.id === specificItem) {
        inventory.setItem(i, new ItemStack(ItemTypes.get(replacementItem), item.amount));
      }
    }
  }
  
  // Schedule the function to run again after 20 ticks (1 second)
  await new Promise(resolve => system.run(resolve, 20));
  checkAndReplaceItems();
}

// Start the loop
checkAndReplaceItems();

Something like this I believe. Not really tested, but it's written up to be asynchronous to help it from jamming up the main thread, allowing other code operations to continue smoothly in your script, should that be applicable.

shy leaf
round bone
#

if you have some of your custom cooldowns, just ad to this array

shy leaf
#

i mean well

#

im asking cuz there are a bit too much categories spyBruh

#

but thanks anyway, better than nothing

round bone
#

there' s no other way, just add them to this array'

#

AND for a bit of a type safety, you can add type to this

/**
 * @type {readonly srtring[]}
 */
const cooldowns = [
    "minecraft:chorusfruit",
    "minecraft:ender_pearl",
    "minecraft:goat_horn",
    "minecraft:shield",
    "minecraft:wind_charge"
];
shy leaf
#

meh im using custom cooldown categories so

round bone
#

you have to add them to this array

#

there's not really any other solution in API to remove all of these cooldowns

shy leaf
#

there are like 40 categories to add but

#

meh ive had worse

round bone
#

at this point you can build yourself a small API

shy leaf
#

sounds a bit overkill for one functionality

round bone
#
import { Player } from "@minecraft/server";

/**
 * @type {readonly string[]}
 */
const categories = [
    "minecraft:chorusfruit",
    "minecraft:ender_pearl",
    "minecraft:goat_horn",
    "minecraft:shield",
    "minecraft:wind_charge"
    // all these categories
];

class PlayerServer {
    static resetItemCooldowns(/** @type {Player} */player) {
        for (const cooldownCategory of categories) {
            player.startItemCooldown(cooldownCategory, 0);
        };
    };
};

export { PlayerServer };
round bone
shy leaf
#

to be more specific the cooldown reset only happens when you use a special item

#

so

#

yeah

#

actually i should do that lol, dont wanna make that one item code in particular to look larger than rest of the code

abstract cave
#

umm, how do I summon an entity with scripts

shy leaf
hazy nebula
turbid oriole
#

Excuse my absence, my children. I'm studying basic web programming.

turbid oriole
shy leaf
#

me too

turbid oriole
abstract cave
prisma shard
prisma shard
#

get the projectile component first

abstract cave
prisma shard
abstract cave
sudden nest
#

Anyone knows where's the docs for Experimental Features toggles and what it means? πŸ˜…

prisma shard
#

You don't know what is Experimental Features Toggle?

abstract cave
#

bruhh

prisma shard
wary edge
sudden nest
#

Internet so slow

#

Thanks

fiery solar
feral minnow
#

can i use getBlocks to get all blocks in the world?

#

without needing to load them

wary edge
feral minnow
#

so you just afk the player

wary edge
#

Last i checked you cant get outside loaded chunks

distant tulip
#

getBlocks have allowUnloadedChunks parameter
but getBlocks return only positions
you still need to deal with that

feral minnow
#

so i cant getBlock for the unloaded chunk?

abstract cave
#
    player.dimension.spawnEntity({ identifier: "minecraft:pig" }, location())
#

do i make an object inside location

#

and is there a neater way to do this

distant tulip
distant tulip
abstract cave
#

inside an object

#

or do I put it into a constant anddo it that way

distant tulip
#
    player.dimension.spawnEntity({ identifier: "minecraft:pig" }, {x:number,y:number,z:number})
abstract cave
solar dagger
#

Heh

distant tulip
#
const entity = player.dimension.spawnEntity({ identifier: "minecraft:pig" }, {x:number,y:number,z:number})
#

change number to a number

abstract cave
distant tulip
#

it is alr
you should take a basic js course

solar dagger
#

What are you trying to do with that?

abstract cave
#

I have but its still new to me so I'm polishing my js skills with scripts

abstract cave
solar dagger
#

Yes

distant tulip
#

btw spawnEntity is not object it is a function

abstract cave
#

im trying to make an item shoot a projectile when I rightclick

solar dagger
#

Oh

#

Bro I got you

abstract cave
#

am I doing it right?

solar dagger
#

well that only spawns the entity, you need to get the location numbers right

#

and since you're using an item you might want to spawn it in front of the player

abstract cave
distant tulip
#

kinda
but you are just spawning it there is a shot function and it is better to spawn it in head location

solar dagger
distant tulip
solar dagger
#

ye so you need to get the player's head position

distant tulip
# abstract cave okee
world.afterEvents.itemUse.subscribe(async event => {
  const { source, itemStack } = event;

  const power = 1
  const velocity = Vector3Multiply(source.getViewDirection(), power)

  const location = Vector3Add(source.getHeadLocation(), source.getViewDirection())
  const arrow = source.dimension.spawnEntity("minecraft:arrow", location)
  const projectile = arrow.getComponent('projectile');
  projectile.shoot(velocity)
})

function Vector3Add(a, b) {
  return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z }
}

function Vector3Multiply(a, b) {
  return { x: a.x * b, y: a.y * b, z: a.z * b }
}
abstract cave
#

whoa this is uhhh...

distant tulip
#

change the power to change the velocity
also there is a lot of parameters in the projectile component
like gravity and other things

abstract cave
#

after the projectile const I don't understand anything, lol

distant tulip
distant tulip
hushed ravine
#

Does @minecraft/math contain Vector as well?

distant tulip
#

the multiply is kinda obvious

distant tulip
#

check the pined messages

hushed ravine
#

How do I use @minecraft/math

feral minnow
#

is there a way to load/generate chunk without needing the player to go to the position

hushed ravine
#

Answer to my question: yes

distant tulip
hushed ravine
#

I just used that NPM package and bundled it how I usually would

#

Also, can I change gamerules without using commands?

#

The gamerules fields in World seems to be read-only

distant tulip
#

you can

#

huh

#

let me see

hushed ravine
#

Wait

#

NVM

#

What about the difficulty?

distant tulip
hushed ravine
distant tulip
hazy nebula
#

How to use dimension.fillBlock?

hushed ravine
#

Is there any way to load chunks? Even by using commands

#

I need this because the function I made requires it when 0 0 isn't loaded due to the location being in the ocean

function getHighestOverworldBlock(x: number, z: number) {
  return server.world
    .getDimension("overworld")
    .getBlockFromRay(
      { x, y: 319, z },
      { x: 0, y: -1, z: 0 },
      { maxDistance: 320 },
    )?.block;
}
hushed ravine
wary edge
#

Ye

frigid cape
#

Hello, does anyone know how I can get the player's hunger percentage with a script?

fallow rivet
#

Item lore limit is 50 letters, is it possible to increase it?

valid ice
#

no

grand heart
#

tameable component is undefined on wolf, why?

frigid cape
frigid cape
unique dragon
#

i don't think it's possible to get the hunger percentage by any way

#

only modding

twilit crag
grand heart
twilit crag
#

only wild wolves have the tameable component

grand heart
twilit crag
#

yes

grand heart
#

it's not yet tamed so it's wild yet it's still an error

#

my code

let wolfie = overworld.spawnEntity("minecraft:wolf", player.location);
wolfie.getComponent("minecraft:tameable").tame(player);

console error

... TypeError: cannot read property 'tame' of undefined ..

the wolfie is spawned, yet no tame

twilit crag
#

try putting system.run around wolfie.getComponent("minecraft:tameable").tame(player);

#

i mean

let wolfie = overworld.spawnEntity("minecraft:wolf", player.location);
system.run(()=>wolfie.getComponent("minecraft:tameable").tame(player));
grand heart
twilit crag
#

np, it's basically because the wild component group of the wolf isn't added instantly

#

so you delay the taming a little with system.run

wheat condor
# hazy nebula i tried ```tickingarea add ~36 ~-1 ~-45 ~45 ~-5 ~45 ddc``` and then ``` fill ~36...

ok so basically you can add a ticking area only if the area is currently ticking and there is a limit, so basically if the area is larger than 64x64 blocks you need to teleport you in one side and then add a ticking area then teleport on the other side and add another tickingarea then remove the areas, is s bit complicated becouse there isnt any way to start loading a chunk in bedrock edition without using the player to render it

grand heart
wheat condor
# wheat condor ok so basically you can add a ticking area only if the area is currently ticking...

ill make it simpler

if area < 64x64 : fill.

if area > 64x64 : add the firts tickingarea, teleport the player in the remaining part, add the second ticking area,(more area uncovered more tickingareas), fill all the area(if fill is more than the limit just do 2 times fill), remove all ticking areas

if area > ten times 64x64 : add the firts tickingarea, teleport the player in the remaining part, add the second ticking area,(more area uncovered more tickingareas), fill all the area(if fill is more than the limit just do 2 times fill), remove all ticking areas. redo the process for the rest

remember to add like 5 ticks of delay between all the operations to optimize it or the game will crash
or just add a menu with ticks based on the device to make slower (40 ticks) less laggy for mobile players and faster (3 to 5 ticks) for pc players
@hazy nebula

#

and use scripting to fill

true isle
#

how to i play an animation like the vanilla axe swing when stripping custom logs instead of the awkward place only lol

cinder shadow
#

you make your own πŸ˜”

true isle
#

? im confused why i have to make my own animation when using bonemeal does the item swing thing

true isle
#

whats the difference theyre both items

distant tulip
#

the swing animation is hard coded

true isle
#

right i know that. but why does bonemeal do the swing when in a script and using an axe doesnt

cinder shadow
grand heart
#

how to add wolf armor to wolf using scripting

buoyant wolf
dense skiff
#

"@minecraft/vanilla-data" doesn't need to be in the pack's manifest dependencies, does it?

#

import { MinecraftItemTypes } from "@minecraft/vanilla-data";
is throwing
[ReferenceError: Module [@minecraft/vanilla-data] not found. Native module error or file not found.]

wary edge
#

It's not a module technically

dense skiff
#

bundle it?

grand heart
somber cedar
buoyant wolf
neat hound
# dense skiff `import { MinecraftItemTypes } from "@minecraft/vanilla-data";` is throwing `[R...

you will need to npm it @ your scripts folder to get the download of it. If you are doing JS, may need to make a package.json with {} in it, then run npm init, then npm the vanilla data... then the vanilla data js file isn deep in there, can pull out or reference it.... if ts.... well.. however that works, you still need to get that node-modules folder installed.... I had to deal with this frustration the other day. King and Kiro has to hold my hand thru it.

#

I suggest running a formatter on the index.js file cause it's ugly-style...

dense skiff
#

Thanks all

#

I've also got an entity that looks like this:

    "format_version": "1.20.40",
    "minecraft:entity": {
        "description": {
            "identifier": "canopy:probe",
            "is_spawnable": false,
            "is_summonable": true,
            "is_experimental": false,
            "properties":{"canopy:light":{"type": "int","range":[0, 15],"default":0}}
        },
        "components": {
                  // components
                }
          }
}```
But things like projectiles and player hits still interact with it. Can I make it even more invisible?
cold grove
#

#1067869022273667152

#

Not channel topic

amber granite
#

Agree

feral minnow
#

does adding ticking area on ungenerated chunk makes it generate the chunk?

wary edge
feral minnow
#

how about simulated players?

wary edge
#

I do not know

distant tulip
shy leaf
#

how can i add custom armor equip sounds

#

i could use itemUse event but that wont work when wearing the armor directly in inventory

fiery solar
feral minnow
rich kernel
#

im not sure to understand how to use this

#
world.beforeEvents.playerInteractWithBlock.subscribe(bruh => {
  world.sendMessage("no way")
})
``` can't call it like that
shy leaf
rich kernel
#

i can't even use afterEvent

shy leaf
#

other than using beforeEvents for custom components

shy leaf
#

why

rich kernel
#

idk

shy leaf
wary edge
#

@rich kernel are you using the beta apis?

rich kernel
#

no

wary edge
#

There's your answer

rich kernel
#

oh noomg

wary edge
#

PlayerInteract is in beta APIs

shy leaf
rich kernel
#

is there any way I can know if the player is interacting with a block (like itemUseOn but with the hand also)?

#

without beta

shy leaf
#

theres afterEvents for playerInteractWithBlock

#

if you can use afterEvents that is

rich kernel
shy leaf
#

its on stable

#

its beforeEvents thats in beta API

#

wait no

#

both are in stable

granite badger
#

The class is stable, but there’s no way to access that class

rich kernel
#

that's weird

shy leaf
#

WHY?????

#

WTF

rich kernel
wary edge
shy leaf
#

yeah i should unpin microsoft docs off my chrome

#

so called creators of one of the largest operating system

granite badger
wary edge
shy leaf
#

meh i can just leave it open in the tab

shy leaf
#

wrong reply but its close enough

granite badger
#

itemuse triggers when player rights clicks the jtem (eg eat)

shy leaf
#

and no trigger for wearing the armor itself?

granite badger
#

probably not. You probably have to make your own event to listen for that armor in the slot

shy leaf
#

spyBruh sounds like runInterval thing

inland merlin
#

Sounds like it

#

I have a feeling they def want to add inventory events one day. I bet it's alot of backend work.

shy leaf
#

yeah

fiery solar
# wary edge Will that generate the terrain?

Yeah, just tested it in a random location of a brand new world. I can get any block in a chunk that has never been visited by a player.

I guess I can't be sure if that's proof that it generated the whole chunk though... Might have to try to load the data in a world editor

shy leaf
#

god, i dont like using runInterval for events

#

im in boomerang level of fear

wary edge
shy leaf
#

not knowing when the game will kick me out for making a tiny mistake in math

neat hound
#

"tiny"

remote oyster
shy leaf
#

its a damn 50/50 chance too

neat hound
#

nah

shy leaf
#

the game will either have mercy and do watchdog

#

or my phone will run out of memory

#

and the content log's last words would be Out of Memory

neat hound
#

There is logic behind everything... else nothing in the world would work

inland merlin
remote oyster
inland merlin
#

Lol

shy leaf
#

all of my out of memory errors were from not being able to clear runinterval and were related with texts lmao

inland merlin
remote oyster
shy leaf
#

like when i was optimizing the code

granite badger
#

how do you guys managed to use up all the script memory

shy leaf
#

i saw that one block of code, thinking "why did i put this here? clueless" and removed it

remote oyster
shy leaf
remote oyster
#

That's really bad haha

shy leaf
inland merlin
#

When your screen is full of thousands of new intervals... your fkd

shy leaf
#

my phone UI literally restarted

#

basically i was making dynamic health bar using nametags and i had to keep track of the entity's health using runInterval

you know the rest

near siren
#

Didnt they add something new to get the top most block?

remote oyster
near siren
#

Just to get the top most block from a location

wary edge
#

Yes they did

near siren
#

Do you know what class its a part of?

near siren
#

Ah, thank you

inland merlin
#

Dang that's so much better then previous raycast

remote oyster
rich kernel
#

we can't set damage on custom items?

wary edge
rich kernel
#

waht does data-driven items mean?

wary edge
rich kernel
#

ohh lmao

#

do I need beta to make it works?

shy leaf
wary edge
#

Seems like a #1067869136606220288 questiob

rich kernel
#
let dura = item.getComponent("durability")
dura.damage = 50;
#

this is what I got but im not sure if this is what im supposed to do

shy leaf
#

and im outside the home

rich kernel
#

ahh np

shy leaf
#

brb ill check smth

rich kernel
#

alr

shy leaf
#

so damage part represents how much 'damage' the item has gotten

#

(duh)

#

but if you were to add damage (or in other words, reduce durability), you need to add values on it

#

dura.damage += 50 iirc

#

cant tell if this is how you do cuz i only touched durability component for once

rich kernel
runic crypt
#

guys anyone has a addon/script that introduces command cooldown ?

#

please i need it

runic crypt
#

like not vanilla commands

#

things like !kit

#

these

shy leaf
#

both vanilla and custom

runic crypt
#

wait really ?

shy leaf
#

but rn no i cant use my tablet rn

runic crypt
shy leaf
#

you need to use an event that triggers upon chat send

runic crypt
#

ok

shy leaf
#

its in beta API, and make sure to use beforeEvents for it

runic crypt
#

imma search it up

#

if you get the time can you pls make it ?

shy leaf
#

no sorry i have other stuff to do

runic crypt
#

oki np

#

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

world.beforeEvents.chatSend.subscribe((eventData) => {
const player = eventData.sender;
if (!player.hasTag('Admin')) return;
switch (eventData.message) {
case '!gmc':
eventData.cancel = true;
player.runCommandAsync('gamemode c');
break;
case '!gms':
eventData.cancel = true;
player.runCommandAsync('gamemode s');
break;
default: break;
}
});

where do i add the cooldown in this ?

shy leaf
#

#1067535608660107284 message

runic crypt
shy leaf
#

i dont recommend it

runic crypt
#

like instead of has tag

#

i use scoreboards ?

runic crypt
shy leaf
#

no

runic crypt
#

how do i do it ?

shy leaf
#

trust me

runic crypt
#

come on i wanna try :)

shy leaf
#

use setDynamicProperty and getDynamicProperty

#

instead of scoreboard

runic crypt
#

idl what taht is 😭

shy leaf
#

its like scoreboard but without scoreboard

runic crypt
#

im kinda new to scripting

shy leaf
#

ok uh let me explain tbis

runic crypt
shy leaf
#

uh idk, i dont have your code so

#

except that

#

tell me what you need scoreboard for

runic crypt
#

like when score "cooldown" hits 0 then a text msg is sent saying you can use the command again

#

if player tries to use command before then a msg saying "no" is sent

shy leaf
#

ok then i think you dont need dynamic property for this too

#

gimme a second

runic crypt
#

oki thanks :)

#

after u dont can u tag me ?

shy leaf
runic crypt
shy leaf
#

uh

#

should be easy though

runic crypt
#

@shy leaf

shy leaf
#

please for the gods sake dont use scoreboard for scripting

runic crypt
#

i wanna :(

shy leaf
#

not to mention i dunno how to manipulate scoreboard in scripts

#

cuz i dont use em

runic crypt
#

what was the idea u were suggesting ?

#

can you implement that one ?

shy leaf
#

give me a second then

runic crypt
#

oki

#

tag me when u make it ?

shy leaf
#

ok

subtle cove
#

Anyone benchmerked item dynamic prop so far yet?

prisma shard
shy leaf
#

@runic crypt

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

world.beforeEvents.chatSend.subscribe((eventData) => {
    const player = eventData.sender;
    const time = Date.now();
    if (!player.hasTag('Admin')) return;
    if (!(player['cooldown'] > time)) {
    switch (eventData.message) {
        case '!gmc':
            eventData.cancel = true;
            player.runCommandAsync('gamemode c');
            player['cooldown'] = time + 15000
            break;
        case '!gms':
            eventData.cancel = true;
            player.runCommandAsync('gamemode s');
            player['cooldown'] = time + 15000
            break;
        default: break;
    }
    } else player.sendMessage('Command is in cooldown')
});```
#

cant guarantee itll work

prisma shard
shy leaf
#

compared to after one

#

and aside from that

#

i dont feel the difference

prisma shard
#

why

shy leaf
#

like

#

i dont need canceling events that much

#

maybe in future

prisma shard
prisma shard
shy leaf
runic crypt
#

ok

shy leaf
#

i think i made the chat to cancel regardless of the command

runic crypt
#

well uhhh

#

also how do i adjust the time ?

#

and does it send a msg on how much time is left ?

shy leaf
#

see the 15000 thing?

runic crypt
#

yea

shy leaf
#

its in milliseconds

runic crypt
#

ohkkk

#

tahts 3min right ??

shy leaf
#

no, 15 seconds

#

1000ms is 1 second

#

i edited the code, check it again

runic crypt
#

how do i make it show how much time is left tho ?

shy leaf
#

you could do
player['cooldown'] - time

#

itll show in milliseconds so youd need to divide it by 1000

runic crypt
#

} else player.sendMessage('Command is in cooldown')

subtle cove
#

Since it's attached on player, u can access that anywhere

runic crypt
#

here ?

runic crypt
shy leaf
runic crypt
#

oki

#

lemme add it

#

so now it will work ?

#

imma try it out

shy leaf
#

shrug

#

you can test it

tiny tartan
shy leaf
runic crypt
#

@shy leaf
didn't work :<

shy leaf
#

☠️

runic crypt
#

like i can do !kit

#

get a kit

#

but i cant do it for the next 24hrs

#

is it possible ?

tiny tartan
shy leaf
#

also are you sure youre using beta api

subtle cove
#

Prob the undefined > time

shy leaf
#

oh wait yeah that

tiny tartan
#

probably required privilege

#

error

shy leaf
#

also that since its beforeEvents

subtle cove
#
if ((player["cooldown"] ??= 0) < time)