#Script API General

1 messages · Page 38 of 1

quick shoal
#

It doesn't matter of addons

umbral scarab
#

How would I check that?

quick shoal
#

Keep in mind

open urchin
#

I think they're stored like this, based on the pack's uuid, meaning packs cannot access each others properties

World
└── Dynamic Properties
    ├── 3f7242c6-639e-4216-8087-bfe905b36989
    │   └── my_property: true
    └── 13e2b202-182b-46d3-aec4-2556a2653c6f
        ├── my_property: 13
        └── another_property: "hello"
rigid torrent
open urchin
#

I don't think so

dim tusk
rigid torrent
#

And what would be the best way to pass information between addons

dim tusk
#

It also kinda depends what information you are trying to pass

rigid torrent
#

So scoreboards could be considered dynamic properties and they can be read between packs with just getScoreboardObjective

dim tusk
shadow geyser
#

how do i fetch player's scoreboard

dim tusk
#

Is this what you meant? Getting the score of the player in an objective?

rigid torrent
#

Ok thanks good info!

shadow geyser
#

30 of if/else statement time.

rigid torrent
#

pain begins

granite badger
#

what if else statement

dim tusk
#

What are you trying to check in the first place?

shadow geyser
#

I'm aware of switch statement just poking.

#

otherwise i wouldn't be asking for scoreboard stuff

dim tusk
#

Oof, I'm kinda bored so I'll convert scoreboard into binary that can convert those into words... What a nice idea, I just need to learn how binary works

granite badger
shadow geyser
#

can't really say anything much tbh.

umbral scarab
#

I've installed NPM typings but my intellisense still isnt working. Any ideas?

shadow geyser
#

honestly i might attempt to install script-api's type/npm to my neovim to see if it works

dim tusk
crude flame
#

how do you make custom events/ spawn entities with components

jolly citrus
#

can applyImpulse be used on player

wary edge
jolly citrus
#

can i change the gravity of applied knockback or no

jolly citrus
#

how do i know whether a fence gate is open or not

shadow geyser
gaunt salmonBOT
uncut summit
#

