#Script API General

1 messages · Page 42 of 1

gusty bramble
#

What’s up here?


import { system } from '@minecraft/server';
import extension from 'config';
import ArgumentParser from 'lib/canopy/ArgumentParser';
import { ItemSummonCommandCallback } from 'src/commands/ItemSummonCommand';

system.afterEvents.scrpitEventReceive.subscribe((event) => {
    if (event.id !== 'storageutilities:itemsummon') return;
    const sender = getSource(event);
    if (sender === null) return;
    if (!extension.getRuleValue('StorageUtilites')) return sender.sendMessage('§cThe StorageUtilites rule is disab');
    const [ item, amount, x, y, z ]= ArgumentParser.parseArgs(event.message);
    const args = { item, amount, x, y, z };
    for (const key in args) {
        if (args[key] === undefined) {
            args[key] = null;
        }
    }
    ItemSummonCommand(sender, args);
});
warm mason
remote oyster
#

Got to really appreciate typos lol.

gusty bramble
#

I’m stupid

#

I mean that’s at least something

wheat condor
#

is there alredy a world edit mod that has a full preview of what you re copyin g like all blocks?

coral ermine
#

the function is fine it working with itemUseOn but not working with playerPlaceBlock

past blaze
#

#old-editor

wheat condor
past blaze
#

Because editor mode has that

#

I don't think WorldEdit itself even has a paste preview

wheat condor
past blaze
#

In fact you can access it from the launcher

wheat condor
past blaze
wheat condor
#

yeah

#

its on creator tools

past blaze
#

Well then, check out the new "Creator Tools" tab in the launcher

wheat condor
#

is it new?

past blaze
#

Editor mode has been in development for a while

wheat condor
#

couse i was trying to create a world edit that has the same as java and better i was trying to recreate something like fortnite creative phone

#

with prefabs of minecraft structures

simple arch
#

How can I have NPCs/player have custom slim skins

#

Using Server UI

coral ermine
astral quarry
#

Moved my post, nvm.

simple arch
patent tapir
#

Is it possible to use Infinity as a number in player.addEffect

slow walrus
#

no

patent tapir
#

..bruh

#

Is there any way to make an infinite effect (not using obscenely large numbers or really numbers at all)

slow walrus
#

use a runCommand

#

its not supported in scripts yet

patent tapir
#

Oh ok, then can I use ${ (scoreboard value) - 1 } in the runCommand

#

Would that work?

#

I’ll just try it

#

I’m in the world right now and the pack in in development folder

patent tapir
#

Ok

#

player.runCommand(`effect @s speed infinite ${speedLevel - 1} true`)

#

Cool

#

I wanted to reduce unnecessary load, so I added extra logic that’s only supposed to run when the player doesn’t have haste here, why isn’t it working?player.getEffects().includes("haste") == true ? player.runCommand(`effect @s haste infinite ${hasteLevel - 1} true`) : null

#

Oh

#

I literally just now see the issue

#

Anyway is there a way to NOT run anything if the logic returns true?

#

Right now I just have it set to : null

#

Idk if that works tho

distant tulip
#

if statement...

patent tapir
#

Ffine

distant tulip
#

it is best if you only use conditional ternary operator when assigning a value to a variable conditionally
const v = x?y:z

patent tapir
#

Yeahh

#

Probably is

#

I like the look of short code because my adhd brain likes it

#

So I just try to shorten my code as much as possible lol

distant tulip
#

yeah, i can relate

round bone
#

But as your friend said: it's better to use if statement

patent tapir
#

I did

#

I already had an if statement to check if they even had the point anyway

#

So I just && on them

#

Right now I’m working on making sure wind charges don’t get button abused again

#

Or, tp buttons don’t get wind charge abused

round bone
#

Add some cooldown checks

patent tapir
#

Why cooldown checks

distant tulip
# patent tapir ?

idk if this is what he meant but
if time left for the effect is 10 ticks for example, and you are using interval with 80 tick delay the effect will run out before the next check

round bone
#

Won't get abused cooldown

patent tapir
#

It already gives the effect immediately back to the person if they have effectsScore > 0 AND they don’t have the effect

#

The only time that would happen is if they just bought the effectScore point or they died

#

Because the effect is infinite

gusty bramble
#
import * as mc from '@minecraft/server'
import { ItemStack } from '@minecraft/server'
import {Command} from 'lib/canopy/CanopyExtension';
import  extension from 'config'
const ItemSummonCommand = new Command({
    name: 'itemsummon',
    description: 'A command to summon any items from nothing',
    usage: 'itemsummon [item] [amount] [location]',
    callback: ItemSummonCommandCallback,
    args: [
      { type: 'string|number', name: 'item' },
      { type: 'number', name: 'amount' },
      { type: 'number', name: 'x' },
      { type: 'number', name: 'y' },
      { type: 'number', name: 'z' },
    ],
    contingentRules: ['StorageUtilities'],
    adminOnly: false,
    helpEntries: [
    ],
    helpHidden: false
});
extension.addCommand(ItemSummonCommand);

function ItemSummonCommandCallback(sender, args){
    let { item, amount, x, y, z } = args;
    const location = {x: x, y: y, z:z}
    sender.dimension.spawnItem(new ItemStack(item, amount), location);
    itemEntity.clearVerocity();
};

export { ItemSummonCommandCallback }

[Scripting][error]-TypeError: cannot read property 'dimension' of undefined at ItemSummonCommandCallback (src/commands/ItemSummonCommand.js:28)
at <anonymous> (src/scriptevents/ItemSummonCommand.js:18)

i get this error when I run this with a script event

#

I’m aware the issue is the sender.dimension part but how can I replace it without messing up the script when typed in chat normal (not as a script event)

tawny jungle
#

how can i clone an item but keep the data of said item after reloading?

tawny jungle
#

i need itemStack.clone to copy nbt data from a book, but i am moving that data out of the original function into a map, then calling the map to then use the data.

export function funcBookFilled(player, block, itemStack) {
    const playerMainHandSlot = player.getComponent("equippable").getEquipment("Mainhand");
    const clonedBook = player.getComponent("equippable").getEquipment("Mainhand")?.clone();
    const bookFilled = block.permutation?.getState("sci:book_filled")
};
export function funcBookBreak(hitBlock, ItemStack, damagingEntity) {
    const clonedBook = clonedBookMap.get('clonedBook')
    const bookFilled = hitBlock.permutation?.getState("sci:book_filled")
    if (hitBlock?.typeId === "sci:lectern_mini" && bookFilled === true) {
        hitBlock.dimension.spawnItem(clonedBook, hitBlock.center())
        hitBlock.setPermutation(hitBlock.permutation.withState("sci:book_filled", false));
    }
}```
#

the problem is after reloading the map data is gone

#

is there a way around this?

dim tusk
#

Since /reload or restarting the world delete all stored datas inside of objects, maps or other things

#

And you definitely can't store it on dynamic property

tawny jungle
#

i see

#

you got some documentation for making a container?

patent tapir
#

Can someone please tell me why no matter what button I push, as long as it’s defined as a vector3, it iterates through every single case statement and teleports me to 1000, 64, 1000?

#

I first tried to compare the data.block.location directly to the defined vectors but that didnt work so I thought only comparing one value would help but that still didnt work

wary edge
#

You dont have break.

patent tapir
#

Oh…

dim tusk
patent tapir
#

Wow I’m so dumb

tawny jungle
patent tapir
#

So I can’t compare the entire vector to another entire vector, that’s dissatisfying

#

But I can just compare the x values

patent tapir
#

If I do a switch statement to check the data.block.location I can’t just use case (vector3)

#

Am I wrong?

distant tulip
#

ah, no you can't directly
make a function that compare them and call it there

patent tapir
#

Uh

#

Do case values accept true/false though?

#

When I’m not comparing for true/false

distant tulip
#

in switch?

patent tapir
distant tulip
#

they do

patent tapir
#

Huh, ok

distant tulip
#

switch(value){
case true: //...
case false: /...
}

patent tapir
#

BIIIIG problem there buddy

#

I have 10 different locations I need to check.

#

I whipped up a function to return true/false but now I don’t think it’ll work

#
  if (vector1.x == vector2.x && vector1.y == vector2.y && vector1.z == vector2.z) return true
  return false
}```
#

I’d have to use absurd amounts of if/else statements if I were to do that

distant tulip
#

switch is a bad idea for that anyway

patent tapir
distant tulip
patent tapir
distant tulip
patent tapir
#

Due to this converation though I assume the only option I have is to write out WAYY too many if/else statements

#

Unless I wanna do some tomfoolery with iteration and for loops, which I quite frankly don’t want to do

#

-# (myself, at least)

distant tulip
#

make an array
[
{button:vec3, tpTo:vec3},
{button:vec3, tpTo:vec3},
{button:vec3, tpTo:vec3},
{button:vec3, tpTo:vec3},
]
and find the right tpTo vector

patent tapir
#

Oh boy.

tawny jungle
distant tulip
patent tapir
patent tapir
distant tulip
distant tulip
# patent tapir That’s something i don’t know how to do
const buttonMap = new Map()

// examples
buttonMap.set(JSON.stringify({ x: 1, y: 2, z: 3 }), { x: 10, y: 20, z: 30 })
buttonMap.set(JSON.stringify({ x: 4, y: 5, z: 6 }), { x: 40, y: 50, z: 60 })
buttonMap.set(JSON.stringify({ x: 7, y: 8, z: 9 }), { x: 70, y: 80, z: 90 })

