#Script API General

1 messages · Page 8 of 1

amber granite
#

Why didn't u use of instead

grand heart
#

i need to

let item = itemStack.clone();
item.nameTag = "New name";
smth.setItem(item)
amber granite
#

Because it s an array

#

And not an object

subtle cove
#

Array would need u to loop

#

Why not just use {}

amber granite
#

Oh it s an object

grand heart
subtle cove
#

ctnr.setItem(slotIndex, item)

grand heart
#

but this tho?

#

it just doesn't upate if i just assign

subtle cove
#

Cus it's not ContainerSlot, it's just ItemStack

#

Assigning on ItemStack would need the cntnr.setItem(slotIndex, itemStack)

grand heart
subtle cove
#
//ContainerSlot
const cSlot = cntr.getSlot(slotIndex)
if (cSlot.hasItem()) {
    cSlot.amount += 2 //item changed
    cSlot.nameTag = cSlot.typeId //item changed
    //no need for setItem
    //changing component stuff like enchantments would be different 
    const item = cSlot.getItem()
    const ench = Item.getComponent("enchantable") 
    ench.addEnchantment({ type: new EnchantmentType("mending"), level: 1})
    cSlot.setItem(item)//item changed
} ``````js
//ItemStack
let slotIndex = 16
const item = cntnr.getItem(slotIndex)
if (item) {
    item.nameTag = item.typeId
    item.amount *= 3
    const ench = Item.getComponent("enchantable") 
    ench.addEnchantment({ type: new EnchantmentType("mending"), level: 1})
    cntnr.setItem(slotIndex, item) //item changed
} ```
remote oyster
naive tinsel
#

whats difference in Save to memory and save to disk in structure blocks

#

and do i need to use save to disk to use the structure manager?

valid ice
#

Disk is temporary for that world session, if I recall correctly.

#

Memory saves to the world DB

naive tinsel
#

ok

#

thanks

glacial widget
#

tried still getting the error

amber granite
#

._what ?

devout dune
#

@wary edge sorry i meant to ask this #1070606638525980753 message
here. I am trying to do it with scripts. or maybe an Effect?

wary edge
#

TP it in place?

amber granite
#

With runInterval?

devout dune
misty pivot
#

i know damage is read only in entity hurt event but is it possible to edit it? i was thinking something like damage = 0

misty pivot
#

alright, thanks

#

well is there another way where i can half the damage dealt to the player instead of healing/giving back half the health back?

devout dune
# wary edge TP it in place?

Hey what could i do for size? of an entity.
I noticed entity.setRotation() in the docs, but couldnt fiund size

wary edge
devout dune
wary edge
#

Yeah

remote oyster
amber granite
#

Hey can i get dyied armor

#

@wary edge is there a way to get dyied leather armor ?

shy leaf
#

in EntityQueryOptions for getEntities in dimension class, does maxDistance and/or closest, farthest, etc work if location is not defined?

#

something like this

const entities = player.dimension.getEntities({
    maxDistance: 10,
    closest: 5,
    families: [ 'mob' ]
    });
entities.forEach(entity => {
        ...
});
amber granite
#

Yes

shy leaf
#

i could test it but i cant open minecraft rn

amber granite
#

What ?

shy leaf
#

like

#

you said it works, right?

#

does it automatically use player.location

amber granite
#

Yes

shy leaf
#

neato

amber granite
#

Ofc

naive tinsel
#
        world.structureManager.place("island", player.dimension, {
            x: (slot*1000)+61,
            y: 31,
            z: (slot*1000)+59
        }, {
            animationMode: StructureAnimationMode.Layers,
            animationSeconds: 2,
        })```how come it says structure doesnt exist when i can load it ingame through the chat?
amber granite
#

Does any one know how to make a structure generator

#

I want to use barrels as containers

naive tinsel
#

huh

remote oyster
#

@devout dune

In player.json just add something like this as a component.

"components": {
    "minecraft:scale": {
        "value": 1.5 // set to whatever you want
    }
}

Then in your script here is an example on how to change it.

system.run(() => {
    const player = world.getPlayers()[0];
    const scale = player.getComponent("scale").value;
    if (scale > 0) {
        // This cannot be edited in read-only mode
        player.getComponent("scale").value = 0;
    }
});
shy leaf
#

wheres the namespace

naive tinsel
#

if thats what your asking

shy leaf
#

hmmmmm

naive tinsel
#

through the structure block

shy leaf
#

no i was asking if you did put the namespace on the structure's id

#

like how you put minecraft:

naive tinsel
#

oh

#

is that required?

amber granite
#

What is ur structure name ?

naive tinsel
#

island

amber granite
#

Is in in structures file in ur behaviour pack?

shy leaf
#

yea, it defaults to minecraft: if it doesnt have one

#

which is probably why it doesnt work

naive tinsel
shy leaf
#

the script is trying to run mystructure:island

naive tinsel
#

so
mystructure:island?

amber granite
#

Yes

naive tinsel
#

ah yes it works now

shy leaf
#

ok nvm i thought i was tripping

amber granite
#

I want structure generator._.

naive tinsel
#

ok then make one

shy leaf
#

can you be more specific

amber granite
#

So

#

In script resources

#

I saw someone that used barrels as containers

#

Using mcstructure

shy leaf
#

huh

amber granite
#

But

#

When i saw his files

#

I found that he has 108 structure

shy leaf
#

itemStack check in runInterval

#

and when the player has the item, spawn particle

gaunt salmonBOT
#

Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
gray tinsel
#

doing minecraft damage gonna be fun :)

grand heart
#

how to catch and cancel fatal damage?

random flint
grand heart
amber granite
#

Can i detect when player uses command or command block get used ?

#

Like :
/tag

#

Or idk

subtle cove
subtle cove
amber granite
#

Sad

subtle cove
#

/scriptevent, yes

amber granite
#

Not even with chatsend ?

amber granite
cold shoal
#

Is it possible to get the equipped armor of an armor stand?

subtle cove
cold shoal
amber granite
#

It s possible

#

Get the armor stand entity

#

And access container

subtle cove
cold shoal
#

The inventory component returns undefined.

cold shoal
amber granite
#

Use "equippable"

#

Component

cold shoal
#

Same thing, returns undefined

amber granite
#

Huh

