#Script API General

1 messages · Page 103 of 1

distant tulip
#

uh what

distant gulch
#

i was asking how to convert something to a string

distant tulip
#

did you just ask how to make a string or am i seeing things

#

oh

distant tulip
#

like a number or what?

distant gulch
distant tulip
#

either JSON.stringify(3) or `${3}` or "" + 3 work there is a lot of ways

distant gulch
#

thx

distant tulip
#

np

dusky flicker
#

depends on what you want to do

#

if you want to print objects, its better using JSON.stringify

#

with numbers the toString method is pretty good by the way, you cam convert it to any base between 1..36 i guess

#

so N.toString(16) returns it in hex

loud brook
#

Hey guys, is there a way to know the max permutation of a block?

#

for example if the max is 2?

random flint
# loud brook Hey guys, is there a way to know the max permutation of a block?
  1. Get the permutation: block.permutation
  2. Get all the block state names Object.keys(permutation.getAllStates())
  3. Iterate each key and get the state type inside BlockStates Class: BlockStates.get(blockStateName)
  4. Retreive the quantity of the valid enums/ranges: blockStateType.validValues.length;
  5. Accumulate each quantity and you'll get how many enums/range permutation that the block has.

Edit: 🗿 I over complicated it didn't I?

random flint
# loud brook Tysm!

If you just want to know how many block states it has, just stop at step #2.
permutation.getAllStates().length

I'm 2 AM in the morning, so I might just misinterpret it and overcomplicate it

loud brook
#

Thanks!

round bone
#

too many ways

sly valve
#

Ugh.. wait

#

Yepp, we got many ways

#

Like

const str = "23";
const num = +str;
round bone
sly valve
#

imagine

function numToString(input: unknown): string {
  // Symbol-Falle für extra Overhead
  const TO_STRING = Symbol("toString");

  const handler = {
    get(target: any, prop: PropertyKey) {
      if (prop === TO_STRING) {
        return () => String(target);
      }
      return Reflect.get(target, prop);
    }
  };

  // Dummy Proxy, weil... warum nicht?
  const proxied = new Proxy(input, handler);

  // Safety First, obwohl völlig unnötig
  if (typeof proxied !== "number" && !(proxied instanceof Number)) {
    throw new TypeError("Expected a number-like input.");
  }

  // Match digits via Regex (unnötig, aber ja)
  const match = String(proxied).match(/-?\d+(\.\d+)?/g);
  if (!match) return "";

  // Konvertieren wir das Match unnötig auf Zahlen und wieder zurück
  const result = match
    .map(str =>
      [...str].reduce((acc, char) => acc + char, "")
    )
    .join("");

  // Noch ein bisschen unnötiger Check
  if (!/^-?\d+(\.\d+)?$/.test(result)) {
    throw new Error("Something went unnecessarily wrong.");
  }

  return result;
}
#

Thats better

sly valve
#

But actually just use

String(num)
distant tulip
#

We should benchmark all of those

sly valve
#

We should

distant gulch
#

there is a function to spawn a entity?

dusky flicker
#

i think i got quickjs installed on my computer

#

i might test it and show the benchmarsk

#

for sure im ask gpt to generate the benchmarks

round bone
#
    private static stringifyValue(value: RedisClientValueTypes): string {
        switch (typeof value) {
            case "string":
                return value
            case "boolean":
                return value ? "true" : "false"
            case "number":
                return value.toString()
            case "object":
                return JSON.stringify(value)
        }
    }

    private static parseValue<T extends RedisClientValueTypes>(value: string): T {
        switch (value) {
            case "true":
                return true as T
            case "false":
                return false as T
            default: {
                const parsedNumber: number = Number(value)
                if (!Number.isNaN(parsedNumber)) return parsedNumber as T

                try {
                    return JSON.parse(value) as T
                } catch {
                    return value as T
                }
            }
        }
    }
#

I am using my own parsers

sly valve
sly valve
subtle cove
#

Symbol(key) is exclusively unique unless it's Symbol.for(key) or declared and reused

#

With that use case, it's better to test what keys are actually referenced

north frigate
#

man I wish block.getState() and block.getAllStates() was asynchronous

subtle cove
#

It is in permutation object

#

And when block is setPermutationd

north frigate
subtle cove
#

Wdym, it's just small difference so it's not promise type

#

Well u can still await anything

north frigate
# sly valve but why

because sometimes they give me undefined when I get them in a system.runJob();

subtle cove
#

block.permutation.getState?

sly valve
#

Only returns undefined, when state is not "on it"

#

getAllStates alaways returns an record

#

see

getAllStates(): Record<string, boolean | number | string>
sly valve
north frigate
chilly fractal
#

So by now I should be asleep if I wanna be up okay without feeling my back shattered a hundred pieces in the morning, but anyway

#

Uh

#

So I am moving to item custom components.. took me long enough lol

#

I would love an explanation of how exactly they work

subtle cove
#

Is it possible to have variant custom components that's inside permutation

chilly fractal
#

😭

#

I don't think I even know what you just said.

#

I legitimately just started messing with custom components.

#

The question probably isn't targeted to me but yea, just sayin'

#

Good luck with the cool wizardry you always make tho.

dusky flicker
#
function benchmark(name, fn, iterations = 1_000_000) {
    const start = Date.now();
    for (let i = 0; i < iterations; i++) fn();
    const end = Date.now();
    const total = end - start;
    return {
        name,
        total,
        avg: total / iterations
    };
}

function runBenchmarks(value, label, iterations = 1_000_000) {
    console.log(`\n== ${label} ==`);

    const results = [];

    results.push(benchmark('String(x)', () => {
        const str = String(value);
    }, iterations));

    results.push(benchmark('x + ""', () => {
        const str = value + "";
    }, iterations));

    results.push(benchmark('x.toString()', () => {
        try {
            const str = value.toString();
        } catch (_) {}
    }, iterations));

    results.push(benchmark('`${x}`', () => {
        const str = `${value}`;
    }, iterations));

    results.push(benchmark('JSON.stringify(x)', () => {
        try {
            const str = JSON.stringify(value);
        } catch (_) {}
    }, iterations));

    // Display all results
    for (const r of results) {
        console.log(`${r.name.padEnd(20)}: ${r.total} ms total, ${r.avg.toFixed(6)} ms avg`);
    }

    // Find slowest and fastest
    const validResults = results.filter(r => !isNaN(r.avg));
    const fastest = validResults.reduce((a, b) => a.avg < b.avg ? a : b);
    const slowest = validResults.reduce((a, b) => a.avg > b.avg ? a : b);

    console.log(`Fastest : ${fastest.name} (${fastest.avg.toFixed(6)} ms avg)`);
    console.log(`Slowest : ${slowest.name} (${slowest.avg.toFixed(6)} ms avg)`);
}

// Sample values
runBenchmarks(123.456, 'Number');
runBenchmarks(true, 'Boolean');
runBenchmarks({ a: 1, b: 2 }, 'Object');
runBenchmarks([1, 2, 3], 'Array');
runBenchmarks(null, 'Null');
runBenchmarks(undefined, 'Undefined');
runBenchmarks({ toString: () => "custom!" }, 'Custom toString');
subtle cove
#

custom components is like id where that id can have features that's registered in block initialization

chilly fractal
#

Ahh, nice.

dusky flicker
# dusky flicker

everything was gpt who provided, i didnt even try to optimize the code

chilly fractal
dusky flicker
#

would it be a good idea for me to create a topic on script-resources only to show benchmarks?

sly valve
granite cape
#

.

dusky flicker
rustic ermine
#

my codebase is getting pretty solid now. yesterday decided to make a new branch to start a complete rewrite of my older systems and ideas to better integrate with the event system because spent a good 2-3 weeks getting familiar with the minecraft api and typescript. still haven't redone the item classes yet, but the idea here is that the super(8) would be super(item.actionSpeed). different tier items will perform actions at a faster tick rate (like runescape).