function handleButtonPress(location) {
  const key = JSON.stringify(location)
  if (buttonMap.has(key)) {
    const tpTo = buttonMap.get(key)
    console.warn(`Teleporting to: ${JSON.stringify(tpTo)}`)
    //...
  } else {
    console.warn('No matching button found.')
  }
}
patent tapir
#

Making the array right now

#

Oh.

patent tapir
distant tulip
#

yeah lol

#

maybe do

const buttons = [
    { button: { x: 1, y: 2, z: 3 }, tpTo: { x: 10, y: 20, z: 30 } },
    { button: { x: 4, y: 5, z: 6 }, tpTo: { x: 40, y: 50, z: 60 } },
    { button: { x: 7, y: 8, z: 9 }, tpTo: { x: 70, y: 80, z: 90 } },
]
const buttonMap = new Map(
    buttons.map(({ button, tpTo }) => [JSON.stringify(button), tpTo])
)
gusty bramble
#

If so how would I go about that?

patent tapir
distant tulip
distant tulip
gusty bramble
# distant tulip sure use world.getDimension(id)

Could I possibly do it so the player inputs the dimension manually

(Basically replace the “sender.dimension.spawnItem” with an input like I have for “item”, “amount”, “x”, “y”, “z”)

#

So it would be

[ item ] [ amount ] [ dimension ] [ x y z ]

patent tapir
#

I just finished creating the array for button vectors and tpTo vectors

#

What now

patent tapir
#

It’s making an array, out of an array

#

It isn’t achieving what i sought to achieve

#

I literally do not even understand how map works

gusty bramble
distant tulip
gusty bramble
#

Oh ok

distant tulip
patent tapir
#

I’m trying to actually tp the player on button push, this really doesn’t seem to actually help towards that goal

gusty bramble
# distant tulip yeah just replace the id with player input

Sorry if I’m not understanding but do you mean something like this?

import * as mc from '@minecraft/server'
import { ItemStack } from '@minecraft/server'
import {Command} from 'lib/canopy/CanopyExtension';
import  extension from 'config'
const ItemSummonCommand = new Command({
    name: 'itemsummon',
    description: 'A command to summon any items from nothing',
    usage: 'itemsummon [item] [amount] [location]',
    callback: ItemSummonCommandCallback,
    args: [
      { type: 'string|number', name: 'item' },
      { type: 'number', name: 'amount' },
      { type: 'number', name: 'x' },
      { type: 'number', name: 'y' },
      { type: 'number', name: 'z' },
      { type: 'string|number', name: 'dimension' },
    ],
    contingentRules: ['StorageUtilities'],
    adminOnly: false,
    helpEntries: [
    ],
    helpHidden: false
});
extension.addCommand(ItemSummonCommand);

function ItemSummonCommandCallback(sender, args){
    let { item, amount, dimension, x, y, z } = args;
    const location = {x: x, y: y, z:z}
    world.getDimension(dimension).spawnItem(new ItemStack(item, amount), location);
    itemEntity.clearVerocity();
};

export { ItemSummonCommandCallback }
distant tulip
gusty bramble
#

I don’t know how to do that ;-; I’m actually awful at this

patent tapir
#

I keep thinking I’m getting better at js and then stuff like this happens -.-

dim tusk
patent tapir
#

You know what, I put 1% of my brainpower into this and came up with a for loop that should work

#
    if (compareVectors(buttons[i].button, data.block.location) == true) {
      pusher.teleport(buttons[i].tpTo)
      break
    }
  }```
dim tusk
#

You just put it in a map for easy changing of locations

dim tusk
gusty bramble
dim tusk
gusty bramble
#

What does that mean?

dim tusk
#

What part that doesn't work at all?

gusty bramble
#

One sec

dim tusk
gusty bramble
patent tapir
# gusty bramble

Well for your line 29 the dimension variable didn’t convert into a string correctly

#

So that’s an issue with the variable definition

#

Might be that you’re missing () after .stringify

#

Or something else

patent tapir
patent tapir
#

I have no idea how map’s work.

#

I just want the person who pushed the button to get tp’ed instead of the nearest player.

#

I just figured it out..

#
    data.source.teleport(buttons.find((btn => btn.button.x == data.block.location.x && btn.button.y == data.block.location.y && btn.button.z == data.block.location.z == true)).tpTo)
  }```
#

That was all I needed

dim tusk
#

Lmao.... Kinda annoying to look at but okay

patent tapir
#

Why

distant tulip
#

anyway i gtg to sleep

patent tapir
#

I literally have no idea how to use maps

#

Stop telling me to use maps without telling me how to use maps

cold grove
#

you dont have google?

cold grove
#

he already searched the docs for you

dim tusk
#
const buttons = [
    { button: { x: 1, y: 2, z: 3 }, tpTo: { x: 10, y: 20, z: 30 } },
    { button: { x: 4, y: 5, z: 6 }, tpTo: { x: 40, y: 50, z: 60 } },
    { button: { x: 7, y: 8, z: 9 }, tpTo: { x: 70, y: 80, z: 90 } },
]
const buttonMap = new Map(buttons.map(({ button, tpTo }) => [JSON.stringify(button), tpTo]));

world.afterEvents.buttonPush.subscribe(({ block, source }) => {
    const tpTo = buttonMap.get(block.location);
    if (tpTo) source.teleport(tpTo);
})
patent tapir
#

God I hate the docs

patent tapir
#

It’s so hard for me to get anything useful for my adhd brain from there

cold grove
dim tusk
dim tusk
distant tulip
dim tusk
wary edge
#

If you're on Brave you can turn on Speedreader on Mozilaa.

dim tusk
#

And thinking of it... I don't need to stringify it 😭

distant tulip
#

same with arrays

patent tapir
patent tapir
dim tusk
dim tusk
cold grove
dim tusk
distant tulip
simple zodiac
#

I think you actually can use references as a key for Maps. Just gotta make sure to pass exactly that reference to retrieve the value

distant tulip
#

not in that sense at least

#

yeah you can for example use player obj reference as key

subtle cove
#
map.get(bloc)
distant tulip
#

but in his case you can't get a vector3 and get the value

tight plume
#

How do i get weather in stable? Currently getWeather() is in beta.

dim tusk
#

Maybe you could try weatherChange to get the new or previous weather

#

This auto correct sucks

distant tulip
dim tusk
distant tulip
#

change it and change it back using previousWeather

dim tusk
#

Just use before events?

tight plume
dim tusk
#

It only triggers when the weather changes unlike the getWeather it will give you the current weather any time

patent tapir
#

Why are maps all high and mighty when that doesn’t even work

dim tusk
distant tulip
patent tapir
dim tusk
subtle cove
dim tusk
patent tapir
#


  const tpTo = buttonMap.get(data.block.location);
  if (tpTo) data.source.teleport(tpTo);```
subtle cove
#

Depends where ur efficient with actually

gusty bramble
patent tapir
#

Also why do you people ALWAYS seem to use (block, source) instead of (data)

#

(block, source) DOESNT WORK

dim tusk
distant tulip
dim tusk
#

And wtf you mean doesn't work 😭😭

subtle cove
dim tusk
#

It does work it's a you problem, always use that and I have no problem at all

patent tapir
dim tusk
subtle cove
#

Keys were string, so...

patent tapir
#

It’s the same code for everyone.

dim tusk
patent tapir
#

“Cannot read property of undefined”, it says

dim tusk
#
world.afterEvents.playerInteractWithBlock.subscribe(({ block, player }) => {

});```
patent tapir
#

Oh sorry wrong error

distant tulip
patent tapir
#

Have to use eventData and data

dim tusk
#

It works for me 😭😭😭

patent tapir
#

Then why doesn’t it work for me?

dim tusk
#

Wadahell you are doing something wrong that's why

patent tapir
#

Minecraft throws errors

dim tusk
#

Srnd the code

#

Can't help you when we just imagine here 😭

subtle cove
patent tapir
#

It’s literally the same code as everything else except there’s “data” at the start of every event value and it’s “data” instead of “block, source”

#

If I do the extended values from the subscribe Minecraft hates me

subtle cove
#

Uhh, get the block.location from somewhere

patent tapir
dim tusk
#

If not read docs first then come back

patent tapir
#

Ugh

dim tusk
#

Nah jk

patent tapir
#

The doc’s search function DOESNT EVEN WORK THAT WELL WTF

distant tulip
patent tapir
#

I’m looking for a specific element and the results are from completely different pages

tight plume
dim tusk
#

Umm it's a js built thing not a minecraft thing knly

dim tusk
distant tulip
dim tusk
#

Man I'm dead ☠️

pale terrace
#

how can I get crafting slots in inventory?

subtle cove
#

Nuh uh

dim tusk
#

Crafting slots aren't inventory that's why when you close it it returns to your inventory

patent tapir
#

IT DOESNT EVEN THROW ERRORS

dim tusk
#

Who wants unreadable codes? At least for a bit...