amber granite
cold shoal
#
const armorStands = world.getDimension("overworld").getEntities({type: "minecraft:armor_stand"})
for (const armorStand of armorStands) {
    const equippable =  armorStand.getComponent("minecraft:equippable");

    const bootsArmor = equippable.getEquipment(EquipmentSlot.Feet)

    console.warn(bootsArmor.typeId)
}

something like this

amber granite
#

remove minecraft:

subtle cove
#
world.sendMessage(armorStand.getComponents().map(c=>c.typeId).join('\n')) 
cold shoal
cold shoal
#
for (const armorStand of armorStands) {
    console.warn(armorStand.typeId) // I'm sure armor stand exists

    world.sendMessage(armorStand.getComponents().map(c=>c.typeId).join('\n')) 
}
subtle cove
#

Breh

#

c?.typeId

cold shoal
#

Ohh, type_family and health are the only components readable ig?

#

It only sends message for those comps

subtle cove
#

That not beta, right?

cold shoal
#

Yeah

subtle cove
#

Mhm

amber granite
#

How can i add colors to an objective on display

subtle cove
#

addObjective(objId, displayName)

amber granite
#

No i mean

#

I just add
" | " + "§3green"

#

To the second argument

#

And i get this error

#

[Scripting][error]-TypeError: Native type conversion failed. Interface property ['objective'] expected type: ScoreboardObjective (failed parsing interface to Function argument [1]) at teleportToTeam (forbiddenAreas.js:118)
at <anonymous> (forbiddenAreas.js:61)

#

Why is that ?

subtle cove
#

ScoreboardObjective, not objective string

amber granite
#

Huh ?

#
addObjective( "something" , colors[color] + color)
#

That s how i got it

#

colors[color] and color are both strings

subtle cove
#

world.scoreboard.addObjective(objId, display)

amber granite
#

Yes i did that

misty pivot
#

how would i add a property/method to a prototype?
like entity.myPrototype.action(1)

amber granite
#

what ?

#
entity.prototype.urMethod = function ( paramters) {
//Code
}
cold shoal
amber granite
#
setObjectiveAtDisplay("BelowName") , {objective : "something"})
cold shoal
#

The "objective" property should be a Socreboard Objective

amber granite
#

Oh yeah i see

subtle cove
#

its getObjective there

cold shoal
#
world.scoreboard.addObjective("idString", "§pColored")
const scoreboardObjective = world.scoreboard.getObjective("idString")
world.scoreboard.setObjectiveAtDisplaySlot(DisplaySlotId.Sidebar, {objective: scoreboardObjective})

like this

amber granite
#

My bad so

#

Thank u guys very much

misty pivot
subtle cove
#

Search "Proxy"

turbid oriole
#

How do I reduce the durability of an item? Without losing your current enchantments.

misty pivot
turbid oriole
turbid oriole
misty pivot
#

what kind of ways?

amber granite
#

Hmm ?

amber granite
#

@misty pivot

amber granite
#

@misty pivot

misty pivot
#

mb, i was away earlier

amber granite
#

What are u trying to do ?

#

Make new method or proprety

#

Into an entity?

#

Or player

misty pivot
#

yeah pretty much, but like i can add another method to that method

#

similar to how you can put dimension after entity

amber granite
#

Ah

#

It s possible

#

Just ur function must return an object

#

That s all

#

U mean
player.method().method2()

#

@misty pivot

misty pivot
#

yeah

amber granite
#

Then use something like

misty pivot
amber granite
#

something like this?

Entity.prototype.method1 = {
    function() {
        return { method2 : function() {
            ...
        } }
    }
}```
misty pivot
#

ah i see

amber granite
#

Put it in prototype, so u can use it in any player or entity

misty pivot
#

can i declare the functions outside it because if i where to have a ton of methods it would look like a mess

amber granite
#

Yes

#

U can declare it somewhere else

#

Like

function foo(){}
#

method2 : foo

misty pivot
#

alright thanks, also do you think it's more efficient than using classes? because i usually do something like class(player, /*a ton of properties*/)

amber granite
#

What u mean

#

By that

valid ice
#

jsdocs?

amber granite
#

It is

#
  • Player is a class by itself
misty pivot
#

well i declare a class then i convert it to an object and put it in events (like world events and such) and to declare the player in the class i put the player in it

valid ice
#

.d.ts is a magical thing :3

amber granite
valid ice
#

Used to declare types for js code

amber granite
#

Oh yeah

valid ice
misty pivot
#

is ts used more than js for scripting?

amber granite
amber granite
misty pivot
valid ice
#

.ts needs to be compiled to .js to run within minecraft

amber granite
amber granite
valid ice
#

extend prototype is pretty poggers ngl

amber granite
#

Wait ,

valid ice
#

.d.ts doesn't do anything but provide autocompletion & intellisense in the editor

amber granite
#

Oh

#

That s cool

#

So it s like ts file that s compatible with js

#

It s for notations

valid ice
amber granite
#

I get it

#

But why is it magical

#

Isn't a normal thing :T

valid ice
#

I get autocompletion for inventory component, and a custom message to tell me what's happening

amber granite
#

I don't get it

valid ice
amber granite
valid ice
#

It does nothing in-game itself

amber granite
valid ice
#

Only used for the editor and ease of use for the coding

amber granite
valid ice
#

Alright

amber granite
#

Alright that s cool too , i hope u are happy with it : )

valid ice
#

I definitely am yessir

#

I cannot use typescript

#

It yells at me too much 😭

amber granite
valid ice
#

"YOU CANNOT USE A string | number | boolean | undefined FOR A NUMBER TYPE YOU IDIOT"

amber granite
#

But ngl it just used for big projects

valid ice
#

(I really should use it tbh)

amber granite
#

There is no reason to use it in an add-on

amber granite
valid ice
#

I just cannot be bothered to change my scripts

valid ice
#

That's what ts does

#

stricter rules than a prison warden

#

It catches stupid mistakes

amber granite
tight sparrow
#

How to make your entity knockback mobs with resistance

amber granite
#

UsIng script api ?

misty pivot
#

or if you mean entities just use minecraft:knockback_resistance

amber granite
#

He can use
entityHitEntity event too

tight sparrow
#

And how do you make mob walk backwards when the target is near

misty pivot
#

erm, are you sure you're in the right channel?

random flint
#

also ocelot.json

lapis heart
#

Hey guys. How many characters are allowed in a textField description?

turbid oriole
misty pivot
#

lmao you are so delayed, but yeah kiro taught me that i could make it return objects

turbid oriole
#

How do I add custom components to items?

turbid oriole
#

Although this is not to learn Javascript. Here is to get my question answered.

#

How do I add custom components to items?

amber granite
turbid oriole
#

I don't want to read the component.

turbid oriole
#

Can I change the durability of an item in the inventory?

amber granite
#

Oh custom component

#

Yesh u can make it using script

lapis heart
turbid oriole
misty pivot
#

"minecraft:custom_components": [ "name" ]

#

i believe like this

turbid oriole
misty pivot
#

mb mb, it is actually plural

turbid oriole
misty pivot
#

and must be 1.20.80+ format

turbid oriole
#

Oh.

#

Can I put format 1.21.0?

misty pivot
#

yep

amber granite
#
world.beforeEvents.worldInitialize.subscribe((e) => {
// Custom for block
e.blockComponentRegistry.register.CustomComponent("ur:custom_comp" , {
// An example
onPlace(e) {
//Ur code
}
})
}
turbid oriole
#

Formatting is always a pain in many jsons.

turbid oriole
obsidian coyote
amber granite
obsidian coyote
amber granite
#

Replacement for my precious events

obsidian coyote
#

imo it allows for way more

amber granite
#

Why they are lazy

turbid oriole
#

XD don't use 1.21.0

amber granite
#

Js dosen't bite pplz

obsidian coyote
misty pivot
#

also, i tested custom components in a server, it doesn't seem to work :/

distant tulip
shy leaf
turbid oriole
#

How strange, the icon component is failing me when updating the format version.

amber granite
distant tulip
shy leaf
obsidian coyote
turbid oriole
#

:v ?

obsidian coyote
#

Trying to use the "minecraft:custom_components" component with both Beta APIs and HCF enabled will cause issues

obsidian coyote
lapis heart
distant tulip
amber granite
misty pivot
distant tulip
#

15000 char

shy leaf
#

yep thats what happened to me, but with nametags instead

lapis heart
obsidian coyote
# turbid oriole Scam.

Don't worry, the toggle has been removed in 1.21.20 so all you need to do is wait for stable release

amber granite
#

What are u cooking

lapis heart
distant tulip
turbid oriole
lapis heart
#

I think I explained it wrong 🤣

obsidian coyote
turbid oriole
lapis heart
distant tulip
lapis heart
distant tulip
#

it start to lag but let me see
those are 10 000 char

obsidian coyote
lapis heart
obsidian coyote
#

(both of these work) ```json
{
"minecraft:icon": "reforged:copper_pickaxe"
}

