#Script API General

1 messages · Page 96 of 1

rustic ermine
#

If you ray cast up (2nd field in the vec3 for direction) so (0.0, 5.0, 0.0) that should do it. That would be 5 units on the Y axis I believe. I'm not honestly sure what directions Minecraft uses because there isn't really a standard between game engines but in other engines that would be valid

#

Can debug by spawning a particle at the end of the ray probably

#

If Minecraft uses the mesh base as the origin, which I think it does, also add 1.6 to the Y of the origin vec3 to cast from the player head

grim raft
#

soooo I just checked

rustic ermine
#

getBlockFromRay(location: Vector3, direction: Vector3, options?: BlockRaycastOptions): BlockRaycastHit | undefined

grim raft
#

I was mixing it with getTopmostBlock 🙏

#

mb gang

rustic ermine
#

So it would be getBlockFromRay(player.position, (0.0, 5.0, 0.0))

grim raft
#

yea ty

amber granite
#

They added the most unuseful thing

#

Copper tools

woven loom
#

why

honest spear
#
export class LootTableManager { public generateLootFromBlock(block: Block, tool?: ItemStack): (ItemStack[] | undefined); public generateLootFromBlockPermutation(blockPermutation: BlockPermutation, tool?: ItemStack): (ItemStack[] | undefined); public generateLootFromBlockType(scriptBlockType: BlockType, tool?: ItemStack): (ItemStack[] | undefined); public generateLootFromEntity(entity: Entity, tool?: ItemStack): (ItemStack[] | undefined); public generateLootFromEntityType(entityType: EntityType, tool?: ItemStack): (ItemStack[] | undefined); private constructor();};
#

New APIs damn cool

simple zodiac
#

thats nice

#

wait

#

thats huge what

honest spear
#

yea really nice

#

fianlly vein mine is possible with fortune and other enchantments

woven loom
#

do ores have some sort of spwan pattern ? can we predict pos

rustic ermine
#

Moved EntityEquippableComponent properties totalArmor and totalToughness from beta into 2.1.0

On preview 👀

sterile epoch
#

just with workarounds

#

but you're right, this will be 10x eaiser

honest spear
#

what about if they added new ore

#

or other addon would make one

#

there is no way to know what loot it drops

sterile epoch
#

you update it

honest spear
#

you can't deal with infinity addons that could be applied to the world

#

no workaround

sterile epoch
#

????

honest spear
#

what about if they added new ore
or other addon would make one

sterile epoch
#

you're overthinking this

#

it's not hard to update your add-on

honest spear
#

well sometimes you want something that works at least as Java mods do

honest spear
#

thats the point

sterile epoch
#

ohh it works with custom blocks??

#

that's dope

rustic ermine
#

How are you uploading it?

dusky flicker
rose light
buoyant canopy
#

Is there any known way to distinguish between 2 falling block entities?

narrow patio
#

Using a ModalFormData are you able to detect which submit buttons is being pressed if there are more than 1?

wicked girder
#

How much does it take to tank tps with scripting? Hosting a server and it has a fair amount of scripts but for some reason every so often tps just tanks. Ive checked chunks, entities, and the server specs and all them are fine. the only think I can think of is the scripts

distant tulip
#

use the debugger to look into it

celest relic
#

Can somebody explain how to use parameters for custom block components? I don't quite understand how to register and use the parameters, and an example would be great.

celest relic
rustic ermine
#
{
    "components": {
        "some_component:name": {
            "first": "hello",
            "second": 4,
            "third": [
                "test",
                "example"
            ]
        }
    }
}


...


type SomeComponentParams = {
    first?: string;
    second?: number;
    third?: string[];
};

system.beforeEvents.startup.subscribe(init => {
    init.blockComponentRegistry.registerCustomComponent('some_component:name', {
        onStepOn: (e : BlockComponentStepOnEvent, p : CustomComponentParameters) : {
            let params = p.params as SomeComponentParams;
            ...
        }
    });
});
random flint
shrewd relic
#

im so close

#

not even changing the /execute did anything

distant tulip
#

Anyone tried apply impulse in the new preview?

rustic ermine
# shrewd relic im so close

when scriptAPI 2.0 was released they mentioned

Removed runCommandAsync as most commands did not actually run asynchronously. If you are looking to run a function asynchronously, please investigate using Jobs via System.runJob

possible that could be why in your case? try just runCommand? If that's completely off sorry, still familiarizing myself with scriptAPI.
https://learn.microsoft.com/en-us/minecraft/creator/documents/scriptingv2.0.0overview?view=minecraft-bedrock-stable

Describes the fundamentals of how script API modules are versioned

ivory bough
#

For some reason, I just updated my scripts a bit and now when I try to load into my world, it says "There was a problem loading into the server" even though I am not in a server and instead in a normal singleplayer world

celest relic
woven loom
#

Yo, does anyone know of a default particle that we can tweak using scripts?

vast grove
#

The only one that comes to mind would be music notes since well, they're colored by molang iirc

rustic ermine
celest relic
woven loom
#

Thhx

rose light
#

I think so too, because if I spawn the entity in the script, it doesn't update the name in the bossbar, but if I use /summon, it updates it right away

snow knoll
#

Has anyone else had this content log before or could anyone help me in figuring out what it means

round bone
#

you're passing smth to a function that is not a number

#

could you send your code?

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

let constantBeam;

const ignoreList = new Set([
  "minecraft:minecart",
  "minecraft:chest_minecart",
  "minecraft:hopper_minecart",
  "minecraft:tnt_minecart",
  "minecraft:xp_orb",
  "minecraft:item",
  "minecraft:tnt"
]);

function newBeam(player,itemStack) {
  const constantBeam = system.runInterval(() => {
    const view = player.getViewDirection();
    const head = player.getHeadLocation();
    const distance = 24;
    const range = {
      x: head.x + view.x * distance,
      y: head.y + view.y * distance,
      z: head.z + view.z * distance
    }
    const hitEntities = player.dimension.getEntities({ location: head, closest: 1, maxDistance: 24 });
    for (const entity of hitEntities) {
      if (entity.location > head && entity.location < range && !ignoreList.has(entity.typeId) && !hitEntities.includes(player)) {
        entity.applyDamage(15, {
          cause: "lightning",
          damagingEntity: player
        });
      }
    }
  }, 4);
}

world.afterEvents.itemStartUse.subscribe(({ source, itemStack }) => {
  const player = source;
  const item = itemStack.typeId;
  if (item == "ltng:newbeam") {
  newBeam(player, itemStack);
  }
});

world.afterEvents.itemStopUse.subscribe(( e, ) => {
  const { itemStack } = e;
  const item = itemStack.typeId;
  if (item !== "ltng:newbeam") return;
  system.clearRun(constantBeam);
});```
#

This is it

round bone
#

which line is 49

snow knoll
#

The last one
system.clearRun(..)

round bone
#
if (constantBeam) system.clearRun(constantBeam);
#

use this instead just clearing the run

snow knoll
#

It was that simple
Thank you

round bone
#

yeah

#

if you need even more safety, just check for it's type

#
if (typeof constantBeam === "number" && !Number.isNaN(constantBeam) system.clearRun(constantBeam);
nova flame
#

wtf is this error

#
const overworld = world.getDimension("overworld");
``` this is line 4 btw
round bone
#

use a provider

nova flame
#

wdym

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

class Dimensions {
    #constructor() {}
    /** @type {import("@minecraft/server").Dimension}*/
    static #overworld

    static init() {
        this.#overworld = world.getDimension("overworld")
    }

    static get overworld() {
        return this.#overworld
    }
}

world.afterEvents.worldInitialize.subscribe(() => {
    Dimensions.init()
})
#