world.afterEvents.tick.subscribe(() => {

#

anything wrong with this?

#

subscribe?

random flint
#

example:

//say "Hello world" every 20 tick
system.runInterval(()=>{
    world.sendMessage("Hello world");
},20)
#
  • system.run() to run a code on the next tick (especially to exit beforeEvents scope)
  • system.runTimeout() to delay a code with xxx amount of tick.
  • system.waitTicks() a tick delay in the form of a promise to be used with the conjunction of the await keyword, or .then()
#

-# Check the System class in the docs

uncut summit
#

anything wrong with this?

#

balance => {
const currentMoney = parseInt(balance);
if (currentMoney >= material.cost) {

random flint
#

Looks normal. Maybe you want to tell me what error or the full code you have

uncut summit
#
function upgradeGenMaterial(player) {
        const materialNames = materials.map(mat => mat.name);
    
        new ModalFormData()
            .title("Upgrade Gen Material")
            .dropdown("Select new material", materialNames, 0)
            .show(player)
            .then(response => {
                if (response.canceled) return;
    
                const selectedMaterialIndex = response.formValues[0];
                const material = materials[selectedMaterialIndex];
    
                // Check player's current balance first using scoreboard values
                player.runCommandAsync(`scoreboard players get @s money`)
                    .then(balance => {
                        const currentMoney = parseInt(balance);
                        if (currentMoney >= material.cost) {
                            // Deduct only if enough money is available
                            player.runCommandAsync(`scoreboard players remove @s money ${material.cost}`);
                            currentMaterial = material.id;
                            if (!availableGenTypes.includes(material.name)) {
                                availableGenTypes.push(material.name);
                            }
                            player.sendMessage(`Material upgraded to: ${material.name} for ${material.cost}`);
                        } else {
                            player.sendMessage(`Not enough money to buy ${material.name}. You need ${material.cost - currentMoney} more.`);
                        }
                    })
                    .catch(error => {
                        player.sendMessage(`Error checking balance: ${error}`);
                    });
            });
    }```
random flint
#

invalid scoreboard command ig

uncut summit
#

its right

#

oo wait

random flint
#

its say CommandError, so its the runCommandAsync problem

uncut summit
#

i figured it out

slow walrus
#

so what you're doing it completely wrong

#

use world.scoreboard.getObjective('money').getScore(player) instead

terse tide
#

How can I make everywhere I get an item execute a script?

random flint
#

pickup item?

terse tide
#

Yep

random flint
#

Ironically, getting an accurate reading of "who picks up the item" is the hard part.

terse tide
#

it's for anyone

#

I'm making a achievements addon

deep yew
#

easiest way fs:
get everyone's inventory slots near the item and save them, get the dropped item stack, test if the item isn't a thing anymore, then test whose inventory has the item

#

kinda sarcasm but might actually be the best way

terse tide
#

Can you send me an example so I can understand better?

deep yew
#

i have no example but I can explain it maybe a tiny bit more specific

terse tide
#

Ok

uncut summit
deep yew
#

Get the item (by your methods, either specific item typeid, nametag, etc.), then test for all entities (filter for players) around the item, get the inventory of the player and save all of the inventory slots using a loop to a table (let inventorytable = {}) or a Map like "Zappy NE": {...inventory} where inventory has the item typeid, nametag, etc. and slot number of each item 0-35, then use runInterval either every tick or every like 5 or 10 ticks to see if the item isn't existing, and if so, check the player's inventory and see if the item is in there, for each player it collected inventories from.

slow walrus
#

literally that code

terse tide
#

Thanks

uncut summit
slow walrus
#

ofc it's not gonna work if you just drop it in

deep yew
#

I typed all that into AI and it gave me a good basis to work off, you can do that if you're still confused

random flint
#

Omniac, do the ?? addObjective ig

slow walrus
#

you gotta write it properly

uncut summit
slow walrus
#
world.scoreboard.getObjective('money')?.getScore(player)
random flint
slow walrus
#

otherwise you wouldn't really learn anything

deep yew
# terse tide It's perfect

I don't recommend using this code exactly how it is, due to AI not being very good with vague context, but this is the idea:

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

// Configuration
const CHECK_INTERVAL = 10; // Interval (ticks) to run the check
const TARGET_ITEM_TYPE = "minecraft:diamond"; // Change to the type of item you want to track
const SEARCH_RADIUS = 10; // Radius to search for players around the item

// Storage for tracking
let trackedInventories = new Map(); // Player name as key, inventory as value
let trackedItemLocation = null; // Store the item's location to track

// Function to get all players within a radius of a location
function getPlayersNearby(location, radius) {
  return world.getPlayers({
    location,
    maxDistance: radius,
  });
}

// Function to save a player's inventory
function savePlayerInventory(player) {
  let inventory = [];
  const inventoryComp = player.getComponent("minecraft:inventory");
  if (inventoryComp) {
    const container = inventoryComp.container;
    for (let i = 0; i < container.size; i++) {
      const item = container.getItem(i);
      if (item) {
        inventory.push({
          typeId: item.typeId,
          nameTag: item.nameTag,
          slot: i,
          count: item.amount,
        });
      }
    }
  }
  trackedInventories.set(player.name, inventory);
}

``` ..continued
#

function isItemStillThere() {
  if (!trackedItemLocation) return false;

  const blockEntities = world.getEntities({
    location: trackedItemLocation,
    maxDistance: 1,
    type: "minecraft:item",
  });

  for (const entity of blockEntities) {
    if (entity.getComponent("minecraft:item").itemStack.typeId === TARGET_ITEM_TYPE) {
      return true;
    }
  }

  return false;
}

// Main function to track the item and nearby players
function trackItemAndInventory(itemEntity) {
  trackedItemLocation = itemEntity.location;

  const nearbyPlayers = getPlayersNearby(itemEntity.location, SEARCH_RADIUS);
  for (const player of nearbyPlayers) {
    savePlayerInventory(player);
  }

  // Periodically check for item existence and player inventories
  system.runInterval(() => {
    if (!isItemStillThere()) {
      for (const player of world.getPlayers()) {
        const inventory = trackedInventories.get(player.name) || [];
        for (const item of inventory) {
          const inventoryComp = player.getComponent("minecraft:inventory");
          if (!inventoryComp) continue;

          const container = inventoryComp.container;
          const slotItem = container.getItem(item.slot);
          if (slotItem && slotItem.typeId === item.typeId && slotItem.nameTag === item.nameTag) {
            console.log(`Player ${player.name} has the tracked item in slot ${item.slot}`);
          }
        }
      }
      // Clear tracking if the item is gone
      trackedItemLocation = null;
      trackedInventories.clear();
    }
  }, CHECK_INTERVAL);
}
// Detect and track the item when spawned
world.events.entitySpawn.subscribe((event) => {
  const entity = event.entity;
  if (entity.typeId === "minecraft:item") {
    const itemStack = entity.getComponent("minecraft:item").itemStack;
    if (itemStack.typeId === TARGET_ITEM_TYPE) {
      console.log(`Tracking item: ${itemStack.typeId}`);
      trackItemAndInventory(entity);
    }
  }
});
uncut summit
# slow walrus no I don't really do that, I can point you in the right direction but I can't do...

made it this not works


    new ModalFormData()
        .title("Upgrade Gen Material")
        .dropdown("Select new material", materialNames, 0)
        .show(player)
        .then(response => {
            if (response.canceled) return;

            const selectedMaterialIndex = response.formValues[0];
            const material = materials[selectedMaterialIndex];

            // Check player's current balance using scoreboard values
            world.scoreboard.getObjective('money').getScore(player)
                .then(balance => {
                    const currentMoney = parseInt(balance); // Convert balance to integer
                    if (currentMoney >= material.cost) {
                        // Deduct only if enough money is available
                        player.runCommandAsync(`scoreboard players remove @s money ${material.cost}`);
                        currentMaterial = material.id;
                        if (!availableGenTypes.includes(material.name)) {
                            availableGenTypes.push(material.name);
                        }
                        player.sendMessage(`Material upgraded to: ${material.name} for ${material.cost}`);
                    } else {
                        player.sendMessage(`Not enough money to buy ${material.name}. You need ${material.cost} to buy this material.`);
                    }
                })
                .catch(error => {
                    player.sendMessage(`Error checking balance: ${error}`);
                });
        });
}

random flint
deep yew
#

i said don't use it exactly because it was from AI, change it and triple check

slow walrus
#

so remove the .then and do

const balance = // getscore stuff
deep yew
#

it actually saves the inventories when the item spawns anyway, not every tick

terse tide
#

Ohhhh... Much much thanks

terse tide
#

°-°

terse tide
wary edge
slow walrus
random flint
uncut summit
# slow walrus what don't you understand?
// Upgrade Gen Material
function upgradeGenMaterial(player) {
    const materialNames = materials.map(mat => mat.name);

    new ModalFormData()
        .title("Upgrade Gen Material")
        .dropdown("Select new material", materialNames, 0)
        .show(player)
        .then(response => {
            if (response.canceled) return;

            const selectedMaterialIndex = response.formValues[0];
            const material = materials[selectedMaterialIndex];

            // Check player's current balance using scoreboard values
            const playerScore = world.scoreboard.getObjective('money')?.getScore(player);
            if (playerScore !== undefined && playerScore >= material.cost) {
                // Deduct money and upgrade material
                world.scoreboard.getObjective('money')?.removeScore(player, material.cost);
                currentMaterial = material.id;
                if (!availableGenTypes.includes(material.name)) {
                    availableGenTypes.push(material.name);
                }
                player.sendMessage(`Material upgraded to: ${material.name} for ${material.cost}`);
            } else {
                player.sendMessage(`Not enough money to buy ${material.name}. You need ${material.cost} to buy this material.`);
            }
        });
}

slow walrus
#

yes that should be correct

#

ah no

#

removeScore doesn't exist

#

use setScore, and subtract the value from the playerScore

random flint
#

Oh my god, it's definitely AI! 🔥

slow walrus
#

so setScore(player, playerValue - material.cost)

uncut summit
slow walrus
#

don't use AI

#

it sucks

uncut summit
#

cuz i didnt understand

slow walrus
#

just actually learn how to write it

terse tide
#

M9SSE use mctools to write if you are in an phone

uncut summit
uncut summit
# slow walrus just actually learn how to write it
// Upgrade Gen Material
function upgradeGenMaterial(player) {
    const materialNames = materials.map(mat => mat.name);

    new ModalFormData()
        .title("Upgrade Gen Material")
        .dropdown("Select new material", materialNames, 0)
        .show(player)
        .then(response => {
            if (response.canceled) return;

            const selectedMaterialIndex = response.formValues[0];
            const material = materials[selectedMaterialIndex];

            // Check player's current balance using scoreboard values
            const playerScore = world.scoreboard.getObjective('money')?.getScore(player);
            if (playerScore !== undefined && playerScore >= material.cost) {
                // Deduct money and upgrade material by subtracting the cost
                world.scoreboard.getObjective('money')?.setScore(player, playerScore - material.cost);
                currentMaterial = material.id;
                if (!availableGenTypes.includes(material.name)) {
                    availableGenTypes.push(material.name);
                }
                player.sendMessage(`Material upgraded to: ${material.name} for ${material.cost}`);
            } else {
                player.sendMessage(`Not enough money to buy ${material.name}. You need ${material.cost} to buy this material.`);
            }
        });
}```
#

this fine?

jade grail
#

yall know how i can use player.getEntitiesFromViewDirection().filter() to get 1 entity which is closest to my camera cuz i got 0 idea of raycast works thanks

terse tide
uncut summit
random flint
# terse tide

His code is AI-generated. I doubt he's using any tool for coding bruh

jade grail
#

yall know how i can use player.getEntitiesFromViewDirection().filter() to get 1 entity which is closest to my camera cuz i got 0 idea of raycast works thanks?

deep yew
#

from there, you can use a loop to iterate over each slot using inventory.getSlot(i) or .getItem for the itemStack

deep yew
wary edge
jade grail
#

idk if that a realy query

#

just an example

random flint
wary edge
#

I meant jist do [0]

jade grail
#

?

wary edge
#

No.

jade grail
#

...

random flint
#

player.getEntitiesFromViewDirection()[0]

wary edge
#

getEntitiesFromViewDirection()[0].entity

I also just learned EntityRaycastHit has a distance option so you can filter by that as well.

jade grail
#

Ohhh

#

kkkk

wary edge
jade grail
#

im just reading this is there a website which has information on how i can configure it?

random flint
jade grail
#

but i dont know what to fixed and others do

hidden bramble
#

Do you need Beta APIs to be enabled for (non-beta) scripts to work or is it only required for scripts using the beta modules?

jade grail
#

i think i got it working

uncut summit
#

need help

#
function switchGenType(player) {
    // Ensure the player has bought materials available for selection
    if (boughtMaterials.length === 0) {
        player.sendMessage("You haven't bought any materials yet!");
        return;
    }

    // Create the dropdown list with material names that are bought
    const boughtMaterialNames = boughtMaterials.map(matName => matName);

    // Show the form with the bought materials
    new ModalFormData()
        .title("Switch Gen Type")
        .dropdown("Select the new gen type", boughtMaterialNames, 0)
        .show(player)
        .then(response => {
            if (response.canceled) return;

            // Get the selected material name from the form
            const selectedMaterialName = response.formValues[0];

            // Find the full material object based on selected name
            const selectedMaterial = materials.find(mat => mat.name === selectedMaterialName);

            if (selectedMaterial) {
                // Set the current gen type to the selected material's ID
                currentMaterial = selectedMaterial.id;
                player.sendMessage(`Generation type switched to: ${selectedMaterial.name}`);
            } else {
                player.sendMessage("Invalid selection for gen type.");
            }
        });
}


#

sorry to bother u guys

#

any help?

uncut summit
#

nvm

#

i fixed it

dim tusk
#
world.afterEvents.entitySpawn.subscribe(({
    entity
}) => {
    if (entity.hasComponent('item')) {
        const getDistance = (vector1, vector2) => {
            const dx = vector1.x - vector2.x;
            const dy = vector1.y - vector2.y;
            const dz = vector1.z - vector2.z;
            return Math.sqrt(dx * dx + dy * dy + dz * dz);
        };

        const player = entity.dimension.getPlayers().find(mob => {
            getDistance(mob.getViewDirection(), entity.getViewDirection()) === 0;
        });
        const item = entity.getComponent('item').itemStack;

        if (player && player.getRotation().x === entity.getRotation().x && player.getRotation().y === entity.getRotation().y && player.getRotation().z === entity.getRotation().z) {
            console.error(`${player.name} dropped ${item.typeId}x${item.amount}`);
        }
    }
});```

Inefficient item drop detection.
chilly fractal
#

Yo do I need anything other than @minecraft/server-net module in my manifest to make a simple bedrock to discord link work? (I know I need BDS)

#

Cuz uh this

#

Why exactly would I need server admin?..

#

Or do these depend on the @minecraft/server-net module???

#

I'm dearly confused

distant gulch
# chilly fractal Why exactly would I need server admin?..

@minecraft/server-admin Module
Contains types related to administering a Bedrock Dedicated Server. These types allow for the configuration of variables and secrets in JSON files in the Bedrock Dedicated Server folder. These types cannot be used on Minecraft clients or within Minecraft Realms.

granite badger
knotty plaza
#

Remember its only available for bds

buoyant canopy
#

which particle has a small circular shape, doesn't move and can have its color modified?

random flint
#

custom particle

buoyant canopy
terse pulsar
#

Can i use replaceitem on runCommandAsync?

buoyant canopy
#

it seems like a block placed by a block placer component with replace_block_item set to true, doesn't fire the beforeOnPlayerPlace custom component...

fair quarry
#

Is possible to like translate a form using a .lang file?

#

Cuz I tried and it didn't work (I did something wrong probably)

#

Just to be sure

steady canopy
#

How do i make obsidian destructible by explosion?

#

I dont know if this can be done with scripting, i've tried and seems to be impossible because getImpactedBlocks doesn't return obsidian blocks.

fair quarry
buoyant canopy
distant tulip
steady canopy
#

I tried getting impacted blocks but they aren't detected with the before or after event

distant tulip
#

they are not part of the impacted blocks
get the blocks in radius or using rays and impact them manually

steady canopy
#

but

#

source.location is not accesable for this event

#

in the event

#

so how am i gonna detect the center of the explosion to get the blocks in radius

distant tulip
#

maybe get impacted block and get it location?

steady canopy
distant tulip
#

that is true
weird that there is no location property

buoyant canopy
#

there is source, you might be able to get its location in the before event

steady canopy
#

it just returns undefined

distant tulip
#

after event?

buoyant canopy
#

and at that point the tnt entity is already gone

fair quarry
#

None

distant tulip
#

what is the problem

fair quarry
fair quarry
steady canopy
#

tho i already found a method

#

it's a workaround

#

a little overcomplicated but works

#
import { Block, Dimension, system, Vector3, world } from "@minecraft/server";


function getBlocksInRadius(center: Vector3, radius: number, dimension: Dimension) {
    const blocks: Block[] = [];
    const { x: centerX, y: centerY, z: centerZ } = center;

    for (let x = centerX - radius; x <= centerX + radius; x++) {
        for (let y = centerY - radius; y <= centerY + radius; y++) {
            for (let z = centerZ - radius; z <= centerZ + radius; z++) {
                const distance = Math.sqrt(
                    (x - centerX) ** 2 + (y - centerY) ** 2 + (z - centerZ) ** 2
                );

                if (distance <= radius) {
                    const block = dimension.getBlock({ x, y, z });
                    if (block) {
                        blocks.push(block);
                    }
                }
            }
        }
    }

    return blocks;
}

const tnts: { [id: string]: Vector3 } = {

}

world.afterEvents.entitySpawn.subscribe((res) => {
    const entity = res.entity
    if (entity.typeId !== 'minecraft:tnt') return;

    const tntInterval = system.runInterval(() => {
        if (!entity?.isValid()) return system.clearRun(tntInterval)

        tnts[entity.id] = entity.location
    })
})

world.beforeEvents.explosion.subscribe((res) => {
    const tnt = tnts[res?.source?.id]
    const dimension = res.dimension

    if (!tnt) return;
    const blocks = getBlocksInRadius(tnt, 4, dimension)

    for (const block of blocks){
        if (block?.typeId !== 'minecraft:obsidian') continue;

        dimension.runCommandAsync(`setblock ${block.x} ${block.y} ${block.z} air destroy`)
    }

    delete tnts[res.source.id]
})
#

saving the tnt location when it spawns

buoyant canopy
steady canopy
#

take a look at the code

buoyant canopy
#

gg

distant tulip
steady canopy
#

idk why but now .location is actually working 😭 minecraft sometimes is weird lol

#

whatever

honest spear
#

reload all the packs

#

/reload all

wary edge
jolly citrus
#

If you guys are ever running low on storage all of a sudden try clearing your content log history

distant tulip
jolly citrus
#

i was wondering why I went from 100gb to 5gb of disk space in the span of 3 days

#

🔥

honest spear
#

lmao

#

thats crazy

jolly citrus
#

how do i use the debugger with vsc again, i forgot

distant tulip
#

95gb of log is crazy too lol
you get errors a lot? or is it you using warn

honest spear
jolly citrus
jolly citrus
honest spear
jolly citrus
honest spear
#

i mean are you generating world or something?

jolly citrus
#

checking for armor every second,

honest spear
#

then what lol?

jolly citrus
#

checking for held item every tick

honest spear
#

ohh

jolly citrus
#

checking claim area every time you interact with block

honest spear
#

ya ItemStacks are expensive

jolly citrus
#

bc if u held down a block for more than 1 sec

#

you could basically crash the world

honest spear
#

well you should optimize the code

jolly citrus
#

i tried already

distant tulip
jolly citrus
# honest spear well you should optimize the code

how does one optimize this

const effectsMap = {
    "minecraft:iron_ingot": { effect: "resistance", amplifier: 0 },
    "minecraft:ghast_tear": { effect: "regeneration", amplifier: 0, unique: true },
    "minecraft:blaze_powder": { effect: "strength", amplifier: 0 },
    "minecraft:sugar": { effect: "speed", amplifier: 1 },
    "minecraft:magma_cream": { effect: "fire_resistance", amplifier: 0 },
    "minecraft:feather": { effect: "jump_boost", amplifier: 0 }
};

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const playerClass = player.getDynamicProperty("class");
        if (playerClass === "bard") {
            const inventory = player.getComponent("inventory");
            const heldItem = inventory.container.getItem(player.selectedSlotIndex) ?? null;
            
            if (!heldItem) continue;

            const effectData = effectsMap[heldItem?.typeId ?? null];
            if (!effectData) continue;

            const team = player.getDynamicProperty("team");
            const nearbyPlayers = world
                .getDimension(player.dimension.id)
                .getEntities({
                    type: "minecraft:player",
                    maxDistance: 25,
                    location: player.location
                });

            for (const target of nearbyPlayers) {
                if (target.getDynamicProperty("team") === team) {
                    const hasEffect = effectData.unique 
                        ? target.getEffect(effectData.effect) != undefined 
                        : false;

                    if (!hasEffect) {
                        target.addEffect(effectData.effect, 100, {
                            amplifier: effectData.amplifier
                        });
                    }
                }
            }
        }
    }
}, 1);
#