or
```json
{
  "minecraft:icon": {
    "textures": {
      "default": "reforged:copper_pickaxe"
    }
  }
}
turbid oriole
distant tulip
lapis heart
distant tulip
obsidian coyote
turbid oriole
#

How do I reduce the durability? Without losing the current state of the object.

#

There is no point in increasing the damage of the durability component.

lapis heart
turbid oriole
obsidian coyote
#

1.20.70 changelog

#

I think

turbid oriole
#

TnT I should check.

obsidian coyote
turbid oriole
#

The damage property of the durability component on itemStack objects.

turbid oriole
open urchin
#

you need to set the item

obsidian coyote
#

You'd have to set the item back

open urchin
#

with equippable.setEquipment or slot.setItem

turbid oriole
#

:'v And it doesn't remove the enchantments or anything?

obsidian coyote
#

Nope

turbid oriole
#

TnT okey

obsidian coyote
#

iirc if you use container.getSlot it should update without having to set it back

open urchin
#

slots dont let you get components, only ItemStacks

obsidian coyote
#

I thought they always did, huh

open urchin
#

you can change amount though

turbid oriole
#

Do the Source properties of the events return only one entity? They don't return a player?

amber granite
#

Returns the source entity

#

The entity which triggered the event

obsidian coyote
#

An entity can be a player

amber granite
#

Can be any entity also

turbid oriole
obsidian coyote
#

Mhm

open urchin
#

you can check with

if (source instanceof Player) {
  // source is player
}
turbid oriole
#

:'v I'll have to verify it on my own then.

amber granite
#

U can use type id also

#

There are more than one way

#

To do that

open urchin
#

but instanceof gives automatic type stuff so i find it better

amber granite
#

Yesh

#

Yeah

amber granite
#

import Player

open urchin
#

yes you need to

turbid oriole
#

Suspense mode.

#

I forgot a letter.

#

I'm hungry.

amber granite
#

Vrom vrom

turbid oriole
#

Recommend movies.

woven loom
#

anyone know whats the diffrence b.w getPlayers() vs getAllPlayers() without query

amber granite
#

Yes

obsidian coyote
turbid oriole
amber granite
#

getPlayers() has options

#

getAllPlayers() dosen't have

turbid oriole
#

One receives a filter parameter and the other nothing.

obsidian coyote
woven loom
#

yea why do we even have 2

turbid oriole
amber granite
#

Idk only players who has some tags

#

Included

turbid oriole
#

Filter function.

woven loom
#

query is optiomal

#

in getPlayers()

turbid oriole
amber granite
#

Yes

neat hound
#

I cannot get this to workjs import { MinecraftEntityTypes } from "@minecraft/vanilla-data";if I do not have it, MinecraftEntityTypes is undefined, if I do have it and TRY to throw in the dependency, it says ```
[Scripting][error]-Plugin [§cPreview§r: §6Beta§r: Test Space BP - 1.0.0] - failed to create context.

[Scripting][error]-Plugin [§cPreview§r: §6Beta§r: Test Space BP] - module [§cPreview§r: §6Beta§r: Test Space BP - 1.0.0] depends on unknown module [@minecraft/vanilla-data - 1.21.20].

[Scripting][error]-Plugin [§cPreview§r: §6Beta§r: Test Space BP - 1.0.0] - run failed, no runtime or context available.

obsidian coyote
woven loom
#

hmm

amber granite
turbid oriole
#

With iterators.

obsidian coyote
amber granite
#

getAllPlayers() give u all players that are connected to that world

obsidian coyote
turbid oriole
amber granite
obsidian coyote
# amber granite Yes