world.afterEvents.playerBreakBlock.subscribe(({ player, brokenBlockPermutation, itemStackBeforeBreak, itemStackAfterBreak }) => {
    const stats = JSON.parse(player.getDynamicProperty('stats') || '{}');
    stats['minecraft:mined'][brokenBlockPermutation.type.id] = (stats['minecraft:mined'][brokenBlockPermutation.type.id] || 0) + 1;

    if (itemStackBeforeBreak) {
        const durabBefore = itemStackBeforeBreak?.getComponent('durability');
        const durabAfter = itemStackAfterBreak?.getComponent('durability');

        if (durabBefore) {
            if (!itemStackAfterBreak || itemStackAfterBreak.typeId !== itemStackBeforeBreak.typeId || !itemStackAfterBreak.hasComponent('durability')) stats['minecraft:broken'][itemStackBeforeBreak.typeId] = (stats['minecraft:broken'][itemStackBeforeBreak.typeId] || 0) + 1, console.error('Broke Item');
            else if (durabAfter?.damage > durabBefore?.damage) stats['minecraft:used'][itemStackBeforeBreak.typeId] = (stats['minecraft:broken'][itemStackBeforeBreak.typeId] || 0) + 1, console.error('Use Item');
        }
    }

    player.setDynamicProperty('stats', JSON.stringify(stats));
});```
patent tapir
#
  if (vector1.x == vector2.x && vector1.y == vector2.y && vector1.z == vector2.z) return true
  return false
}
world.afterEvents.buttonPush.subscribe((data) => {
  const pusher = data.source
  const buttons = [
    {
      button: {
        x: -20,
        y: 65,
        z: -19
      },
      tpTo: {
        x: -1000,
        y: 64,
        z: 1000
      }
    },
    {
      button: {
        x: -19,
        y: 65,
        z: -20
      },
      tpTo: {
        x: -250,
        y: 64,
        z: 0
      }
    },
    {
      button: {
        x: -17,
        y: 65,
        z: -20
      },
      tpTo: {
        x: 0,
        y: 64,
        z: 250
      }
    },
    {
      button: {
        x: -15,
        y: 65,
        z: -20
      },
      tpTo: {
        x: 250,
        y: 64,
        z: 250
      }
    },
    {
      button: {
        x: -15,
        y: 65,
        z: -20
      },
      tpTo: {
        x: 250,
        y: 64,
        z: -250
      }
    },
    {
      button: {
        x: 13,
        y: 65,
        z: -20
      },
      tpTo: {
        x: 250,
        y: 64,
        z: 0
      }
    },
    {
      button: {
        x: 15,
        y: 65,
        z: -20
      },
      tpTo: {
        x: 0,
        y: 64,
        z: -250
      }
    },
    {
      button: {
        x: 17,
        y: 65,
        z: -20
      },
      tpTo: {
        x: 0,
        y: 50,
        z: 0
      }
    },
    {
      button: {
        x: 19,
        y: 65,
        z: -20
      },
      tpTo: {
        x: -250,
        y: 64,
        z: -250
      }
    },
    {
      button: {
        x: 20,
        y: 65,
        z: -19
      },
      tpTo: {
        x: 1000,
        y: 64,
        z: 1000
      }
    }
  ]

  const buttonMap = new Map(buttons.map(({ button, tpTo }) => [JSON.stringify(button), tpTo]));
  const tpTo = buttonMap.get(JSON.stringify(data.block.location))
  if (tpTo) data.source.teleport(tpTo);
})```
patent tapir
#

I JUST WANT IT TO WORK

#

AHHHH

dim tusk
dim tusk
#

I ain't commenting because if I do... I'll be dead asf

distant tulip
#

that formatting is the reason i compact all my code to one line

dim tusk
#

Anyways unrelated but tomorrow is our Christmas party

patent tapir
#

IMMA GO BACK TO USING MY SLOW AF IF STATEMENTS

#

IF YALL DONT TELL ME HOW TO FIX

subtle cove
#

u should practice variable printing

pale terrace
patent tapir
subtle cove
#

sendMessage every declared variable to understand the code flow

patent tapir
#

Reading variable values like that hurts my brain so much

onyx lantern
#

how can I detect what block the player is holding in mainhand?

subtle cove
#

Like

const loc = data.block
console.warn(loc)//delete this afterwards 
world.sendMessage(JSON.stringify(loc))//delete this afterwards 
if (stuff....){
}```
patent tapir
subtle cove
#

Nice

#

Now, guess what to fix

tight plume
#

dude read error stacks

patent tapir
patent tapir
distant tulip
patent tapir
#

DOES IT MATTER IF I USE CONST/LET/VAR INTERGANABLY

subtle cove
#

Nuh uh

patent tapir
#

Ok nice

subtle cove
#

Only matters when u go dynamic with ur variable pool

patent tapir
#

What’s the significance

subtle cove
#

Teach how to debug...

dim tusk
#

Btw the xyz are flip that's why

distant tulip
#

-# script-admin channel

subtle cove
#

Acknowledge errors like feedback...

patent tapir
#

Ok but why doesn’t this work const buttonMap = new Map(buttons.map(({ button, tpTo }) => [JSON.stringify(button), tpTo])); const tpTo = buttonMap.get(JSON.stringify(data.block.location)) if (tpTo) data.source.teleport(tpTo);

tight plume
dim tusk
#
const buttons = [
    { button: { z: 67, y: 70, x: 154 }, tpTo: { x: 10, y: 20, z: 30 } },
    { button: { z: 6, y: 5, x: 4 }, tpTo: { x: 40, y: 50, z: 60 } },
    { button: { z: 9, y: 8, x: 7 }, tpTo: { x: 70, y: 80, z: 90 } },
]
const buttonMap = new Map(buttons.map(({ button, tpTo }) => [JSON.stringify(button), tpTo]));

world.afterEvents.buttonPush.subscribe(({ block, source }) => {
    const tpTo = buttonMap.get(JSON.stringify(block.location));
    if (tpTo) source.teleport(tpTo);
});```
#

Hey @patent tapir majesty here you go

#

When you put locations make sure you put it on zyx not xyz

patent tapir
#

I really have to flip every single x/y/z value

distant tulip
#

ask ai to do it

dim tusk
#

I just peed and I remember that getting location for the block it's flipped in most cases

patent tapir
dim tusk
distant tulip
patent tapir
#

I’m getting so tired of how much I need to figure out with some stupid code.

dim tusk
#

-# not sure

dim tusk
dim tusk
subtle cove
#

flipped xyz peepoNotes emoji_18

#

Letz play with dat laterz

dim tusk
#

I spend 3 minutes of my life with these 5 lines of code ughh
-# not fuckin worth it

patent tapir
#

FINALLY IT’S DONE I CAN GO BACK TO USING COMMAND BLOCKS FOR A BIT HBAGSUVDYTFTYSDGYGBFUYWTVNDST&UDGVYTUWE

dim tusk
#

Did it work?

dim tusk
patent tapir
#

Ok but seriously, why doesn’t data.cancel work in TWO FILES of mine```import { world } from "@minecraft/server"

world.beforeEvents.effectAdd.subscribe((eventData) => {
const entity = eventData.entity.typeId
if (entity == "minecraft:wandering_trader") {
eventData.cancel = true
}
})```

#

Ok well that’s dumb first of all

#

I did effect add instead of entity spawn

#

Incredibly stupid of me

#

But the other file is definitely chatSend and data.cancel doesn’t work

dim tusk
#
world.beforeEvents.chatSend.subscribe(ev => {
   if (ev.message === '!test') {
      ev.cancel = true;
   }
});```
#

This works idk why it's not working for you

distant tulip
patent tapir
#
import { world, system } from "@minecraft/server";

const ascendPos = { x: 9999.5, y: 99, z: 9999.5 };
const lookAtPos = { x: 10003.5, y: 99.5, z: 9999.5 };

const netheriteArmor = [
  "minecraft:netherite_helmet",
  "minecraft:netherite_chestplate",
  "minecraft:netherite_leggings",
  "minecraft:netherite_boots",
];

function hasFullArmor(player, armor) {
  const inventory = player.getComponent('inventory').container;
  const foundArmor = new Set();
  for (let i = 0; i < inventory.size; i++) {
    const item = inventory.getItem(i);
    if (item && armor.includes(item.typeId)) {
      foundArmor.add(item.typeId);
    }
  }

  return armor.every(piece => foundArmor.has(piece));
}

function getScore(player, objName) {
  const obj = world.scoreboard.getObjective(objName);
  return obj ? obj.getScore(player) || 0 : 0;
}

world.beforeEvents.chatSend.subscribe((data) => {
  const player = data.sender;
  const msg = data.message.trim();

  if (msg.toLowerCase() === "!ascend") {
    data.cancel = true;


    const coins = getScore(player, "coins");
    const kills = getScore(player, "kills");

    if (coins >= 75000 && kills >= 20 && hasFullArmor(data.sender, netheriteArmor)) {
      system.run(() => {
        player.teleport(ascendPos, { facingLocation: lookAtPos });
      });
    } else {
      system.run(() => {
        player.onScreenDisplay.setTitle({
          rawtext: [{ text: "§5You can't\nascend yet" }],
        });
      });
    }
  }
});```
#

Too bad

#

data.cancel doesn’t work

dim tusk
#

The code is running right just the message isn't cancelled

#

First of all can you code block your code so it can be seen better? Like this

```js
// codes
```

dim tusk
patent tapir
#

It does nothing to me

#

Looks the same

#

Acts the same

dim tusk
#

Just try it....

patent tapir
#
//sjajdsajdjadjajsdjads
#

Yep

#

Looks the same

#

Exaaaact same

patent tapir
subtle cove
#

Kewl

patent tapir
#

What does it do???

distant tulip
#

mobile?

patent tapir
distant tulip
patent tapir
#