maybe i should cache different properties more

#

but idk

honest spear
#

yA

#

Do it based on player

jolly citrus
honest spear
#

also use ContainerSlot class

jolly citrus
honest spear
jolly citrus
#

how can you cache a slot if the item can change and you're only supposed to store it on join

honest spear
#

I am not saying item i am saying the slot

#

Check ContainerSlot in docs

#

its direct reference

jolly citrus
#

what is the difference between that and getItem

jolly citrus
#

[container.getSlot(0...35)] ?

honest spear
honest spear
#

thats under the equipment componennt

honest spear
jolly citrus
# honest spear use mainHandl slot, not numbered hotbar slot

like so?

world.afterEvents.playerSpawn.subscribe(({player, initialSpawn})=>{
    if (initialSpawn) {
        playerCache[player.id] = {
            inventory: player.getComponent("inventory").container,
            selectedSlot: player.getComponent("equippable").getEquipmentSlot(EquipmentSlot.Mainhand)
        }
    }
})

export let playerCache = {}
#

is that what you meant

#

and then i use playerCache[player.id].selectedSlot for the heldItem variable or

honest spear
#

Ya, but i would use sets and maps

#

here is example

jolly citrus
#

map can store objects right

#

if yes then i was actually going to use those at 1st i was just unsure

honest spear
#
const PLAYER_CACHE = new WeakMap();

world.afterEvents.playerSpawn.subscribe(({player, initialSpawn})=>{
    if (initialSpawn) {
        playerCache.set(player, {
            inventory: player.getComponent("inventory").container,
            selectedSlot: player.getComponent("equippable").getEquipmentSlot(EquipmentSlot.Mainhand)
        });
    }
})
jolly citrus
#

weakmap means unordered

#

?

#

or

honest spear
#

WeakMap is better bc you don't have to care about deleting old stuff

jolly citrus
#

i forgot what the difference is

honest spear
#

also its Map cache so you can use object directly as keys

#

and its faster

jolly citrus
honest spear
#

i already sended that example tho

jolly citrus
#

wdym by using object directly as keys

honest spear
jolly citrus
#

OH

honest spear
#

also once the player is not available then it gets deleted

#

but in general there is not much to optimize bc you are calling nested loops anyway

jolly citrus
honest spear
#

but not sure if that helps much

jolly citrus
#

why is my game crashing every time i open the world after i implemented this cache thing

honest spear
#

i have no idea

#

¯_(ツ)_/¯

last latch
#

TypeScript related:

I have gotten an issue, i want to use Class Proxy for my DataBase but i cant implement dynamic typings to it (example: new DataBase<Properties>();). I would love some help, by either saying it isnt possible or helping.

All i need is to implement T as either a index signature or a typing in another way.

I want Intellisense to show Properties of my given Interface.

This is the code i came up with :

class DataBase<T extends { [key: string]: any }> {
    constructor() {
        return new Proxy(this, {
            get(target, prop: string | symbol, receiver: any) {
                const value = new DynamicPropertyManager(prop as string).get();

                try {
                    return JSON.parse(value as string);
                } catch {
                    return value;
                };
            },
            set(target, prop: string | symbol, value: any) {
                let replacedValue = value

                if (typeof value === "object")
                    replacedValue = JSON.stringify(value);

                new DynamicPropertyManager(prop as string).set(replacedValue);

                return true;
            }
        });
    };

    // implement either T as a index signature or T as a typing somehow
};

export { DataBase };
jolly citrus
#

wait could it be bc playerCache is in index and i use heldItem in another file

#

yea that was it

fair quarry
honest spear
dim tusk
#

You can't detect what items can break a block right?

uncut summit
#

need help