Their question was why do we have two despite them doing the same thing excluding queries

amber granite
#

Oh

amber granite
#

Yeah , they just can make the queries inside getAllPlayers()

#

Instead of making two methods

#

That s a dumb thing

#

That s weird

neat hound
woven loom
obsidian coyote
amber granite
#

vanilla-data needs to be compiled to js

obsidian coyote
#

It already has a bundled JS file ready inside the package

amber granite
#
  • u need to download it first
#

Because isn't included in the game

neat hound
#

The auto completion is working, maybe because I have the npm? download it from where

turbid oriole
turbid oriole
turbid oriole
amber granite
#

What are u talking about :T

neat hound
#

I have npm

turbid oriole
#

I, who am in cel, would only translate those packages and rush them to my script.

neat hound
#

I need @minecraft/vanilla-data

amber granite
neat hound
#

I mean I need it towork

amber granite
#

I mean where did u put it

turbid oriole
obsidian coyote
#

Right click on your scripts folder, then open in terminal

#

Run npm i @minecraft/vanilla-data

neat hound
amber granite
#

U didn't put it in script's file ?

obsidian coyote
amber granite
#

Did u use it directly from the game , i mean like server module ?

turbid oriole
obsidian coyote
turbid oriole
#

It's not a question of intellisense, it's a question of compatibility. Better convert to js and put them where they need to go.

turbid oriole
amber granite
#

There is already a js file called index.js

#

In vanilla module

turbid oriole
turbid oriole
obsidian coyote
amber granite
#

Tell her to put the
Index.js in scripts file

#

And use it from there

#

@neat hound

turbid oriole
#

:v we are the powerful of the server. XD

neat hound
turbid oriole
#

I lack power >:v

amber granite
#

vanilla-data

obsidian coyote
amber granite
#

Dosen't exist in the game

turbid oriole
#

Do you know where I can find people for a small project that I have with a graphic designer?

obsidian coyote
#

also you need to download it in your scripts folder using NPM

amber granite
#

U need to download it via npm

turbid oriole
neat hound
#

I ran that npm but it did not add any files to a folder that I can see

amber granite
#

Now

#

Go to the module

#

Copy the index.js

#

From vanilla-data

obsidian coyote
amber granite
#

Put it in script file

neat hound
#

Not sure it did it, it is talking about an audit

amber granite
#

Then

import { MinecraftEntityTypes } from "./index.js"
obsidian coyote
amber granite
#

I gtg :T

turbid oriole
#

Is Minecraft native with TypeScript?

#

Oh no. I get it.

turbid oriole
obsidian coyote
#

sorry?

amber granite
neat hound
amber granite
#

Please ma'am

#

Just copy index.js from vanilla-data module

#

Put it in ur scripts file

obsidian coyote
neat hound
#

What vanilla-data module.. where be this file on my computer

amber granite
#

Then change the import to :

import { MinecraftEntityTypes} from "./index" 
amber granite
#

U see that path

obsidian coyote
amber granite
glacial widget
#

put the full name with the id

feral minnow
#

its been a longgg time

neat hound
neat hound
glacial widget
obsidian coyote
#

Or you can create the file yourself and just make the content this {}

turbid oriole
#

Can I simulate breaking an object easily or will I have to play the sound and remove the object?

obsidian coyote
turbid oriole
#

Item

obsidian coyote
#

But what does sound have to do with an object?

#

Ah

#

Yeah, you could do that

turbid oriole
neat hound
obsidian coyote
#

Does importing the JS file work now?

neat hound
obsidian coyote
#

Wait wha-

feral minnow
#

hey

glacial widget
#
world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
    const {block, player, itemStack} = ev
    const tokens = {
        "minecraft:nether_wart": 100,
        "minecraft:nether_star": 200
    }
    const ores = ["minecraft:coal", "", ""]

    const money = world.scoreboard.getObjective("Money")

    if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){

        if (itemStack?.typeId in tokens) {
            const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand") 
            if (itemStack.amount === 1) hand.setItem()
            else hand.amount--
            player.addScore(player, tokens[itemStack.typeId])
        }

    }
})

Could someone help? itemStack is not defined why?

glacial widget
feral minnow
#
player.getComponent("inventory").container.getItem(player.selectedSlot)
glacial widget
#

still nothing at all

neat hound
feral minnow
#

try console.warn

obsidian coyote
glacial widget
#

and it works

#

but this does not run

if (itemStack?.typeId in tokens) {
                const hand = player.getComponent("inventory").container.getSlot(player.selectedSlot)
                if (itemStack.amount === 1) hand.setItem()
                else hand.amount--
                player.addScore(player, tokens[itemStack.typeId])
            }
feral minnow
#

its

#

{1,2,3,4}

glacial widget
#

{1,2,3,4} ?

obsidian coyote
feral minnow
#

what does this mean

itemStack?.typeId in tokens
amber granite
#

It s synatx to see if that property exist in an object or not

glacial widget
obsidian coyote
obsidian coyote
amber granite
#

in - includes prototype properties

feral minnow
#

you are using faceLocation instead of the itemStack

obsidian coyote
glacial widget
# feral minnow you are using faceLocation instead of the itemStack

    if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){
        console.warn("hello")
            if (itemStack?.typeId in tokens) {
                const equippable = player.getComponent("equippable");
                const hand = equippable.getEquipmentSlot("Mainhand") 
                if (itemStack.amount === 1) equippable.setEquipment("Mainhand")
                else hand.amount--
                money.addScore(player.scoreboardIdentity, tokens[itemStack.typeId])
              };
    }
})

Nope

amber granite
feral minnow
# glacial widget ```js if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 &...
world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
   // const {block, player, itemStack} = ev
    const itemStack = ev.itemStack
    const block = ev.block
    const tokens = {
        "minecraft:nether_wart": 100,
        "minecraft:nether_star": 200
    }
    const ores = ["minecraft:coal", "", ""]

    const money = world.scoreboard.getObjective("Money")

    if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){

        if (itemStack?.typeId in tokens) {
            const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand") 
            if (itemStack.amount === 1) hand.setItem()
            else hand.amount--
            player.addScore(player, tokens[itemStack.typeId])
        }

    }
})
obsidian coyote
amber granite
#

Not good

obsidian coyote
amber granite
#