and use Dimensions.overworld.

nova flame
#

wtf is this!?!

round bone
#

due to 2.0.0, most of functions are native now

#

this code is initializing overworld as soon as the world has loaded

nova flame
#

so where did const overworld go

round bone
#

use Dimensions.overworld from now

nova flame
#

so replace everywhere where it mentions overworld to Dimensions.overworld

round bone
#

yeah

nova flame
#

alright thanks

round bone
#

no problem

nova flame
#

???

round bone
#

it's not the easiest solution, but probably the best one to be honest

#

oh sorry

round bone
nova flame
#

are the hashtags supposed to be there

round bone
#

😅

#

copy the code again

#

I fixed it

#

you can remove constructor if it's throwing you an error/warning

nova flame
#

@round bone

round bone
#

yeah

#

don't worry

remote oyster
# nova flame wtf is this!?!
// main.js
import { world } from "@minecraft/server";

let overworld = null;

// Wait for world to fully load
world.afterEvents.worldLoad.subscribe(() => {
  overworld = world.getDimension("overworld");
  overworld.runCommand("say World loaded!");
  console.log("Overworld is ready");
});

In Script API v2, most API calls cannot be made in global scope, especially during early script initialization. The worldInitialize event has been removed, and you now need to listen to the worldLoad event instead. That means:

Use world.afterEvents.worldLoad.subscribe(...) to get a reference to your world or dimensions.

You can either:
1 - Assign that reference to a global let variable and use it later.
2 - Export the reference from one module for use in others.

The above example references number 1 but number 2 is just as liable and simple.

Its either that or you can make multiple API calls versus just the one, but if you make multiple API calls, be sure that the API call is being called when it's appropriate, which in most cases must be during or after worldLoad.

snow knoll
sharp elbow
#

You are doing a logical comparison of objects. if (entity.location > head) @snow knoll
JavaScript does not know how to really interpret this, because how should {x, y, z} be greater than / less than another {x, y, z}?

#

AFAICT those comparisons always return false.

snow knoll
#

Oh, I see

#

What would you reccomend in do instead

sharp elbow
#

Depends on what you're wanting it to do. What should it mean for an entity's location to be greater than the head location? (or less than the range?)

#

Should the values of each coordinate be within those two points? Like a volume check

snow knoll
#

Yes, that was the intention

sharp elbow
#

You could write a function that determines if a point lies between two points. I don't expect that to be too useful here though; such a function would be comparing each axis of those points, which would give very tight volumes along axis-aligned directions and very large volumes across diagonals

#

I suppose what you want is the distance instead. For that, you can use a little vector math to find out if the entity is too far or too close

#
for (const entity of hitEntities) {
  const entityLocation = {...entity.location};
  // find difference between two points
  const delta = {
    x: entityLocation.x - head.x,
    y: entityLocation.y - head.y,
    z: entityLocation.z - head.z,
  };
  // distance formula: sqrt(x^2 + y^2 + z^2)
  const entityDistance = Math.hypot(delta.x, delta.y, delta.z)
  if (entityDistance <= distance && !ignoreList.has(entity.typeId)) {
    /* ... */
  }
}
snow knoll
#

Thank you so much

sharp elbow
#

With that, your sphere of what entities should find is limited to a shape like this.

#

From a point that is distance away, you grab all entities in a sphere of distance radius, then filter those who are further than distance meters away from the origin. It creates this kind of Venn diagram

snow knoll
#

Thank you

sterile epoch
#

question: is it a glitch that form dividers and labels show up as null in the result.formValues array?

open urchin
#

it's intentional

scenic bolt
#

Unique Question: If I have a feature/feature rule place a block, and have that block do an onTick event (Not Repeatable, 0.5 Seconds), will it summon an entity I have it summon on that tick, or will that entity not appear because the world isn’t loaded?

wary edge
scenic bolt
#

That’s what I thought, I have a plant that uses a block as a base and summons an entity with the geo due to restrictions with the geo size of blocks. If this is true then I unfortunately don’t see another way to do this other than maybe making these flowers have spawn rules lol, and have a timer for those that place a block

#

I’ll figure it out somehow, thanks for the help!

sterile epoch
#

dividers and labels have no user input value

open urchin
#

apparantly it fixed something

#

with how people were already handling forms

sterile epoch
#

mkay...

north rapids
#

is there any way to get the amount of bees inside a nest?

little hull
#

how can i check in scripts if a player is in first person?

distant tulip
#

store beehives with all possible amounts in structure, when loading them get the items and check if they can stack with your item

north rapids
#

ty

#

is there any way to get the max value of an int block state?

#

like the "growth" state in crops

wary edge
north rapids
#

how do I get it?

whole axle
#

Is it possible to get players profile pictures in local worlds with scripting? non bds

fallow minnow
#

Nop

#

e

woven loom
#

anyone used loot manager

livid elk
#

Is there a way to save variables value so that if the player rejoins, the value remains the same as the last save?

woven loom
#

dps

livid elk
#

what's that? sorry im new to this 😅

woven loom
#

dynamic properties

#

they gets saved onto the world nbt

#

player.setDynamicProperty('myvalue', 'foobar')

let myValue = player.getDynamicProperty('myvalue')

livid elk
#

is there a docs for that? i cant find that on microsoft thing

woven loom
#

u can find them in World, Entity andItemStack

livid elk
#

thank you!

livid elk
#

is there a tool to see all dynamic property of the world?

round bone
livid elk
#

like this

round bone
#

NBT Editor?

sage portal
#

can you import files with worldLoad or do I just need to wrap each file with it?

prisma shard
#

wasn't there something like getAllDynamicProperties?

#

Can't find now but I very much feel like it existed

round bone
ivory bough
prisma shard
prisma shard
#

Hmmm, I see it in the MS docs

#

But i always use jayly's docs

#

Can't find it in his docs, i tried searching..

round bone
#

I prefer using Microsoft docs

prisma shard
#

Lets see on stirante's docs

round bone
prisma shard
#

OH

#

sorry jayly for the ping,,, im just stupid

prisma shard
#

its getDynamicPropertyIds

round bone
edgy elm
#

Hi here! Does anyone here have a script that checks the performance of script if it perform well or the code is optimized. Like a memory usage evaluation.

shy leaf
#

you can also use diagnostics in game to export a file that tells you how long it takes to call functions and methods

edgy elm
#

I have a server and for some reason i manage the server thru this very complicated codes, too many codes running at once. I check the performance of it by checking the ram usage, memory usage etc.. But i notice every time that memory usage rising dramatically every 5 hours so I need to restart the server in order for other people to join.

I dont know whats causing the memory usage to go up max

shy leaf
#

its memory leak

#

i dont know what behavior packs youre using, but testing it in singleplayer with VSC hooked up on your game should give you live diagnostics of memory usage for scripts and your game

edgy elm
shy leaf
#

googling it should explain it better

edgy elm
#

Thanks for the time!

shy leaf
#

you can ask here anytime about it, though the best thing we can only recommend is to not use behavior packs that has bad optimization

hushed ravine
#

With the new custom commands API, is it possible to create subcommands?

shy leaf
#

i heard you cant

#

yet

hushed ravine
shy leaf
#

or no "yet"

#

i dunno if its gonna be a thing

hushed ravine
#

Welp, time to create multiple commands

shy leaf
#

sob

prisma shard
#

How would a subcommands work

shy leaf
#

think of execute command

#

execute as @p at @s if ...

#

camera and camerashake too

prisma shard
#

hmm

shy leaf
#

you can give multiple params and get various results from one main command

#

but you cant do that with custom commands currently

little hull
#

does anyone know how this method works plsss help me apply it