#
// Event listener for chat input to trigger custom commands
world.beforeEvents.chatSend.subscribe((ev) => {
    const player = ev.sender;
    let message = ev.message;

    // Check for custom command prefix
    Object.values(customCommands).forEach(command => {
        if (message.startsWith(command.prefix)) {
            const commandName = message.replace(command.prefix, '').trim();
            
            if (customCommands[commandName]) {
                // Ensure command is valid before executing
                try {
                    world.getDimension('overworld').runCommand(customCommands[commandName].action); // Or use 'world' context directly
                    player.sendMessage(`Executed custom command: ${commandName}`);
                } catch (error) {
                    player.sendMessage(`Error executing command: ${error.message}`);
                }
            }
        }
    });
});```
uncut summit
# dim tusk Wrap it in *system.run(() => { })*

like this

system.run(() => {
    world.beforeEvents.chatSend.subscribe((ev) => {
        const player = ev.sender;
        let message = ev.message;

        // Check for custom command prefix
        Object.values(customCommands).forEach(command => {
            if (message.startsWith(command.prefix)) {
                const commandName = message.replace(command.prefix, '').trim();
                
                if (customCommands[commandName]) {
                    // Ensure command is valid before executing
                    try {
                        world.getDimension('overworld').runCommand(customCommands[commandName].action); // Or use 'world' context directly
                        player.sendMessage(`Executed custom command: ${commandName}`);
                    } catch (error) {
                        player.sendMessage(`Error executing command: ${error.message}`);
                    }
                }
            }
        });
    });
});

#

??

uncut summit
#

ok

uncut summit
# dim tusk No the run command only
world.beforeEvents.chatSend.subscribe((ev) => {
    const player = ev.sender;
    let message = ev.message;

    // Check for custom command prefix
    Object.values(customCommands).forEach(command => {
        if (message.startsWith(command.prefix)) {
            const commandName = message.replace(command.prefix, '').trim();
            
            if (customCommands[commandName]) {
                // Wrap the runCommand in system.run()
                system.run(() => {
                    try {
                        player.runCommand(customCommands[commandName].action);
                        player.sendMessage(`Executed custom command: ${commandName}`);
                    } catch (error) {
                        player.sendMessage(`Error executing command: ${error.message}`);
                    }
                });
            }
        }
    });
});```
uncut summit
ruby haven
#

How do you check for players in an if statement

ruby haven
uncut summit
dim tusk
#

or you can just put js if (damageSource.damagingEntity.typeId === 'minecraft:player')

ruby haven
dim tusk
ruby haven
uncut summit
dim tusk
dim tusk
# uncut summit ^^^^^^^^^

Server form? Do it like you always do

new ActionFormData().title('title')
   .button('0')
   .button('1')
   .show(player)
   .then(res => {
      if (res.canceled) return;
      console.error(res.selection);
   });```
uncut summit
#

Or smtg like that

ruby haven
#
world.afterEvents.entityDie.subscribe(({ damageSource, deadEntity }) => {
  const killer = damageSource.damagingEntity;
  if (killer?.typeId === 'minecraft:player') {
    if (deadEntity.typeId === 'minecraft:villager') {
      killer.runCommand('scoreboard players add @s Kills 1');
    }
  }
})

Just to make sure, the player is the one running the command or any damaging.entity

drowsy scaffold
#

Which one is better for raw performance: Script API's native methods or tick.json and mcfunctions?

uncut summit
#

world.events.playerJoin.subscribe(ev => {

#

whats wrong with this code??

drowsy scaffold
dim tusk
ruby haven
dim tusk
#

You defined that the player is damaging entity

#

since this would only run if the killer is a player

ruby haven
dim tusk
# uncut summit But how can we /scriptevent gui:hi
import { system, world } from "@minecraft/server";

system.afterEvents.scriptEventReceive.subscribe(({ id, message, sourceEntity, sourceType }) => {
    console.error(id); // wiki:test
    console.error(message); // Hello World
    console.error(sourceEntity); // Player object
    console.error(sourceType); // Entity
});

world.getPlayers().forEach((player) => {
    player.runCommand("scriptevent wiki:test Hello World");
});```
uncut summit
#

?

dim tusk
dim tusk
# uncut summit how do i open a form with it?
import { system, world } from "@minecraft/server";

system.afterEvents.scriptEventReceive.subscribe(({ id, message, sourceEntity, sourceType }) => {
   if (id === 'gui:hi') {
      ... code ...
   }
});```
ruby haven
#

I never thought there are 2 types of villager in Minecraft

ruby haven
slow walrus
uncut summit
olive briar
#

How can I detect an entity that is within a radius of 2 blocks in front of me (which affects whoever is in the two blocks ahead and not just the second one)?

slow walrus
wary edge
uncut summit
uncut summit
#

?

olive briar
wary edge
dim tusk
slow walrus
#

I already told you yesterday to not use AI

uncut summit
dull shell
#

so 2 questions im still learning all this

  1. how can I divide my js files? i have everything in 1 js file
#
  1. whats wrong with this?
system.runInterval(()=>{
  let property = "jay:base_shop"
  for (let entity of world.getDimension("overworld").getEntities()) {
    if (entity.typeId === "jay:base_shop") {
      let containerType = hopper_minecart;
      let inventorySize = 54;```
dull shell
#
import { system, world } from "@minecraft/server"
import "scripts/generators.js"; ```
#

right?

olive briar
#
system.runInterval(() => {
    for (const player of world.getPlayers()) {
        for (const stand of world.getDimension('overworld').getEntities({
            type: 'dekuh:star_platinum'
        })) {
            const view = player.getViewDirection();
            const dimension = world.getDimension('overworld');
            const targets = player.getEntitiesFromViewDirection({
                maxDistance: 2
            });
            if (!stand.hasTag('punch') && stand.hasTag(`stand_of_${player.nameTag}`)) return;
            stand.removeTag('punch')
            for (const target of targets) {
                system.run(() => {
                    (line 60) target.applyKnockback(view.x, view.z, 6, view.y);
                    target.applyDamage(15);
                })
            }
        }
    }
});

its possible apply an knockback in the detected entities?

shut citrus
#

How to get entity fieldofview?

slow walrus
#

and the same for the other parts using target

#

or change your for loop to

for (const { entity: target } of targets)
#

that's an awful explanation lmao

dim tusk
#

Lemme delete that and redo it. Or let others do it.. i suck at this 🙃

slow walrus
#
dim tusk
#

Can I get the total time of the world since it was created?

slow walrus
#

currentTick

#

or

#

actually

#

no nvm

sharp elbow
ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityDie.subscribe(({ damageSource, deadEntity }) => {
  const killer = damageSource.damagingEntity;
  if (killer?.typeId == 'minecraft:player') {
    if (deadEntity.typeId == 'minecraft:villager' || deadEntity.typeId == 'minecraft:villager_v2') {
      killer.runCommand("scoreboard players add @s Kills 1");
    }
    else if (deadEntity.typeId == 'mz:smile') {
      killer.runCommand("")
    }
  }
})

As you can see in the else if statement I want to run a command that rides the dead entity

ruby haven
dim tusk
ruby haven
dim tusk
#

How do you transform it? Using events in the json?

dim tusk
#

so if the dead mob is mz:smile you'll transform it to another entity and make player ride that mob?

ruby haven
dim tusk
#

Probably possible but idk a way to grab the transformed entity tho...

ruby haven
#

You see I'm creating a death scene from smile where the entity enters the players mouth so I need the transformed entity grab the player who killed him and do the possession

ruby haven
#

Wait is there a function to detect after an entity transforms?

slow walrus
#

you'll have to do a lil workaround:

  1. grab the deadEntity's location and dimension
  2. delay by 1 tick (system.run)
  3. get entities near that location (within 1 block or something) in the dimension
  4. filter for your new entity
  5. do the ride stuff
ruby haven
#

Thanks

ruby haven
#

Can an if statement contain world.afterEvents.something like this?

dull shell
#
import { system, world } from "@minecraft/server"
import { system, world } from './generators';```
rapid nimbus
#

Hey everyone

#

I have a script to run that shows the title when going to a certain place in Minecraft like the Traveler's Titles mod for Minecraft Java Edition but my script only runs when going to a certain dimension in Minecraft Bedrock like Overworld, Nether and The End, I want my script to run and show the title when going to a certain biome in Minecraft Bedrock too, please help me with this script of mine and I will thank you for helping me with this script

#

Here is the my titles script:

dim tusk
ruby haven
slow walrus
#

no?

#

you're setting victim to a bool

ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityDie.subscribe(({ damageSource, deadEntity }) => {
  const killer = damageSource.damagingEntity;
  if (killer?.typeId == 'minecraft:player') {
    if (deadEntity.typeId == 'minecraft:villager' || deadEntity.typeId == 'minecraft:villager_v2') {
      killer.runCommand("scoreboard players add @s Kills 1");
    }
    else if (deadEntity.typeId == 'mz:smile' && killer.hasTag('survivor')) {
      deadEntity.runCommand('event entity @s bridge:dead')
    }
    else {
      deadEntity.runCommand('event entity @s bridge:fake_death')
      killer.runCommand('ride @s start_riding ${deadEntity.id}' teleport_rider)
    }
  }
})

Is there a more flexible way than using ride command?

ruby haven
shut citrus
random flint
#

That's amazing. The use of display entities is mindblowing. Such a great way to demonstrate Script-API in Bedrock Editions.
( My sarcasm was not obvious enough apparently )

dim tusk
# shut citrus rpg item

I thought my phone was broken cause it keeps becoming black... But God dam it looks so good

wooden zealot
#

is there a way to get data like this

shut citrus
remote oyster
wooden zealot
#

i think its for the dimension

slim spear
#

very late reply
Kind of, with async functions and an entity with an environment sensor. But it won't get all types of biomes due to limitations.

#

These are the only biomes that can be detected

unique acorn
wooden zealot
#

it worked thanks

slim spear
ruby haven
#
import { world, EntityRideableComponent } from '@minecraft/server';