What if that property was in constuctor prototype?

glacial widget
#

the file in imported to the main.js

amber granite
#

U can't detect it

glacial widget
#

i can detect the block and location

feral minnow
#
world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
   // const {block, player, itemStack} = ev
    const itemStack = player.getComponent("inventory").container.getItem(player.selectedSlot)
    const block = ev.block
    const tokens = {
        "minecraft:nether_wart": 100,
        "minecraft:nether_star": 200
    }
    const ores = ["minecraft:coal", "", ""]

    const money = world.scoreboard.getObjective("Money")

    if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){

        if (itemStack?.typeId in tokens) {
            const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand") 
            if (itemStack.amount === 1) hand.setItem()
            else hand.amount--
            player.addScore(player, tokens[itemStack.typeId])
        }

    }
})
#

dumbway

obsidian coyote
#

Don't think that would work

feral minnow
#

why

amber granite
obsidian coyote
amber granite
#
  • wrong
    hasOwnProperty
    Only exists on Object class
glacial widget
amber granite
neat hound
#

Okay, I am in business... now to test...

amber granite
#

Made with prototype

obsidian coyote
amber granite
obsidian coyote
amber granite
#

U can use
tokens[itemStack.typeId]
Instead of all that sh** 🤦🏻‍♂️

feral minnow
amber granite
#

What s the problem?

glacial widget
feral minnow
#

console.warn

glacial widget
feral minnow
#

oh

glacial widget
#

all the code works outside of this

if (itemStack?.typeId in tokens) {
            const hand = player.getComponent("equippable").getEquipmentSlot("Mainhand") 
            if (itemStack.amount === 1) hand.setItem()
            else hand.amount--
            player.addScore(player, tokens[itemStack.typeId])
        }
amber granite
#

That doesn't work ?

feral minnow
#

guys how do i disable timeout

glacial widget
#

i found another way of doing it which works but now i would need to get the vaule of the tokens from the objects

world.afterEvents.playerInteractWithBlock.subscribe((ev) =>{
    const {block, blockFace, faceLocation, itemStack, player} = ev
    const tokens = {
        "minecraft:nether_wart": 100,
        "minecraft:nether_star": 200
    }
    const ores = ["minecraft:coal", "", ""]

    const money = world.scoreboard.getObjective("Money")

    if(block.typeId == "minecraft:lime_stained_glass" && block.x == -17 && block.y == 176 && block.z == 32){
        console.warn("hello")
        player.runCommand(`/clear @s ${tokens[0]}`)
        money.addScore(player, tokens)
    }
})
amber granite
#

What s the problem !!!

feral minnow
#

kiro

#

how do i disable script itmeout

amber granite
feral minnow
#

what

glacial widget
amber granite
#

U must put the interval in a variable

glacial widget
amber granite
#

Use

#

tokens[itemStack.typeId]

neat hound
#

.. no idea that there are 1178 blocks

feral minnow
#

how do i disable watchdog

amber granite
#

Go to Creator setting in settings

#

U will see the watchdog slider put it in max value

amber granite
#

Or see if there is a toggle to stop it

feral minnow
#

i cant change anything

granite badger
amber granite
feral minnow
#

okay

#

this?

system.beforeEvents.watchdogTerminate.subscribe((ev) =>{
    ev.cancel = true
})
remote oyster
grand heart
#

how to clear all effects without run command?

glacial widget
#

is this how i detect mending on gear

system.runInterval((e) =>{
    for(const player of world.getAllPlayers()){
        mending = new EnchantmentType()
        const inventory = player.getComponent("inventory").container
        const item = inventory.getItem()
        const ench = item.getComponent("enchantable")
        const men = ench.hasEnchantment({ type: new EnchantmentType("mending"), level: 1})
        if(player.hasTag() !== "t1" && men){
            player.runCommand(`/clear @s ${men}`)
        }

    }
})
remote oyster
prisma shard
amber granite
prisma shard
glacial widget
#

some as the target selections in commands

prisma shard
#

what

glacial widget
prisma shard
#

uh i dont want to use commands

#

I meant scripting

glacial widget
#

yeah ik

#

so probably like this

#

player.location.dx == 1

remote oyster
prisma shard
amber granite
#
function chebyshevDistance(vector1, vector2) {
    let differenceX = Math.abs(vector1.x - vector2.x);
    let differenceZ = Math.abs(vector1.z - vector2.z);

    return Math.max(differenceX, differenceZ);
}

// Example usage
const vector1 = { x: 1, z: 2 };
const vector2 = { x: 4, z: 0 };

console.log(chebyshevDistance(vector1, vector2)); // Output: 3
remote oyster
# prisma shard How to get the "distance" between two vector3?
const playerLocation = player.location;
const blockLocation = block.location;

const distance = Math.sqrt(
    Math.pow(blockLocation.x - playerLocation.x, 2) +
    Math.pow(blockLocation.y - playerLocation.y, 2) +
    Math.pow(blockLocation.z - playerLocation.z, 2)
);

console.log(`Distance: ${distance}`);
prisma shard
#

to calculate the distance betwern two vector3

turbid oriole
prisma shard
#

Can you make it a function

#

..

turbid oriole
#

Do you like mathematics?

prisma shard
#

I don't want to use chevyshev distance as kiro

#

i want to do as VisualImpact did

turbid oriole
#

...Make a function that receives 2 objects with 3 attributes each.

amber granite
turbid oriole
#

Then you do the calculation and a return with the formula, Pythagorean theorem.

amber granite
#

Because it calculates the distance in grid area

#

And that games uses most of times

turbid oriole
#

I remembered that Mojang has a public library of mathematical utilities for working with vectors.

#

It is in npm attached to @minecraft

prisma shard
#
function distance(vector1, vector2) {
return Math.sqrt(
Math.pow(vector1.x - vector2.x, 2) +
    Math.pow(vector1.y - vector2.y, 2) +
    Math.pow(vector1.z - vector2.z, 2)
)
};
#

@remote oyster is this right?

#

I made a function using your method

amber granite
#

No

turbid oriole
amber granite
#

Y musn't be included

prisma shard
amber granite
#

If u want to calculate distance in 2D plane

prisma shard
#

vector3..…..

prisma shard
turbid oriole
amber granite
#

Ok i told u :T , what to do it s ur choice