woven loom
livid elk
ruby haven
#

Can dynamic properties be detected through molang?

wary edge
#

No.

sly valve
round bone
#

of course, you can use a hashmap

round bone
#

still it might take a lot of iterations

sly valve
#

Ofc but it wont cause spikes

round bone
#

at least it's reducing spikes

sly valve
#

Yes

#

I love runJob

mystic herald
#
function showVaultInvites(player) {
    const VaultInvites = JSON.parse(player.getDynamicProperty("VaultInvites") ?? "[]");
    if (!VaultInvites.length) return player.sendMessage("§bYou do not have any incoming vault invites!");
    new ModalFormData()
        .title("§bVault Invites")
        .dropdown("\n§7Here is a list of vault invites you have received.\n\n§8Joining a vault will add it to your name tag and chat rank!\n\n", VaultInvites)
        .toggle("§7Clear All Invites", false)
        .show(player).then(res => {
            if (res.canceled) return;
            const [dropdown, clearInvites] = res.formValues;

            if (clearInvites) {
                player.sendMessage("§aSuccessfully cleared all your pending vault invites.");
                player.setDynamicProperty("VaultInvites", undefined);
                return;
            }

            if (player.hasTag("vault_owned"))
                return player.sendMessage("§bYou are already in a vault. Leave your current vault to join other vaults.");

            const invitingPlayerName = VaultInvites[dropdown];
            const invitingPlayer = world.getPlayers({ name: invitingPlayerName })[0];
            if (!invitingPlayer)
                return player.sendMessage(`§b${invitingPlayerName} is no longer online.`);

            const invitingVaultId = getScore(invitingPlayer, "vault");
            if (!invitingVaultId) return player.sendMessage(`§b${invitingPlayerName} does not have an active vault.`);

            const vaultLocation = { x: 5500, y: 100, z: 5000 + (50 * invitingVaultId) };
            player.teleport(vaultLocation, { dimension: Dimensions.overworld });
            player.runCommand(`tag @s add vault_member`);
            player.setDynamicProperty("vaultId", invitingVaultId); // Store vault ID to player's properties
            player.runCommand(`scoreboard players operation @s vault = "${invitingPlayerName}" vault `)
            const updatedInvites = VaultInvites.filter(invite => invite !== invitingPlayerName);
            player.setDynamicProperty("VaultInvites", JSON.stringify(updatedInvites));
            player.sendMessage(`§aSuccessfully joined the vault of ${invitingPlayerName}!`);
            invitingPlayer.sendMessage(`§a${player.name} has joined your vault.`);
        });
}```
#

guys whys my modal form dropdown not working?

round bone
#

what error are you getting?

mystic herald
#

give me on sec

round bone
#

ohh

mystic herald
#

its giving an error at the dropdown

round bone
#

ohh a toggle

#

sorry

#

xD

#

to provide a default value, you have to use:

.toggle("§7Clear All Invites", {
    defaultValue: false
})
round bone
mystic herald
#

if this is correct im gonna cry

round bone
mystic herald
#

dude thank you so muhc

round bone
#

no problem

#

👍

final ocean
#

What chatsend name in api 2.0.0

round bone
#

are you using beta APIs?

final ocean
round bone
#

you can't use chat events then

#

😦

final ocean
wary edge
#

It's beta only.

final ocean
wary edge
#

Yes.

final ocean
#

Ok

buoyant canopy
#

What's the difference between this script ```
console.log("test" )