world.afterEvents.entityDie.subscribe(({ damageSource, deadEntity }) => {
  const killer = damageSource.damagingEntity;
  if (killer?.typeId === 'minecraft:player') {
    if (deadEntity.typeId === 'minecraft:villager' || deadEntity.typeId === 'minecraft:villager_v2') {
      killer.runCommand("scoreboard players add @s Kills 1");
    } else if (deadEntity.typeId === 'mz:smile' && killer.hasTag('survivor')) {
      deadEntity.runCommand('event entity @s bridge:dead');
    } else {
      deadEntity.runCommand('event entity @s bridge:fake_death');
      const rideableComponent = deadEntity.getComponent('minecraft:rideable');

      if (rideableComponent) {
        rideableComponent.addRider(killer);
      }
    }
  }
});

So in this code ones the player kills the entity smile it triggers an event called fake death that adds the rideable component to the entity smile then force the killer to ride the entity smile but it doesn't work I tried debugging it in the debugging playground it says no errors, does anyone know what is the problem?

dim tusk
ruby haven
ruby haven
ruby haven
dim tusk
ruby haven
ruby haven
dim tusk
ruby haven
dim tusk
ruby haven
ruby haven
dim tusk
#
world.afterEvents.entityDie.subscribe(({ damageSource: { damagingEntity }, deadEntity }) => {
   if (damagingEntity.typeId !== 'minecraft:player) return;

   if (deadEntity.typeId === 'minecraft:villager_v2') {
      world.scoreboard.getObjective('kills').addScore(damaginEntity, 1);

   } else if (deadEntity.typeId === 'mz:smile' && damagingEntity.hasTag('survivor')) {
      deadEntity.triggerEvent('bridge:dead');

   } else {
      deadEntity.triggerEvent('bridge:fake_death');
      const ride = deadEntity.getComponent('rideable');
      system.runTimeout(() => {
         ride?.addRider(damaginEntity);
      }, 2);
   }
});```
remote oyster
ruby haven
remote oyster
#

Very interesting.

sharp elbow
# dull shell what would go into something?

You would import whatever variables, functions, or classes you have defined inside something.js.
You might split up functions you commonly use into their own file so you may import them later.

//something.js
function doOperation(arg) {
  return arg;
}
export doOperation;
//entry.js
import {world, system} from '@minecraft/server';
import {doOperation} from './something';

var foo = "hi";
console.warn(doOperation(foo));  //[Script][warning] hi
random flint
ruby haven
#
import { world, system } from '@minecraft/server';

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

  if (!damagingEntity || damagingEntity.typeId !== 'minecraft:player') return;

  if (deadEntity.typeId === 'minecraft:villager_v2') {

    world.scoreboard.getObjective('Kills').addScore(damagingEntity, 1);

  } else if (deadEntity.typeId === 'mz:smile' && damagingEntity.hasTag('survivor')) {
    deadEntity.triggerEvent('bridge:dead');

  } else {
    deadEntity.triggerEvent('bridge:fake_death');
    const ride = deadEntity.getComponent('minecraft:rideable');
    if (ride) {
      system.runTimeout(() => {
        ride.addRider(damagingEntity);
      }, 2);
    }
  }
});
random flint
#

equivalent to forceShow or smt:

async function forceRide(ride,rider,maxAttempt=200) {
    const rideable = ride.getComponent("rideable");
    if (!rideable) return;
    while (maxAttempt--) {
        if (rideable.addRider(rider)) return true;
        async system.waitTicks(1);
    }
    return false
}
north rapids
#

How do I get the item (item stack) from the dropped item (entity)?

random flint
thorn flicker
north rapids
thorn flicker
warm mason
random flint
random flint
#

Oh, you mean, that, yey

#

Is the minecraft:arrow hardcoded to be destroyed upon hitting an entity? I tried putting true on stopOnHit EntityProjectileComponent.

If true, the projectile will stop moving when an entity is hit as though it had been blocked. E.g. Thrown trident on hit behavior.

The arrow disappeared regardless. 😔
( Using it inside entitySpawn )

warm mason
random flint
#

damn, JSON takes priority

warm mason
#

Or just create a custom arrow

random flint
#

I would prefer it to be on all server-side. Luckily, arrow is spawnable with entitySpawn, so I'll just recreate it... though, It would lack the original damage affected by enchants.

tawny reef
#

Étés vous influanceur ???

warm mason
tawny reef
#

im france

#

je parle le francais

#

vous etes vraiment pas sympa

#

bande de lopsa

warm mason
#

We don't care what language you speak. You need to write in English here.

random flint
#

Do you expect people to keep copy-paste your message on Google Translate? Lol.
-# (Ik there's a bot to translate here)

Translation tools are also not 100% accurate. So English is always preferred.

distant tulip
rapid thorn
#

is there a way to have a score act as a players health?

distant tulip
rapid thorn
#

so if the score is 60 they would have 60 health

rapid thorn
distant tulip
#

get the health component and set it as score
need help with that?

warm mason
random flint
distant tulip
distant tulip
#

@granite badger

random flint
#

just use microsoft docs 🤪

warm mason
#

It's time to go to the dark side)) That is, Microsoft documentation

distant tulip
#

i use both
just prefer his layout

random flint
wary edge
#

Use stirantes.

distant tulip
ripe swan
#

I've got a generic "string_property" function and I'm trying to figure out what value to pass to check an entity's nameTag property. I know the Entity class has a nameTag property, but I'd rather not have special logic to handle just that property. Is there a corresponding string value that works for the entity.getproperty() method? I've tried "nameTag" and "name" and "nametag", all of which have come back as undefined.

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

system.runInterval(() => {
  for (let player of world.getAllPlayers()) {
    let hp = player.getComponent("health")
    world.scoreboard.getObjective("health").setScore(player, hp.currentValues)
  }
})```
distant tulip
rapid thorn
distant tulip
rapid thorn
#

its working now but how do i make it so if the score is 60 the player then has 60 health?

granite badger
#

I'm still experimenting with the new typedoc and vuepress layout cuz it looks nice, so some drastic changes might happen

dim tusk
rapid thorn
warm mason
rapid thorn
#

so if the players score is 100 they have 100 health and damage done to them will be taken off the scoreboard and not their actual health

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

system.runInterval(() => {
  for (let player of world.getAllPlayers()) {
    let hp = player.getComponent("health")
    hp.setCurrentValue(world.scoreboard.getObjective("health").getScore(player) || hp.currentValue)
  }
})

world.afterEvents.entityHealthChanged.subscribe(data => {
  let player = data.entity
  if (player.typeId == "minecraft:player") {
    world.scoreboard.getObjective("health").setScore(player, data.newValue)
  }
})
#

True, I’m not sure about the regeneration of the player’s hearts, since health is not an integer, due to such manipulations, health will always be rounded up and is unlikely to be able to regenerate

distant tulip
rapid thorn
warm mason
rapid thorn
warm mason
#

Just use the health component or, as a last resort, create functions if you are too lazy to write

rapid thorn
dim tusk
#

What's the best way to detect if the item you used to hit an entity decreased it's durability?

jade grail
#

yall im wondering how i can check for the blocks around the player

#

in commands its execute if block ~~~

#

i can get the player pos

#

but idk how to test for the blocks around the player

dim tusk
# jade grail in commands its execute if block ~~~

This how you detect blocks. There's also getBlocks() but you need to import BlockVolume in the server

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

// one block
player.dimension.getBlock({ x: 0, y: 0, z: 0 });

// multiple blocks
const locations = player.dimension.getBlocks(new BlockVolume({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }), true);

// get all locations inside of the volumes you used in *getBlocks()*
for (const location of locations.getBlockLocationIterator()) {
   cosnt block = player.dimension.getBlock(location);
}
dim tusk
distant tulip
gusty bramble
#

Would that also detect items going into hoppers tho?

jade grail
#

-_- this is what i tried to do

#

yes ik im very dumb

dim tusk
#

Tho there's player.isInWater function too

jade grail
#

thankssssss

dim tusk
turbid gulch
#

How can I force show form using custom chat commands beacuse when I tried normally it wouldnt close my chat

unique acorn
#

you cant close chat

#

what force show form does is wait for player to close chat, then open form

#

you can maybe damage the player so it closes?

#

how?

random flint
#

nvm

unique acorn
#

👍

random flint
#

I forgor uiManager was not that far yet

turbid gulch
random flint
#

Cant close chat. But you can keep sending form.show() until the player successfully opens it.

distant gulch
#

Omg

#

I never realised that the java redstone resource pack was so easily created (scuffed)

#
system.runInterval(() => {
    world.getAllPlayers().forEach((e) => {
        const redstoneGrab = e.getBlockFromViewDirection().block.getRedstonePower();
        const blockGrab = e.getBlockFromViewDirection().block.typeId.slice(10).replace("_", " ").toUpperCase();
        if (redstoneGrab == undefined) e.onScreenDisplay.setActionBar();
        e.onScreenDisplay.setActionBar(`§c${blockGrab}: §f${redstoneGrab}`);
    })
})
#

its like 10 lines of code

#

and itll say the name of the redstone component ur looking at, and its output power

#

i made it for my redstone friend

wary edge
#

I mean, in java you can easily assign textures to each blockstate.

distant gulch
#

so here's the bedrock equivalent

distant gulch
#

Will adding too many dynamicProperties cause lag? I'm sure they're probably less laggy than scores, but I want to make sure

ruby haven
#

Is it possible to remove the hearts of the entity your riding or make it invisible so it doesn't show?

dim tusk
distant gulch
#

Though you might be able to change onScreenDisplay

distant gulch
#

so I don't have to stress about it?

dim tusk
distant gulch
dim tusk
#

no comments on this..
-# not allowed here

distant gulch
#

oh dang

#

wasn't me?

#

yeah, never happened

slow walrus
#

just spend the 30 bucks tbh, it's pretty hard to find other versions that are safe and up to date

#

plus you get java with it

distant gulch
#

and 25 is taken up thru system files

distant gulch
#

I need to finally learn how this works

#

So it would be

#

setHudVisibility(false,

#

then how do I call on a hudElements?

#

setHudVisibility(false, {[HorseHealth]})

#

?

dim tusk
#
player.onScreenDisplay.setHudVisibility(0, [ 0, 1 ])```
distant gulch
#

[0, 1]?

dim tusk
#

It's number

distant gulch
#

the number of?

distant gulch
#

Oh, I thought I called on the name of the element

dim tusk
#
player.onScreenDisplay.setHudVisibility(0, [ 10 ])```
distant gulch
#

I see

#

Thanks

distant gulch
#

That should hide (0), the HorseHealth (10)

dim tusk
# distant gulch Ohh, it's an array

You can hide it thru words just need to import that in the server.

import { HudVisibility, HudElement }  from '@minecraft/server';

player.onScreenDisplay.setHudVisibility(HudVisibility.Hide, [ HudElement.HorseHealth ])```
distant gulch
#

fun

#

Is that permanent

#

or is that something I need to run on an interval?

#

not permanent*, but toggled

dim tusk
distant gulch
#

They can bring it back?

ruby haven
distant gulch
#

just getting off and on the horse?

distant gulch
#

What do u wanna pcik?

#

someone with a certain tag?

#

I'll write a code for u rq

ruby haven
distant gulch
ruby haven
distant gulch
#

custom:smile

#

oh alr

#

well, I'm dumb with custom entities

#

but I gotcha

#

one sec

#

is custom smile the one riding the horse?

distant gulch
ruby haven
distant gulch
#

does it have horseHearts?

ruby haven
ruby haven
distant gulch
#

ho dang

ruby haven
# distant gulch ho dang

Well it is actually a boss based on the smile horror movie where the smile entity makes you think you beat him but then suddenly it is actually alive and that is where the smile entity forces you to ride and that is where I create the scene where it enters the players mouth

ruby haven
distant gulch
#

oh, creepy

#

I watched Smile 2

#

I have an entire theory now

#

it's a dumb theory

#

but it's a theory nonetheless

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

system.runInterval(() => {
    const overworld = world.getDimension('overworld');

    for (const entity of overworld.getEntities({ type: 'mz:smile' })) {
        const rideable = entity.getComponent('rideable');
        if (rideable) {
            const riders = rideable.getRiders();

            for (const rider of riders) {
                if (rider.typeId === 'minecraft:player') {
                    rider.onScreenDisplay.setHudVisibility(0, [ 10 ]);
                }
            }
        }
    }

    for (const player of world.getPlayers()) {
        let isRiding = false;

        for (const entity of overworld.getEntities({ type: 'mz:smile' })) {
            const rideable = entity.getComponent('rideable');
            if (rideable && rideable.getRiders().some(rider => rider.id === player.id)) {
                isRiding = true;
                break;
            }
        }

        if (!isRiding) {
            player.onScreenDisplay.setHudVisibility(1, [ 10 ]);
        }
    }
});
ruby haven
dim tusk
distant gulch
#

oh dang, he did it for me

#

his script is better too

ruby haven
distant gulch
#

mine was innaccurate

#

mine was just

system.runInterval((e) => {
    world.getAllPlayers().forEach((player) => {
        if (player.getComponent("minecraft:riding") == true) {
            const smileGrab = player.dimension.getEntities({ location: { x: player.location.x, y: player.location.y - 1, z: player.location.z }, maxDistance: 1 })
            if (smileGrab.length == 0) return;
            player.onScreenDisplay.setHudVisibility(0, [10]);
        }
    })
})
#

lol

#

Thanks @dim tusk

#

idk if mine even works

#

it's trial and error lol

#

oh wait

#

I forgot to detect if the entity wa mz:smile

#

its alr

distant gulch
#

I'm in the process of learning script

#

my biggest scrip is only 250 lines, and it's broken up between multiple tests

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

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const entities = player.dimension.getEntities({ type: 'mz:smile' });
        let isRiding = false;

        for (const entity of entities) {
            const rideable = entity.getComponent('rideable');
            if (rideable & rideable.getRiders().some(rider => rider.id === player.id)) {
                isRiding = true;
                break;
            }
        }

        if (isRiding) {
            player.sendMessage("riding 'mz:smile'");
        } else {
            player.sendMessage("not riding 'mz:smile'.");
        }
    }
});
#

Smaller version

ruby haven
distant gulch
#

I gotta use async

dim tusk
#

And also it does make sense you're modifying it before it happens

distant gulch
#

I usually need to do a runCommand("tag @s")

distant gulch
#

runCommandAsync

#

then I run an entire system.runInterval to take the person with a tag

#

then remove the tag

#

it's a hassle

dim tusk
#
system.run(() => {
   player.addTag('test');
});```
distant gulch
#

I was trying to detect when an item was picked up

dim tusk
#

You're probably doing it wrong.

distant gulch
#

then do stuff to the person who picked it up

dim tusk
distant gulch
#

was yes, but I managed a scuffed way

#

the issue was that none of my script worked in the beforeEvents category

#

I had to runAsynch

#

Async

#

and use a seperate system.runInterval

#

and those with that tag

#

it wouldn't even let me run a dynamicProperties script

#

it was on an entityRemove

dim tusk
# distant gulch was yes, but I managed a scuffed way
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
   if (itemStack.typeId === 'minecraft:stick') {
      system.run(() => {
         source.addTag('test');
         system.runTimeout(() => {
            source.removeTag('test');
         }, 2); // remove after two ticks
      });
   }
});```
#

Kinda like this.

distant gulch
#

oh dang

#

alr, why does using system.run fix it up?

dim tusk
distant gulch
#

ahh, I see

#

Thanks a lot

dim tusk
#

As long as it runs it different tick it's good, you can use interval, run, runtInterval

distant gulch
#

dope,thanks a lot!

#

also, system.run is the same as system.runTimeout with no tick delay right?

dim tusk
# distant gulch dope,thanks a lot!
world.beforeEvents.entityRemove.subscribe(({
    removedEntity
}) => {
    if (removedEntity.hasComponent('item')) {
        const player = removedEntity.dimension.getPlayers({
            location: {
                x: removedEntity.location.x - 1.5,
                y: removedEntity.location.y - 0.5,
                z: removedEntity.location.z - 1.5
            },
            volume: {
                x: 3,
                y: 2,
                z: 3
            }
        })[0];

        if (player) {
            const itemComponent = removedEntity.getComponent('item');
            const itemStack = itemComponent.itemStack;

            const typeId = itemStack.typeId;
            const amount = itemStack.amount;
            const nameTag = itemStack.nameTag || '';
            const lore = itemStack.getLore() || [];
            const durability = itemStack.getComponent('durability')?.damage || 0;
            const enchantments = itemStack.getComponent('enchantable')?.getEnchantments() || [];
            const cooldown = itemStack.getComponent('cooldown');

            const cooldownCategory = cooldown?.cooldownCategory || '';
            const cooldownTicks = cooldown?.cooldownTicks || 0;

            if (
                itemInventory(
                    player, typeId, amount, nameTag, lore,
                    durability, enchantments, cooldownCategory, cooldownTicks
                )
            ) {
                console.error(`${player.name} picked up ${typeId}x${amount}`);
            } else {
                console.error(`Item ${typeId}x${amount} not found in ${player.name}'s inventory.`);
            }
        }
    }
});