amber granite
prisma shard
#

my function is for vec3

#

not vec2

amber granite
prisma shard
#

bro are you crazy

amber granite
#

If block's Y is different even if their x and z was the same

prisma shard
#

for example, if my code gets distance betwen x,z and x,z (from block to player)... And if i fly up from the block, it wont measure the distance....

amber granite
#

Y still included

#

And will give u some horrible calculations

prisma shard
amber granite
#

Bruh

amber granite
prisma shard
#

How is y not needed 😭

amber granite
#

Distance is calculated in 3D plane

#

So let s say u have two block in the same x and z

#

But their Y is different

#

As example block above other block

remote oyster
# amber granite

You include the Y coordinate if you want to calculate the distance in 3D space, and you ignore the Y coordinate if you want to calculate the distance in 2D space. So depending on what your goals are will depend on which one you may desire.

turbid oriole
amber granite
turbid oriole
#

By the way, I'm a math student, I can help.

amber granite
#

Good

amber granite
#

So he will come back later

#

And tell us why my code isn't working

#

Because he calculating distance in 3d but he is assuming that the distance in 2D space

turbid oriole
#

I returned. Make me a list of the boy's needs, be precise. I speak Spanish and I must translate, I want just one message.

#

The boy needed to measure the distance of two vectors, right? Now you need to measure the distance of two volumes?

amber granite
remote oyster
# amber granite But in that situation i don't think Y is useful

That depends on their goal. If they only want the horizontal difference between two points then 2D space is fine, but if they are wanting true straight-line distance between two points, where height matters, such as teleportation, projectiles, or vertical movements, then 3D space is necessary.

turbid oriole
#

It is called space metric.

amber granite
#

Only the horizontal one

remote oyster
amber granite
#

I said mostly

remote oyster
#

Mostly is still false. The majority here don't even know the difference let alone how to apply it correctly.

amber granite
#

Ok let him uses the 3D space and i bet that he will return again , and tell us why my script isn't working

turbid oriole
glacial widget
#

yes a maths class

remote oyster
amber granite
#

Ok :-: my bad

turbid oriole
amber granite
turbid oriole
#

I think we should have told you that you can measure the intersection of two volumes and also that you can measure radial and vector sectors. XD

amber granite
#

@prisma shard what are u trying to make ?

prisma shard
#

bruh you guys started a war lol

#

i just figured it out

#

so i dont need help now

#

calm down everyone

amber granite
#

Block distance? @prisma shard

#

I mean one block between them , two blocks etc... ?

distant tulip
#

Math.hypot()

wary edge
#

All could been avoided if people knew how to ask good questions

amber granite
#

Yeah :T

distant tulip
amber granite
#

Or the straight line distance

#

I don't think anyone would use the straight line distance, because it can cause some weird calculations

#

And results

#

Like distance between
{ x : 0 , y : 0 , z : 0 }
And
{ X : 64 , y : 70 , z : 64 }

#

114.42027792310242

distant tulip
#

i know?
that what hypot dose

amber granite
#

Yes

#

For that it not good to include y

distant tulip
#

bruh
no you have to

remote oyster
# amber granite I don't think anyone would use the straight line distance, because it can cause ...

I don't think you are fully understanding the difference between the two scenarios and how they can apply.

const player = world.getPlayers()[0];
const blockLocation = { x: 100, y: 64, z: 100 }; // Example block location

// Function to calculate 2D distance (ignoring the y coordinate)
function calculate2DDistance(point1, point2) {
    return Math.sqrt(
        Math.pow(point2.x - point1.x, 2) +
        Math.pow(point2.z - point1.z, 2)
    );
}

// Function to calculate 3D distance
function calculate3DDistance(point1, point2) {
    return Math.sqrt(
        Math.pow(point2.x - point1.x, 2) +
        Math.pow(point2.y - point1.y, 2) +
        Math.pow(point2.z - point1.z, 2)
    );
}

// Get the player's location
const playerLocation = player.location;

// Calculate the 2D and 3D distances between the player and the block
const distance2D = calculate2DDistance(playerLocation, blockLocation);
const distance3D = calculate3DDistance(playerLocation, blockLocation);

// Define maximum allowed distances
const maxDistance2D = 10;
const maxDistance3D = 15;

// Check if the player is within the allowed 2D distance
if (distance2D <= maxDistance2D) {
    console.log("Player is within the allowed 2D distance.");
} else {
    console.log("Player is too far away in 2D space.");
}

// Check if the player is within the allowed 3D distance
if (distance3D <= maxDistance3D) {
    console.log("Player is within the allowed 3D distance.");
} else {
    console.log("Player is too far away in 3D space.");
}

The 2D calculation is useful for horizontal range checks, such as detecting if players are near each other for PVP or interaction purposes.

The 3D calculation is crucial for vertical interactions, such as checking if a player can interact with blocks or entities at different heights. Such as determining the effective range of vertical traps, elevators, or in scenarios where altitude affects gameplay mechanics.

amber granite
amber granite
amber granite
remote oyster
#

Y included can also count for horizontal direction because it's 3D space.

amber granite
#

Yes but

remote oyster
#

It's application can vary depending on what it's needed for

amber granite
#

Yes

#

But let s say : someone want s to calculate distance between him and his home

#

He will never use the 3D space

#

And most used is horizontal 2D space

amber granite
#

Or maybe i m wrong

#

After all it doesn't worth it

remote oyster
# amber granite After all it doesn't worth it

Try using 2D calculation when monitoring pvp battles and see how that works out.

As I said before, the application varies. Your example shows that 2D would be best preferred if height is not a concern in relation to whether the home is below ground or in the sky.

However, there are other scenarios where if you do not utilize 3D calculations, you will erroneously handle the environment.

amber granite
#

What we must use

remote oyster
amber granite
#

ok

#

I feel dumb rn XD

misty pivot
#

is there a math function similar to math.clamp from molang? i want to make it so the summed value will be returned as 20 maximum

amber granite
#

math.clamp ?

#

U mean dosen't pass the limit ? Of 20 ?

granite badger
#
amber granite
#
function clamp(value, min, max) {
    return Math.max(Math.min(value, max), min);
}

// Usage
let value = 10;
let minVal = 5;
let maxVal = 15;
let clampedValue = clamp(value, minVal, maxVal);
console.log(clampedValue)
distant tulip
#