GEEZ

dim tusk
#

This is what I see rn

patent tapir
patent tapir
dim tusk
patent tapir
#

now im on the website

#

does it look the same?

dim tusk
#
world.beforeEvents.chatSend.subscribe(ev => {
   if (ev.message === '!test') {
      ev.cancel = true;
   }
});```

Can you try this @patent tapir and send in the chat *!test* if the message still sends
patent tapir
#

NO

#

NO IT DOESNT

gusty bramble
patent tapir
#

i gtg eat dinner ill be back later

#

but nobody will miss me

#

beacause im an a-hole

#

right?

dim tusk
patent tapir
dim tusk
#

But at least in a good way

distant tulip
#

huh

subtle cove
#

I see progress, it's kewl

dim tusk
#

Sorry my bad, it's a Filipino joke 😔

distant tulip
#

whats with that react emoji

#

remember me is Filipino
that sus

dim tusk
subtle cove
#

🧼blush1

distant tulip
#

lol

dim tusk
#

potan- nvm

tight plume
dim tusk
#

Another fellow Filipino

#

Lezz goo

#

I'm not alone here.

distant tulip
#

this is flipping crazy

subtle cove
#

Lez dominate

dim tusk
#

Lmao, I'm not sure when my nitro expired

#

Imma check if I still have it

patent tapir
tight plume
#

Is getTopmostBlock some sort of broken? Why is it returning the block below instead of block above?

const blockAbove = dim.getTopmostBlock(source.location, source.location.y);
console.warn(blockAbove.typeId);

It returns grass even though theres no grass above me

dim tusk
#

I checked the dos and i saw the the first argument doesn't accept the Y only XZ then the second argument is the height which you put the location of the player.

#

that's why it chcked downward i guess?

#

you could try just use getBlock() but i'm not sure what's your plan tho

#
const block = player.dimension.getBlock(player.location);
console.error(block?.above()?.typeId)```
wary edge
#

I'm confused. What do you expect the function to return?

tight plume
tight plume
wary edge
#

Its the starting height to search it from.

tight plume
wary edge
tight plume
wary edge
#

Ok, what does that mean? Just check if the returned block y val is below the players.

tight plume
tight plume
# wary edge .

I don't understand how getTopmostBlock works, there is a leaves above me, why did it not return leaves?

tight plume
patent tapir
#

Hey uh

#

Why

#

Why is it

#

That the instant another player joins my world

#

My console gets flooded with THIS

#

And main.js stops working

#

Do I need to add .id at the end of every scoreboardIdentity functions?

dim tusk
patent tapir
#

Nope.

#

It keeps going until I close the world

#

It might stop when everyone but me leaves, but idk

dim tusk
patent tapir
dim tusk
patent tapir
#

Plenty, I use scoreboard for MANY things

#

But every time I use .scoreboardIdentity I only use scoreboardIdentity

dim tusk
patent tapir
#

Do i need another extension on the end?

#

Do you want me to send my bp for your scanning

#

I have no idea wtf I did wrong

#

It works fine until another player joins

thorn flicker
#

you should just send the function.

patent tapir
#

It’s EVERY script with a .scoreboardIdentity in it

dim tusk
#

just give the function

thorn flicker
#

the entity needs a scoreboard Identity first before you try to get it.

patent tapir
thorn flicker
#

dude

dim tusk
patent tapir
thorn flicker
patent tapir
tight plume
# thorn flicker there isn't

This works out: dim.getBlockFromRay(source.location, { x: 0, y: 1, z: 0 }, { includePassableBlocks: false })?.block;

deep garden
#

Is playerInteractWithEntity stable yet?

thorn flicker
#

it is

thorn flicker
deep garden
#

Thank you @thorn flicker 😊 I thought it was but this is not doing anything so I wanted to make sure

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

world.beforeEvents.playerInteractWithEntity.subscribe((ev) => {
    const { player, itemStack, target } = ev;

    player.sendMessage("You interacted with an entity!");
});```
thorn flicker
#

what server version are you using?

#

latest stable is 1.16.0

deep garden
#
"module_name": "@minecraft/server",
      "version": "1.16.0"
        },
        {
      "module_name": "@minecraft/server-ui",
      "version": "1.3.0"```
        }@thorn flicker  yep, which was odd
deep garden
#

I know right, I am thinking maybe I am using it wrong.

thorn flicker
#

is it in your entry file?

#

because if not, it wont run.

deep garden
#

import "./SpawnEgg.js"

For my Main.js

And it is called SpawnEgg.js

#

Maybe I can just put it in my main.js all together and see if it works

#

/Behavior/scripts/Main.js

/Behavior/scripts/SpawnEgg.js

thorn flicker
#

well, the m is capitalized

#

is the entry stated in the manifest have a capitalized M too?

deep garden
#

Nope lol 😅 That will do it... So sorry, I forgot to add the entry point

thorn flicker
#

yeah, that would do it

#

lmao

#

its fine...

deep garden
#

Yep, as soon as you said that I checked a different addon with scripts and that was missing lol. Thank you for the help

deep garden
#

❤️ Thanks 👍

quick shoal
#

Guys how about this one

#

The main problem I get is the animation

#

BC I can't do any animation in chest Form data

#

Or someone who thinks possible can try I will be grateful

#

🙏

gusty bramble
#
import * as mc from '@minecraft/server'
import { ItemStack, world } from '@minecraft/server'
import {Command} from 'lib/canopy/CanopyExtension';
import  extension from 'config'
const ItemSummonCommand = new Command({
    name: 'itemsummon',
    description: 'A command to summon any items from nothing',
    usage: 'itemsummon [item] [amount] [location]',
    callback: ItemSummonCommandCallback,
    args: [
      { type: 'string|number', name: 'item' },
      { type: 'number', name: 'amount' },
      { type: 'number', name: 'x' },
      { type: 'number', name: 'y' },
      { type: 'number', name: 'z' },
    ],
    contingentRules: ['StorageUtilities', 'CreativeOnly'],
    adminOnly: false,
    helpEntries: [
    ],
    helpHidden: false
});
extension.addCommand(ItemSummonCommand);

function ItemSummonCommandCallback(sender, args){
    let { item, amount, x, y, z } = args;
    const location = {x: x+0.5, y: y, z:z+0.5}
    sender.dimension.spawnItem(new ItemStack(item, amount), location);
    itemEntity.clearVerocity();
};

export { ItemSummonCommandCallback }

Would it be possible to add a list for the item input so like this

Dirt, grass, wool, cobblestone 64

Would summon those all those items?

#

Even better if I could input different amounts for them all like so:

Dirt 32, grass 16, wool 64, cobblestone 48

#

Oh and can the clear.veracity() be optional? Like you can specify if you want it to trigger or not with an arg

ruby haven
#

Is it possible to make an entities hitbox rotate with the animation of the body in RP?

Cause I have this entity that bends it's head so hitting the head doesn't damage it cause the hitbox is still stuck on its original position?

warm mason
ruby haven
warm mason
#

But in entities this is quite possible

gusty bramble
# warm mason I don't understand what you need, explain again

Ok so right now my script takes a chat command like:

./itemsummon dirt 10 7 6 9
This will summon 10 dirt blocks at 7 6 9

I was wondering if it’s possible to make something like:

./itemsummon dirt 10, wool 20, cobblestone 5 8 8 8
This would summon 10 dirt, 20 wool and 5 cobblestone at 8 8 8

So it can summon multiple items not just one

warm mason
gusty bramble
#

How would I do that tho? Because wouldn’t each item need a separate argument which means there’s a limit?

warm mason
gusty bramble
#

Wdym?

#

Well ok I understand that actually. Hummmm can arguments be optional?

#

I could just add 10 (a good enough amount imo) and if you don’t use them all then it’s fine

warm mason
# gusty bramble Wdym?

The fact that you cannot accept infinity of arguments is a problem with the library you are using. But you can try accepting a json object. For example, /summonitem {"dirt":10,"stone":30} 1 23 0

solar dagger
#

Has anyone made a dropper game? I wanted to see if there's a way to increase the sway movement of the player

jolly citrus
#

how do i change a player's dimension

thorn flicker
jolly citrus
#

thx

thorn flicker
#

np

jolly citrus
#

can somebody help, in the end the portal im warping through is at -100, 59, 95 but when i go through the portal it tells me fromLocation is something completely different .. ?

function locationWithin(location) {
    const min = { x: -101, y: 57, z: 94 };
    const max = { x: -99, y: 62, z: 96 };

    if (location) {
        // Check if the location is within the bounds
        const withinX = location.x >= min.x && location.x <= max.x;
        const withinY = location.y >= min.y && location.y <= max.y;
        const withinZ = location.z >= min.z && location.z <= max.z;

        return withinX && withinY && withinZ;
    }

    // If location is null or undefined, return false
    return false;
}

world.afterEvents.playerDimensionChange.subscribe(({toDimension: {id}, player, fromDimension: {id: id_}, fromLocation })=>{
    player.setDynamicProperty("intercool",false)
    Frozen.Info(JSON.stringify(fromLocation))
    if (id == "minecraft:the_end") {
        player.teleport({ x: 38, y: 57, z: -118})
    }
    else if (id == "minecraft:overworld" && id_ == "minecraft:the_end" && locationWithin(fromLocation)) {
        player.teleport({x: 0, y: 59, z: 500})
    }
  })
chrome cove
#

100k+

distant tulip
#