round bone
rustic ermine
# round bone you are using bridge for development?

yeah. normally I use vscode for programming but Bridge is what I started this project on when I was still learning and it has been fine. I mainly just like that is has TS already configured and automatically updates the type files if you change dependancy versions. Is also nice because when I am doing live-testing on dedicated server compared to just singleplayer, I can tell it to just output the dev packs straight to the dedicated server folder

round bone
round bone
# sly valve W H Y

WebStorm is really good for writing softwares like add-ons in TypeScript

round bone
#

also I have it for free

sly valve
#

But what makes WebStorm better than VScode

#

Name it and perchance ill switch

#

@round bone nvm it's I researched - seems like its pretty good

round bone
#

a lot of things tbh

midnight ridge
#

to check if a mob is passive using a hasComponent("minecraft:attack") method is a good way to do it or there is another way?

sly valve
empty grail
#

reading json when?

dusky flicker
sly valve
empty grail
#

also when physic component will be integerated

empty grail
sly valve
empty grail
rustic ermine
sly valve
sly valve
#

;-; I don't understand what you want, must bemy lack in understanding

empty grail
sly valve
#

At least I think so

#

Because minecraft's code isnt just simply like

if (entity.get("physic").isTurnedOn) {
  doPhysicsStuff(entity)
}
empty grail
#

there is a work around using entity event but it's not as efficient if we use script

sly valve
#

hmm okay then script would be better

sly valve
empty grail
#

can component value read entity property using q.property()?

sly valve
#

hmm. well im not well known with Entities

#

But I think you should be able to read properties from the entity

unreal cove
leaden elbow
#

whats the event for right clicking npcs? (not entityhitentity)

open urchin
#

playerInteractWithEntity probably

leaden elbow
#

gotta try

#

i think it only works when something like mounting or trading

midnight ridge
#

what is the stable version of @minecraft/server-ui?

round bone
midnight ridge
#

wait

#

isnt that beta?

open urchin
#

no

midnight ridge
#

kk

round bone
#

nope, 2.1.0 is beta

open urchin
#

2.0.0 released in 1.21.90

#

for server and server-ui

round bone
#

I am using stable for my project for the first time xD

#

2.0.0 is pretty neat

#

are slash commands released in this version?

midnight ridge
#

and what about minecraft server?

round bone
midnight ridge
#

ty guys

round bone
midnight ridge
#

1.19.0

#

BYC_r what does it mean

open urchin
#

to use server-ui v2 you have to also be using server v2

midnight ridge
open urchin
#

what do you mean

#

server 2.0.0 is also stable

#

oh

#

i see

midnight ridge
open urchin
#

idk why 2.0.0 is missing from there

round bone
midnight ridge
open urchin
midnight ridge
#

wait

#

let me check

#

kkkk works

#

i see it now

#

ty

livid elk
#

how to cancel the attack in entityHitEntity?

wary edge
livid elk
#

is there something I can use like that, which can cancel the attack dmg?

wary edge
livid elk
#

ohh yeah, why i didnt think about that. thank you!!

#

is there a way to refresh form without calling/opening the form again?

stark kestrel
#

does any1 have exact vanilla player hit by player knockback replica?

stark kestrel
#

holy im suffering

prisma shard
# stark kestrel does any1 have exact vanilla player hit by player knockback replica?

let horizontalKB = 0.2789
let verticalKB = 0.1023
let knockbackX = victimLocation.x - attackerLocation.x;
let knockbackZ = victimLocation.z - attackerLocation.z;