√((Ax-Bx)² + (Az-Bz)² + (Ay-By)²)

amber granite
#

Yes

distant tulip
#

you are using 2d space
a = √b²+c²

remote oyster
distant tulip
remote oyster
distant tulip
#

i use it for a lot tbh even some animations

halcyon phoenix
#

what yall tryna do?

halcyon phoenix
amber granite
misty pivot
#

how do i make a variable in the constructor of a class work for all of its methods, like

class ClassExample {
    constructor(entity) {
        //the entity
    }
    method1() {
        this.entity.kill()
    }
}```
subtle cove
#

constructor(entity) {
this.entity = entity
}

misty pivot
#

do i still have to use this in the other methods?

amber granite
#

I told u what this used for

misty pivot
#

yeah lmao i forget 😂

#

but for functions is it

this.myFunction = function() {
    ...
}```
amber granite
#

In class ?

amber granite
misty pivot
#

how would that look like?

amber granite
#

Ahhh

#

Use it inside it

#

Don't put it beside myfunction

misty pivot
#

particularly where inside?

amber granite
#

function() { this.idk }

misty pivot
#

ah i see, thanks

#

so it would look like this?

function myFunction() {
    this.idk
}```
amber granite
#

Yes

#

But idk must be inside the object

misty pivot
#

which object?

#

hold up

#

alright, yeah at this point im just guessing

amber granite
#

There is object and class

prisma shard
#
Math.sqrt(x * x + y * y + z * z);

And

Math.hypot(x, y, z);

It's the same, right?

#

@distant tulip

valid ice
valid ice
prisma shard
#

yeah your right

#

But which one should i use

valid ice
#

Doesn't really matter for minecraft use

#

whichever you prefer- I use hypot because it's easier to read

prisma shard
#

I just tested it

#

It's just a difference of decimal number

valid ice
#

That's just truncation error

#

Not a difference in method

prisma shard
#

Truncation error?

valid ice
#

yeh

prisma shard
#

alr

valid ice
#

Computer inaccuracies

#

Happens a lot, nothing to really be worried about for regular use

amber granite
#

Hey guys

#

Can i use Player class like that :

Player.myprop = { something : true } 
prisma shard
#

prototype

amber granite
#

I don't want to make prototype

prisma shard
#

idk

valid ice
#

yeh you can assign arbitrary properties to the player after runtime.

amber granite
valid ice
#

world.getPlayers().forEach(plr => plr.myprop = true)

amber granite
#

I can't make it into the class itself?

valid ice
#

myprop would be true for all players in that case

prisma shard
#

world.getPlayers()[0] and using forEach is the same?

valid ice
amber granite
#

Prototype*

valid ice
prisma shard
amber granite
#

Does it work tho ?

valid ice
tiny tartan
valid ice
#

as world.getPlayers() returns Player[]

prisma shard
#

oh oops

valid ice
amber granite
#

Nice

valid ice
#

Note that the stored data is deleted when the world is reloaded/loaded

#

But it does carry between sessions- aka if a connected player has data saved that way, then logs out and back in, it will stay.

amber granite
#

Thx u

valid ice
#

If the host relogs, though, it will be lost, as the world is being restarted when that happens

#

Just assume they will be deleted upon logout and you'll be fine

gaunt salmonBOT
#

Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Latest NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]

Preview Beta APIs NPM Types

npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
npm i @minecraft/[email protected]
amber granite
#

@valid ice it didn't work

valid ice
#

whar

amber granite
#

Wait a mib

#

A min

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

world.afterEvents.playerSpawn.subscribe(e => {
if ( !e.initialSpawn ) e.player.colorsTags = {
      black: { isAdded: player.getDynamicProperty("black") ?? false },
      blue: { isAdded: player.getDynamicProperty("blue") ?? false },
      cyan: { isAdded: player.getDynamicProperty("cyan") ?? false },
      green: { isAdded: player.getDynamicProperty("green") ?? false },
      orange: { isAdded: player.getDynamicProperty("orange") ?? false },
      pink: { isAdded: player.getDynamicProperty("pink") ?? false },
      purple: { isAdded: player.getDynamicProperty("purple") ?? false },
      red: { isAdded: player.getDynamicProperty("red") ?? false },
      white: { isAdded: player.getDynamicProperty("white") ?? false },
      yellow: { isAdded: player.getDynamicProperty("yellow") ?? false }
}
})
system.runTimeout(()=> {
system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    if (!player.colorsTags?.[getColorTag(player)]?.isAdded) {
      let ColorTag = getColorTag(player);
      teleportToTeam(player, ColorTag);
    }
  }
}); } , 20)
#

It tell me cannot access undefined of undefined

valid ice
amber granite
#

What ?

distant tulip
#

undefined of undefined lol

amber granite
#

Yes

fallow rivet
#

Will a mod using Minecraftserver 1.0.0 run smoothly on all versions?

valid ice
amber granite
#
function getColorTag(player) {
  for (const colorTag in player.colorsTags) {
    if (player.hasTag(colorTag)) return colorTag;
  }
}
valid ice
#

tbh I do not see why you would need to temporarily store such a large amount of information

amber granite
#

Need it to make switches

#

For something not suspicious

valid ice
#

Wouldn't it be better to just stringify an array of objects or something to save in a dynamic property?

amber granite
#

No

valid ice
#

Instead of separate properties for every color

amber granite
#

I tried it , isn't the best choice

valid ice
amber granite
#

So do u have a fix for that

#

It looks like game rejectes my object

valid ice
#

Not really no

amber granite
#

: (

#

So changing the Player.

valid ice
#

That's just a very... odd way of saving data..

valid ice
#

Oh lmao

spring dove
#

whats the best i can do to run a code whenever the world creates only

valid ice
#

World initialize event?

spring dove
#

Ok

spring dove
valid ice
#

Only when the world is loaded up

spring dove
#

mmm so if i relog to the same world it will load again

valid ice
#

Yep

spring dove
#

if thats the case i can just make it happen once with scoreboard

valid ice
#

You can set a dynamic property on the world to prevent it tho

subtle cove
#

Or world time

valid ice
#

if (world.getDynamicProperty('yes')) return;

spring dove
#

this test didnt worked me idk why

#

Ok it works but it has to have a little delay so it appears when the client completely logged in

subtle cove
#

@amber granite

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

world.afterEvents.playerSpawn.subscribe(e => {
    if (e.initialSpawn) e.player.colorsTags = ["black", "blue", "cyan", "green", "orange", "pink", "purple", "red", "white", "yellow"].reduce((o, k) => {
        o[k] = {
            get isAdded() {
                return e.player.getDymamicProperty(k)
            }
        }
        return o
    }, {}) 
})
system.runTimeout(()=> {
system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    if (!player.colorsTags?.[getColorTag(player)]?.isAdded) {
      let ColorTag = getColorTag(player);
      teleportToTeam(player, ColorTag);
    }
  }
}); } , 20)
inland merlin
#

Can someone lead me to a basic tutorial in using typescript instead for script api?

wary edge
iron jewel
#

you can't bypass this right?

sudden nest
#

Does dynamic import works in the latest stable version of scripting api?

Nvm, searched a keyword, and found out a "Yes" in the latest 1.21.0+

valid ice
iron jewel
#

wait a minnute

#

this is literally above 50

valid ice
#

separate lore lines

#

It takes and returns an array for a reason

iron jewel
#
           case "setlore":
                if (player.isOp()) {
                    let commandText = command.join(" ").trim();
                    let newLore = commandText.slice(8).trim().replace("\\n", "\n");
                    if (!newLore) {
                        player.sendMessage("§cLore text cannot be empty.");
                        break;
                    }            
                let inventory = player.getComponent("inventory").container;
                    let item = inventory.getItem(player.selectedSlotIndex);
                    if (item) {
                        item.setLore([newLore]);
                        inventory.setItem(player.selectedSlotIndex, item);                            player.sendMessage(`§gSet lore to ${newLore}`);                            } else {
                        player.sendMessage("§cYou need to hold an item to set it's lore.");
                    }
                }
            break;```
