#Script API General
1 messages · Page 103 of 1
lol
like a number or what?
yeah a number
either JSON.stringify(3) or `${3}` or "" + 3 work there is a lot of ways
thx
np
normally you have toString method
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
Hey guys, is there a way to know the max permutation of a block?
for example if the max is 2?
- Get the permutation:
block.permutation - Get all the block state names
Object.keys(permutation.getAllStates()) - Iterate each key and get the state type inside BlockStates Class:
BlockStates.get(blockStateName) - Retreive the quantity of the valid enums/ranges:
blockStateType.validValues.length; - Accumulate each quantity and you'll get how many enums/range permutation that the block has.
Edit: 🗿 I over complicated it didn't I?
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
No no, your first method worked liked a charm
Thanks!
(3).toString()
too many ways
`${3}`
Ugh.. wait
Yepp, we got many ways
Like
const str = "23";
const num = +str;
Number, parseFloat, parseInt
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
Use that ⬆️
But actually just use
String(num)
We should benchmark all of those
We should
there is a function to spawn a entity?
yes
Documentation for @minecraft/server
JSON.stringify is slower
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
Yup, it's for a bit more complex cases
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
nice
Have u tested that?
-# nope
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
man I wish block.getState() and block.getAllStates() was asynchronous
wait what so I can await them?
Wdym, it's just small difference so it's not promise type
Well u can still await anything
but why
because sometimes they give me undefined when I get them in a system.runJob();
block.permutation.getState?
Only returns undefined, when state is not "on it"
getAllStates alaways returns an record
see
getAllStates(): Record<string, boolean | number | string>
¯_(ツ)_/¯
(await UserManager.fetch("NEKODE"))
.attack(await UserManager.fetch("Leonidaaa"));
I think I should make a new forum post about my problem
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
Is it possible to have variant custom components that's inside permutation
😭
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.
about earlier, i asked gpt to write some benchmark code
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');
custom components is like id where that id can have features that's registered in block initialization
Ahh, nice.
everything was gpt who provided, i didnt even try to optimize the code
It's pretty dumb but uh.. I initially thought they were the "backend" of custom items/blocks but that "component" part just kept me wondering. Anyway thanks for the clarification, ima go sleep now, good luck to you sir.
would it be a good idea for me to create a topic on script-resources only to show benchmarks?
Yes, please do that
You can show Critical methods (with high "delay")
.
i'd do so only for benchmarking quickjs, but i think people could contribute
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).
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
I use WebStorm for scripting and other tasks, for JSON-related stuff I use VS Code
W H Y
WebStorm is really good for writing softwares like add-ons in TypeScript
Reason
also I have it for free
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
- better Intellisense
- built-in frameworks to test code
- GUI for VSC
- refactoring tools
a lot of things tbh
Thats cool
babe
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?
Probably. you can also use minecraft:angry = Defines an entity's 'angry' state using a timer
reading json when?
i think you should write a copy of minecraft from scratch
maybe never.
so i can turn on/off gravity easily
for Entities?
yuh
meh, I've done similar, but working with the bedrock engine and established player-base is a lot easier than making a game from the ground up and marketing
i mean for Script API
You mean - "When can I turn on/off dynamically if a Entity has physics or not" ?
;-; I don't understand what you want, must bemy lack in understanding
simply that you cannot change the physic component of entities using Script yet
And this will probably never be possible
At least I think so
Because minecraft's code isnt just simply like
if (entity.get("physic").isTurnedOn) {
doPhysicsStuff(entity)
}
there is a work around using entity event but it's not as efficient if we use script
hmm okay then script would be better
But why do you event want to change the physics meanwhile the runtime?
"minecraft:input_air_controlled" need the entity doesn't have gravity to work
and I want the entity have gravity if player not ride it
can component value read entity property using q.property()?
hmm. well im not well known with Entities
But I think you should be able to read properties from the entity
Maybe you'll find anything here https://learn.microsoft.com/en-us/minecraft/creator/reference/content/entityreference/?view=minecraft-bedrock-stable
very few components like the minecraft:experience_reward can, but majority of them can't
whats the event for right clicking npcs? (not entityhitentity)
playerInteractWithEntity probably
what is the stable version of @minecraft/server-ui?
yes
2.0.0
no
kk
nope, 2.1.0 is beta
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?
and what about minecraft server?
no
2.1.0 or 2.2.0-beta
ty guys
sadge
to use server-ui v2 you have to also be using server v2
but how to do that if it is not avaible 🙂
i tried it
idk why 2.0.0 is missing from there
use 2.0.0 for server and server-ui
it says invalide
it says you used 2.1.0, not 2.0.0
how to cancel the attack in entityHitEntity?
You cant.
You have to edit the entity JSON
ohh yeah, why i didnt think about that. thank you!!
is there a way to refresh form without calling/opening the form again?
does any1 have exact vanilla player hit by player knockback replica?
holy im suffering
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
tysm
Learning about classes
i never used classes in javascript
'-' how?
do you program things like in C?
const obj ={...};
function doSomething(o){...}
doSomething(obj);
?
yes 🤷♂️
Its not the class, its your cide
If your update runs every tick y you gotta optimize it
Send me the Update code private, and I will help yiu
optimize your cide
They told me that classes reduce lag
Depends on what you do
But its a lie
Sometimes Functions or Literal objects are better
Sometimes classes
classes just make code more organised
or can make
it always depends on who is writing the code
Inheritance, polymorphism
How are you
it is not that bad
good hbu?
Love classes for the inheritance and polymorphism
Thats awesome
But dude, is the script still unperfomant?
Want me to optimize it a bit?
Shore
haha dont worry, you are Spanish right?
I'm a brasilian girl
Ahh thats cool
Thanks, also, with this I will be able to replicate it in other codes of mine that need optimization
Alright, Ill send in DDM
:o what the-
play animation plays only one animation?
Yeah
there is any way to play more animations at same time?
Try to use setProperty or something for more complex animations
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
Like entity.setPropery('aaaa:dance', true);
I always try to do this, but it still ends up happening
how to use it with the animations?
In resource packs, wait
queries?
Yeah
But you need to create the property in the entity behavior
theres another way?
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
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
I want to do this without modifying the player.json or player animations
ok, ty
You merge those two animations together.
one uses molang and the other smooth animation
whats TS
typescript
Brute force it with tons of linear keyframes.
-# (My "caveman method")
never heard of it
damn
What's TypeScript?
is it some kinda of script that you type? "type script"
Better version of JavaScript
lol
so JavaScript++?
I think it's a type of script
its javascript premium
Superset, not a second JavaScript
sound interesting
That's subjective. I call it strict JavaScript that requires a compiler for it to work
here we go
It's better to maintain your code for a longer time
Yes, that works for you. But for me, on a phone with no slimmer of JSDoc or TypeScript compiler or any trace of effort to set it up. Plain JavaScript is perfect as it is.
-# (Plus I can brag about it out)
lol
im lazy to set it up aswell
I think we are so much different
True. But the essence is still the same... It's still ScriptAPI.
Once you'll start working with larger codebase, we could have a talk then
Sure.
Hello gega
Hello Rosmon. It's 2:34 AM in the morning for me.
Sleep is overrated.
Be like Kal, she doesn't even knows what sleep is
Still bad for your health. (She said)
Unless you're at zero sanity. (Doctor said)
Patting Romsontis gains +6969 Sanity
it depends, it actually makes code slower than using "pure functions"
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
Classes may be superior when using Inheritance or Polymorphism
inheritance is dynamic dispatch
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)
Yeah so I don't wanna be that guy
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)
But classes are great for keeping code organized and providing a stable public API for later you and other developers working on the project.
but the performance you gain by using functions is not that much
They have a little bit of an overhead compared to normal functions but it's very marginal.
It's unnoticeable almost always.
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
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.
by the way, composition might be better for performance
and is better than inheritance
when you have a long chain of classes that inherit, things can get confuse
composition?
Composition over inheritance (or composite reuse principle) in object-oriented programming (OOP) is the principle that classes should favor polymorphic behavior and code reuse by their composition (by containing instances of other classes that implement the desired functionality) over inheritance from a base or parent class. Ideally all reuse ca...
Distro name?
yeah ik, i got problems with version 1.21.30 and later ones, so i rely on 1.21.23
i think its hardware limitation
i actually got the most actual installed
Hardware?
by the way, you know what i have to write on the stream of the debugger to fully initialize it?
Script debugger?
yeah, the debugger on vscode
I haven't used it yet
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
Can you maybe just read packets (without any manipulation of them) and try sending the same then?
I would scrap out everything and try with this data
i just connect it at the port
I am not really into Rust xD
creates a listener on port 19144, and keeps reading the content that is sent
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
It's midnight for me, I am awake for 18 hours from now
12:21 PM for me
i actually wanted making some kind of api for interacting with the debugger
then i might make a tui application to read it
I am working on a simple idle map
graphs and etc, maybe i make it for the web as well, an application you open and it shows the specs on the web
Neat idea
Maybe
do i have to add interact component to the entity json?
wdym?
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
Probably yes
alr working i just need to use beforeEvent thanks tho
guys
guys
I need a better initial as ATKSPD
nvm chat were to slow, Anime server responded faster
what a shame
what's the new initial
ASPD
"Attack Interval" :3
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())
Too long my dear gega
this will return your initial
....
please dont...
🚙
anyone I can dm about scripting?
iirc it's a uuid so yeah
whatchu need?
which version?
are you talking about a commission or just a help?
there's no information about that in documentation
Just some help and general conversation
if you have any problems, sending it here or creating a post might help you a bit faster I think
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
I remebered I asked somebody and that's what they said I forgot who though
I don't think it's always 11 characters long
yeah probably
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
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
What a good way to do UI, should I script it or JSON it?
depends on your needs tbh
what type of UI, does it have to look fancy
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
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
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
thanks!
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.
weird how?
like it feels i get stuck in air for few ms or so
try lowering vertical strength to something like 0.02
other than that, not sure. knockback is weird and I hate dealing with it
😭
thanks!
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);
}
})
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
Bridge is the easiest way IMO. it has TS natively
like is it even possible or u just make it for prevent errors before converting it js?
yeah but can it be implemented in beh?
that is all TS actually is. you write your code in TS, then it transpiles your code to javascript. nothing actually executes typescript code
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
so typescript is just to prevent syntax and type errors when you transpile it
got it
thx
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
can't i just set a script in a TS file and then just do import './example.ts'?
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
Use interfaces, they're a bit faster
how so?
easy change if true atleast. I've only been doing TS for 3-4 weeks so open to improvement
Replace type keyword with interface and remove =
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 🙂
Not QJS, it's due to TSC
Use const enums
Compiler will in-line these values
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
No problem, this server is for learning
It's my favorite for last year xD
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
The only missing thing is built-in final keyword for classes, but still it's pretty solid
yeah. at least that's an easy problem to avoid if you are the only dev on your project though
You can use a decorator to create a final class
not enforced though I'm guessing?
I use it sometimes and it's pretty solid aswell
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
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
Can't you set a rotation of projectile?
elaborate
i was curious abt the thing that makes that multiple projectiles can't be spawned at the same time and i learned that it is due to the limitation of js being a single-threaded language 😭
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
No that json ui
You have to do it in script xD
In textures *
oh are you answering to someone else's question?
Dude, that is obviously script api and is obviously to you
my bad, I don't really know scripts that well or at all T-T
I am not at my laptop, so I can't really show you an example
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?
No, that have hard coded values.
It will always shoot to the same direction
TOT
Send this and that code to chatgpt
(Ignore the haters)
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
server projectile doesn't exist
figured since it's ai
it depends on the transpiler, swc transpiles it down directly to their variant
same as bun
prefer choosing a transpiler focused on performance, tsc might not be the best one for this case
TSC is okay, just some things require a bit deeper knowledge
Also you're supporting Micro$oft if you stay with their tooling
and is there a way to avoid those objects on tsc?
js sucks in every kind of thing you can imagine
the std of it is literally shit
Use const enums
didnt know about it
It does not suck in being shit
good to know
you got a point
How TypeScript enums work
Does anyone know if I can translate text in the description of custom commands?
I don't think that's possible
😭
Awww man I've been changing all my commands to translate them, and now I see that it doesn't work lol
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
Use F2 in VS Code to replace it all back
yeah i tried already, wont work
thx
spawn the projectile, get the player view direction, rotate it by N rad in Y axis, apply it as the impulse of the projectile
Quaternions are really helpful for this
i prefer them over matrices
o.O
what does setItemData do?
On phone so can't format, but ..
private _itemData: Map<ItemID, ItemConfig>
public setItemData(config: ItemConfig) {
this._itemData.set(config.itemId, config)
}
Lol
nah AI is good sometimes
specially only for math help
sometimes = almost never?
normally it tends to destroy my code because AI is just good for copy pasting stackoverflow and github
is there a way to get a loot table of a block
world.getLootTableManager().generateLootFromBlock(block);
but it only works on beta-API on the latest previews
oh
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
dang that's too advance for me I gotta learn more complicated syntax
I still have no idea how to use public, private and this stuff
public value: T;
anything outside the class can acess
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
@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() } }
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
}
use private keyword
uhm, es2020 does this
can you show me your tsconfig?
if you're using # in method's name with keyword, it throws an error
{
"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"]
}```
simply remove # from method name
probably due to the lack of support on es2020
i know before it, the normal was using a WeakMap
-# #makeyourcodeslower
nvm, esnext can make it
altho the exports and other stuff might be different, sheesh
i hate syntax for private members in JS
i just use private mark in TS only as keyword
oh I see
mightve to try more useless stuff ;-;
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}`;
}
That's some insane typings I have ever seen...
Happens when you go low-level JS in TS
theres a binary serializer on npm already
i think you should use it
just more of the usual,a buffer and data view manipulation
im startin to have a fetish withObject.create(null)
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
same I can't even understand your code 
Its all right me and AI has it the same haha
con's OverTakes is way too op
bytheway, document the functions, it should be easier to understand
its all right
im addicted to document everything
thats what i am addicted to
I am mean i am writing code for 6 hours without even single test
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
yea, reasonable
i also write code at once then test at last
well good luck guys with your projects, see you later
i just think youre making things too complex on the serializer
depends in what state is the project in, at the beginning it make sense but later on not at all
it would be better to simply define a list of primitives
like a normal compiled lang does
con, do you have a itemstack database
thats what i do
wait, what are those functions for, then?
Proof of concept but
and NBT
if you parse NBT you have to save number type as well if you want to serialize it back
PascalCase ;-;
yea i use them for decorators
so you know its decorator and not regular function
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
Bruh its world.sendMessage() stop with AI man sendText aghh
isnt that the standard for classes, structs and decorators?
I said I've been tampering with it and used ai, I'm still newer I figured it knew it was wrong, I couldn't recall the thing for it
other than delete obj.property anyone knows other ways or it's the only one?
damn, id make things simpler, a simple enum and asserting everything is little endian
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
i think there are methods on Reflect and Object to do so
PascalCase does look good for decorators, and long names, I just acidentaly said it
yea Reflect has one
but it has same behavior as that same keyword
i would go for it as its more explicit
Is there a site that would have the list of the functions and what not?
i love how dbs for people here are(in general) simply hashmaps
i mean i am part of the C# community as well where is PascalCase almost every where so pretty valid qestion also on my image there are only one identifier thats in camelCase so i understand
like damn, hashmap is more like a "caching system"
yea
DB is really out of context, but that term is used here a lot in sense of Dynamic Properties wrappers
afaik decorators are camelCase in most cases, but i choose Pascal for them
there is the documentation
Where could I find that?
i really wanted implementing a database for minecraft, it would be an interesting projecg
not sure if that woukld have a use, but it might be fun of implementing, anyway i am waiting for Uint8Array support for dp
well depends on lang i see
dp?
dynamic properties
oh
i would use strings for so, the problem would be null bytes
that is understood as string finalization
yea
i have no idea why strings in js are like this
its not bc of JS
i thought they were length based
its bc C++ old strings from C days
yeah ik about C
JS just passes the string with the null byte without problem, once it gets native side then its unpredictable
didnt think of that
bytheway, is there something about wasm that the engine might adopt?
well until they switch to v8 i think there is no reason to talk about wasm
really? i thought quickjs had support for wasm
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
by the way, where did you find that information?
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
thats cool, i got no idea on how to write some
same, seeya
I hate myself for understanding this
😭
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
depends, i use it for class' cache purposes
example?
||vines|| just boolean for this one
for using private/protected keywords of encapsulation?
2023 stuff
How to check the lore of an item?
Thanks.
by the way, as you are making a binary serializer, i made a lib that transfer data between addons, such as mcbe ipc, the thing is, i want adding binary support to it. by default it is sending json, how could i serialize the data in a way that i avoid the null bytes
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
just shift it all by 1
0 is 1, 1 is 2
and so on
yeah but what if i get a 0xff
0xff is not valid UTF-8 char anyway
i dont want making it human readable
its a binary serializer just like yours, to transfer data
literally getting the bytes of a struct
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
hell no, it will increase the size of the content
secured IPC?
idk
i just made it
and now i want to add binary transfer
damn working with uint8arrays would be way easier than strings
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
p
isnt null strngifyable...
they aren't talking about JSON null
we are talking about string representation, JSON is inefficient format to store data in
you can use charCodeAt and fromCharCodes
to build string from byte array like
Ohkey
we are talking about null byte which is simply 0
well, i found base32768(im already on a rabbit hole)
i think it might be some good solution
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
how can i get a value of a entity query using script api
What query?
You cant read molang queries via scripting. Youll have to find an alternative if such exists.
oh okay i just wanna debug because when eating an item with an attahable it doesnt animate, thanks tho
q.is_eating is for the snacking behaviour, not players using food
Hello, does anyone have a solution to block access to a chest with the API, especially against cheats?
make it works like a RP (wont turn off ur achievements)
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
beforeEvents.playerInteractWithEntity (custom entitiy blocks) or beforeEvents.playerInteractWithBlock
const tags = player.getTags(); // Get all tags as array
const rankTag = tags.find(tag => tag.startsWith("rank:")); // Find tag starting with "rank:"
const rank = rankTag ? rankTag.split(":")[1] : "member"; // Extract rank or use "member"
.body(`Welcome ${playerName}, your rank is: ${rank}`)```
? 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
Hmm, not sure about it being forced open, but might be worth tryn to place an entity around it?
Prevent interactions?
hmm
that would work, but other players wont be able to interact too,
So the normal before event doesnt stop the interaction?
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
You say cheats bypass it?
try making some custom chests ig
like its not that hard, and u can control if u can open the inventory or not
I wanted to keep the basic chests 😭😭
thats just an option,
Thank you
bedrock limitations:
gl looking for a solution ig
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.
Endstone might be worth a look
Has a way to stop packets of course
But stays wrapped around bds
I'll think about it, if you have any ideas for safes, send me a PM
hmmm since form.show() returns a promise i can await it without problems right?...
Yup!
i said that 3 seconds ago
how can i kill an item after 30 seconds that it touches the ground
U wake up at 23:11?
Yep, my life is terrible atm
how would I compress my chat ranks, floating text, floating leaderboars and chat nicknames all into 1 function / event?
If you want to talk about it just dm me
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
Ill keep that in mind, thanks
Np
Okay thx
If you need help, feel free to dm me
-# but right now im busy, watching Uma Musume
Ill keep that in mind, thanks
Dw lol
Does it allow usage of script api inside it?
Or we have to use their api in python
i must start loving mine again
Do you know of a way to transfer scoreboards from one world to another? Like on a network between maps?
and its damn simple, pushups
you don't
Probably need to convert the scripts to python
its not possible ?
You better should do it.
If you need someone to talk with, feel free to dm em
Ah then I'll just stick to the script api, unless my server core needs a re-code 😂 thanks!
Not really. but you can output the data of the scoreboard, copy it throught the console and input it in your other world again
Or
You fetch all scoreboard with python from world A, and edit world's B scoreboard data
idk if this is possible
Its really not that hard and worth it
Basically wrapped around it uses simialr setup
Could even do c++ if you hate ur life
I would love to learn c++ right now
Start a endstone bds server you can make c++ plugins for it
Fun cause its still minecraft
Uh?
Oh nah I don't know c++ I just know python and js
Can do either, python or c++
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
Worth it because more events that is not in vanilla scriot api
Like beforeEvents
Cancel damage
beforeEvents.entityHitEntity
I made my own yesterday
xD
Knockback was the main issue tbh
Oo
I think the main issue is, even if you cancel the damage, he still can die
What??
pushups are the solution to my problems
as simple as a bunch of pushups
How is that?

Lol
beforeEvents.entityHitEntity, did you used afterEvents for that?
Are we talking bout the same thing
uh yeah
Let me show my test code for the pvp
based on what i know, its not
For normal script api they can only cancel through the player.json properly
So if you apply too much damage to an entity, he will die and you cannot recover his hp
If its one hit
Ah
Yes, thats the only problem
Things work differently in my server that shouldn't be a big issue for me
And what about armor, armor still takes damage
Can do stuff for that
I was dying cuz man my custom enchants can't work without it
There's insane logic in it
Lol
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
I see
Well, would be cool if one of these previews they add beforeEvent cancel
Lol I feel you
😭
Agree
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 🥲
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?
I test with single player usually because the iteration time while using dedicated server with a DB server is annoying
I think 11 choices is plenty of variance if you're able to choose the wood and leaf type. In past games I've done, we'd have anywhere from 3 to 15 variants for terrain props (rocks, trees, cliff pieces, etc) although might need to be on the higher end of that with Minecraft because we can't really rotate or scale
rotate or scale? mine do lol
Nice. 11 should be plenty then
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
Any screenshots? Sounds really interesting actually. World creation tools always fascinate me lol, especially if any kind of procedural gen is used
That's awesome, nice work
The fourth pink one looks a little flat at the top. Not sure how to explain what I mean
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
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)
nope no structure files all script
Sweet. That is seriously impressive
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
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
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
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 😛
lmao yeah my saplings only rely on randomticking to grow it doesnt use states or anything like that so its alway constant
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
im not that experienced i just read and do alot of trial and error
That's all experience is lol. Knowing what to read and how to apply it
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
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
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
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
thats what the plan was. my structure tools addon helps with that part cuz i hate using commands to place anythign
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
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
Yeah, stairs are by far the worst. It's the only one you can't get away with saying "good enough" lol
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
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
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
Ohhh yeah. You almost need to make a dumbed down wave function collapse to get it right
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
Amazing and terrifying 😂
i wanted to throw my laptop a few times
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
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
Oh you mean theres just a place that you typed the wrong orientation?
Ahh yeah I see above sorry. Still waking up
ill dm it to you i dont wanna keep blowing up api for blocks lmao
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
well shit i didnt see this untill after i dmed lol
All good can just move to dm then
yes, it's BDS based so anything you can do in vanilla BDS you can do with Endstone
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?
God, wish this can get out of beta soon
Class BlockDestructionParticlesComponent
why?
is it possible to spawn an entity that only a player with specific tag or something can see?
Use setOverrideProperty to have player specific rendering.
does the entity can attack other players or only the specific person?
Youll need to set up the entity to attack specific tags.
Thanks!
ahhh i see, thank you!!
do any of you use regolith?
ive seen a few talk about using it but what is the actual purpose or advantages to using it?
I have no idea too
it says that it's kind of an importer
like bridge
is this what you meant?
Documentation for @minecraft/server
I'm curious on how it works
it probably just sends an actor data packet with the property override
it compiles the addon ur working on to the minecraft folders so no need to import mcpack/mcaddons
normally property updates are synced to all players, but with that you can send a specific property update to a specific player
I see, I already made one with java so too late I guess, I should've know this earlier. but hey at least I learned java
oh so basically if you have an invisible entity, and then you use this method to override a property for the player that will make it visible then it will be visible only for the player?
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
)
yep
iirc property are custom variables for entities right?
yes
Is it possible to change textures of an item using scripts
yep thanks
looks like there was a lot feature I missed with it
damn, back to setblock destroy
can we cancel target of entities?
Someone alredy made a spawner like donut smp addon?
is it normal for my script api to blow up my phone
depends on performance of your phone
but it still should not blow up your phone
anyone know how to use setDynamicProperties
world.setDynamicProperties({
id: 'value',
id2: 123
});
yooo thats cool
It's even better if you're preparing it with queues
wait, dont you guys modify the addon inside com.Mojang folder?
Depends on what we doin, either addon, testing, or sth else
wait, how do you write it so?
I do ot always in the com.mojang/behavior_dev thingy
What neko said
Do people dont write in it?
Imagine after changing a little detail you gotta export or move the folder again
I code in a GitHub workspace folder and have a script compile and copy them over on save if it detect a manifest
Is it possible to save a items nametag and lore when its placed?
before place event
Blocks dont have the same data as items I believe
I mean when they r in the world
they don’t retain data
Correct
LOL LMAO
you mean item to blocks?
I code directly in it sometimes
But for monorepos I prefer custom copying scripts
if that's what you mean yes it could be posible
Would you like to help me coding a "system"
anyone has a video about how to make a player animation using blockbench?
isn't there a lot of resources for blockbench? and also go to blockbench discord for this
A quick tour of all the animation features of Blockbench.
If the tutorial is too fast, you can slow it by going to Settings, Playback Speed.
Download Blockbench: https://www.blockbench.net/downloads
Snowstorm Particle Editor: https://snowstorm.app/
MoLang Grapher: https://jannisx11.github.io/molang-grapher/
MoLang Guide: https://bedrock.dev/d...
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
What do you mean by a system?
I gotta do a whole Enemy system for my Tower Defense.
Including:
- Enemy Type Definiton
- Enemy Instances -> literal objects
- Enemy Movement system
- Enemy death system
but im kinda lazy...
You can create your own event listeners
The event listeners are not a problem
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
somebody pinged me...
I saw him but forgot his name
Must have been the guy you sent the video to, since he sent a imagine with the similar character
what does it mean