function itemInventory(player, typeId, amount, nameTag, lore, durability, enchantments, cooldownCategory, cooldownTicks) {
    const inventory = player.getComponent('inventory').container;

    for (let i = 0; i < inventory.size; i++) {
        const slot = inventory.getItem(i);
        if (slot) {
            const slotDurability = slot.getComponent('durability')?.damage || 0;
            const slotEnchantments = slot.getComponent('enchantable')?.getEnchantments() || [];
            const slotCooldown = slot.getComponent('cooldown');
            const slotCooldownCategory = slotCooldown?.cooldownCategory || '';
            const slotCooldownTicks = slotCooldown?.cooldownTicks || 0;

            if (
                slot.typeId === typeId &&
                slot.amount >= amount &&
                (nameTag === '' || slot.nameTag === nameTag) &&
                (lore.length === 0 || JSON.stringify(slot.getLore()) === JSON.stringify(lore)) &&
                slotDurability === durability &&
                JSON.stringify(slotEnchantments) === JSON.stringify(enchantments) &&
                slotCooldownCategory === cooldownCategory &&
                slotCooldownTicks === cooldownTicks
            ) {
                return true;
            }
        }
    }
    return false;
}```

I made this pick up detection but not very accurate...
distant gulch
#

ah, I see

distant gulch
#

I also didn't detect WHAT they picked up

#

just if they were closest player within 2 blocks, had the item that was removed, and then I gave em an effect or whatnot

dim tusk
distant gulch
#

I just didn't

dull shell
# sharp elbow You would import whatever variables, functions, or classes you have defined insi...
generators.js
function doOperation(arg) {
  return arg;
}```
```js
StarterTests.js
import { system, world } from "@minecraft/server"
import {world, system} from '@minecraft/server';
import {doOperation} from './generators';

system.runInterval(()=>{
  let property = "jay:base_shop"
  for (let entity of world.getDimension("overworld").getEntities()) {
    if (entity.typeId === "jay:base_shop") {
      containerType = hopper_minecart;
      inventorySize = 54;
    }
  }
}
)```
dull shell
#