and this script ```
import {world} from "@minecraft/server" 
world.afterEvents.worldInitialize.subscribe(()=> console.log("test"))
sharp elbow
#

This is for scripting 1.0, right? They may execute at rather similar times

#

I would expect that the second script executes around when the world is "more finished loading" than the first, but this distinction may be blurry, I am not sure

#

In scripting 2.0, the world load order is much more clearly defined. The simiarly named worldLoad call happens after the first tick executes; so the difference is much more clear

final ocean
#

Does anyone know json ui?

round bone
buoyant canopy
sly valve
#

Guys I think i will make me an super perfomant Scoreboard database, because the data is persistent and can't be removed when removing the addon.
Or am I just stupid?

#

Nvm changed my mind

tight bloom
#

is there a existing method in scripting to break a block in the world?

woven loom
#

only with cmd

livid elk
#

is there a way to get the position of specific block? like for example, oak leaves

hushed ravine
#

Can I teleport a player into an unloaded chunk?

hushed ravine
#

I'll test that, ty :3

alpine wigeon
#

how do you get the worldspawn location

alpine wigeon
#

how do you get the ground height at a xz location

alpine wigeon
#

how do i use getTopmostBlock???

#

is VectorXZ like Vector3?

distant tulip
alpine wigeon
#

okie

#

ty

#

i think i figured out the thing

glacial widget
#

where are new npms

sly valve
glacial widget
#

thats cool

little cedar
#

Is it possible to display a video on your screen

thorn flicker
#

no

little cedar
#

😔

#

Maybe with the title command?

thorn flicker
little cedar
#

Not even photos?

thorn flicker
#

you can use photos.

#

you need to make a custom emoji

little cedar
#

Oh ok I'll search for it

thorn flicker
#

no need, theres the link

untold magnet
#

u need to use flipbook thing in order to do that

thorn flicker
#

i dont think you can make animated custom emojis.

#

wdym animated photos

untold magnet
#

and i think there is a tool that can change videos to a very long flipbook texture that u can use on minecraft

dusky flicker
untold magnet
untold magnet
thorn flicker
#

im asking how?

untold magnet
#

ah,

dusky flicker
untold magnet
#

the same way u make flipbook blocks or making an entity has animated texture

thorn flicker
#

so an emoji

#

per frame

untold magnet
#

no custom emojis needed, u can render an image by sending a specific title or even chatmessages

#

and that image can be modified to have a flipbook texture

thorn flicker
#

using json ui

untold magnet
#

yes

thorn flicker
#

right, you can use images.

untold magnet
#

animated images*

thorn flicker
#

which are images

untold magnet
#

but if u dont want to use jsonUi

#

u can use attachables or entities or even blocks

thorn flicker
#

custom emojis.

#

which would take years

dusky flicker
untold magnet
thorn flicker
#

that would take years aswell

#

but you did say there was a tool

dusky flicker
#

you know that if the video is atleast 256x256, the 'video' would be big as hell, right?

untold magnet
dusky flicker
#

and you'd have to put each frame on the image

thorn flicker
#

you can scale the entity/attachable down.

untold magnet
untold magnet
untold magnet
thorn flicker
untold magnet
thorn flicker
#

can a model even fit it

untold magnet
#

i think so

untold magnet
whole axle
#

How to remove players footstep particles and noise if they have a tag?

whole axle
whole axle
thorn flicker
whole axle
#

i could create a separate walking sound and script it to play when players without the tag walk

#

but idk

thorn flicker
#

that would be terrible

#

lol

whole axle
#

ik

livid elk
#

is custom / command still in beta?

bold bison
#

[Scriptinglferror-Plugin [Enderaltar BP-1.0.0]-[rmain.js] ran with error: [TypeError: cannot read property 'subscribe of undefined at <anonymous> (main.js:13)

shadow geyser
woven loom
#

ping?

coral ridge
#

do you guys know how to make a 5 letter Minecraft related word dictionary?

woven loom
#

what

halcyon phoenix
#

LOL

#

he's making wordle in minecraft

nova flame
#

anyone know why the icons are off ill send code in 1 sec

#

help would be appreciated

round bone
#

probably due to an update

nova flame
#

@round bonehow do i get this to stop throwing this error without having the chunks generated 24/7 js system.runInterval(() => { const dimension = world.getDimension('overworld'); dimension.spawnParticle('server_icon', { x: 30.5, y: 117, z: 67.31 }) }, 10);

round bone
#

put it into try-catch block

#

also read #welcome

untold magnet
#

uhhhh,,

#

im using this player?.sendMessage(weakImpacts[parseInt(Math.random() * weakImpacts.length)]); to send a random message from the array

#

how am i going to send two messages from the array?
like there is 6 different messages in the array, and i need to send a random one twice, how?

round bone
#

the same message twice?

untold magnet
#

yes, the same random message, but twice instead of once

round bone
#
const msg = weakImpacts[parseInt(Math.random() * weakImpacts.length)]
for (let i = 0; i < 2; i++) player?.sendMessage(msg)
untold magnet
#

ill try it ig

nova flame
nova flame
round bone
#

you can just copy-paste the method 2 times

#

it's simpler, but using a for loop is cleaner in my opinion

sage portal
#

did getGamemode() change in 2.0.0?

#

all my code related to checking gamemodes have been failing ever since I've updated

#

bruh
nvm they just capitalized the string now bao_ext_toldyouso

nova flame
#

i think they changed it when they added spectator mode

sage portal
#

apparently it has been lowercase all the way up to 1.21.80

nova flame
#

oh lol

untold magnet
round bone
#

as far as you'll save a random message via variable, you can just re-use it

untold magnet
#

i see,,,

#

yah, ill use that instead of the loop

sullen ocean
#

The type of people who try to make a full 3D video game without knowing how to program yet .... that's why I say learning the basics first is required.
Also, I cannot help with people who don't even have the basics down yet.

sullen ocean
thorn flicker
sullen ocean
#

I assume parseInt() converts it input value to a string, which means that you could get weakImpacts.length out of the result, if unlucky.

woven loom
#

Parse int capture first number from the string

dusky flicker
sullen ocean
woven loom
#

parseInt('8080wave9000') == 8080
parseInt('wave9000') == NaN

sullen ocean
#

Wave, the input is a number...

woven loom
#

oh my bad

#

xd

rustic ermine
#

aside from just rewriting fishing mechanics, is there a way to detect when a player has completed a fishing event?

thorn flicker
#

that would be tricky, if not impossible.

rustic ermine
#

which part?

thorn flicker
#

mainly the last part.

rustic ermine
#

rewriting it wouldn't be that bad. dont see a vanilla way to see when the vanilla event completed though

thorn flicker
#

yeah.

sullen ocean
#

If you replace the entire loot table...

sullen ocean
thorn flicker
sullen ocean
thorn flicker
#

boom, fishing complete afterEvent.

#

good idea.

rustic ermine
#

that sounds inefficient though

#

trying to avoid looped processing

sullen ocean
thorn flicker
#

wdym

#

there's entitySpawn afterEvent

rustic ermine
#

hmm yeah that would work. thanks

sullen ocean
#

The only problem would be calculating how to do the movement arc for the item being fished.

thorn flicker
#

check if the typeId is minecraft:item and get the item component, then get itemStack property.

rustic ermine
sullen ocean
thorn flicker
#

but lets say we dont care about that

rustic ermine
#

I dont. It's a self hosted dedicated server lol

thorn flicker
#

welp, thats not a problem for him

rustic ermine
#

mainly just working on a fishing skill with xp/unlocks so was trying to think of a way to make experience gain possible. the dummy entity will probably work. thanks

thorn flicker
#

dummy item, not an entity

#

well, it will be an entity

#

but you dont need to create an entity

rustic ermine
#

yeah when it travels from water to player, right?

#

but the script should detect it spawning before or very quickly after it becomes visible

thorn flicker
#

just despawn it as soon as it spawns

thorn flicker
#

there's no beforeEvents for entitySpawn

#

it might be rough to giving the player that did it xp though, unless you plan on spawning the xp orbs

sullen ocean
#

Can you swap out the entity's itemStack without affecting anything else like velocity?

thorn flicker
#

you cant change an itemstack

#

unless its in an inventory

sullen ocean
#

... so the only easy way is to just grab the position and velocity, destroy the item, and create the proper, new item entity with the copied position and velocity.

thorn flicker
#

assuming you could set the velocity on the item entity...

sullen ocean
#

... is that not possible?

thorn flicker
#

no

#

you can apply impulse however.

sullen ocean
#

Is setting the velocity of a non-player entity impossible, @rustic ermine?

thorn flicker
#

I said no

#

there's no method for that

#

apply knockback wont work because items dont support it I believe.

sullen ocean
#

A method isn't the same as a property... is there anything, even NBT-side, that stores it?

thorn flicker
#

no really?

sullen ocean
#

If nothing stores the velocity, then how does it know, after you drop an item from your inventory, which way horizontally to move it on the next tick, and the tick after, and the next after that?

thorn flicker
#

you can get the velocity.

#

entity.getVelocity()

sullen ocean
#

So the only way to fling a player as if out of a cannon (but without any damage) is by knockback means?

thorn flicker
#

apply knockback or apply impulse (which player now supports in preview I think)

#

yes

sullen ocean
#

... and you are 100% certain neither exist for item entities?

thorn flicker
#

what do you mean? I said apply impulse works on items

sullen ocean
#

...

thorn flicker
#

...

sullen ocean
thorn flicker
#

because you mentioned player...

sullen ocean
#

both are entities...

thorn flicker
#

I know.

#

some methods dont work on certain type of entities.

round bone
thorn flicker
sullen ocean
#
// Normal JavaScript btw
const getAllPropertyNames = (obj) => {
  const results = new Set();
  for ( ; obj != null; obj = Object.getPrototypeOf(obj)) {
    for (const prop of Object.getOwnPropertyNames(obj)) {
      results.add(obj);
    }
  }
  return Array.from(results.keys()).sort();
};
round bone
thorn flicker
#

say you dont want to be tagged then

#

its not clearly stated

#

you are going to screenshot this and link this everytime someone pings you? lol

round bone
#

I don't think that telling me the same approach, but with a different method which is returning the same value is a necessary thing

round bone
thorn flicker
#

its not that big of a deal, but now since you made it clear...

#

👍

snow knoll
#

Sorry to interrupt but:
How does player.getEntitiesFromViewDirection() actually work?
I'm just really confused, is it detecting if an entity is in the players crosshair from a certain distance (like a direct, straight line) or is it like a cone from the players view of every entity they see?
Can someone help to shed some light on the topic

nova flame
#

how would i go about not letting players hit entities when they are in a certain place i have the location set up but how do i cancel them being able to hit entities

round bone
sullen ocean
thorn flicker
#

in the script api, currently.

nova flame
#

i have this set up but it only works for players

snow knoll
nova flame
#

in player.json

round bone
#

you have to cancel all attacks, then hit if none of conditions to cancel a hit are true

nova flame
#

how?

sullen ocean
thorn flicker
#

taking damage

round bone
round bone
#

it requires a bit of work, but it's possible in the end

nova flame
sullen ocean
# shut vessel ok

Yeah, sorry for the late response, but I thought it was required to understand why I felt that way.

thorn flicker
nova flame
sullen ocean
#

... hopefully mobile users are noticing my responses because I am not @-pinging them when they already turned their screen off / switching back to their game...

thorn flicker
round bone
nova flame
#

any idea where i could find an example of what your suggesting with player.json

sullen ocean
#

So on_damage is for taking damage... what would be for dealing damage?

nova flame
sullen ocean
#

Though I do recommend to keep void damage as something that damages it.

#

(you don't want a bunch of entities you don't know about at the bottom of the world, right?)

nova flame
#

well there is 2 of them and they spawn nly via command so im chilling id say

thorn flicker
#

I dont think there's a filter for location, but you can give the player a tag if they are in the location, and you can filter this tag in the damage sensor.

thorn flicker
azure sentinel
#

I made something via. command blocks long ago that throws people into adventure if they are within one of several separate areas

#

then puts them into survival after they leave

thorn flicker
#

they said they got the location thing down

#

I think

thorn flicker
#

because thats how raycasting works

snow knoll
#

Cool

#

Thank you very much

#

And thanks Katie for offering to test

azure sentinel
#

Do some testing with solid blocks, transparent blocks, and awkwardly-shaped blocks in the way… bonus to know how it works.

thorn flicker
#

its a straight line that collides

snow knoll
#

Awkward?

azure sentinel
thorn flicker
#

odd shaped, like a fence.

snow knoll
#

Ohhhh

#

Cool

azure sentinel
#

Fences too

snow knoll
#

I thought you meant awkward shapes made from several blocks

thorn flicker
#

lol

azure sentinel
#

Thanks Void, and sorry I got all agitated / etc.

thorn flicker
#

its chill.

azure sentinel
#

Not everyone has the same capacity of handling stress / etc. that others do.

nova flame
#

i got it chat lets gio

thorn flicker
azure sentinel
#

End of the random off-topic

nova flame
#

jojo refrence in the bedrock api channel

#

🔥

azure sentinel
nova flame
#

yeah ik

nova flame
#

anyone know why this doesnt work

buoyant canopy
#

can we use raw text on signs?

wary edge
buoyant canopy
#

Do i just write the localization key, or is there another way?

wary edge
#

Yeah.

buoyant canopy
wary edge
#

peeposhrug Never heard of setting text via commands.

buoyant canopy
#

ok

nova flame
#
world.afterEvents.playerInteractWithEntity.subscribe((event) => {
    if (event.target.typeId == "neptune:cratesnpc") {
        CrateUI(event.player);
    }
});```
#