#

so I'd have to like

#

make it detect when you do \n

#

and make a new phyical line

valid ice
#

.split('\n')

#

'this is a testing string!'.split(' ') -> ['this', 'is', 'a', 'testing', 'string!'] Example of splitting on spaces

iron jewel
#

so what I'm understanding here

valid ice
#

Do note that there is a limit on lines as well- 20 max.

glacial widget
iron jewel
#

is that it's making it so you can have infinite lines, but each word must be <50 charaters each

glacial widget
iron jewel
#

ohhhhhh

#

I undestand

valid ice
#

I've been asking for it to be extended since forever now...

iron jewel
#

1000 charaters isn't that bad

valid ice
#

It's not, but color codes take up a decent chunk of mine

#

Even if it were increased to like, 50 lines 50 chars I'd be happy

#

I just want a lil more

#

just a pinch of extra lore

solar dagger
#

Is there a way for me to check what script event is causing a lot of lag?

solar dagger
#

Yes

wary edge
solar dagger
#

Is that an app or something?

wary edge
#

Or not...thanks slow internet

solar dagger
#

Okay thanks 👍

pallid portal
#

Is it possible to group custom components into one script file?

Say for example there is a block that does 3 things:

  • it can be interacted with
  • when placed, it does something every few ticks
  • it does something when it is broken

Can you make a custom component where these 3 components are in the same script.
Or do you have to make a script for each component separately?

wary edge
pallid portal
#

one block, 3 custom components.

wary edge
#

You should be able to

subtle cove
pallid portal
pale terrace
#

how can I modify a projectile damage?

#

I want to make any projectile double its damage after a certain player action

naive tinsel
#

is there a limit to structure blocks saves

pale terrace
naive tinsel
pale terrace
#

even if you use /structure load, will never load

#

and with world generation is worse, the limit is 48x48

last latch
#

How much is enough ram for a "waiting server". Just for people to join and "wait". I thought about 1gb but I think even the server won't handle. ||I am talking about BDS here||

last latch
#

Hmm if you say so

solar dagger
#

anybody know why the item interaction is not working while riding the entity? it works when the player is not riding

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

world.beforeEvents.playerInteractWithEntity.subscribe(
  ({ player, target, itemStack: item }) => {
    let event = system.run(() => {
      const isRiding =
        player.getComponent('minecraft:riding')?.entityRidingOn.target;
      if (isRiding) {
        const cooldownComp = item?.getComponent('minecraft:cooldown');
        if (item?.typeId === 'fs:melee_mm' && cooldownComp) {
          const remainingTime = cooldownComp.getCooldownTicksRemaining(player);
          if (remainingTime === 0) {
            cooldownComp.startCooldown(player);
            target.triggerEvent('fs:melee_ability');
            console.error(
              `${player.id} triggered the Melee Ability for ${target.typeId} Id: ${target.id}`
            );
          }
        }
      } else {
        console.error('Player is not riding target');
        system.clearRun(event);
      }
    });
  }
);
wary edge
#

Why did you just copy their message? @turbid oriole

solar dagger
#

xD

#

i was looking at it too

wary edge
wary edge
solar dagger
turbid oriole
solar dagger
#

i have the console errors there :/

#

it explains itself really

#

it's just an interaction event bud, nothing huge

wary edge
#

@turbid orioleDude, don't be a dumbass please

turbid oriole
turbid oriole
wary edge
#

Anyways, @solar dagger could you try my suggestion? playerIntearctwith block? I have a feeling it might be the riding entity interfering since you said the event works if you're not riding an entity. Maybe also just put console.warn or sendMessage in the first line before the system.run?

turbid oriole
#

The Wei uses cooldownComp in the condition of an if, it is a component object.

#

When I did that by accident it failed me. It only works in case of undefined but I don't know how to declare true.

solar dagger
solar dagger
turbid oriole
#

cooldownComp !== undefined.

solar dagger
#

Uh I really don't think that's the issue

#

But ok

turbid oriole
#

:v I haven't tried it completely but you're right.

#

When in doubt I retire to sleep.

wary edge
#

yeah pro tip...don't help someone if you yourself don't know it either

#

It's rather annoying

turbid oriole
wary edge
#

This is my final warning

turbid oriole
turbid oriole
#

I have to go do something, I'll be back with the answer.

wise crown
turbid oriole
turbid oriole
#

I'm not looking forward to it, that's life daddy.

dusky cipher
#

😭i was going to ask a question but i think i’ll pass after seeing that