here we go again

velvet swallow
#

Are there any loaders or methods to ensure a player is fully loaded before running a script?

distant tulip
#

define "fully loaded"

velvet swallow
# distant tulip define "fully loaded"

By 'fully loaded,' I mean when the player has fully spawned and finished joining the game. Instead of running the script immediately, I want to wait until the player is fully loaded before executing the script.

slow walrus
#

playerspawn event

meager pulsar
#

How do you use the playerInteractWithEntity on stable?

#

like this? world.afterEvents.playerInteractWithEntity.suscribe(()=>{ console.warn(`a`) })

tight plume
#
world.afterEvents.playerInteractWithEntity.suscribe((data)=>{
    console.warn(data);
})
pseudo marlin
#

Hello! I wanted to help, I wanted to know if anyone knows how to locate a structure using a script, for example, I locate a structure and it will show its coordination, but it's not like /locate and I wanted to know if there is something like world.getStructure

#

I've been trying to find something like this for almost 2 days

pseudo marlin
#

let structure = await player.runCommandAsync(locate structure village);
var message = structure.statusMessage.match(/-?\d+/g);
if (message && message.length >= 3) {
var xStructure = parseInt(message[0]);
var yStructure = parseInt(message[1]);
var zStructure = parseInt(message[2]);
console.log(X:${xStructure}, Y:${yStructure}, Z:${zStructure});
} else {
console.log("ops.");
}

#

I wanted to know if you know what the problem with this script is, can you help me?

pseudo marlin
#

the error that is causing damage is in that part structure.statusMessage.match

wary edge
#

Where did you even get the statusMessage field?

pseudo marlin
#

I've done everything

pseudo marlin
#

but I think it changed, but I think

turbid delta
#

is there an attribute for player saturation

turbid delta
#

😢

pseudo marlin
wary edge
pseudo marlin
#

but thank you, that's just what I needed

valid ice
#

Is there a way to pass an animation location to the server so I can use it (for instance, the position of a locator on the player model)

sharp elbow
#

I expect not. But if you know the model's skeletal hierarchy and TRS, the animation, and the current time of the animation, then in theory you could compute where the offset should roughly be.

valid ice
#

I just have a particle that sets some endpoints via a script API-calculated formula, and an animation will be happening at the same time- so I want to get the position of a certain point on the model, so I can set where the particle is being "attached" to.

I could move my script API calculations to scripts, but doing trapezoid rule with molang sounds like a royal PITA 😅

sharp elbow
#

Could you make a visual demonstration? I am struggling to visualize this in my head

valid ice
#

I have an animation where I want to attach the line at the end of the rod- the line is particles, and has variables set via script API. The endpoints for the particles is set inside of the script, and the length of the line under sag is also calculated in scripts.

#

I looked into using seats, but those are hard-position locked on the server, and locators cannot be 'gotten' via scripts.

tawny jungle
#

is there any way to test typeId for items with data?

#

i need it to only test for a water bottle, but the typeId is potion with data 1

dim tusk
#

I mean like just full API version

#
function isWaterBottle(player) {
    const testfor = player.runCommand('testfor @s[hasitem={item=potion,location=slot.weapon.mainhand,data=0}]').successCount;
    if (testfor > 0) return true;
    else return false;
}```
tawny jungle
tawny jungle
warm mason
#

So far only this

bright dove
#

how do you set a block using scripts ?

warm mason
bright dove
#

is there anything wrong with this

chilly fractal
#

Nahhhh minecraft is high or smth

#

Ima open a post

#

Cuz I just lost my sanity.

sterile epoch
#

how do I fix dates? when someone claims something, it logs the date of the claim, but it goes off my timezone

#

even if they're in a different timezone it saves in my own, is there a way to fix this?

distant tulip
#

store dates in UTC format

#

gtg right now, look it up

ruby haven
#

Can you force a player to get kicked out of the game?

dim tusk
buoyant canopy
#

can we make dimension.fillBlocks destroy blocks
or can we replicate the action of fill ~~~ ~~~ air destroy with scripts?

dim tusk
#

If you're in single player you can but you need to edit the player.json

wary edge
buoyant canopy
#

ok

#

i will use the regular fill command then

distant tulip
dim tusk
#

Oof I kinda forget, use while true

#

It does the script over BLA BLA

distant tulip
cold grove
warm mason
#

I remember when I kicked a player I just showed him a huge text through the title until he crashed

dim tusk
elfin rose
#

can anyone give me getScore function

distant tulip
#

world.scoreboard.getObjective(id).getScore(participant)

elfin rose
#

this code aint working

function getPlayerScore(player, objectiveName) {
    const objective = world.scoreboard.getObjective(objectiveName);
    if (!objective) {
        player.sendMessage(`§cObjective '${objectiveName}' not found.`);
        return 0;
    }

    try {
        const score = objective.getScore(player.scoreboard);
        return score; // Return the fetched score
    } catch (error) {
        player.sendMessage(`§cError retrieving score: ${error.message}`);
        return 0; // Default to 0 if retrieval fails
    }
}```
#

idk why

distant tulip
#

errors?

elfin rose
distant tulip
#

const score = objective.getScore(player);

elfin rose
# distant tulip const score = objective.getScore(player);

anything wrong with this?

// Function to set the player's score
function setPlayerScore(player, objectiveName, newScore) {
    try {
        const objective = world.scoreboard.getObjective(objectiveName);
        if (!objective) {
            player.sendMessage(`§cObjective '${objectiveName}' is missing.`);
            return false;
        }
        objective.setScore(player.scoreboard, newScore);
        return true;
    } catch (error) {
        player.sendMessage(`§cFailed to set score for '${objectiveName}': ${error.message}`);
        return false;
    }
}

warm mason
#

Don't use AI

elfin rose
#

i didnt my friend made it for me

#

i guess he used ai

#

lol

cold grove
#

scoreboardIdentity

warm mason
#
const Score = new class {
  add(name, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(name, score)
  }
  remove(name, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(name, -score)
  }
  get(name, objective) {
    let scor = 0
    try {
      scor = world.scoreboard.getObjective(objective)?.getScore(name)
    } catch {
      return 0
    }
    return scor
  }
  set(name, objective, score) {
    return world.scoreboard.getObjective(objective)?.setScore(name, score)
  }
}

You can use this. Examples of use:

Score.set(player, "money", 123)
Score.get(player, "money)

|| I made this class because I'm too lazy to write long functions ||

elfin rose
#

is this correct

moneyObjective.setScore(player.name, 0);

||i hate my friend||

warm mason
#

No

#
moneyObjective.setScore(player, 0);
elfin rose
# warm mason No

i sent it to my friend he said he updated me and sent me this but it doesn't work

// Score class for handling scores
const Score = new class {
  add(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(player, score)
  }
  remove(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(player, -score)
  }
  get(player, objective) {
    let scor = 0;
    try {
      scor = world.scoreboard.getObjective(objective)?.getScore(player);
    } catch {
      return 0;
    }
    return scor;
  }
  set(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.setScore(player, score);
  }
};

// Player initialization on join
world.afterEvents.playerJoin.subscribe((event) => {
    const player = event.player;
    const moneyObjective = world.scoreboard.getObjective("money");
    if (!moneyObjective) {
        world.scoreboard.addObjective("money", "dummy");
    }
    try {
        if (moneyObjective.getScore(player) === undefined) {
            moneyObjective.setScore(player, 0);
        }
    } catch {
        moneyObjective.setScore(player, 0);
    }
});

// Get player's score from the scoreboard
function getPlayerScore(player, objectiveName) {
    try {
        return Score.get(player, objectiveName); // Using player directly
    } catch (error) {
        player.sendMessage(`§cError retrieving score: ${error.message}`);
        return 0;
    }
}

// Set player's score on the scoreboard
function setPlayerScore(player, objectiveName, newScore) {
    try {
        const success = Score.set(player, objectiveName, newScore); // Using player directly
        if (!success) {
            player.sendMessage(`§cFailed to update score for '${objectiveName}'.`);
            return false;
        }
        return true;
    } catch (error) {
        player.sendMessage(`§cFailed to set score for '${objectiveName}': ${error.message}`);
        return false;
    }
}

warm mason
#

Your friend..

#
// Score class for handling scores
const Score = new class {
  add(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(player, score)
  }
  remove(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(player, -score)
  }
  get(player, objective) {
    let scor = 0;
    try {
      scor = world.scoreboard.getObjective(objective)?.getScore(player);
    } catch {
      return 0;
    }
    return scor;
  }
  set(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.setScore(player, score);
  }
};

// Player initialization on join
world.afterEvents.playerJoin.subscribe((event) => {
    const player = event.player;
    let moneyObjective = world.scoreboard.getObjective("money");
    if (!moneyObjective) {
        moneyObjective = world.scoreboard.addObjective("money", "dummy");
    }
    try {
        if (moneyObjective.getScore(player) === undefined) {
            moneyObjective.setScore(player, 0);
        }
    } catch {
        moneyObjective.setScore(player, 0);
    }
});

// Get player's score from the scoreboard
function getPlayerScore(player, objectiveName) {
    try {
        return Score.get(player, objectiveName); // Using player directly
    } catch (error) {
        player.sendMessage(`§cError retrieving score: ${error.message}`);
        return 0;
    }
}

// Set player's score on the scoreboard
function setPlayerScore(player, objectiveName, newScore) {
    try {
        const success = Score.set(player, objectiveName, newScore); // Using player directly
        if (!success) {
            player.sendMessage(`§cFailed to update score for '${objectiveName}'.`);
            return false;
        }
        return true;
    } catch (error) {
        player.sendMessage(`§cFailed to set score for '${objectiveName}': ${error.message}`);
        return false;
    }
}
jolly citrus
#

how do i get the item stack of minecraft:item entity

sharp elbow
# elfin rose

A few issues.

  • PlayerJoinAfterEvent does not return a "player" property. You have either playerId or playerName.
  • moneyObjective could be undefined if the scoreboard objective does not exist. There's a condition for this just below that creates said objective, but the moneyObjective variable is still undefined; accessing getScore will throw an error.
distant tulip
jolly citrus
warm mason
#

And there is no need to use try/catch so often, the debugger copes quite well with outputting errors and outputting errors to the player in the chat is a bad practice

jolly citrus
#

if i add it to a player's inventory will it exactly match what was dropped

distant tulip
#

yeah

distant tulip
sharp elbow
#

What do you experience now?

elfin rose
#

same error

sharp elbow
#

Refer to my comment earlier

warm mason
sharp elbow
#

You probably want const player = event.playerId; although I'm not sure if the player's ID is acceptable as a score identity

#

May need to use world.getEntity in that case?

warm mason
#
const Score = new class {
  add(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(player, score)
  }
  remove(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.addScore(player, -score)
  }
  get(player, objective) {
    let scor = 0;
    try {
      scor = world.scoreboard.getObjective(objective)?.getScore(player);
    } catch {
      return 0;
    }
    return scor;
  }
  set(player, objective, score) {
    return world.scoreboard.getObjective(objective)?.setScore(player, score);
  }
};

// Player initialization on join
world.afterEvents.playerSpawn.subscribe((event) => {
    if (!event.initialSpawn) return
    const player = event.player;
    let moneyObjective = world.scoreboard.getObjective("money");
    if (!moneyObjective) {
        moneyObjective = world.scoreboard.addObjective("money", "dummy");
    }
    try {
        if (moneyObjective.getScore(player) === undefined) {
            moneyObjective.setScore(player, 0);
        }
    } catch {
        moneyObjective.setScore(player, 0);
    }
});

// Get player's score from the scoreboard
function getPlayerScore(player, objectiveName) {
    try {
        return Score.get(player, objectiveName); // Using player directly
    } catch (error) {
        player.sendMessage(`§cError retrieving score: ${error.message}`);
        return 0;
    }
}

// Set player's score on the scoreboard
function setPlayerScore(player, objectiveName, newScore) {
    try {
        const success = Score.set(player, objectiveName, newScore); // Using player directly
        if (!success) {
            player.sendMessage(`§cFailed to update score for '${objectiveName}'.`);
            return false;
        }
        return true;
    } catch (error) {
        player.sendMessage(`§cFailed to set score for '${objectiveName}': ${error.message}`);
        return false;
    }
}```
sharp elbow
elfin rose
#

it says that and removes money from my bal

sharp elbow
#

That must be part of a different system not shown here. Your code snippet does not call setPlayerScore.

#

You should probably open a post in #1067535382285135923

elfin rose
#

should i just use this

// Get player's score from the scoreboard using /scoreboard players
function getPlayerScore(player, objectiveName) {
    try {
        const score = world.scoreboard.getObjective(objectiveName)?.getScore(player);
        return score ? score : 0;
    } catch (error) {
        player.sendMessage(`§cError retrieving score: ${error.message}`);
        return 0;
    }
}

// Set player's score on the scoreboard using /scoreboard players
function setPlayerScore(player, objectiveName, newScore) {
    try {
        world.scoreboard.getObjective(objectiveName)?.setScore(player, newScore);
        return true;
    } catch (error) {
        player.sendMessage(`§cFailed to set score for '${objectiveName}': ${error.message}`);
        return false;
    }
}

warm mason
#

Ahhhhh, this is all bad code. I'll just rewrite this normally

elfin rose
#

ok

jolly citrus
#

can anybody see if there might be edge cases where this might function improperly

world.afterEvents.playerBreakBlock.subscribe((data) => {
    const { player, block } = data;
    const { dimension } = block;

    const centerLocation = block.center();
    const nearbyItems = dimension.getEntities({
        type: "minecraft:item",
        location: centerLocation,
        maxDistance: 1.5,
    });

    if (nearbyItems.length > 0) {
        const itemEntity = nearbyItems[0];
        const itemComponent = itemEntity.getComponent("item");

        if (itemComponent) {
            /** @type {ItemStack} */
            const itemStack = itemComponent.itemStack;

            const inventory = player.getComponent("inventory")?.container;

            if (inventory) {
                const addedSuccessfully = inventory.addItem(itemStack);

                if (!addedSuccessfully) {
                    dimension.spawnItem(itemStack, block.location);
                }

                itemEntity.remove();
            }
        }
    }
});

meant to be an auto-pickup script, for me (world host) it works fine i havent tested from any other player's perspective tho

warm mason
#
const Score = new class {
  objective(name) {
    return world.scoreboard.getObjective(name) || world.scoreboard.addObjective(name)
  }
  add(name, objective, score) {
    return this.objective(objective)?.addScore(name, score)
  }
  remove(name, objective, score) {
    return this.objective(objective)?.addScore(name, -score)
  }
  get(name, objective) {
    return this.objective(objective)?.getScore(name)
  }
  set(name, objective, score) {
    return this.objective(objective)?.setScore(name, score)
  }
}

world.afterEvents.playerSpawn.subscribe(data => {
  if (Score.get(data.player, "money") == undefined) {
    Score.set(data.player, "money", 0)
  }
})
#

@elfin rose

elfin rose
#

k imma try it out

#

works

gusty bramble
#

Can an item despawning be detected?

jolly citrus
#
world.beforeEvents.entityRemove.subscribe(({ removedEntity }) => {
    if (removedEntity.typeId === "minecraft:item") {
        // code here
    }
})
#

idk if it's subscribed to when items get removed but maybe

#

try it out and see

#

if u want the info of the stack when it's removed use this

world.beforeEvents.entityRemove.subscribe(({ removedEntity }) => {
    if (removedEntity.typeId === "minecraft:item") {
        const item = removedEntity.getComponent("item").itemStack;
        // code here
    }
})
distant tulip
#

fun fact, when you pick up an item, the item get a velocity boost away from the player

jolly citrus
#

why does the "picked up" item not get removed from the ground with .remove()

world.afterEvents.playerBreakBlock.subscribe((data) => {
    const { player, block } = data;
    const { dimension } = block;

    const centerLocation = block.center();
    const nearbyItems = dimension.getEntities({
        type: "minecraft:item",
        location: centerLocation,
        maxDistance: 1,
    });

    if (nearbyItems.length > 0) {
        const inventory = player.getComponent("inventory")?.container;

        nearbyItems.forEach((itemEntity) => {
            const itemComponent = itemEntity.getComponent("item");

            if (itemComponent && inventory) {
                /** @type {ItemStack} */
                const itemStack = itemComponent.itemStack;

                const addedSuccessfully = inventory.addItem(itemStack);

                if (!addedSuccessfully) {
                    dimension.spawnItem(itemStack, block.location);
                }

                itemEntity.remove();
            }
        });
    }
});
#

they still get the item in their inv but it doesnt get removed

#

ohh

#

nvm

steady canopy
# gusty bramble ```js import * as mc from '@minecraft/server' import { ItemStack, world } from '...

just create a single string argument, get that string argument and then parse it. Example:

/summonitem "dirt 32,grass 32" 10 60 10

so this arg is called itemList

const itemListArg = "dirt 32,grass 32"
const itemsAmounts = itemListArg.split(",")
const itemsParsed = itemsAmounts.map(itemAmount => {
  const splited = itemAmount.split(" ")
  return { id: splited[0], amount: Number(splited[1]) }
})

itemsParsed.forEach(item => {
   sender.dimension.spawnItem(new ItemStack(item.id, item.amount), location);
})
#

Your command handler should support quoted args. So "dirt 32,grass 32" can be a single arg.

gusty bramble
#

Oooo ok I’ll see what I can do

#

Much appreciated

proud saddle
#

is where javascript file with all script api classes?

thorn flicker
buoyant canopy
#

do you know of an algorithm that generates a better circle than this?

function make_grid() {
    const grid = []
    for (let i = -20; i <= 40; i++) {
        for (let j = -20; j <= 40; j++) {
            const point = {x: i, z: j}
            if (get_distance(point) <= 20) {
                grid.push(point)
            }
        }
    }
    return grid
}
function get_distance(a, b = {x: 0, z: 0}) {
  return Math.sqrt((a.x - b.x)**2 + (a.z - b.z)**2)
}
#
make_grid().forEach(point => player.runCommand(`setblock ~${point.x} 100 ~${point.z} stone`))```
warm mason
buoyant canopy
#

i miss spoke the question,
is there a better algorithm to generate perfect circles such as this?

jolly citrus
#

why does the glass always show tails?

class Coin {
    constructor(side) {
        if (side.toLowerCase().startsWith('h')) {
            this.side = "Heads";
        } else if (side.toLowerCase().startsWith('t')) {
            this.side = "Tails";
        } else {
            throw new Error("Invalid side given, must start with 'h' or 't'.");
        }
    }

    flip() {
        const result = Math.random() < 0.5 ? "Heads" : "Tails";

        return result === this.side;
    }
}

const conditionTypeIds = ["minecraft:tripwire_hook","minecraft:ender_chest"]

const itemCondition = (itemStack) => {
    const lore = itemStack.getLore();

    if (lore.length > 0) {
        if (lore[lore.length-2] == "§0" && (conditionTypeIds.includes(itemStack.typeId) || itemStack.typeId.includes("dye"))) return true;
    }

    return false;
}

const headsStack = new ItemStack("minecraft:orange_stained_glass",1)
headsStack.nameTag = "§r§l§6Heads"

const tailsStack = new ItemStack("minecraft:yellow_stained_glass",1)
tailsStack.nameTag = "§r§l§eTails"

const stackChoices = [headsStack, tailsStack]

const duration = 3;  // in seconds

export const inventories = new Map();

Commands.registerCommand("!coinflip","<side: string>",["!cf"],undefined,({ sender, args }) => {
    let item = playerCache.get(sender).selectedSlot;
    let { selectedSlotIndex: selectedSlot } = sender;
    if (item) {
        if (itemCondition(item)) {
            system.run(() => {
                const coin = new Coin(args.side);
                const win = coin.flip();
                /** @type {Container} */
                const inventory = sender.getComponent("inventory").container;

                const oldInventory = []
                for (let i = 0; i < inventory.size; i++) {
                    oldInventory.push(inventory.getItem(i))
                    inventory.setItem(i)
                }

                inventories.set(sender,oldInventory)

                let i = 0;
                let stackChoice = coin.side == "Heads" ? 1 : 0; 
                const runId = system.runInterval(() => {
                    if (i < duration * 10) {
                        inventory.setItem(4,stackChoices[stackChoice]);
                        sender.playSound("random.click",{ pitch: 2 });
                        stackChoice = Math.abs(stackChoice - 1);
                        i++
                    } else {
                        system.clearRun(runId);

                        if (win) {
                            sender.playSound("random.levelup")
                        } else {
                            sender.playSound("random.explode")
                        }

                        system.runTimeout(()=>{
                            inventory.clearAll()

                            const _oldInventory = inventories.get(sender)
                            for (let i = 0; i < inventory.size; i++) {
                                inventory.setItem(i,_oldInventory[i])
                            }
                        },20)
                    }
                },2)
            })
        }
    }
})
warm mason
#

Maximum - you can save the shape of the circle so that you don’t have to generate it again later

buoyant canopy
#

nice, i don't know how i got it right first try

distant tulip
#

there is multiple algo to generate one
using a grid is a bad way

buoyant canopy
#

oh, i would like to learn

distant tulip
#

give me a sec to look if i still have a script

buoyant canopy
#

in my scenario i need a grid of coords that is in this shape

distant tulip
#
function generatePolarCircle(radius) {
    const p = [];
    for (let r = 0; r <= radius; r++) {
        for (let t = 0; t < 2 * Math.PI; t += Math.PI / 180) {
            const x = Math.round(r * Math.cos(t));
            const z = Math.round(r * Math.sin(t));
            p.push({ x, z });
        }
    }
    return p
}
#

r is the radius

#

20 radius result

sharp elbow
#

🤔 wouldn't the local variable r shadow the function parameter r?

warm mason
buoyant canopy
#

can you return it as {x, z} and still be an object?

distant tulip
buoyant canopy
#

i mean is p.push({x, z}) valid syntax

sharp elbow
#

Yes, the property name takes on the parameter name; so it will return an object with {x: number, z: number}

#

It's shorthand for {x: x, z: z}

warm mason
buoyant canopy
buoyant canopy
warm mason
buoyant canopy
#

well, my code uses a sqrt while his uses round, cos, and sin
which is better for performance?

distant tulip
buoyant canopy
#

ok, thank you very much

autumn seal
warm mason
autumn seal
#

except in performance?

warm mason
distant tulip
#

unless i am doing something wrong

buoyant canopy
#

@warm mason i did some math, and his method is more efficient if r is 90 or greater

autumn seal
buoyant canopy
#

so because i am not going with large radi i will use my method.

warm mason
buoyant canopy
#

does it leave gaps?

warm mason
distant tulip
#

what @past blaze is using in his worldedit

warm mason
past blaze
#

What's happening?

distant tulip
odd path
#

Is it possible to identify a cave with a script?

warm mason
distant tulip
buoyant canopy
#

the grid method:
f(r) = (2r)²
Minato's method:
g(r) = 360r
solve f(r) < g(r) for r greater than 0

past blaze
buoyant canopy
distant tulip
#

@warm mason

autumn seal
buoyant canopy
#

anyway, i want to run a function each coordinates in the grid one tick per location,
and i am failing to use async

buoyant canopy
odd path
#

Like, how do I know I'm not looking at the sky?

warm mason
distant tulip
odd path
buoyant canopy
autumn seal
# odd path <@497959003909783552>

The obvious answer would be to iterate upwards looking for solid blocks but the most elegant answer is probably the is_underground filter

#

I've never messed with it so I can't say

#

sorry I can't help more

buoyant canopy
warm mason
# odd path <@497959003909783552>
function isUndeground(player) {
  let block = player.dimension.getTopmostBlock(player.location)
  if (player.location.y >= block.y) return false
  while (!block.isSolid && block.y > player.dimension.heightRange.min) {
    if (player.location.y >= block.y) return false
    block = block.below()
  }
  return true
}
warm mason
#

And the radius is the same

distant tulip
buoyant canopy
#

ah makes sense, computers take longer to count from 10000 to 10100 compared to from 0 to 100

odd path
warm mason
odd path
warm mason
# odd path

Shows the location of the selected biome, not the biome in the selected location

warm mason
#

If you don't like my method, then do your own.

odd path
odd path
#

I was just asking for help

warm mason
distant tulip
#

mob filters do have is_underground
maybe use that

thorn flicker
#

where did this hostility come from

warm mason
distant tulip
#

is_undeground only check top block?

warm mason
#

Yes, I made an exact analogue of this function

distant tulip
#

yeah, that is disappointing tbh
there is no perfect way to check for caves/undeground

thorn flicker
warm mason
#

I'm waiting for the Biome class to be added to the scriptAPI

thorn flicker
#

but same here, being able to check for biomes in the api would be awesome.

distant tulip
#

there is getClooestBiome but it is limited

thorn flicker
warm mason
thorn flicker
#

not a good solution for checking what current biome an entity is in.

buoyant canopy
sharp elbow
#

Bonus tip! Use the new "minecraft:transient" component—it keeps Minecraft from saving your entity

#

With that there should be no need for despawning on world initialize, right?

buoyant canopy
#

oh that's genius

sharp elbow
#

You must be the genius to have pulled a 4D chess move like this though

#

I wonder if it only works in format version 1.21.50 though

buoyant canopy
distant tulip
#

why not use scriptevent

buoyant canopy
buoyant canopy
distant tulip
#

your welcome
-# i don't remember lol

buoyant canopy
# distant tulip why not use scriptevent

i am not using a scriptevent because the entity itself is being spawned by a script and i need it in the same context, if i send a scriptevent event i create another context

buoyant canopy
distant tulip
#

wasn't that for a fill function

buoyant canopy
#

how to force load a chunk without using a ticking area?

thorn flicker
#

there's no api alternative

#

how is this script api related

distant tulip
tidal wasp
#

Wait this is molang not script api

thorn flicker
tidal wasp
#

Whoops

thorn flicker
distant tulip
#

commands can do that no?
if not spawn and tp it

thorn flicker
#

so the api method can't but commands can?

#

in that case why not just use the tick area command...

patent tapir
#

How do I .teleport() players into a certain dimension???? ```js

data.sender.teleport(tpTo, { Dimension: "overworld" })``` doesn’t work

distant tulip
patent tapir
thorn flicker
thorn flicker
patent tapir
#

[Scripting][error]-TypeError: Native type conversion failed. Interface property ['dimension'] expected type: Dimension | undefined (failed parsing interface to Function argument [1]) at <anonymous> (chatSystem.js:140)

thorn flicker
#

oh right, it needs a dimension, not a dimension id (which is a string)

patent tapir
#

I tried world.getDimension too

buoyant canopy
patent tapir
#

It didnt throw an error it just ignored the entire dimension option

thorn flicker
distant tulip
patent tapir
buoyant canopy
#

i place a command block in an area
go far away
spawn my entity
teleport it to the command block
the entity ticks but the command block doesn't.

thorn flicker
buoyant canopy
thorn flicker
patent tapir
patent tapir
patent tapir
#

I guess that’s not an issue anymore lmao

buoyant canopy
thorn flicker
#

oh

distant tulip
thorn flicker
#

it happens

#

lol

distant tulip
#

can we see your full code @patent tapir ?

thorn flicker
distant tulip
#

oh, alr

buoyant canopy
patent tapir
#

Why do you need to see it

#

Sorry for the delay I just recorded a hacker in my world for proof

distant tulip
#

nvm

distant tulip
thorn flicker
woven mural
#

Hey

#

I'm having problems when I put an enchantment on an item, when I leave the world the game crashes

buoyant canopy
#

and if i don't use system.run it won't work.

devout dune
#
const spawnLocation: Vector3 = {
      x: Math.round(player.location.x + 0.5 + (Math.floor(Math.random() * 100) - 50)), // Random X offset rounded to nearest whole number
      y: 150, // I WANT THIS TO BE AT 150 WORLD HEIGHT. REGARDLESS OF PLAYER LOCATION
      z: Math.round(player.location.z + 0.5 + (Math.floor(Math.random() * 100) - 50)) // Random Z offset rounded to nearest whole number
    };```


Hey! I am trying to create a spawn location. That is at player positiion (x / z)
BUT I want the y spawn pos to be '150' units. So i can always get the object to spawn at the same height in the sky! 

Any easy built in methods? like ```player.dimension.GetPosition(player.pos.x, 150, player.pos.z)```
#

@wary edge Hey, any idea! 😄

wary edge
devout dune
buoyant canopy
dim tusk
wary edge
#

Is there any way to grab all entities in a world and filter them via family without needing to spawn them? I could easily do this with items as ItemStack has a public constructor but not Entity.

deep yew
#

make it ig

#

EntityStack

patent tapir
#

Why doesn’t this force the button to respawn???```js

      while (world.getDimension("overworld").getBlock({ x: 10003, y: 101, z: 9999 }).typeId === "air") {
        world.getDimension("overworld").runCommand('setblock 10003 101 9999 crimson_button["facing_direction"=4]')
      }
      while (world.getDimension("overworld").getBlock({ x: 9995, y: 101, z: 9999 }).typeId === "air") {
        world.getDimension("overworld").runCommand('setblock 9995 101 9999 crimson_button["facing_direction"=5]')
      }```
deep yew
#

try minecraft:air

patent tapir
#

Why

#

Why the stone face

#

I only didn’t do minecraft: because last time I used that in a block comparison it didn’t work

deep yew
#

yeah with block.typeId it returns minecraft:block, but some other ways might not return minecraft: in the string

#

depends

dim tusk
#

Use the API version of it as much as possible

deep yew
#

I was going to ask as well but what would you use?

dim tusk
#
import { BlockPermutation } from '@minecraft/server';

const block = world.getDimension('overworld').getBlock({ x: 0, y: 0, z: 0});
block.setPermutation(BlockPermutation.resolve('minecraft:button', { <state name>: <state value>});```

I missed a thing but just snippet
patent tapir
patent tapir
deep yew
#

may not work out of simulation distance/ticking area

dim tusk
patent tapir
#

Also doesn’t setBlock api function thingy and setBlockPermutation run at different ticks, so buttons would break?

dim tusk
patent tapir
deep yew
#

I said may not work out of one, so it's good it's in one

dim tusk
#

Then find a solution 😭 just because it doesn't work just stop finding a solution to make it work?

patent tapir
dim tusk
#

Anyways, just don't change it if you don't want... Just dnt rush it

dim tusk
patent tapir
#

And if runCommand didn’t work for one tick (which is the reason I put it in a while loop in the first place), that probably wouldn’t either

#

Too much lag completely skipped the runCommand

dim tusk
#

Idk what you are doing so I ain't saying shit now...

dim tusk
patent tapir
#

What you want me to do wouldn’t work, period because it’s TWO DIFFERENT FUNCTIONS and the while loop CANT CHECK FOR PERMUTATIONS

#

Unless it can and I’m dumb.

#

And I’m exceptionally stupid.

ruby haven
#
import { world, system } from "@minecraft/server";
import { getArenaCenter } from "./center.js";


world.afterEvents.entityDie.subscribe(({ damageSource: { damagingEntity }, deadEntity }) => {

  if (!damagingEntity || damagingEntity.typeId !== 'mz:smile') return;

  if (deadEntity.typeId === 'minecraft:player' && damagingEntity.typeId === 'mz:smile') {
    const center = getArenaCenter();
    deadEntity.setProperty('smile:ride', true);

    deadEntity.camera.fade({
      fadeColor: { red: 0, green: 0, blue: 0 },
      fadeTime: { fadeInTime: 1, holdTime: 1, fadeOutTime: 1 }
    });
    deadEntity.camera.setCamera('minecraft:first_person');

    damagingEntity.kill();
    damagingEntity.clearVelocity();
    damagingEntity.triggerEvent('bridge:fake_death');

    damagingEntity.teleport(center, { facingLocation: deadEntity.location });

    deadEntity.triggerEvent('bridge:no_movement');

    let dx = deadEntity.location.x - damagingEntity.location.x;
    let dz = deadEntity.location.z - damagingEntity.location.z;

    let length = Math.sqrt(dx * dx + dz * dz);

    if (length === 0) {
      dx = 1;
      dz = 0;
      length = Math.sqrt(dx * dx + dz * dz);
    }

    const normalizedX = dx / length;
    const normalizedZ = dz / length;

    const newX = damagingEntity.location.x + normalizedX * 5;
    const newY = damagingEntity.location.y;
    const newZ = damagingEntity.location.z + normalizedZ * 5;

    system.runTimeout(() => {
      deadEntity.teleport({ x: newX, y: newY, z: newZ }, { facingLocation: damagingEntity.location });
    }, 20);

    system.runTimeout(() => {
      deadEntity.runCommand('/execute as @s at @s positioned ~~~ rotated ~110~ run camera @s set minecraft:free ease 4 out_cubic pos ^4 ^6 ^7 facing @s');
    }, 40);
    system.runTimeout(() => {
      deadEntity.triggerEvent('bridge:health');
    }, 500);
    system.runTimeout(() => {
      deadEntity.kill();
    }, 550)
  }
});
ruby haven
patent tapir
#

Two different functions

dim tusk
dim tusk
patent tapir
#

……

ruby haven
#

Could it be that it is confusing who is the real deadentity? Cause I actually also kill the damaging entity

dim tusk
dim tusk
patent tapir
#

That works?

#

Well you need to remember that I’M REALLY BAD AT JAVASCRIPT, you CANNOT expect me to know EVERYTHING THERE IS TO KNOW, ESPECIALLY not the little things. And searching for things on the docs is an absolute PAIN because the docs search function is AWFUL

#

Specifically bedrock.dev

dim tusk
#

Like Jayly, stirante or Ms docs

patent tapir
dim tusk
#

I keep telling you it would work but you keep saying "it wouldn't work because it's in while loop, it's two different functions BLA BLA BLA BLA"

patent tapir
#

Oh im sorry, Microsoft docs i do use but only when it shows up in DuckDuckGo

patent tapir
#

And hate to ask

#

Because you people hate answering me

dim tusk
dim tusk
deep yew
#

Chill, both of you

#

nobody's winning

dim tusk
patent tapir
#

But whatever

wary edge
#

Calm down.

deep yew
#

Just don't ask to ask, "can I ask a question?"

#

and don't be scared to not know

#

ignorance is a gift to some, but always allows learning to be had

#

Please let it go, Coddy

dim tusk
deep yew
#

...

dim tusk
#

Hmm, sorry for everyone then... Change topics 🤔

patent tapir
# dim tusk ```js import { BlockPermutation } from '@minecraft/server'; const block = world...

Cool, so this should work ```js

while (world.getDimension("overworld").getBlock({ x: 10003, y: 101, z: 9999 }).typeId === "minecraft:air") {
world.getDimension("overworld").getBlock({ x: 10003, y: 101, z: 9999 }).setPermutation(BlockPermutation.resolve('minecraft:crimson_button', { facing: 4 }));
}
while (world.getDimension("overworld").getBlock({ x: 9995, y: 101, z: 9999 }).typeId === "minecraft:air") {
world.getDimension("overworld").getBlock({ x: 9995, y: 101, z: 9999 }).setPermutation(BlockPermutation.resolve('minecraft:crimson_button', { facing: 5 }));
}```

#

For some reason you used ‘north’ in your code but it only accepts numbers…?

dim tusk
patent tapir
#

Just like in /setblock

dim tusk
deep yew
#

might be facing_direction?

patent tapir
patent tapir
dim tusk
#

That might crash your game tho

deep yew
#

Should use system.runInterval

patent tapir
#

Also

#
    at <anonymous> (betterButtonTp.js:242)```
dim tusk
deep yew
#

facing_direction

wary edge
dim tusk
patent tapir
ruby haven
#

You can't override minimum health component cause once you die the game expects you to be dead like in expectator there is no way for you to be revived

dim tusk
patent tapir
dim tusk
#

And it's 'north', 'east' etc...

ruby haven
dim tusk
patent tapir
dim tusk
dim tusk
dim tusk
patent tapir
#

I even made my own map for warps.

#

At least, if that’s what you’re talking about.

patent tapir
#

Hey uh.

#

The api thing.

dim tusk
# patent tapir At least, if that’s what you’re talking about.
const buttons = [
    { button: { z: 67, y: 70, x: 154 }, tpTo: { x: 10, y: 20, z: 30 } },
    { button: { z: 6, y: 5, x: 4 }, tpTo: { x: 40, y: 50, z: 60 } },
    { button: { z: 9, y: 8, x: 7 }, tpTo: { x: 70, y: 80, z: 90 } },
]
const buttonMap = new Map(buttons.map(({ button, tpTo }) => [JSON.stringify(button), tpTo]));

world.afterEvents.buttonPush.subscribe(({ block, source }) => {
    const tpTo = buttonMap.get(JSON.stringify(block.location));
    if (tpTo) source.teleport(tpTo);
});```

*?*
patent tapir
#

It doesn’t replace the button.

patent tapir
#

Why do you ask

patent tapir
dim tusk
patent tapir
#

I can send you the whole darn file if you want to.

#

That part doesn’t work for some reason.

dim tusk
dim tusk