anyone know why this wouldnt work

round bone
nova flame
# round bone can you show code of a function?
export default function CrateUI(player) {
    const form = new ModalFormData();

    form.title("Crate UI");
    form.dropdown("Choose a crate to open", ["Common", "§2Rare", "§uEpic", "§eLegendary", "§mMythic", "§1Neptune"]);
    form.slider("Amount of crates to open", 1, 64, { defaultValue: 1, valueStep: 1 });
    form.show(player)
        .then((r) => {
        })
        .catch((e) => {
            console.error(e, e.stack);
        });
}```
round bone
#

did you import this file?

nova flame
#

yes

round bone
#

are you sure that entity's type ID is equal?

nova flame
#

yep

thorn flicker
#

if your entity does not have the interact component, playerInteractWithEntity afterevent will not trigger.

thorn flicker
#

yeah.

nova flame
#

what do i put as the thing

thorn flicker
#

what

nova flame
#

in the brackets

thorn flicker
#

you dont need to put anything.

nova flame
#

yeah but that doesnt work

thorn flicker
#

it should.

nova flame
#

it doesnt

thorn flicker
#

I dont know what to do then.

nova flame
#

me neither

#

lol

thorn flicker
#

alternatively you could use beforeEvents instead, but keep in mind there's the beforeEvent privilege system.

nova flame
#

okay i switched to before event and it threw an error

#

progress

#

what could this mean

#

?

#

code : ```js
export default function CrateUI(player) {
const form = new ModalFormData();

form.title("Crate UI");
form.dropdown("Choose a crate to open", ["Common", "§2Rare", "§uEpic", "§eLegendary", "§mMythic", "§1Neptune"]);
form.slider("Amount of crates to open", 1, 64, { defaultValue: 1, valueStep: 1 });
form.show(player)
    .then((r) => {
    })
    .catch((e) => {
        console.error(e, e.stack);
    });

}```

thorn flicker
#

did you even click the link I sent you lol

nova flame
#

mb

nova flame
#

is it possibel to name an entity with a double line name

#

like "Sheep \n 10hp" type thing

valid ice
#

ya

nova flame
#

how?

valid ice
#
system.runInterval(() => {
    const [testEnt] = world.getDimension('overworld').getEntities({ type: 'minecraft:sheep', location: { x: 0, y: 0, z: 0 }, closest: 1 });
    if (!testEnt?.isValid) return;
    testEnt.nameTag = "Sheep \n 10hp";
}, 1)
alpine wigeon
#

how do i do a teleport with keepVelocity

#

is there a page with documentaion of all the scripting functions

north frigate
#

bro helix is so damn cool

woven loom
#

Ye

gaunt salmonBOT
snow knoll
#

Guys what's wrong with this
It threw no errors, no content logs, just won't work
Anyone who can help, in any way, is sincerely appreciated

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

let constantBeam;

const ignoreList = new Set([
  "minecraft:minecart",
  "minecraft:chest_minecart",
  "minecraft:hopper_minecart",
  "minecraft:tnt_minecart",
  "minecraft:xp_orb",
  "minecraft:item",
  "minecraft:tnt"
]);

world.afterEvents.itemStartUse.subscribe(({ source, itemStack }) => {
  const player = source;
  const item = itemStack.typeId;
  if (item !== 'ltng:newbeam') {
  constantBeam = system.runInterval(() => {
    const entities = player.getEntitiesFromViewDirection({
      maxDistance: 24
    });
        entities.entity.applyDamage(15, {
          cause: "lightning",
          damagingEntity: player
        });
        player.runCommand('give @s diamond');
    })
  };
});

world.afterEvents.itemStopUse.subscribe((e) => {
  const { itemStack } = e;
  const item = itemStack.typeId;
  if (item !== 'ltng:newbeam') return;
  try {
    system.clearRun(constantBeam);
  } catch (e) {
    //pls catch error or give me no trouble
  }
});```
fervent topaz
snow knoll
#

Would that affect the runInterval from running in the first place?

fervent topaz
#

o wait i didnt see the let at the thing

#

why not remove the try and catch to get the error

snow knoll
#

Good idea

#

Try and catch the entire runInterval to be specific?

fervent topaz
#

no

#

remvoe try catch

snow knoll
#

I got an error
Solved the problem of the error using
if (constantBeam) system.clearRun(constantBeam)
but the runInterval still wont run

shy leaf
#

make sure constantBeam is number and not something else

outer wyvern
#

Hello does anyone know How do I use the addEnchantment inside the enchantable component for items I'm trying to figure it out but couldn't find any docs on it. I tried to guess but it wouldnt throw any error but also not work

outer wyvern
#

No. I haven't

#

I'll try

#

But I don't get it setItem doesn't have any more params than any regular item param as far as I'm Aware

#

Doesn't work. I'll open a thread maybe I'll get more answers

woven loom
#

can someone link a good menifest generator for scripts

woven loom
#

thx

rare dawn
#

Is there a script where if we see an evil (monster) then a saying will appear saying it's a monster?

rare dawn
round bone
rare dawn
round bone
#

what do you mean by "seeing"

#

on entire screen?

#

or on a crosshair?

rare dawn
round bone
#

it's a bit of work

#

you would have to invole some math

rare dawn
round bone
#

you would have to check if player's camera could see it in 55 deg for each side

#

then check if mob is not behind some block

rare dawn
snow knoll
shy leaf
snow knoll
#

Should I put it into a function and call the function through the itemStartUse event instead then?

round bone
snow knoll
#

I was asking you😭

#

But anyways I moved it out into a function (it was one initially in the first place) and did a variable check on all players with for (const player of world.getPlayers()) and it still didn't work

shy leaf
#

huh

snow knoll
#

Maybe I'm the problem and the script doesn't like me🥲

snow knoll
#

I was calling it incorrectly

#