oops sorry I didnt notice that

dim tusk
distant gulch
#

at least that

dim tusk
#

Add the export cause you're calling the function from another file into another file.

dull shell
#

okay I have a different error now but thats bc my scripts wrong

#

but my generators is not running anymore

#
generators.js
export function doOperation(arg) {

system.runInterval(()=>{
  let property = "jay:diamondgen"
  for (let entity of world.getDimension("overworld").getEntities()) {
    if (entity.typeId === "jay:diamondgen") {
        let dynamicProperty = entity.getDynamicProperty(property);
        if (dynamicProperty === undefined) {
            entity.setDynamicProperty(property, 30)
        } else 
        if (dynamicProperty > 0) {
            entity.setDynamicProperty(property, dynamicProperty - 1);
        } else 
        if (dynamicProperty <= 0) {
          entity.setDynamicProperty(property, 30);
          entity.runCommandAsync("execute @s ~~~ function game/gens/diamond");
          
        }

        entity.nameTag = `§bDiamond Generator\n§7[ §fSpawns in §c${entity.getDynamicProperty(property)}§fs §7]`
    }
  }
}, 20)

system.runInterval(()=>{
let property = "jay:emeraldgen"
for (let entity of world.getDimension("overworld").getEntities()) {
  if (entity.typeId === "jay:emeraldgen") {
      let dynamicProperty = entity.getDynamicProperty(property);
      if (dynamicProperty === undefined) {
          entity.setDynamicProperty(property, 65)
      } else 
      if (dynamicProperty > 0) {
          entity.setDynamicProperty(property, dynamicProperty - 1);
      } else 
      if (dynamicProperty <= 0) {
        entity.setDynamicProperty(property, 65);
        entity.runCommandAsync("execute @s ~~~ function game/gens/emerald");
        
      }

      entity.nameTag = `§2Emerald Generator\n§7[ §fSpawns in §c${entity.getDynamicProperty(property)}§fs §7]`
    }
  }
}, 20)
return arg;
}```
ruby haven
#

What would be the maximum script file I can run in one addon?

ruby haven
random flint
ruby haven
tawny jungle
#

can you not run setPermutation in onStepOn in a custom block component?

tawny jungle
#

hmm

#

is this correct?
block.setPermutation(BlockPermutation.resolve("sci:redstone_ore_mini", { "sci:poweredState": true }));

wary edge
tawny jungle
#

8x8x8

#
        "origin": [-4, 0, -4],
        "size": [8, 8, 8]
      },```
random flint
#

Any error?

wary edge
#

Does console.log run?

#

Best debugger.

random flint
#

Have you tried breaking and placing back the block :D

tawny jungle
#

it says:
[Scripting][error]-TypeError: not a function at onStepOn (mBFramework.js:231)

tawny jungle
random flint
#

onStepOn(evd) {
const block = evd.block;
block.setPermutation()
}

tawny jungle
#

this is the whole event

            const source = data.entity.typeId;
            const block = data.block?.typeId;
            if (source === "minecraft:player" && block === "sci:redstone_ore_mini") {
                world.sendMessage("This works now");
                block.setPermutation(BlockPermutation.resolve("sci:redstone_ore_mini", { "sci:poweredState": true }));
                console.log(error)
            }
        }```
#

the sendMessage works

#

wait

random flint
#

block is a string there

tawny jungle
#

did console log wrong

random flint
#

you put .typeId extracting the block identifier.

tawny jungle
#

it says the same without the ?

random flint
#

When .setPermutation is called, is being run on a string, not block class

#

const block = data.block;
if ( block?.typeId == "identifier") {
block.setPermutation()
}

  • move the ?.typeId into the if expression
#
onStepOn: (data) => {
            const source = data.entity.typeId;
            const block = data.block;
            if (source === "minecraft:player" && block?.typeId === "sci:redstone_ore_mini") {
                world.sendMessage("This works now");
                block.setPermutation(BlockPermutation.resolve("sci:redstone_ore_mini", { "sci:poweredState": true }));
                console.log(error)
            }
        }```
tawny jungle
#

oddly enough that does apply A state, but not THE state i wanted it to use

#

it set it to the default state instead but did not apply true to the sci:poweredState

wary edge
#

You should do withPermutation.

tawny jungle
wary edge
#

Yeah.

tawny jungle
#

ah

tawny jungle
# wary edge Yeah.

block.setPermutation(block.permutation.withState("sci:poweredState", true));
i tried this and the console is saying nothing, nor are any of the states changing

random flint
#

Check if the block state name is correct, or if it indeed affected.

#

Or you could check if there are things that cause it to revert.

tawny jungle
random flint
#

Is it supposed to change the texture or smt?

tawny jungle
#

it is supposed to change the "minecraft:light_emission" to 5

random flint
#

show the block json

#

the permutation part

tawny jungle
#
    "permutations": [
      {
        "condition": "q.block_state('sci:poweredState') == true",
        "components": {
          "minecraft:light_emission": 5
        }
      }
    ]```
random flint
#

hmm... Maybe leave and join the world? Cause custom component often needs that

tawny jungle
#

ok

#

its saying the same thing

#

should i add a second permutation for when its false?

random flint
#

what error now

tawny jungle
#

sorry, its not saying anything apart from the console.warn you sent

#

i worded it poorly

random flint
#
"description": {
      "identifier": "namespace:name",
      "states": {
        "namespace:booleans": [false, true]
    
      }
}
#

Did u set it like that?

tawny jungle
#

yes

#
  "format_version": "1.21.20",
  "minecraft:block": {
    "description": {
      "identifier": "sci:redstone_ore_mini",
      "menu_category": {
        "category": "nature",
        "group": "itemGroup.name.ore"
      },
      "states": {
        "sci:poweredState": [false, true]
      }```
random flint
#

So the block has the block state. But it doesn't glow? bruh.

tawny jungle
#

thats what im sayin

#

when i power it with redstone it glows

random flint
#

Try using command: /setblock?

#

manually setting it

#

oh

#

you're using that... well now it make sense

tawny jungle
#

momentarily of course

random flint
#

Either you find a way to integrate it with it, or avoid using it

tawny jungle
#

that makes good sense

#

well

#

thanks for helping me firgure out what it was

random flint
# tawny jungle that makes good sense

I have a solution. Maybe a new state specifically for onStep, then in permutation, you could use the OR operator || along with the redstone event's block state

(You just need to set it back to false on stepping off)

tawny jungle
#

i considered that, i was just hoping to use the existing permutation

#

my performance is going through the floor

#

this block will now have 1,152 permutations

random flint
#

That's crazy

tawny jungle
#

(unless i figure out a way to integrate it)

shut citrus
#

Why mojang does not allow using c++ for moding in mc worlds

distant gulch
#

how do you import a function from another script, but not the entire script with it?

#

nvm lol, I got it runninng

#

nvm again, bc now it's running my entire script, and not just the function

wary edge
distant gulch
#

I like to have things organized, and ready for use, but not always active

#

I could also use dynamicProperties to add and remove scripts

#

but I don't want to make 50 js files, or multiple addons lol

#

I like to keep organized, but not that organized

wary edge
distant gulch
wary edge
#

If your files are just exported function you're fine.

distant gulch
#

but I'd rather not

#

I'd like to be ableto pick and choose which functions are running while I'm testing

#

I have 2 scripts in my redstone.js

#

one tells me the redstone power when I right click the redstone component

#

one just tells me constantly in the actionbar

#

Sometimes I only want one of them working, and I don't want to separate them by js files

#

Curse you minecraft!

wary edge
#

That seems like an easy fix? Make it an export function and call it in syste.run in your main file?

#

Im failing to see an issue.

distant gulch
wary edge
#

But not functions since they need to be called.

distant gulch
#

One sec

#

lemme show u my setup rq

#
world.afterEvents.itemUse.subscribe((e) => {
    if (e.itemStack.typeId == "minecraft:leather") {
        const redstoneGrab = e.source.getBlockFromViewDirection({ maxDistance: 25 }).block.getRedstonePower();
        const blockGrab = e.source.getBlockFromViewDirection({ maxDistance: 25 }).block.typeId.slice(10).replace("_", " ").toUpperCase();
        if (redstoneGrab == undefined) {
            e.source.sendMessage("Invalid Block");
            return;
        }
        else if (redstoneGrab == 0) {
            e.source.sendMessage(`§c${blockGrab} §fhas no redstone signal`);
            return;
        }
        else if (redstoneGrab > 0) {
            e.source.sendMessage(`§c${blockGrab}: §f${redstoneGrab}`);
            return;
        }
    }
});