const magnitude = Math.sqrt(knockbackX * knockbackX + knockbackZ * knockbackZ);
if (magnitude !== 0) {
    knockbackX /= magnitude;
    knockbackZ /= magnitude;
}
entity.applyKnockback(knockbackX, knockbackZ, horizontalKB, verticalKB);```
#

here

#

this might be old

#

but i had in my code

#

applyKnockback structure might be updated, but the math should work

#

It's a exact player hit knockback replica

slim forum
#

Learning about classes

distant tulip
#

i never used classes in javascript

sly valve
#

Classes are powerful

dusky flicker
#

do you program things like in C?

const obj ={...};

function doSomething(o){...}

doSomething(obj);
?

slim forum
#

Still dropping to 18 tick

#

Hmmm

sly valve
#

If your update runs every tick y you gotta optimize it

#

Send me the Update code private, and I will help yiu

distant tulip
#

optimize your cide

slim forum
#

They told me that classes reduce lag

sly valve
#

But its a lie

#

Sometimes Functions or Literal objects are better

#

Sometimes classes

deep quiver
#

classes just make code more organised

#

or can make

#

it always depends on who is writing the code

sly valve
#

Inheritance, polymorphism

sly valve
deep quiver
sly valve
#

Love classes for the inheritance and polymorphism

sly valve
#

Just woke up. Its 20:25

#

I hate my life

slim forum
sly valve
sly valve
sly valve
slim forum
#

But, wait

sly valve
#

Shore

slim forum
#

Sure

sly valve
slim forum
sly valve
#

Ahh thats cool

slim forum
# slim forum

Thanks, also, with this I will be able to replicate it in other codes of mine that need optimization

slim forum
#

There are many

sly valve
#

:o what the-

north rapids
#

play animation plays only one animation?

slim forum
north rapids
#

there is any way to play more animations at same time?

slim forum
#

Try to use setProperty or something for more complex animations

sly valve
# slim forum There are many

so uhh.. its pretty big
You should optimize the main loop.
Try to prevent Overheads and Double Work e.g Double Fetching, Repeated Computation or Recursion

slim forum
#

Like entity.setPropery('aaaa:dance', true);

slim forum
north rapids
#

how to use it with the animations?

slim forum
north rapids
#

queries?

slim forum
#

But you need to create the property in the entity behavior

north rapids
#

theres another way?

slim forum
#

"q.property('aaa:dance') == 'true'"

#

Or

#

Just do "q.property('aaa:dance)"

north rapids
#

if (wieldType === 'twoHands') {
player.playAnimation(animation.combat.wield.two_hands, { blendOutTime: 0.3 });
player.playAnimation(animation.combat.fix_runing)}

#

i use this in my script

slim forum
#

I recommend using an int or float property, as it can accommodate more changes and doesn't take up as much space in the entity's behavior properties

north rapids
#

I want to do this without modifying the player.json or player animations

slim forum
#

Hmmm, no idea then

#

Maybe someone here knows how

north rapids
#

ok, ty

random flint
north rapids
#

one uses molang and the other smooth animation

round bone
#

But for TS?

#

💀

distant tulip
#

whats TS

thorn flicker
#

typescript

random flint
distant tulip
#

never heard of it

north rapids
#

damn

random flint
#

What's TypeScript?

distant tulip
#

is it some kinda of script that you type? "type script"

round bone
north rapids
#

lol

distant tulip
north rapids
thorn flicker
round bone
distant tulip
#

sound interesting

random flint
thorn flicker
#

here we go

round bone
random flint
thorn flicker
#

im lazy to set it up aswell

round bone
random flint
#

True. But the essence is still the same... It's still ScriptAPI.

round bone
random flint
#

Sure.

sly valve
random flint
#

Hello Rosmon. It's 2:34 AM in the morning for me.

sly valve
random flint
sly valve
dusky flicker
#

due to dynamic dispatch

#

but i don't think you should use functions over classes if you havent a real reason to do so

#

other than "speed"

#

what you could do is paralelize the code

#

instead of using blocking functions

sly valve
limber leaf
#

actually, polymorphism

#

a class in minecraft, MIGHT be 16bytes(on 64bit architeture, on 32bit it MIGHT be 8bytes), 1 is a pointer to the underlying object, and another is for the vtable, which is a way to map names to function pointers. when you have polymorphism the code must know which is the correct function to call, but as there is absolutely no way to tell js what is the correct function of what, it has to find which is a little slower. i mean o.f() is slower than f(o)

chilly fractal
#

Yeah so I don't wanna be that guy

limber leaf
#

normally on typed langs, like rust for example, if you got no dyn(dynamic dispatch) the code of obj.f() is generally compiled to f(obj)

chilly fractal
#

But classes are great for keeping code organized and providing a stable public API for later you and other developers working on the project.

limber leaf
#

but the performance you gain by using functions is not that much

chilly fractal
#

They have a little bit of an overhead compared to normal functions but it's very marginal.

#

It's unnoticeable almost always.

limber leaf
#

specially on fucking js where everything is heap allocated, variables can change type anytime, and new Array(50) is slower than new Array() because it simply does not malloc because, wow, theres no way to know the size of data

chilly fractal
#

Yet it is still overhead, if you genuinely can't optimize your script whatsoever. Like you did every possible optimization you could, maybe try considering breaking down classes into functions, but that's literally near impossible unless you're doing A CRAP TON of calculations that you cache, optimization and do other techniques in.

#

Again, I can't stress this enough, almost always you should use classes over functions.

#

I was about to explain why the overhead but realized someone explained it before me.

#

Oh well, I will go now.

limber leaf
#

and is better than inheritance

#

when you have a long chain of classes that inherit, things can get confuse

sly valve
#

composition?

limber leaf
sly valve
#

Ahh I see

#

thats cool

limber leaf
#

minecraft debugger sends jsons, xd

#

yeah i can do a in terminal application

round bone
limber leaf
#

with hyprland

#

im in love with blur

round bone
#

Your NIX launcher is outdated, by just a bit

#

xD

limber leaf
#

i think its hardware limitation

#

i actually got the most actual installed

round bone
limber leaf
#

i3 2100

#

8gb ram

#

im poor

round bone
#

I heard that macOS support will be dropped soon

#

😭

limber leaf
#

by the way, you know what i have to write on the stream of the debugger to fully initialize it?

round bone
#

Script debugger?

limber leaf
#

yeah, the debugger on vscode

round bone
#

I haven't used it yet

limber leaf
#

for mc

#

when i run /script debugger connect

#

it does connect to my tcp listener and i got the following:
Read 71 from 127.0.0.1:19144
Content: [48, 48, 48, 48, 48, 48, 51, 101, 10, 123, 34, 116, 121, 112, 101, 34, 58, 34, 101, 118, 101, 110, 116, 34, 44, 34, 101, 118, 101, 110, 116, 34, 58, 123, 34, 116, 121, 112, 101, 34, 58, 34, 80, 114, 111, 116, 111, 99, 111, 108, 69, 118, 101, 110, 116, 34, 44, 34, 118, 101, 114, 115, 105, 111, 110, 34, 58, 50, 125, 125, 10]
Content to String: 0000003e
{"type":"event","event":{"type":"ProtocolEvent","version":2}}

#

i got no idea to what return because it errors on initialize

#

and it doesnt seem to be documented

#

because boohoo vscode

round bone
#

Can you maybe just read packets (without any manipulation of them) and try sending the same then?

limber leaf
#

yeah i can

#

but i dont think that would solve

round bone
#

I would scrap out everything and try with this data

limber leaf
#

i just connect it at the port

round bone
limber leaf
#

stream.write_all(b"{'type': 'minecraftCommand', 'command':{'command':'reload', 'dimension_type':'overworld'}}").unwrap();
and i try to send this back

#

i might do something focused on it later

#

must finish the addon

round bone
#

It's midnight for me, I am awake for 18 hours from now

limber leaf
#

holy hell

#

for me its 7:21pm

#

you gotta sleep bro

round bone
#

12:21 PM for me

limber leaf
#

i actually wanted making some kind of api for interacting with the debugger

#

then i might make a tui application to read it

round bone
#

I am working on a simple idle map

limber leaf
round bone
leaden elbow
leaden elbow
#

like minectaft:interact "interactions": [
{
"on_interact": {
"event": "open_form",
"target": "self"
},
"use_action": "interact"
}
]

#

because seems like when i right click my entity doesnt work

#

but if i right click entities that has interact button it works

#

eg horse, minecart, etc.

#

or i have to use beforeEvent

#

now it works lol

leaden elbow
#

alr working i just need to use beforeEvent thanks tho

sly valve
#

guys

#

guys

#

I need a better initial as ATKSPD

#

nvm chat were to slow, Anime server responded faster

#

what a shame

warped blaze
sly valve
random flint
#

"Attack Interval" :3

prisma shard
#
        const text = "Attack Speed of the tower in ticks"
        const length = 4;
        const space = /\s+/g;
        const post = /\s+|§./g;
        const invalid = /\"|\\/;
        let result = "";
   
        result = text.split(space).reduce((res, s) => res + s[0], "");
        if (result.length <= 1) result += text.replace(space, "")[1];
        console.warn(result.substring(0, length).toUpperCase()) 
sly valve
prisma shard
sly valve
prisma shard
#

@sly valve

#

the initial is ASOT

sly valve
#

please dont...

granite cape
#

🚙

copper quartz
#

anyone I can dm about scripting?

livid elk
halcyon phoenix
halcyon phoenix
round bone
round bone
round bone
copper quartz
round bone
copper quartz
#

I did no luck yet

#

It's a simple question and gpt sorted it

#

It was folder organization

#

But wondering if I should JSON UI or js it

halcyon phoenix
round bone
halcyon phoenix
#

yeah probably

livid elk
#

is the length of other entities' ids different from the player's id? i tried getting the player id, and it's always 11 characters long (at least in the tests i did), and the id of other entities is 13 characters long

round bone
#

technically you can test it on your own by just spawning few hundreds of entities and checking their length

#
import { world, Dimension, Entity } from "@minecraft/server"

const lengthsTesting = (): Map<number, number> => {
    const lengths: Map<number, number> = new Map<number, number>()
    const dimension: Dimension = world.getDimension("overworld")
    for (let i = 0; i < 1000; i++) {
        const { id }: Entity = dimension.spawnEntity("minecraft:zombie", {
            x: 0, 
            y: 0,
            z: 0
        })

        const idLength: number = id.length
        lengths.set(idLength, lenghts.get(idLength) ?? 0 + 1)
    }

    return lengthsTesting
}

world.afterEvents.worldLoad.subscribe(() => {
    const lengths: Map<number, number> = lengthsTesting()

    for (const key of lengths.keys()) {
        console.log(key + ": " + lengths.get(key))
    }
})
#

smth like this

copper quartz
#

What a good way to do UI, should I script it or JSON it?

round bone
#

what type of UI, does it have to look fancy

rustic ermine
#

yay. codebase rewrite done. now can start adding stuff again. I moved everything away from CustomComponent parameters to be driven by the typescript side. component parameters are awesome but it was a huge PITA when I changed my mind how a type/interface should look because then I'd need to go back and change every item or block and because it's JSON there would be no errors or autocompletion

#

here's how it looks now

#

and the code side of things is also much much cleaner and easier to reason with now

stark kestrel
#

const config = {
  horizontalKB: 0.2789,
  verticalKB: 0.14,
  sprintMultiplier: 1.05
};

world.afterEvents.entityHitEntity.subscribe(({ damagingEntity, hitEntity }) => {
  if (!damagingEntity?.isValid || !hitEntity?.isValid) return;
  if (damagingEntity.getEffect("minecraft:weakness")) return;

  hitEntity.applyDamage(4);

  const atk = damagingEntity.location;
  const vic = hitEntity.location;

  let dx = vic.x - atk.x;
  let dz = vic.z - atk.z;
  const mag = Math.hypot(dx, dz);
  if (!mag) return;

  dx /= mag;
  dz /= mag;

  let horizontalStrength = config.horizontalKB;
  let verticalStrength = config.verticalKB;

  if (damagingEntity.isSprinting) {
    horizontalStrength *= config.sprintMultiplier;
  }

  hitEntity.applyKnockback(
    { x: dx * horizontalStrength, z: dz * horizontalStrength },
    verticalStrength
  );
});

is there better way to do this

#

this feels very weird and im trying to replicate vanilla knockback on hit

rustic ermine
# stark kestrel ```js const config = { horizontalKB: 0.2789, verticalKB: 0.14, sprintMult...
  if (!damagingEntity?.isValid || !hitEntity?.isValid) return;

don't need the ? there because it is doing the same thing as isValid, and the event is triggered by an entity so there is no chance of the entity not being valid (isValid is still good though incase they somehow logged out or crashed or something at the exact millisecond the event fires)
other than that, looks good. knockback is unfortunately one of those things that needs to be calculated each time it happens because of different directions/positions/etc

rustic ermine
#

you could also probably just make those values constants

const HORIZONTAL_KB = 0.2789;
const VERTICAL_KB = 0.14;
const SPRINT_MULTIPLIER = 1.05;

micro-optimization but this would make the JS engine not have to do a property lookup on an Object. property lookups are still very, very fast though so it really just comes down to what you prefer to code.

stark kestrel
#

alright!

#

also uh is there a way to fix it being like very weird

rustic ermine
#

weird how?

stark kestrel
#

like it feels i get stuck in air for few ms or so

rustic ermine
#

try lowering vertical strength to something like 0.02

#

other than that, not sure. knockback is weird and I hate dealing with it

rustic ermine
#

this is some really old code I did with knockback a long time ago and it used 0.2 for the vertical :/ so, not sure, i'm sorry

world.afterEvents.entityHurt.subscribe((entity) => {
    if (entity.hurtEntity.typeId !== "minecraft:player") { return; }
    let player: Entity = entity.hurtEntity;
    const playerEquipment: EntityEquippableComponent = player.getComponent(EntityComponentTypes.Equippable);
    let offhand: ItemStack = playerEquipment.getEquipment(EquipmentSlot.Offhand);
    if (entity.damageSource.damagingEntity?.isValid() && playerIsBlocking(player, offhand)) {
        world.playSound('item.shield.block', player.location);
        let health: EntityHealthComponent = player.getComponent(EntityComponentTypes.Health);

        let damageReduction: number = 0;
        if (shieldDamageReduction.has(offhand.typeId)) { damageReduction = shieldDamageReduction.get(offhand.typeId) }
        health.setCurrentValue(health.currentValue + (entity.damage * damageReduction));

        const viewDirection: Vector3 = player.getViewDirection();
        entity.damageSource.damagingEntity?.applyKnockback(viewDirection.x, viewDirection.z, 1.75, 0.2);
    }
})
warped blaze
#

yo is there a way to implement ts on a behavior pack? I'm quite interested on learn more abt it and i saw ppl talking a lot

rustic ermine
#

Bridge is the easiest way IMO. it has TS natively

warped blaze
#

like is it even possible or u just make it for prevent errors before converting it js?

warped blaze
rustic ermine
#

but I would say it becomes borderline impossible to manage a large project without type safety. after a certain point it becomes a nightmare to make a mental map of what is going on without types

warped blaze
#

so typescript is just to prevent syntax and type errors when you transpile it

#

got it

#

thx

rustic ermine
#

yeah. i'll show an example (give me a min to code some BS code lol)

#

notice how blockId on new_block has an error because I used a string instead of a BlockID

warped blaze
#

can't i just set a script in a TS file and then just do import './example.ts'?

rustic ermine
#

if you have the type files loaded yeah (although you wouldnt import it as .ts .. just ./example), and you'd also need to set up a watcher to detect changes in your JS files to automatically transpile. It's kind of a pain to do without Bridge but people do it all the time

#

Bridge comes with all of it built in and you never even have to look at the .js files

warped blaze
#

well that's helpful information

#

tysm

round bone
rustic ermine
#

how so?

#

easy change if true atleast. I've only been doing TS for 3-4 weeks so open to improvement

round bone
rustic ermine
#

interestingly, too, it looks like enums are also a pretty poor performance choice since we are using quickJS. the generated JS looks disgusting (image attached) 🤮 . I just checked interface vs type and you are correct, thank you 🙂 also says that Type has to get re-cached every time the file is opened because of the complex things it can do, where Interface does not and can stay cached if not changed (that's not a runtime problem though). quick check on my largest type converted to interface confirms that too.. got a noticeably faster editor file load for completions. I appreciate it 🙂

round bone
#

Use const enums

#

Compiler will in-line these values

rustic ermine
#

thanks. and I meant I did not realize that js doesn't have a native enum. I grew up on C# and then eventually moved to Rust.. never really touched JS or TS before this project lol

#

lots to learn. it is a really nice language though (ts.. not js lol). quickly becoming my favorite

round bone
#

No problem, this server is for learning

round bone
rustic ermine
#

really enjoying how easy it can be to do really complex things once you have your base classes and interfaces/etc laid out

#

then also has the flexibility to not care when you just want to test an idea

round bone
#

The only missing thing is built-in final keyword for classes, but still it's pretty solid

rustic ermine
#

yeah. at least that's an easy problem to avoid if you are the only dev on your project though

round bone
#

You can use a decorator to create a final class

rustic ermine
#

not enforced though I'm guessing?

round bone
#

I use it sometimes and it's pretty solid aswell

rustic ermine
#
function final<T extends { new (...args: any[]): {} }>(constructor: T) {
  return class extends constructor {
    constructor(...args: any[]) {
      if (new.target !== constructor) {
        throw new Error(`Cannot inherit from final class ${constructor.name}`);
      }
      super(...args);
    }
  };
}

interesting

round bone
#

Yes

#

Or you can use private constructor

agile bone
#

is it possible to have a projectile be shot on different angle horizontally but on the same level, basically how a crossbow shoots with multishot

round bone
agile bone
#

elaborate

warped blaze
distant tulip
#

Get view direction
Multiply the vec3 to get your desired velocity
Make 3 versions of the vector
Add -x and x to 2 of them
Normalize the two
Use shoot(vector) from the projectile api

agile bone
#

TOT what

#

but it is possible with scripts yeah?

distant tulip
#

No that json ui

round bone
round bone
agile bone
#

oh are you answering to someone else's question?

distant tulip
#

Dude, that is obviously script api and is obviously to you

agile bone
#

my bad, I don't really know scripts that well or at all T-T

distant tulip
#

I am not at my laptop, so I can't really show you an example

agile bone
#
const SHOOTING_ANGLES = [
    { x: 0, y: 0, z: 1  },     // Forward
    { x: 0.5, y: 0, z: 0.87 }, // 30° right
    { x: -0.5, y: 0, z: 0.87 } // 30° left
];
world.afterEvents.entitySpawn.subscribe(event => {
    if (event.entity.typeId === "test:multishot") {
        system.runInterval(() => {
            const entity = event.entity;
            const targets = entity.getEntitiesFromViewDirection({ maxDistance: 16 });
            if (targets.length > 0) {
                SHOOTING_ANGLES.forEach(angle => {
                    const proj = entity.dimension.spawnEntity(
                        "minecraft:snowball", 
                        entity.getHeadLocation()
                    );
                    
                    proj.applyImpulse(angle);
                });
            }
        }, 40); // 2 second interval (20 ticks = 1 second)
    }
});```
#

would this work?

distant tulip
#

No, that have hard coded values.
It will always shoot to the same direction

agile bone
#

TOT

distant tulip
agile bone
#
import { shoot } from "@minecraft/server-projectile";

// Utility: Normalize a vector
function normalize(vec) {
    const length = Math.sqrt(vec.x * vec.x + vec.y * vec.y + vec.z * vec.z);
    if (length === 0) return { x: 0, y: 0, z: 0 };
    return {
        x: vec.x / length,
        y: vec.y / length,
        z: vec.z / length,
    };
}

// Velocity scale
const VELOCITY_MULTIPLIER = 1.5;

world.afterEvents.entitySpawn.subscribe(event => {
    if (event.entity.typeId === "test:multishot") {
        const entity = event.entity;

        system.runInterval(() => {
            const targets = entity.getEntitiesFromViewDirection({ maxDistance: 16 });
            if (targets.length === 0) return;

            const view = entity.getViewDirection();

            // Scaled base vector
            const baseVec = {
                x: view.x * VELOCITY_MULTIPLIER,
                y: view.y * VELOCITY_MULTIPLIER,
                z: view.z * VELOCITY_MULTIPLIER,
            };

            // Create 3 versions of the vector
            const centerVec = baseVec;
            const leftVec = normalize({ x: baseVec.x - 0.5, y: baseVec.y, z: baseVec.z });
            const rightVec = normalize({ x: baseVec.x + 0.5, y: baseVec.y, z: baseVec.z });

            // Shoot using projectile API
            shoot({
                shooter: entity,
                projectile: "minecraft:snowball",
                velocity: centerVec,
            });

            shoot({
                shooter: entity,
                projectile: "minecraft:snowball",
                velocity: leftVec,
            });

            shoot({
                shooter: entity,
                projectile: "minecraft:snowball",
                velocity: rightVec,
            });

        }, 40); // Every 2 seconds
    }
});```
#

it gave this

warped blaze
agile bone
#

figured since it's ai

dusky flicker
#

same as bun

#

prefer choosing a transpiler focused on performance, tsc might not be the best one for this case

round bone
#

Also you're supporting Micro$oft if you stay with their tooling

dusky flicker
dusky flicker
#

the std of it is literally shit

round bone
dusky flicker
round bone
dusky flicker
#

good to know

dusky flicker
hybrid bobcat
#

Does anyone know if I can translate text in the description of custom commands?

round bone
#

😭

hybrid bobcat
round bone
#

Try using a translation key as a raw string, if it does not work, then I am sorry, but you have to add only english translation directly

round bone
hybrid bobcat
hybrid bobcat
dusky flicker
#

Quaternions are really helpful for this

#

i prefer them over matrices

halcyon phoenix
rustic ermine
prisma shard
#

specially only for math help

dusky flicker
#

normally it tends to destroy my code because AI is just good for copy pasting stackoverflow and github

visual zephyr
#

is there a way to get a loot table of a block

warm mason
#
world.getLootTableManager().generateLootFromBlock(block);
#

but it only works on beta-API on the latest previews

warm mason
#

well in a couple of weeks there should be a new release so... although if you don't use the beta API then you'll have a long wait

halcyon phoenix
#

I still have no idea how to use public, private and this stuff

dusky flicker
#

class A {
public value: number = 5;
}

const obj =new A();
obj.value; //accepted

#

private makes it only visible to the class itself

#

class B {
private value:number = 0;
increase(){
return this.value++; //valid
}
}
const b = new B();
const val = b.increase(); //valid
const valx = b.value++; //invalid, in theory(because of js) you cannot access it

#

protected does the same as private, but only the classes that inheritc(as well as the one defined) can see

#

private is only for the class that declares it

#

class C extends B{
increaseBy(n:number){
return this.value += n; //invalid because its only visible inside B
}
}

#

it would be valid if at B it was defined as
protected value:number
instead

#

there are more others such as readonly that well, makes it readonly

#

but for the class itself and any other trying to read

#

you simply cannot write on the prop

#

static is that the thing declared is not bound to an instance but the class itself

class D {
static val:number = 0;
static increase(){
return this.val++;
}
}
//Same modifiers apply here(public, private, protected)
const d = new D;
d.increase(); //error, static are not defined on the prototype of an instance
const val = D.increase();
const valx = D.value;
//both valid

#

the _ on the code is from js actually, there's no need to declare props like _pingu when its already defined as private or protected

#

in js its a common pattern to declare them as "_pingu" for example to tell that that property is "internal" and should not be modified outside the class itself

subtle cove
#

@round bone how can u make private class methods/properties in ts like js class A { static #key = Symbol(); get #curr() { return { id: Date.now() } }

dusky flicker
#

although there is # modifier in js which makes it private

class B {
#value = 5; //js
}
same thing as in ts
class B {
private value = 5; //ts
}

subtle cove
#

uhm, es2020 does this

round bone
round bone
subtle cove
#
{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es2020",
    "module": "es2020",
    "lib": ["es2024"],
    "moduleResolution": "bundler",
    "strict": false,
    // "allowJs": true,
    // "checkJs": true,
    "noEmit": false,
    "skipLibCheck": true,
    "noImplicitAny": false,
    "removeComments": true,
    "outDir": "bin",
    "rootDir": "subpacks/beta/scripts",
    "baseUrl": "subpacks/beta/scripts",
    "paths": {
      "@minecraft/server": ["node_modules/@minecraft/server/index"],
      "@minecraft/server-ui": ["node_modules/@minecraft/server-ui/index"]
    },
    "types": ["@minecraft/server","@minecraft/server-ui","./subpacks/beta/scripts/index.d.ts"]
  },
  "include": ["subpacks/beta/scripts"],
  "exclude": ["node_modules"]
}```
round bone
#

simply remove # from method name

dusky flicker
#

i know before it, the normal was using a WeakMap

subtle cove
#

nvm, esnext can make it

#

altho the exports and other stuff might be different, sheesh

honest spear
#

i hate syntax for private members in JS

#

i just use private mark in TS only as keyword

subtle cove
#

mightve to try more useless stuff ;-;

honest spear
#

also average conmaster's code 😭 I can't even read my own code, i wrote this few mins ago


import { Cursor } from "../../cursor";
import { mergeSourceDirectNoEnumerable, VALUE_TYPE_CONSTRUCTOR_FACTORY, ValueTypeConstructor } from "../base";
import { NumberType } from "../number-type";
import { InlineSerializable } from "../serializable-type";

const {defineProperty} = Reflect;

export interface StaticSizedNumberConstructor<T extends number | bigint> extends ValueTypeConstructor<StaticSizedNumber<T>, T>, InlineSerializable {
    deserialize(cursor: Cursor, littleEndian?: boolean): T;
    serialize(cursor: Cursor, value: T, littleEndian?: boolean): void;
}
export interface StaticSizedNumber<T extends number | bigint> extends NumberType<T> { };
type DataViewSetMethodKey = {[K in keyof DataView]: K extends `set${string}` ? K : never}[keyof DataView];
type DataViewGetMethodKey =  {[K in keyof DataView]: K extends `get${string}` ? K : never}[keyof DataView];
export function generateStaticTypeWithEndianness<T extends number | bigint, S extends DataViewSetMethodKey, G extends DataViewGetMethodKey>
        (name: string, defaultValue: T, sizeOf: number, setMethod: S, getMethod: G): StaticSizedNumberConstructor<T> {
    const $ = VALUE_TYPE_CONSTRUCTOR_FACTORY(name, defaultValue, NumberType);

    mergeSourceDirectNoEnumerable($, {
        deserialize: createDeserializeFunction(getMethod as string, sizeOf),
        serialize: createSerializeFunction(setMethod as string, sizeOf),
        inlineDeserializableCode: ($1: unknown)=>createInlineDeserialize(getMethod as string, sizeOf, $1),
        inlineSerializableCode: ($0: unknown, $1: unknown)=>createInlineSerialize(getMethod as string, $0 as string, sizeOf, $1),
    });


    return $ as any;
}
#

const cursorVariableName = "$";
const valueVariableName = "_";
const endiannessVariableName = "$1";
type CursorKey = keyof Cursor;

function createSerializeFunction(setViewMethod: string, sizeOf: number): (cursor: Cursor, value: number | bigint, littleEndian?: boolean)=>void{
    const $ = Function(cursorVariableName,
        valueVariableName,
        endiannessVariableName,
        createInlineSerialize(setViewMethod, valueVariableName, sizeOf, endiannessVariableName)
    );
    defineProperty($, "name", {
        configurable: true,
        enumerable: false,
        writable: false,
        value: "serialize"
    });
    return $ as any;
}

function createDeserializeFunction(getViewMethod: string, sizeOf: number): (cursor: Cursor, littleEndian?: boolean)=>number | bigint {
    const $ = Function(cursorVariableName, endiannessVariableName,
`const _ = ${createInlineDeserialize(getViewMethod, sizeOf, endiannessVariableName)};
return _;`);
    defineProperty($, "name", {
        configurable: true,
        enumerable: false,
        writable: false,
        value: "deserialize"
    });
    return $ as any;
}

function createInlineSerialize(setMethod: string, value: string, sizeOf: number, endianness: unknown): string{
    return `$.${"view" satisfies CursorKey}.${setMethod}($.${"pointer" satisfies CursorKey}, ${value}, ${endianness}); $.${"pointer" satisfies CursorKey}+=${sizeOf}`;
}
function createInlineDeserialize(getMethod: string, sizeOf: number, endianness: unknown): string{
    return `$.${"view" satisfies CursorKey}.${getMethod}($.${"pointer" satisfies CursorKey}, ${endianness}); $.${"pointer" satisfies CursorKey}+=${sizeOf}`;
}
vast grove
#

That's some insane typings I have ever seen...

honest spear
#

Happens when you go low-level JS in TS

dusky flicker
#

i think you should use it

honest spear
#

all bad

#

mine good and fast

#

i writing runtime compiled serializer optimalizations

dusky flicker
subtle cove
#

im startin to have a fetish withObject.create(null)

honest spear
#

also some of mine favorite functions


export function mergeSourceWithInheritance<T, S extends Partial<T>>(target: T, source: S): T & S {
    return defineProperties(
        target,
        getOwnPropertyDescriptors(
            setPrototypeOf(
                source,
                create(getPrototypeOf(target), getOwnPropertyDescriptors(target))
            )
        )
    ) as T & S;
}
export function mergeSourceDirectNoEnumerable<T, S extends Partial<T>>(target: T, source: S): T & S {
    const raw = getOwnPropertyDescriptors(source);
    for(const key of Reflect.ownKeys(raw)) raw[key as keyof typeof raw].enumerable = false;
    return defineProperties(target, raw) as T & S;
}
#

the first one is also known as OverTakes

halcyon phoenix
honest spear
subtle cove
#

con's OverTakes is way too op

dusky flicker
dusky flicker
#

im addicted to document everything

subtle cove
#

ohboi

#

sth abt prototype pollution

honest spear
#

I am mean i am writing code for 6 hours without even single test

dusky flicker
#

i do the same xd

#

i might implement a N-ary tree as well as a tree diff algorithm for an ui lib im making

#

i probably will just write and test after tje minimum is complete

honest spear
#

yea, reasonable

prisma shard
#

i also write code at once then test at last

honest spear
#

well good luck guys with your projects, see you later

dusky flicker
#

i just think youre making things too complex on the serializer

honest spear
dusky flicker
#

it would be better to simply define a list of primitives

#

like a normal compiled lang does

prisma shard
honest spear
dusky flicker
#

wait, what are those functions for, then?

honest spear
#

and NBT

#

if you parse NBT you have to save number type as well if you want to serialize it back

prisma shard
#

PascalCase ;-;

honest spear
#

so you know its decorator and not regular function

prisma shard
#

:>

copper quartz
#
function executeTransfer(player, targetName, amount) {
    let senderName = player.name;

    if (!targetName || isNaN(amount) || amount <= 0) {
        system.sendText(player, "Invalid transfer command. Usage: /transfer <player> <amount>");
        return;
    }

    system.executeCommand(`/scoreboard players get ${senderName} money`, (result) => {

        let match = result?.data?.[0]?.message?.match(/(\d+)/);
        let targetBalance = match ? parseInt(match[1]) : 0;

        if (amount > senderBalance) {
            system.sendText(player, "You don't have enough money for this transfer.");
            return;
        }

            // Perform the transfer
            system.executeCommand(`/scoreboard players remove ${senderName} money ${amount}`);
            system.executeCommand(`/scoreboard players add ${targetName} money ${amount}`);

            system.sendText(player, `You sent $${amount} to ${targetName}.`);
            system.sendText(targetName, `You received $${amount} from ${senderName}.`);
        
    });
}

wondering if this is valid, I've been tampering with some of it and used a bit of ai, wondering if I need to change the sendText

prisma shard
dusky flicker
copper quartz
subtle cove
#

other than delete obj.property anyone knows other ways or it's the only one?

dusky flicker
honest spear
# prisma shard <@805533255121109022>

Well i stand for **If you want it do it in your own way! **
here is why:

  • Good IS database would propably go for Custom Entity with huge inventories, i don't want to complicate my DB installation
  • Requires special ticking for entity inventory or block inventory to be able to access itemstacks anytime, i don't want to handle this in way it could colide with others ticking areas systems
  • Its not that hard for them to implement
dusky flicker
prisma shard
honest spear
#

but it has same behavior as that same keyword

#

i would go for it as its more explicit

copper quartz
dusky flicker
honest spear
dusky flicker
#

like damn, hashmap is more like a "caching system"

honest spear
#

yea

#

DB is really out of context, but that term is used here a lot in sense of Dynamic Properties wrappers

honest spear
dusky flicker
copper quartz
dusky flicker
copper quartz
#

I found it

#

Never mind lol

honest spear
honest spear
dusky flicker
#

dp?

honest spear
#

dynamic properties

dusky flicker
#

oh

#

i would use strings for so, the problem would be null bytes

#

that is understood as string finalization

honest spear
#

yea

dusky flicker
#

i have no idea why strings in js are like this

honest spear
#

its not bc of JS

dusky flicker
#

i thought they were length based

honest spear
#

its bc C++ old strings from C days

dusky flicker
honest spear
#

JS just passes the string with the null byte without problem, once it gets native side then its unpredictable

dusky flicker
#

didnt think of that

#

bytheway, is there something about wasm that the engine might adopt?

honest spear
#

well until they switch to v8 i think there is no reason to talk about wasm

dusky flicker
#

really? i thought quickjs had support for wasm

honest spear
#

well they are not sure if they want to stick with QuickJS for long as MC uses v8 for OreUI already

#

no plans its just in complicated state now

dusky flicker
#

thank god, at least we got a chance

#

that will make things easier

dusky flicker
honest spear
#

long time moving around the talks and script api devs

#

in most cases its OSS server

#

that OSS that i have as server tag

#

btw i am working on Custom Bedrock Server Software in TS, nothing huge yet just starting but raknet is pretty much done

#

well gtg have a nice day

dusky flicker
dusky flicker
round bone
#

😭

subtle cove
#

btw, abt the #prop

#

it works on es2022

honest spear
#

i still hate that syntax and no one really uses it

#

its more like feature for security based properties where you store information like passwords

subtle cove
#

depends, i use it for class' cache purposes

honest spear
#

example?

subtle cove
round bone
subtle cove
final ocean
#

How to check the lore of an item?

subtle cove
dusky flicker
#

im thinking about converting the null byte to maybe a sequence of bytes, or transform it to a specific byte, but i really think that would lead to bugs

honest spear
#

0 is 1, 1 is 2

#

and so on

dusky flicker
#

yeah but what if i get a 0xff

honest spear
#

0xff is not valid UTF-8 char anyway

dusky flicker
#

i dont want making it human readable

#

its a binary serializer just like yours, to transfer data

#

literally getting the bytes of a struct

honest spear
#

i mean 0xff would get two bytes anyway

#

thats how UTF-8 Works

#

so don't worry

#

i have tested this and it works

#

just shift all by 1 and if possible keep it under 7bit so you don't blow up your data

#

at this point just do Base64 encoding and you are safe

dusky flicker
#

hell no, it will increase the size of the content

dusky flicker
#

i just made it

#

and now i want to add binary transfer

#

damn working with uint8arrays would be way easier than strings

honest spear
# dusky flicker hell no, it will increase the size of the content

actually base64 is 6bit encoding utf8 is 7bit encoding, maybe you loose 1bit but it will cover problem with utf8 and null termination, if you miss by 7bit then it would add another byte so its way to risky, base64 is actually the safest way to store data in string without blowing up the data

granite cape
#

p

subtle cove
#

isnt null strngifyable...

open urchin
#

they aren't talking about JSON null

honest spear
#

you can use charCodeAt and fromCharCodes

#

to build string from byte array like

subtle cove
#

Ohkey

dusky flicker
#

well, i found base32768(im already on a rabbit hole)

#

i think it might be some good solution

tardy pivot
#

is this a bug with redstone conductivity

#

when the block is placed without neighboring activating redstone its redstone power returns undefined

#

and they cant conduct the torch below

visual zephyr
#

how can i get a value of a entity query using script api

visual zephyr
#

or q.is_eating

wary edge
visual zephyr
#

oh okay i just wanna debug because when eating an item with an attahable it doesnt animate, thanks tho

open urchin
#

q.is_eating is for the snacking behaviour, not players using food

mellow jolt
#

Hello, does anyone have a solution to block access to a chest with the API, especially against cheats?

untold magnet
#

make it works like a RP (wont turn off ur achievements)

copper quartz
#

How do I include a members username and tag in a .body line
I want it to say "Welcome ${playerName}, you rank is: staff or smth"

#

I got the name working just need the tag

inland merlin
inland merlin
mellow jolt
#

? It's an event, I'm mainly looking for a solution because it's impossible to find one. I'm talking about the original minecraft:chest

inland merlin
#

Prevent interactions?

mellow jolt
#

hmm

untold magnet
inland merlin
mellow jolt
#

Setting an entity permanently will cause a lag if I generate it with a scan of the area, it will cause a lag, otherwise when the player looks at the chest but we can always be faster especially in case of lag

inland merlin
#

You say cheats bypass it?

untold magnet
#

like its not that hard, and u can control if u can open the inventory or not

mellow jolt
untold magnet
#

thats just an option,

untold magnet
#

gl looking for a solution ig

mellow jolt
#

and if I compare the chest when opened and until the player looks in another direction, I can save it in a setDynamicProperty or Map 😖

#

Are there any unofficial servers that support APIs and plugins? I don't think so.

inland merlin
#

Has a way to stop packets of course

#

But stays wrapped around bds

mellow jolt
#

I'll think about it, if you have any ideas for safes, send me a PM

north frigate
#

hmmm since form.show() returns a promise i can await it without problems right?...

sly valve
#

Hello guys

#

Just joke up, its 23:11

#

I hate my life

north frigate
#

i said that 3 seconds ago

distant gulch
#

how can i kill an item after 30 seconds that it touches the ground

distant gulch
sly valve
copper quartz
#

how would I compress my chat ranks, floating text, floating leaderboars and chat nicknames all into 1 function / event?

distant gulch
sly valve
# distant gulch how can i kill an item after 30 seconds that it touches the ground

Well you cbman iterate each item, check if its on the ground and count till its timer reacheds 30.

Or you are smart and ignore the "touches the ground" part anf just wait till an Item spawns, and add it to an array that iteratee each second, increases a counter by one

Dont forget to remove not existing items to prevent memory leaks.
thats how I would do it.
Dont use splice to remove something out of an array. Replace the item with the last item to fill the emoty space, like a replace

sly valve
distant gulch
sly valve
#

-# but right now im busy, watching Uma Musume

distant gulch
distant gulch
stark kestrel
#

Or we have to use their api in python

dusky flicker
shut vessel
#

Do you know of a way to transfer scoreboards from one world to another? Like on a network between maps?

dusky flicker
#

and its damn simple, pushups

inland merlin
shut vessel
sly valve
stark kestrel
sly valve
#

Or

#

You fetch all scoreboard with python from world A, and edit world's B scoreboard data

#

idk if this is possible

inland merlin
#

Basically wrapped around it uses simialr setup

#

Could even do c++ if you hate ur life

sly valve
inland merlin
#

Fun cause its still minecraft

distant gulch
stark kestrel
inland merlin
shut vessel
#

because I'm trying to make a kind of network that has scoreboards and that you can start games via a server then when the game starts it teleports the players to another map then I would like all the stats that the player gains on the combat map to be put back in the spawn map

stark kestrel
#

I'll give it a try

inland merlin
#

Like beforeEvents

#

Cancel damage

stark kestrel
#

beforeEvents.entityHitEntity

#

I made my own yesterday

#

xD

#

Knockback was the main issue tbh

inland merlin
#

Yeh

#

They had Vincent fixing that i think

stark kestrel
#

Oo

sly valve
dusky flicker
#

as simple as a bunch of pushups

stark kestrel
#

How is that?

inland merlin
#

Lol

sly valve
inland merlin
#

Are we talking bout the same thing

inland merlin
#

Im talking the server

#

Lol

stark kestrel
#

Let me show my test code for the pvp

dusky flicker
inland merlin
#

For normal script api they can only cancel through the player.json properly

sly valve
inland merlin
#

If its one hit

sly valve
stark kestrel
#

Things work differently in my server that shouldn't be a big issue for me

sly valve
#

And what about armor, armor still takes damage

stark kestrel
sly valve
#

best solution may be player.json

#

but nice that you made your own beforeEVent

stark kestrel
#

I was dying cuz man my custom enchants can't work without it

stark kestrel
#

There's insane logic in it

inland merlin
#

Lol

stark kestrel
#

Let me explain something in my PvP custom enchants

If player has tank on their Armor, let's say all 4 pieces since it stacks,

Reduction of damage from axes gets down 12%, 3% each piece

Then comes an enchantment called frenzy, it deals more damage if u get a player in a combo, now here I have to reduce damages, then apply damages and scale them

#

Now this calculation is just for just 2 enchants

#

That's why I needed a beforeEvent for this

sly valve
#

I see

inland merlin
#

Well, would be cool if one of these previews they add beforeEvent cancel

#

Lol I feel you

stark kestrel
#

I deleted them

stark kestrel
inland merlin
#

Lol

#

I got through like half

#

Anyways, yeah bedrock fun to script for.

stark kestrel
rustic ermine
#

Time for my least favorite part of server dev... Turning the database back on and syncing all of the things I did over the last week with it 🥲

true isle
#

so ive got a new tool for structures for creating custom trees ive got like 2 of like 11 of mine done i also have a few variations of vanilla trees done any specific tree i should redo?

rustic ermine
#

I test with single player usually because the iteration time while using dedicated server with a DB server is annoying

rustic ermine
true isle
#

rotate or scale? mine do lol

rustic ermine
#

Nice. 11 should be plenty then

true isle
#

theres also plenty of ways to make wacky shapes with mine so i think ill do what i have and see what happens. so far ive been working with my super birch which was a pain in the ass but i got it. also i tested another with the cordecyps type fungus i made which looks cool so far im still testing the acacia varient i made along with the 2x2 trees

rustic ermine
#

Any screenshots? Sounds really interesting actually. World creation tools always fascinate me lol, especially if any kind of procedural gen is used

rustic ermine
#

That's awesome, nice work

#

The fourth pink one looks a little flat at the top. Not sure how to explain what I mean

true isle
#

thats what they all are lol im trying to combine them all into one so i can create anything on the fly with the configs from the modal form

#

yeah its flater at the top like the cherry or acacia trees

#

theres settings to change that though so its not just flat lol

rustic ermine
#

Ahh ok I was thinking like a willow, but it still looks good. Are you using structure files? Might be tricky to change out the types via code if you are. Storing the positions in a data structure is about the only way I can think of to do it without it looking weird (like placing a tree down then a Generator job swaps the block types out at runtime)

true isle
#

nope no structure files all script

rustic ermine
#

Sweet. That is seriously impressive

true isle
#

but in order to place them in world gen it needs to be saved as a structure or use ontick workaround with the saplings

#

cuz i dont know another way lol

rustic ermine
#

Uhg yeah, I ran into a similar problem with my harvestable blocks refilling their resource if they were in their depleted state when the server shut down

#

I used random tick then check against a global constant Map object. When the harvestable is depleted by a player it gets added to the map, then when it successfully refills it deletes itself from the map. If it ticks and it is not in the map it knows it was abandoned on server restart and instantly refills

#

The first component there

true isle
#

yeah i was thinking about trying to recreate them with using the single block feature or single block structures but that seemed like over kill to me

rustic ermine
#

If your blocks have single state could also just use a local property check on your ticks.

Ontick:
If (!event.block["INITIALIZED"]) { makeTree(event.block.location) } or something. I couldn't do that because somehow it was dropping that property, probably when the state/permutation changed

#

Sorry lol, assuming you already know all that 😛

true isle
#

lmao yeah my saplings only rely on randomticking to grow it doesnt use states or anything like that so its alway constant

rustic ermine
#

Great work though, really happy to see experienced programmers doing addon stuff.

#

Have you profiled onTick? Thought about using it instead of random but wasn't sure if there was an overhead even if they didn't do anything other than a bool check

true isle
#

im not that experienced i just read and do alot of trial and error

rustic ermine
#

That's all experience is lol. Knowing what to read and how to apply it

true isle
#

ive used on tick to try to workaround the world gen issue but it still relys on the player being in the loaded chunk or the chunk itself to be loaded. see if i could created a chunk loader or loaded chunk and turn that on or off to load the trees i could but afaik its not possible with how i need it to work

rustic ermine
#

Yeah if the intention is for it to be a "regular" Minecraft world that has your trees that's the only real solution I can think of. If it's intended to be on a premade world you have more options

true isle
#

yeah thats the downside to using scripted trees is having to do the workaround or structures. i even made an addon specificly for structures lol

rustic ermine
#

There's also just writing some code to generate all variants and save them to structure files on a super flat world or something, then you have all the types to work with that would mesh with the feature files

true isle
#

thats what the plan was. my structure tools addon helps with that part cuz i hate using commands to place anythign

rustic ermine
#

Same. Sounds like you know what you're doing, but feel free to ping if you get stuck on something. Those kind of problems are fun to solve lol

true isle
#

still working on other features for it. its got some fills and directional fills with a preview. worked on copy paste and axis flipping but permutations have been a pain to do

#

specificly stairs are a pain. especially custom ones if theyre used in structures and i try to flip them they dont always behave

rustic ermine
#

Yeah, stairs are by far the worst. It's the only one you can't get away with saying "good enough" lol

true isle
#

yeah...... ive worked on stairs for like 8 months and said good enough cuz it was super close but im still not happy with them

rustic ermine
#

I got so frustrated with orientations on them I just removed the ability to flip them. So can only be placed flat and rotated around the Y

true isle
#

that wasnt my issue it was all the placement checks for shape lol

#

if you really picked thorugh mine you could see where i said "meh works as intended " and kept going with that lmao

rustic ermine
#

Ohhh yeah. You almost need to make a dumbed down wave function collapse to get it right

true isle
#

all checks i did

#

spent like 4 days trying to find a perm that was flipped and just ended up keeping it cuz it worked but it was named wrong in both the script and the blockjson but i couldnt find what i mis typed cuz its just so much

rustic ermine
#

Amazing and terrifying 😂

true isle
#

i wanted to throw my laptop a few times

rustic ermine
#

Lol. If you can describe the exact problem and I have time tonight I can make a small example of weighted generation that would probably fix it if you want

true isle
#

i forgot to do like 2 checks but id have to rewrite all those individual checks to include it and i couldnt bring my self to endure the torture

#

i mean you could try . idk where the permutation is thats flipped cuz its been a while since i worked on it but its a corner permutation

rustic ermine
#

Oh you mean theres just a place that you typed the wrong orientation?

#

Ahh yeah I see above sorry. Still waking up

true isle
#

ill dm it to you i dont wanna keep blowing up api for blocks lmao

rustic ermine
#

All good, would prefer to keep it here because it is somewhat code related. Need to knock out some house cleaning before I get started on my stuff for the night anyway. If you want to make a repo or google drive folder with all of the files that could potentially have the wrong orientation I'll check tonight though and probably just make a quick parser to find it

true isle
#

well shit i didnt see this untill after i dmed lol

rustic ermine
#

All good can just move to dm then

slow walrus
snow knoll
#

Does anyone know why when using playAnimation default animations still play simultaneously, but when using the playanimation command in game the default animations are completely overridden?

I'm playing the same animation in both but only playanimation overrides things like the walking, sprinting, crouching animations, etcetera, and since the playAnimation method is meant to work off/essentially be the same as the playanimation command, this has left be beyond confused

Does anyone know why/has experienced this problem, and could anyone help?

tardy pivot
#

God, wish this can get out of beta soon
Class BlockDestructionParticlesComponent

open urchin
#

it won't

#

it was removed

halcyon phoenix
distant tulip
halcyon phoenix
#

they probably found some exploit on it?

distant tulip
#

yeah

#

seem so

livid elk
#

is it possible to spawn an entity that only a player with specific tag or something can see?

wary edge
livid elk
#

does the entity can attack other players or only the specific person?

wary edge
livid elk
#

ahhh i see, thank you!!

halcyon phoenix
#

do any of you use regolith?

cyan basin
#

ive seen a few talk about using it but what is the actual purpose or advantages to using it?

halcyon phoenix
#

it says that it's kind of an importer

#

like bridge

slow walrus
subtle cove
slow walrus
#

normally property updates are synced to all players, but with that you can send a specific property update to a specific player

halcyon phoenix
halcyon phoenix
slow walrus
#

so if you had say a property size which was an int, you could do

// this player will see a normal size entity
player1.setPropertyOverrideForEntity(
  entity,
  "size",
  1
)

// this player will see a larger size entity
player2.setPropertyOverrideForEntity(
  entity,
  "size",
  5
)
halcyon phoenix
slow walrus
#

yes

stark kestrel
#

Is it possible to change textures of an item using scripts

slow walrus
halcyon phoenix
#

looks like there was a lot feature I missed with it

tardy pivot
dense sun
#

can we cancel target of entities?

distant gulch
#

Someone alredy made a spawner like donut smp addon?

north frigate
#

is it normal for my script api to blow up my phone

round bone
#

but it still should not blow up your phone

fervent topaz
#

anyone know how to use setDynamicProperties

warm mason
fervent topaz
round bone
dusky flicker
subtle cove
dusky flicker
sly valve
subtle cove
#

What neko said

sly valve
#

Do people dont write in it?
Imagine after changing a little detail you gotta export or move the folder again

distant tulip
#

I code in a GitHub workspace folder and have a script compile and copy them over on save if it detect a manifest

wicked girder
#

Is it possible to save a items nametag and lore when its placed?

simple zodiac
#

before place event

lethal bramble
#

I mean when they r in the world

#

they don’t retain data

inland merlin
#

Correct

halcyon phoenix
halcyon phoenix
round bone
#

But for monorepos I prefer custom copying scripts

halcyon phoenix
sly valve
midnight ridge
#

anyone has a video about how to make a player animation using blockbench?

halcyon phoenix
drifting ravenBOT
#
<:blockbench:887506738822131713> Blockbench: Geometry Editor

Blockbench is an all-in-one 3D Editor and Animator for Minecraft, as well as other blocky applications.

Website: https://blockbench.net
Discord Invite: https://discord.gg/blockbench

round bone
sly valve
#

but im kinda lazy...

round bone
sly valve
#

My motivation is -Infinity for doing the Enemy Type Definition system

#

like I got a base class thats abstract

#

and then i can add enemy types like Zombie extends Enemy

halcyon phoenix
#

somebody pinged me...

sly valve
sly valve