I needed a question mark

#

And [0]

shy leaf
#

sob

snow knoll
#

But thing is that its only working when just the runInterval on its own

woven loom
# rare dawn If a player sees an evil mob he will get a warning /say warning

You can do this using a simple dot product check:

  1. First, search for nearby entities around the player.
  2. Loop through each entity and compute the direction vector: entity.position - player.position.
  3. Cast a ray from the player toward that direction.
  4. If the ray hits the entity and the angle between the player's facing direction and the direction to the entity is small (i.e., they’re roughly facing each other — check using dot product ≈ 1), then the player can "see" the entity. Add it to a visible list.
  5. If the visible entity is a monster, trigger an alert for the player.
rare dawn
sharp elbow
#

Some pseudocode:

const facing_dir = player.getViewDirection()
const visible = []

const nearby_entities = player.dimension.getEntities({maxDistance: 16})
for (const entity of nearby_entities) {
  const direction = Vector_sub(entity.location,  player.location)
  const angle = Vector_dot(direction, facing_dir)
  if (angle < Math.PI / 2) continue

  const ray = player.getEntitiesFromViewDirection(direction)
  for (const result of ray) {
    if (result.entity) visible.push(result.entity)
  }
}

if (visible.length > 0) {
  player.sendMessage("Evil mobs spotted! " + visible.map(_ => _.typeId).join(", ");
}
#

You'll want to write or download a Vector library for this. Vector addition/subtraction and the dot product are used in this implementation

nova flame
#

anyone got an idea how to lock an entity on the block where its been placed

shell sigil
#

Guys How to put tags in items and blocks in the itemUse.subscribe event and playerBreakBlock

visual zephyr
#

anyways does anyone here know how can i spawnParticle the block particle of a specific block, like the mace?

rigid torrent
#

Can you check when a recipe is unlocked?

visual zephyr
buoyant canopy
#

was isOp() released to stable?

wheat condor
# rigid torrent Can you check when a recipe is unlocked?

You can abuse commands to do so:

remove the recipe from the player and get the successCount

  if (succes) give the recipe back, return true

  if (failed) return false
/**@param {mc.Player} player @param {string} recipeId @returns {boolean}*/
function playerHasRecipe(player, recipeId) {
    const hasRecipe = !!player.runCommand(`recipe take @s ${recipeId}`).successCount
    
    if (hasRecipe) player.runCommand(`recipe give @s ${recipeId}`)

    return hasRecipe
}
prisma shard
#

never learned commands 😔

halcyon phoenix
#

where do you get knowledge like that?

woven loom
#

@distant tulip Have you unrolled the changes for editor ?

distant tulip
woven loom
#

Yes

buoyant canopy
#

can we clone an entity?

distant tulip
#

structures

buoyant canopy
#

no, i mean, if you have an entity Object, can you use it to create a clone of it in the dimension?

#

I want to kinda cancel the entityRemove event but entityRemoveBeforeEvent doesn't have the canceled property, so i thought i could spawn the entity back

#

It gives you an an Entity instance, which i want to respawn

open current
#

Hi, I have a script that's working, but I'd like to add a function so that the stripped wood stays in the same position as the original log. Is that possible?

buoyant canopy
#

It seems there isn't a release for the 1.21.93 in the addon samples

stark kestrel
#

Event to get when a player starts mining

#

?

wheat condor
stark kestrel
prisma shard
dawn zealot
#
world.beforeEvents.worldInitialize.subscribe(data => {
    data.blockComponentRegistry.registerCustomComponent('osuea:cow_spawner', {
        // onStepOn: e => {
        //     e.block.setPermutation(BlockPermutation.resolve(MinecraftBlockTypes.Air));
        // },
        On
    });
});
``` Never used this before can someone help, im trying to make it so it spawn a cow every 15 seconds
#

i have the block JSON done already just typings arent showing anything about ticks

#

nvm i was doing it so wrong, but i fixed the component shiz but the cow aint spawning

prisma shard
#

how to get what body part the player was hit

jagged gazelle
#

wazzup.

round bone
#

👋

woven loom
#

@wheat condor Hey, I would like to create a keyframe timeline for pos rotation, fov, etc. Any ideas on how to structure that?

floral vessel
#

how can I set molang variables on entities with scripts?

wary edge
floral vessel
#

actually unusable

#

wait...

#

what about this?

woven loom
#

Entity.setProperty

floral vessel
#

if I were to run playAnimation with a stopExpression that modifies some variables then returns true, it would effectively just set those variables

valid ice
#

entity properties & setProperty, and reading that in client or whatever

halcyon phoenix
floral vessel
#

gotta document that one lol

coral ridge
#

I'm learning JavaScript on my phone 🤧

woven loom
#

i still do stuff on phone

prisma shard
#

Starting to learn js with phone is very inefficient

#

I couldn't understand js until I got into my PC and started writing code with hand.

#

PC is more like a faster and practical way to learn

woven loom
#

wym, i use text editor

#

but computer is better for sure

prisma shard
#

.
I mean.... Idk If it's only to me, but, I get bit "comfort" on PC and easier to look at for long at code, write faster, etc

halcyon phoenix
woven loom
#

Using Termux and Shizuku, I created a project template that automatically compiles the TS project and pushes it into the android data folder.

wheat condor
woven loom
#

Not like that , more like how blockbench does it

wheat condor
#

What do you need that for?

woven loom
#

I want to make a cinematic addon but can't decide how to handle timeline thing

stark kestrel
wheat condor
spark kayak
rustic ermine
#

sheesh.. 91 dynamic properties and their associated DB server cache objects/SQL rows created. that took all day.

weary merlin
deep quiver
#

its what the command community does to do some very cool stuff, without addons

#

very powerfull on the visual side

rustic ermine
#

man, probably obvious to anyone here, but last time I did anything with scriptAPI dynamic properties werent a thing so it was extremely limited because there was no way to have data persistance. they are amazing. combined with http .. can do a lot

deep quiver
#

Kinda late, but maybe you still need help lol. Run Set-ExecutionPolicy RemoteSigned in an powershell terminal with administrator (I think you need it, not sure)

safe stream
#

is there localisation in scripting? or do you need to hardcode the translations

open urchin
#

most ways of displaying text support raw text

#
world.sendMessage({ translate: "tile.grass.name" })
visual zephyr
#

im trying to animate the first person but when i run it via script api or commands it only runs in the third person

open urchin
#

what are you trying to animate?

visual zephyr
#

player

open urchin
#

but what about the player

visual zephyr
#

im doing a dual wielding mod

#

bedrock doesnt support hitting with the offhand so i made an animation almost the exact as hitting using offhand

#

but when i run it, it animates on 3rd person

open urchin
#

held items that aren't attachables are not part of the player model in first person

#

so can't be animated

visual zephyr
#

so if i made an attachable for the item will it work?

open urchin
#

yes
the animation will look different to the vanilla swing though

visual zephyr
#

ohh thats why, thanks

void cipher
#

Hey guys I am looking for a coder for my friend's pokemon server if any of you are interested dm me
(it's paid)

rustic ermine
#

on that note, 10ish hours coding today, night all lol

deep quiver
prisma shard
#

@distant tulip (sry for ping lol)

thorn flicker
#

im pretty sure this was discussed not that long ago.

prisma shard
#

uh when

thorn flicker
#

recently.

prisma shard
#

I forgot if it was discussed with me but I don't know

thorn flicker
#

I dont think so

#

ill find it for you.

thorn flicker
#

you were in the post lol

prisma shard
#

That's a different plain entity

thorn flicker
#

and what is a player

prisma shard
#

...what

thorn flicker
#

what is a player

prisma shard
#

bruh wha

thorn flicker
#

its an entity.

#

yes, it works with a player.

prisma shard
#

But I don't know the exact body part location of the player

thorn flicker
#

figure it out.

prisma shard
#

The plain entity there he used doesn't have legs and hand or chest

woven loom
#

dir = ray origin - entity.location
dir.y = 0
plain = normalize( dir )
plain origin = entity.location

woven loom
#

but can be used

#

once u get the plain u can then use that to find the hit location and then based on height we can aprox diff body parts

distant tulip
#

I mean, if you want to know if you hit the arm, legs, body or head you will need a bit more logic, we are delaying with rotatable cubes in that case.

woven loom
#

yea

distant tulip
#

But if you only need the hit position in the hitbox that way simpler

thorn flicker
distant tulip
#

Yeah

woven loom
#

but game's ray func already does the ray vs box and also gives u the pos

distant tulip
#

yeah, i did use that before

prisma shard
#

so now what me do

woven loom
#

just use default thibg

prisma shard
#

default thing what

woven loom
#

ray cast

grim raft
#

Error: Is not a function

let players = world.getPlayers()
    for (let player of players) {
        const getAboveBlocks = world.getDimension("overworld").getBlockFromRay(player.location(0, 5.0, 0))```
#

on the getBlockFromRay line

thorn flicker
#

because its not a function

#

location is not a method, its a property

grim raft
#

oh

tender pier
#

anyone knows what this is, I'm 100% sure it's nothing good at all

woven loom
#

it means ur code is taking longer to run

tender pier
woven loom
#

depends on code

remote oyster
woven loom
#

somehow i get warns with jobs aswell

#

i used debugger and it was showing 30 on avg

#

even tho i yielded everywhere

remote oyster
#

I didn't get any warnings but definitely had some spikes showing a lot of resources being used to execute when checking with the debugger. I fixed it.

woven loom
#

how did u do that

remote oyster
#

Probably different reasons honestly lol.

grim raft
#

I've bee stuck on this for ages lol

woven loom
#

what u want to do ?

grim raft
woven loom
#

Error: Is not a function

let players = world.getPlayers()
    for (let player of players) {
        const getAboveBlocks = player.dimension.getBlockFromRay(player.location, { x: 0, y: 1, z: 0})```
#

@grim raft

grim raft
#

OH ITS PLAYER BRUH

#

idk why I used world

woven loom
#

that wont work if player in some diff dim

grim raft
#

yea thats the point

#

making sunlight burn with scripts

#

YES FINALLY

#

TY

remote oyster
# woven loom how did u do that

I had a conversation about runJob a little bit ago in a forum someone created. Read up on the conversation to get an idea on how I approached it.

#1365029568670335117 message

thorn flicker
#

[Scripting][error]-TypeError: Object did not have a native handle. Interface property ['type'] expected type: EnchantmentType
im trying to copy enchantments over to another item and im getting this error.

const enchantable1 = item1.getComponent('enchantable')
item2.getComponent('enchantable').addEnchantments(enchantable1.getEnchantments())
rose light
#

Is there any way I can put a FOV on the entity, so that it can only shoot if it is in front of it?

sharp elbow
#

Hm. Perhaps you need to copy the result of getEnchantments to a variable first? This should not be necessary, but I wonder if the result is different.

// declare var item1: ItemStack, item2: ItemStack;
const enchantable1 = item1.getComponent('enchantable');
const enchantable2 = item2.getComponent('enchantable');
const enchantments = enchantable1.getEnchantments();
enchantable2.addEnchantments(enchantments);
#

@thorn flicker

thorn flicker
sharp elbow
#

I can take a peek

thorn flicker
#

im editing properties on an itemstack and its not saving.

#

and no, im not dealing with inventories

#

I think this might have to do with enchantment issue, the edits im doing to the itemstack are just not saving.

#
const item = new ItemStack('minecraft:diamond_sword', 1)
item.setCanDestroy(data.canDestroy);
item.setCanPlaceOn(data.canPlaceOn);

entity.dimension.spawnItem(item, entity.location)
sharp elbow
#

And what is data?

thorn flicker
#

im making a database for itemstacks.

#

its just a parsed object.

sharp elbow
#

Can you describe its interface? I assume its canDestroy and canPlaceOn are string[], but it's better to be certain

thorn flicker
#

it is.

#

okay, it has to do with my object, all properties seem like its returning undefined when im trying to use them

#

which is weird because im checking their output, and it showing the values.

thorn flicker
#

like for example, im saving the nametag in the object, and its showing the name value, however when I assign this nametag from the property, onto the item, its undefined

sharp elbow
#

I can confirm your code works when I pass it a simple data stub, so it's definitely not the API there

thorn flicker
#

Yeah, I dont know what im doing wrong though

#

and yes, im aware that im not sharing enough code, ill just try to piece it together myself then.

sharp elbow
#

Always helps to have someone else do a sanity check 😄

thorn flicker
#

I did data.nametag, not nameTag

sharp elbow
#

I hope you're at least a step closer to finding the problem

thorn flicker
#

so the enchantment issue is unrelated.

thorn flicker
#

let me try

#

no difference.

sharp elbow
#

What API version are you using?

thorn flicker
#

2.0.0

#
[Scripting][error]-TypeError: Object did not have a native handle. Interface property ['type'] expected type: EnchantmentType (failed parsing interface to Array element [0], failed parsing array to Function argument [0])    at getItemstack (main.js:63)
    at <anonymous> (main.js:80)

this is the full error.

sharp elbow
#

I'm having trouble reproducing the error with this snippet:

function useItem(arg) {
    console.warn("HI")
    const player = arg.source;
    const inventory = player.getComponent("inventory");
    const item1 = inventory.container.getItem(player.selectedSlotIndex);
    system.run(() => {
        const item2 = new ItemStack("minecraft:diamond_sword", 1);
        const enchantable1 = item1.getComponent('enchantable');
        item2.getComponent('enchantable').addEnchantments(enchantable1.getEnchantments());
    
        player.dimension.spawnItem(item2, player.location);
    })

    return;
}

world.beforeEvents.itemUse.subscribe(useItem);
#

Not sure if the context you're executing your instructions in is different from mine

thorn flicker
#

so what I needed to do was get the enchantments, map them into a new object, indentical to EnchantmentType and create a new instance of EnchantmentType, and use the enchantment id from the data I saved.

#

I guess there's issues stringifying the EnchantmentType class and parsing it afterwards.

halcyon phoenix
#

we can't detect locators location through script right?

woven loom
#

why u want to do that

livid elk
#

how to get the location of a specific block?

woven loom
#

.location @livid elk

prisma shard
floral vessel
#

how can I check if an entity can naturally despawn? (so I don't remove entities with names or other special properties)

livid elk
#

thanks!

wary edge
#

Youll have to check if it has a name or not tjen.

floral vessel
#

oh great... and there's no way to check if an enderman is holding a block

#

oh wait there is... as a molang query

#

oh well theres the is_persistent entity filter

#

no clue how to run that from a script tho

neat hazel
#

Why is the entity not being rotated?

const dx = target.location.x - machine.location.x;
const dz = target.location.z - machine.location.z;
const yaw = (Math.atan2(dx, dz) * 180) / Math.PI;
machine.setRotation({ x: 0, y: yaw });```
halcyon phoenix
halcyon phoenix
#

oh nevermind discord bug

halcyon phoenix
bold stratus
#

What method can be used to show a player form after closing the chat menu?

#

I always use "!test" with slight delay 3 second.

shy leaf
#

this is more reliable since it always ensures the form to open after closing the chat

#

though you can now use custom command to do this nowadays, and it even closes the chat automatically

nova flame
#

this will just try re open the ui every 10 ticks until the user is not busy

bold stratus
#

Oh

nova flame
#

Guys how would i make a system that check if a player has a tag and after 3 IRL days it removes the tag

#

how do i like use irl days in a system

#

like that

nova flame
#

any examples?

sharp elbow
#

Use Date.now() to store a timestamp of when that tag was applied. Then after 3 days worth of milliseconds (86,400,000), you know 3 days have passed; remove the tag then

#

You'd probably want to check periodically when to remove the tag, like every minute

nova flame
#

yeah

#

alright thanks

#

@sharp elbowdo you know where there is any docs on it i cant find Date.now in bedrock wiki or jaylys website

thorn flicker
#

its not a script api thing.

sharp elbow
#

The Date object is a feature native to JavaScript. You can read about it on the MDN docs

thorn flicker
#

its part of javascript itself.

woven loom
#

The challenging part is determining when to remove the tag.

lone thistle
#

Store the timestamp somewhere, compare it with the current timestamp and just check periodically if it's been three days since

woven loom
#

Periodically

final ocean
#

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

What name in 2.1.0-beta ??

lone thistle
thorn flicker
thorn flicker
thorn flicker
#

okay.

dawn zealot
#

is there a way to get the players dynamic property when they leave using the playerLeave event?

dawn zealot
#

swear i saw somewhere that didnt work

distant tulip
#

yep

dawn zealot
#

made my life 10 times easier

distant tulip
dawn zealot
#

tyty

distant tulip
#

np

dawn zealot
#

i was mid way through storing the data etc etc lmao

distant tulip
#

is this for a server or an addon

dawn zealot
#

server

#

not the NDA one you know of

#

im basically storing the players island in a structure

#

so i need their pfid and temp id

distant tulip
#

yeah, just asking to confirm
that event don't trigger in local words in some cases

dawn zealot
#

ah shit

distant tulip
#

local worlds*

dawn zealot
#

yeah im using a world to make the whole server

distant tulip
#

it should work fine for testing

dawn zealot
#

gotcha

#

the chunks shouldnt need to be loaded right

distant tulip
#

the only case it doesn't work is if you force shut the game

#

nope

dawn zealot
#

bet ty

distant tulip
#

your welcome

dawn zealot
#

first time making a skyblock so i just dont wanna mess up the island system

#
world.beforeEvents.playerLeave.subscribe((data) => {
    const player = data.player;

    const pfid = player.getDynamicProperty("pfid");
    const player_id = player.getDynamicProperty("player_id");

    if (pfid === undefined || player_id === undefined) return;

    const islandKey = `island${player_id}`;
    const island = island_save_coords[islandKey];

    if (!island) return;

    overworld.runCommand(`structure save island_${pfid} ${island.bottom_corner.x} ${island.bottom_corner.y} ${island.bottom_corner.z} ${island.top_corner.x} ${island.top_corner.y} ${island.top_corner.z}`)
        console.warn(`✔ Saved island_${pfid} for ${player.name} on leave.`);
})
``` this is my plan for storing it
#

saving*

distant tulip
#

why do you need to save it tho

dawn zealot
#

im having it so that the max amount of islands will be the amount of players online

#

so it cleans up

#

so like plots

#

cuz if u think about it these islands are gonna have loads of entities

distant tulip
#

not sure i fully understand but alright
you can use structure manager btw

#

native method for structure stuff

dawn zealot
#

oh wha

#

never seen that anywhere

dawn zealot
#

i dont want it so that when a new player spawns it just spawns an island like 1k blocks away form the last person that joined, i want it so that it spawns the island in one of the 20 slots available

#

then when they leave it saves everything on their island including entities and loads it back in the available slots when they join back

#

my idea to save lag^

distant tulip
#

oh, so you are removing them when they leave

dawn zealot
#

and having thousands of entities

distant tulip
#

wouldn't that be bad for performance

dawn zealot
dawn zealot
#

its only saving and loading on join and leave

#

plus max island size of 64x64

distant tulip
dawn zealot
#

ima jus use a command for now then switch later

distant tulip
#

sure

#

good luck with the project

dawn zealot
#

ty

#

sneakpeek lmao

distant tulip
#

i seen that in the server lol
look great

dawn zealot
#

ty

#

good sign so far

dawn zealot
meager cargo
#
import * as mc from "@minecraft/server";
const { world, system } = mc;

const TIME = 0.1;
const TIME_AT_POINT = 1;

const allWaypoints = [
  { x: -15, y: -61, z: 47 }, // START
  { x: -19, y: -61, z: 43 },
  { x: -17, y: -61, z: 41 },
  { x: -18, y: -61, z: 36 }  // END
];

const stateMap = new Map();

function moveTo(entity, target, speed) {
  const pos = entity.location;
  const dx = target.x - pos.x;
  const dy = target.y - pos.y;
  const dz = target.z - pos.z;
  const mag = Math.sqrt(dx * dx + dy * dy + dz * dz);
  if (mag < 0.01) return;
  return {
    x: (dx / mag) * speed,
    y: (dy / mag) * speed,
    z: (dz / mag) * speed
  };
}

system.runInterval(() => {
  const entities = world.getDimension("overworld").getEntities({ type: "minecraft:armor_stand", tags: ["test"] });
  for (const entity of entities) {
    if (!stateMap.has(entity)) {
      stateMap.set(entity, { index: 0, waiting: false, waitTicks: 0 });
    }
    const state = stateMap.get(entity);
    const target = allWaypoints[state.index];
    if (!target) {
      entity.removeTag("test");
      stateMap.delete(entity);
      continue;
    }
    const pos = entity.location;
    const dx = target.x - pos.x;
    const dy = target.y - pos.y;
    const dz = target.z - pos.z;
    const dist = Math.sqrt(dx * dx + dy * dy + dz * dz);
    if (dist < 0.4) {
      if (!state.waiting) {
        state.waiting = true;
        state.waitTicks = TIME_AT_POINT * 20;
      } else {
        state.waitTicks--;
        if (state.waitTicks <= 0) {
          state.index++;
          state.waiting = false;
        }
      }
      continue;
    }
    if (!state.waiting) {
      const impulse = moveTo(entity, target, TIME);
      if (impulse) entity.applyImpulse(impulse);
    }
  }
});

Can someone explain me why this is not working? And help me with?
I wanted to make path for entity using applyImpulse, but it keeps staying on the first waypoint.
Also it should work that the latest point is the ending one, but points before are optional.

cerulean cliff
#

we should get Dimension#getBlocksFromRay

livid elk
#

is it possible to change player fov using script?

wary edge
random ibex
#

Can someone help me make something similar, like there will be several commands and for one of these I need to redeem a code to redeem and with this I would get Credits to buy things on my server

neat hazel
cyan basin
#

I didn't realise that Herobrines Chest UI had been updated to support the inventory (lets go) but I had to add the enchants, glint and custom names to the inventory since I noticed those were missing dviperShrug

#

Looking at it now, most people would think it's just a regular chest lol until you "click" in the chests and can't click your inventory slots lol

#

Please don't repeatedly ask the same question. If you want help create a post in #1067535382285135923 and wait

rustic ermine
rustic ermine
random ibex
cyan basin
rustic ermine
#

Fair

cyan basin
#

You could probably make it interactable but there's no point

#

Unless you're using it for trading I don't see any other reason

rustic ermine
#

I was making a player trade system with it

cyan basin
#

Lol yeah

rustic ermine
#

Still ways to work around it though. JSONUI is just a pain, so thankful chestUI is available

cyan basin
#

I think that's also why there's such lag when opening it since it's still technically adding so many buttons

#

Even all of the empty slots are added buttons