export function redstoneWatch() {
    system.runInterval(() => {
        world.getAllPlayers().forEach((e) => {
            const redstoneGrab = e.getBlockFromViewDirection({ maxDistance: 25 }).block.getRedstonePower();
            const blockGrab = e.getBlockFromViewDirection({ maxDistance: 25 }).block.typeId.slice(10).replace("_", " ").toUpperCase();
            if (redstoneGrab == undefined) {
                e.onScreenDisplay.setActionBar("");
                return;
            }
            e.onScreenDisplay.setActionBar(`§c${blockGrab}: §f${redstoneGrab}`);
        })
    })
}
#

this is in my redstone file

#

this is my main file

#
import { world, system } from "@minecraft/server";
import { redstoneWatch } from './productivity.js';

redstoneWatch();
#

But instead of JUST running that function

#

it runs my entire redstone file

wary edge
#

Again...it ran the entire file which is expected.

distant gulch
#

I'm confused on your suggestion then

wary edge
#

Im...not seeing the issue? Just make your event subscriber a function?

distant gulch
#

oh, so just add function example() {

#

and put my other scripts under that?

wary edge
#

Yes then call it in your main.

distant gulch
#

and it'll fix it all?

#

Oh, bet

#

Sorry for the miscommunication then

wary edge
#

Because...once again...it is running the subscribe event.

distant gulch
#

Alr, well I appreciate it

#

gl

tawny jungle
#

how could I call random tick in onstepoff

scarlet sable
#

Is there a costume crafting table addon for public reuse?

tawny jungle
#

love it

buoyant canopy
#

is it possible to query the number of hunger bars of the player in any way?

jolly citrus
#
const distance = 1;

const checkAbove = false;
const checkBelow = false;
const checkIn = true;
const checkBack = true;
const checkPath = true;

world.beforeEvents.entityRemove.subscribe(({ removedEntity }) => {
    if (removedEntity.typeId === "minecraft:ender_pearl") {
        let owner = removedEntity.getComponent("projectile").owner;
        const ownerLoc = JSON.parse(JSON.stringify(owner.location));
        const { location, dimension } = removedEntity;
        let { x: vx, y: vy, z: vz } = removedEntity.getVelocity();
        const loggedLoc = {x: Math.floor(location.x), y: Math.floor(location.y), z: Math.floor(location.z)}
        const loggedOwnerLoc = {x: Math.floor(ownerLoc.x), y: Math.floor(ownerLoc.y), z: Math.floor(ownerLoc.z)}
        DataUtils.addLog(owner.id,createPearlLog(loggedLoc,loggedOwnerLoc,_isPlayerInDisallowedArea_2(owner,{x: location.x, y: location.y, z: location.z}).areaName,Date.now()),"pearl")

        const magnitude = Math.sqrt(vx ** 2 + vy ** 2 + vz ** 2);
        const direction = {
            x: vx / magnitude,
            y: vy / magnitude,
            z: vz / magnitude,
        };

        const backPosition = {
            x: location.x - distance * direction.x,
            y: location.y - distance * direction.y,
            z: location.z - distance * direction.z,
        };
        const inBlock = dimension.getBlock(location);
        Frozen.Info(inBlock.typeId)
        const backBlock = dimension.getBlock(backPosition);
        const aboveBlock = dimension.getBlock(location).above(1);
        const belowBlock = dimension.getBlock(location).below(1);

        let path = pearlMap.get(removedEntity.id);
        path = (path || "") + "" + dimension.getBlock(location).typeId;
        if ((checkPath && path && (path.replace(/minecraft:air/g, '') !== "")) || 
            (checkBack && backBlock.isSolid()) || 
            (checkBelow && belowBlock.isSolid()) || 
            (checkAbove && aboveBlock.isSolid()) ||
            (checkIn && inBlock.isSolid())) {
            
            system.run(() => {
                owner.teleport(ownerLoc);
                pearlMap.delete(removedEntity.id)
            });
        } else {
            Frozen.Info("Teleport condition was not met");
        }
    }
});
scarlet sable
# warm mason ?

Like an add-on with a costume crafting bench that doesn't have copyright

warm mason
#

or use the projectileHitBlock event

scarlet sable
jolly citrus
#

guys need help

#

i pushed out update to my scripts but i forgot what change i made and now it keeps crashin

#

😭

fallen cape
#

They are usually causing crashes

jolly citrus
#

it just suddenly crashed when i reloaded

#

i tried removing the update i was aware of, still crashes

#

did ctrl+z on every other file to find changes, nothing

#

okay idk what it was but i removed something ???? and now it works

#

i cant even remember what it was that i undid

past blaze
jolly citrus
fathom pecan
#

hello I have a little question where you would have and the dev logs of the minecraft api I'm looking for it but I can't find it thank you

warm mason
fathom pecan
wary edge
scarlet sable
#

where do start in making a costume crating table?

#

well a costom container first Ig

scarlet sable
drowsy scaffold
#

how do I stop listening for an event? I'm making events and want them to be as performance-friendly as possible.

distant tulip
scarlet sable
drowsy scaffold
terse pulsar
#

How i give an item to the player

distant tulip
terse pulsar
distant tulip
terse pulsar
distant tulip
#

what error

terse pulsar
distant tulip
terse pulsar
#

Why jayly send a error for that?

distant tulip
#

🤷‍♂️

round bone
#

some typing feature if you're using TypeScript

#

otherwise idk xd

scarlet sable
#

Bruh I was in the wrong channel lmao

#

How do I delete slots?

round bone
scarlet sable
#

🥲

round bone
#

but I think this might be impossible if it's default crafting table

scarlet sable
#

It is

#

Well costume block

#

Crafting table tag

round bone
#

you better ask on #1067876857103536159 or #1067869374410657962 (if it's related to UI)

distant tulip
jade grail
#

is there a limit on dynamic properties?

#

cuz so far i havent reached no problems

#

@distant tulip do u know?

distant tulip
jade grail
#

i asked chat gpt it said max each entity can have is 16

#

i was like Huhhhh

#

consult the experts 😭

random flint
distant tulip
#

assuming each char is 2 bit

valid ice
#

A string property can hold 32767 characters max

valid ice
distant tulip
valid ice
#

nop

distant tulip
#

welp, my bad

jade grail
#

that would have made sense

distant gulch
#

How do I work player.getComponent?

#

if I want to get "is_riding", it's not letting me know

#

I tried

if (player.getComponent("minecraft:is_riding') == true) {
}
#

but it didn't work

slow walrus
#

you have two different quotation marks

#

also I don't think that's a valid component

#

at all

#

none of that is valid

#

lmao

random flint
#

Use .getRiders() (Array of Entities) and check each Entity.id if your player.id is in it

getComponent("rideable") should be called on your ride

#

JSON component and Script API Component are different

past blaze
random flint
#

oki

distant gulch
#

Thanks tho

distant gulch
# slow walrus none of that is valid

I had the correct quotations in the script.
The only thing that wasn't valid was the component.
Instead of "minecraft:is_riding", it was simply "minecraft:riding"

distant gulch
#

Is there a smoother way to teleport? In my case, I can't use knockback or impulse. I want to teleport something forward at a constant rate. Is teleport the best option?

sharp elbow
#

Teleporting can work fine if you implemented your own acceleration and velocity.

coral ermine
#
function setdynamicpropety(unique, entity) {
 if (!entity) return;
  entity?.setDynamicProperty("defense", 100);
}

TypeError: not a function
Someone help

distant gulch
#

Also, does anyone know how I can get the typeId for the item in a players mainhand?

#

nvm I figured it out lol

#

Maybe

dim tusk
distant gulch
#

Thanks for answering tho, rlly helps out

#

I needed it for making a braking system for my car

umbral scarab
#

I've installed NPM typings but my intellisense still isnt working. Any ideas?

remote oyster
umbral scarab
#

I've tried doing it locally in ide console and globally on my pc

remote oyster
# umbral scarab npm i @minecraft/server

Gotcha, so that command (npm i @minecraft/server) installs the module locally within your project, not globally on your PC..

When installed locally, you’ll see a node_modules folder in your project directory containing the module. If you're using TypeScript, you'll need a tsconfig.json file to tell TypeScript where to find the types (e.g., using typeRoots or including node_modules/@types).

For plain JavaScript, the IDE might not recognize the types by default unless you install the module globally (npm install -g @minecraft/server).

umbral scarab
#

Ahh i see i will have a look at my files when I'm home and I'll let you know if I get it figured out 👍

#

Thank you though, that was information I wasn't aware of 😅

remote oyster
umbral scarab
distant tulip
#

we can set selectedSlotIndex?

warm mason
distant tulip
#

i always thought it is read-only

warm mason
distant tulip
#

oh
good to know

umbral scarab
remote oyster
# umbral scarab I've tried this and it still doesn't work. I have the node_modules folder and I ...

vs2022 may not detect global paths automatically like vsc does.

Command:
npm root -g

That will show the global node_modules directory path.

Once you have that, go to Tools then Options. Navigate to Text Editor > Javascript/Typescript > IntelliSense.

Under Included Directories, add the path to your global node_modules directory. Then close vs2022 and open it again for the changes to take effect.

Been a long while since I used vs2022 so assuming I'm correct that should resolve your issues.

ruby haven
#

Is it possible to control where a player is facing?

random flint
ruby haven
honest spear
honest spear
#

it was removed like few months ago

#

basicly the TS Langauge Server doesn't do that anymore

umbral scarab
honest spear