#Script API General
1 messages · Page 70 of 1
its the classic velocity fuckery
you can try wrapping it with runTimeout or run
and hope that it gives you a good result
alr
wait, will it be changed? like updated or something?
in 2.0.0, its been changed to
Entity.applyKnockback(Vector2, verticalStrength)```
so they have removed the horizontal strength thing from it, kinda
for example, this will change to
entity.applyKnockback({ x:0 * 0.16, z: -0.03 * 0.16 }, 0);
rn it's just (Vector2, verticalStrength, diagonalStrengthSomething)
gotcha
stable applyKnockback takes first two as direction and third one as strength
good thing they have updated it before i make my exe addon massive
yeah its better to use too
btw,
should i make my death certificate item show u the death location?
or it would be a bit too OP
whats the death certificate item
this,
showing ur death information, like who killed u and which time u have died at,
just that?
kinda
then yeah, dont add the location
i was trying to add it yesterday,
it returns [object] [OBJECT] thing
or it shows the atoms of the location, ( x: 402.17362815286481618, y: 63, z: 1174.15181653718175168 )
it might be bugged when u die on the void, so I'll just dont add it.
that one is because youre trying to convert an object into string
but it would be nice to see how to fix this issue,
math.floor(x*10) / 10
would return something like 402.1
or .toFixed(0) works too
it shits itself sometimes though but its an issue with programming in general
mhm
I'll try to add multiple different variants of this item,
Hey guys, I have this script:
import { BiomeTypes, system, world } from "@minecraft/server";
import { Vector3Utils } from "@minecraft/math";
import { biomeTranslations } from "./biome_translations.js";
/**
* Lấy tiêu đề của biome theo ngôn ngữ
*/
function getBiomeTitle(biome, lang) {
return biomeTranslations[lang]?.[biome] || biomeTranslations["en_US"]?.[biome] || biome;
}
/**
* Lấy tiêu đề của chiều không gian
*/
function getDimensionTitle(dimension) {
const dimensionTitles = {
"minecraft:overworld": "Overworld",
"minecraft:nether": "§4The Nether",
"minecraft:the_end": "§9The End"
};
return dimensionTitles[dimension] || dimension;
}
/**
* Lấy biome tại vị trí cụ thể trong chiều không gian
*/
function getBiome(location, dimension) {
const biomeTypes = BiomeTypes.getAll();
const searchOptions = { boundingSize: { x: 64, y: 64, z: 64 } };
let closestBiome;
for (const biome of biomeTypes) {
const biomeLocation = dimension.findClosestBiome(location, biome, searchOptions);
if (biomeLocation) {
const distance = Vector3Utils.distance(biomeLocation, location);
if (!closestBiome || distance < closestBiome.distance) {
closestBiome = { biome, distance };
}
}
}
if (!closestBiome) {
throw new Error(`Could not find any biome within given location`);
}
return closestBiome.biome;
}
// Cập nhật tiêu đề biome và chiều không gian cho người chơi
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
let location = player.location;
let dimension = player.dimension;
let biome = getBiome(location, dimension);
let lang = player.getDynamicProperty("language") || "en_US";
let biomeTitle = getBiomeTitle(biome.id, lang);
let dimensionTitle = getDimensionTitle(dimension.id);
let finalTitle = `${dimensionTitle} - ${biomeTitle}`;
player.onScreenDisplay.setTitle(finalTitle);
}
}, 60);
Along with the text in the logs:
14:37:12[Scripting][verbose]-Plugin Discovered [Traveler's Titles Bedrock] PackId [b1c22a08-3e7d-4a6e-b52b-123456789abc_1.0.0] ModuleId [d2a33b14-6c8f-4d93-8a47-987654321def]
14:37:12[Scripting][error]-Plugin [Traveler's Titles Bedrock - 1.0.0] - failed to create context.
14:37:12[Scripting][error]-Plugin [Traveler's Titles Bedrock] - module [Traveler's Titles Bedrock - 1.0.0] depends on unknown module [@minecraft/math - 1.0.0].
14:37:12[Scripting][error]-Plugin [Traveler's Titles Bedrock] - version conflict for module [@minecraft/server].
[1.18.0] requested by [Traveler's Titles Bedrock - 1.0.0],
[2.0.0-beta] requested by [Traveler's Titles Bedrock - 1.0.0]
14:37:12[Scripting][error]-Plugin [Traveler's Titles Bedrock - 1.0.0] - run failed, no runtime or context available.
@minecraft/math module requires a separate install
But I'm on an Android phone so I don't have a Windows computer to use Visual Studio Codes
then you can download a standalone version here
https://jaylydev.github.io/scriptapi-docs/meta/cdn-links.html
How will I use it?
you can import that file instead of module
So can I create a directory to contain those JavaScript module files or not?
uhhh its your choice honestly
just make sure its inside scripts folder
meanwhile Math.floor(): 
irs different than Math.floor()
Uhh what?
vn
unbreakable vanilla items?
uh,
let deathCounter = entity?.getDynamicProperty('deathCounter');
entity?.setDynamicProperty('deathCounter', deathCounter+1);
isn't working
make sure the dynamic property returns a number
let deathCounter = entity?.getDynamicProperty('deathCounter') ?? 0;?
try doing console.log(ntity?.getDynamicProperty('deathCounter')) to check
or that
u can do that
alright it works now
idk why people use Math.floor() for turning float into integer
but Math.round() is better to me
bruh you make that complicated
lmao
That entirely depends on use case.
how so? is there an easier way or something?
-# or d u prefer if else
Like 10:59 is still 10 not 11
let counter;
world.afterEvents.entityDie((e) => {
if (e.deadEntity instanceof Player) {
counter++
}
})```
@untold magnet
ig
but youre supposed to store it in dp
nah, that counter will increase if any player dies
so i can apply it to the item lore
also that too
hmm idk
yeah right then
i mean, u can learn from my codes if u want to, bec i have written docs in the codes

just explaining why im using the cases, ig
kk
like so:
world.afterEvents.entityDie.subscribe(({deadEntity: entity, damageSource: source}) => {
if (entity?.typeId !== 'minecraft:player') return;// Detects only players after they die.
let deathCounter = entity?.getDynamicProperty('deathCounter') ?? 0;// Used to increase the death counter values.
entity?.setDynamicProperty('deathTrigger', true);// Needed to spawn the Death-Certificate item.
entity?.setDynamicProperty('entityName', entity?.nameTag);// Getting the dead player name.
entity?.setDynamicProperty('sourceId', source?.damagingEntity?.typeId);// Getting the killer ID.
entity?.setDynamicProperty('cause', source?.cause);// Getting the damage type.
entity?.setDynamicProperty('dim', entity?.dimension?.id);// Getting the dimension id.
entity?.setDynamicProperty('deathCounter', deathCounter+1);// Will increase the death counter by 1.
entity?.setDynamicProperty('rDate', date.toLocaleString());// Getting the Death Date.
});;```
alright alright
why save the player's name in a dynamic property
to apply it to the death certificate lore
why not just do player.nameTag when you place the lore, you don't need to waste a few bytes just to save nameTag
meh, doesn't really worth it
That's actually an interesting question. If an entity is invalid, does Entity.getDynamicProperty throw?
If so, then there's no advantage (or disadvantage) to using a property, other than the space as Cennac says
I would be tempted to use a world dynamic property for that instead. Store it in a Map that's saved to disk on world close, based on the player's ID (which is always valid until they disconnect)
it should say failed to get dynamic property of undefined
I think
but since the dynamic property in his code is set to a player, that shouldn't be an issue?
Not undefined—just in the case of isValid == false
That's neat ... but also in Java Edition?
it's java
Whats...the purpose of posting that here?
update on saving areas of blocks
I got an idea to get an express.js app running pulling mcstructure files that are saved by the api but turns out you can't save to .mcstructure with scripts
useless
- This is a "bedrock addons" server
- maybe #off-topic would suit you
- This is the Script API discussion channel
so like uhh anyone has any ideas on how to save a region of blocks
A roundabout way I developed in the past was to read the world's level database for the structure
do you have it somewhere
cuz I spent the past 2 weeks trying to figure something out
🤯🤯
I do, but I'm not sure if it will be useful to you. It's in the form of a Godot project, and also, It's been so long since I worked on it, I can't even build it properly again.
Godot project what
Yep. I made an app with a game engine
uhh is there any info anywhere on how to read the world database file(s)?
It's kinda tricky. The only way to read it is with a C++ leveldb library. Any libraries you see in other languages use this library internally
Google leveldb?
Yeah. Although I think Mojang has their own fork of it as well
hmm so I could try using something like this
I am totally cooked
It's fine. It's open source https://github.com/Mojang/leveldb
LevelDB is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values. - Mojang/leveldb
Good morning @quaint birch (or good afternoon). I was wondering if there's a target date for when scripting v2 will release. I'm asking because I'm thinking of releasing WorldEdit 1.0 at the same as that becomes stable.
Is there a way to run scripts client side?
This was really upsetting. It's inconsistent with entityHurt—and the JSDoc comments don't signify this
Certainly not a derp on the OP's end
is there a version of this script that works in 2.0.0-beta, I can not fix it
how custom componentes changed in 2.0.0-beta
Registered in startup.
that's what i changed but is still showing me this
Startup is a system thing not world.
Hey! I am not understanding what is up with this single_block_feature.
The block that is placed has a custom_component.
I am trying to simply spawn a structure onTick. But when I place the block via feature_rules, the onTick is not seeming to work!
But the onPlayerInteract works??
Here is my component logic
onPlayerInteract, logs
but onTick does not
If anyone has any idea id appreciate it!
The block is connected to the custom_component properly. Just curious why the onPlayerInteract is working, but onTick is not. I figured it may be a feature restriction. But i thought i remembered it working before
does anyone know the name for redstone ore glow id, need this for minecraft:can_destroy
Does placing it normally in the world work?
yup! instantly recognizes the onTick, and places a randomstructure
some of the single_block_features seem to work... but not all of them.
im using try/catch
and not seeing any error logs either
Unfortunate, it very might well be the feature.
Interesting.... It's weird that im seeing it work on some blocks though. So i figured i could catch the error, and just try the tick again. But i dont even get the initial tick. Hmm any idea? If i am trying to place a structure via custom_components.
(I am doing this to avoid the cutoff of some structs. without using jigsaw)
I already explained this to you before why this wouldn't work.
I'm so bored, what should I make
I made something weird.
world.afterEvents.entityDie.subscribe(({ deadEntity, damageSource: { damagingEntity, cause } }) => {
if (deadEntity.typeId !== 'minecraft:player') return;
Object.entries({
deathTrigger: true,
entityName: deadEntity.nameTag,
sourceId: damagingEntity?.typeId,
cause,
dim: deadEntity.dimension.id,
deathCounter: (deadEntity.getDynamicProperty('deathCounter') ?? 0) + 1,
rDate: new Date().toLocaleString()
}).forEach(([k, v]) => deadEntity.setDynamicProperty(k, v));
});```
what is even that
seems like a chatgpt thing lol
Ok that hurts me, second it's an object entries.
I guess, you never saw how I code before that's why.
yup, exactly.
So anyways. Just like array instead of just one string, you can get the name and get the values, that's what I did above instead of calling multiples dynamic propertyjs for (const [k, v] of Object.entries({ '<name>': '<value>' })) { console.error(k, v); }
It's in the variable, k = key and v = value.
Object.entries({ '<name>': '<value>' }).forEach(([k, v]) => {
console.error(k, v);
});```
the variable can be any name btw.
const obj = { name: 'Coddy', age: 30 };
for (const [k, v] of Object.entries(obj)) {
console.error(k, v); // "Coddy", "30"
}
Object.entries(obj).forEach(([k, v]) => {
console.error(k, v); // output is the same.
});```
ohh yeah, expect me doing some destructing in some codes lol
my brain isn't braining here
const obj = { name: 'Coddy', age: 30, tall: '5'59.3' };
for (const [k, v] of Object.entries(obj)) {
console.error(k, v); // "Coddy", "30"
}
Object.entries(obj).forEach(([k, v]) => {
console.error(k, v); // output is the same.
});```
adjusted
and I just remembered that there's setDynamicProperties({ '<name>', <value>, '<name>': <value> })
you can set multiple dynamic property without calling individual for then.
and you think it's funny? So you like making fun of short people
i cannot understand how it works for now, but for later i would, ig
isn't that ur actual tall?
adjusted
Nah, this ain't valid. '5'59.3'
use double quotes since you used the single quotes. "5'59.3"
you don't need to really understand it since it's very simple unless you're really that slow.
What I did here isn't really big difference to your original one. Just smaller and easier to edit.
Isn't there a method called setDynamicProperties?
entity.setDynamicProperties({
deathTrigger: true,
entityName: entity?.nameTag,
sourceId: source?.damagingEntity?.typeId,
cause: source?.cause,
dim: entity?.dimension?.id,
deathCounter: deathCounter+1,
rDate: date.toLocaleString()
});
You mentioned it here, yeah
for me its more complicated
That approach is also more overhead. What you had originally was just fine too, if a bit repetitive
"Easier to extend" would probably be a better reason to use either an iteration or setDynamicProperties. You could merge a bunch of properties into a single object, then set that object
Useful for when you don't know ahead of time which properties you are updating, or if you only want to update some properties when they change and not others
const propObj = {};
if (...) propObj.foo = ...;
// ... more statements
entity.setDynamicProperties(propObj);
Yeah... Lol
a script that predict where the player arrow is going to land based on the bow start use duration and some math, preferably draw the arrow path
lol, one of my to do ideas that i will probably never do
Maybe I don't have the mathematical knowledge for that
guys why playerInteractWithBlock event doesn't work anymore
What server should I use script module api?
it does?
2.0.0-beta or 1.18.0
when i use after or beforeevent nothing happens when i interact with any block
yes
yes but use 18
I'll use that, thanks.
it need the interact component, or use the before event
yep
which addon 
uhh idk any ideas
recreation of a java mod?
those are usually fun to do
uhh let me see
and don't choose create mod pls
huh
a tech mod?
sure
m aybe its possible\
but maybe not too much bedrock limitatioins
are there power mods already?
I don't play java mods so irdk
I don't play with bedrock addons much too lol
lmfaooo
last time I played with an actual addon for more than 2min and for fun was 2 years ago
oh? waht the lol
well whatever idea you have in mind I'll do it
Chat, why did Bridge lower the mb count of my addon? I have an exact copy and all I did was change the server from 1.14 to 1.18 😭
I was thinking of a power mod of sorts
Power mod like those superhero armor/morphs?
maybee, so like redstone but better?
Does anyone know why? Did it just automatically remove uneeded textures or something?
"Mekanism’s team of experienced chemical and mechanical engineers have developed advanced ore processing machinery to extract resources from ores with utmost efficiency."
🙂
yes
lowkey when you said does anyone wanna do an addon I thought you were just aiming for a small idea to pass the time
yes not a project
I'm not trying to recreate mekanism i would die
any suggestions'
I mean i'm working on a tree harvester mod rn but everyone already has one
though mine is optimized
sure what kind
Copper wires
Copper infused redstone = more range, customizable output
Or they can crawl the walls and ceilings
aye that mightb e a good idea
I'm so terrible with ideas.
wireless redstone
70% of the time would be getting the idea
Sculk
oh why not a remote that can toggle redstone power from far away
redtooth type thing
huh?
use a custom model ig?
Seems like it works like grass or those item frames
Hi
i can share u my codespace if u want
Go in #off-topic or #add-ons
Okiee
okay
do u have github
yes
user?
CennacEh
addedd
so umm.
yeah...?
He don't do typescript
idk, this is the first time I ever heard of codespace
ohh olkay
I just googled it when you mentioned it and read 3 articles about it and still have 0 info about it
done
that took a while.
yep
okay
Hey anyone able to help with a complex optimisation
what is it
I made a post about it titled battle optimisation
is it a simulation?
I made a tiny tiny change, check if it's showing for u
This isnt typical coding as the code works but stats and order needs to be optimised
sure
Atm its a simulation but ill plug it into the actual world when optimised
@humble lintel so you wanna help or no
whats the new way to do const overworld = world.getDimension("overworld");
{
"module_name": "@minecraft/server",
"version": "1.17.0-beta"
},
{
"module_name": "@minecraft/server-ui",
"version": "1.4.0-beta"
}```
what do you mean by new way?
trying to update an old pack
then you should change the module versions here
already did starts throwing this error
[Scripting][error]-ReferenceError: Native function [World::getDimension] does not have required privileges. at <anonymous> (commands.js:5)
...i dont know where the pointer is pointing at
Put it in a system.run
if its 2.0.0-beta, system.run wont cut it
Lovely new bugs who would have guessed
not a bug
the scripts can start way before the world load
#1355306143676633271 message
works ty
do that
Some things prob didnt change as nuch as you thought
i remember i had to do that for everything a while back too
If the error was caused due to doing the same tick as a verification check thats why system.run can still work
another question fixed one issue open alot more
RefernceError banUtils is not initialized
static ban(player, reason, duration, admin) {
bans.push({
n: player,
d: duration,
tob: Date.now(),
r: reason,
a: admin
});
}
static isBanned(player) {
return bans.some(x => x.n === player);
}
```
anyone know if its possible to make chat ranks without using beta apis? which would ofc require not using chatsend.
wouldn't be the same to use an object instead of a class?
ig it's simpler
huh
no
really not even using json some way that sucks extreemly bad if not
json is not related here
other than using plugins for BDS or something, its just not possible
how do I get plugin for BDS cause I have one
ok well ty anyways
const banUtils = {
ban(player, reason, duration, admin) {
bans.push({
n: player,
d: duration,
tob: Date.now(),
r: reason,
a: admin
})
},
isBanned(player) {
return bans.some(x => x.n === player);
}
};```
the way to use it remains the same:
using class: banUtils.ban()
using object: banUtils.ban()
ah i see
sorry im fixing the errors as they come and they js keep comin
at <anonymous> (moderation.js:100)
[Scripting][error]-Plugin [Zeno Prisons v2.0 - 1.0.1] - [index.js] ran with error: [ReferenceError: Native property getter [World::scoreboard] does not have required privileges. at Database (moderation.js:21)
at <anonymous> (moderation.js:100)
] ```
```21 this.objective = world.scoreboard.getObjective(databaseName) ?? world.scoreboard.addObjective(databaseName, databaseName);
100 const unbans_database = new Database("UnbanDatabase");
why not just do the solution VoidCell gave
world.afterEvents.worldLoad.subscribe(() => {
import("./scripts/levelsystem.js")
import("./scripts/mobstacker.js")
import("./scripts/stack_remover.js")
import("./scripts/placelimit")
import("./scripts/loot_table.js")
})``` this?
worked didnt even see his message
How do I teleport a player to the world spawn?
.teleport(world.getDefaultSpawnLocation());
When I do that, it teleports the player to 0 32676 0 instead of the worldspawn
i forgot about the height
The default Overworld spawn location. By default, the Y coordinate is 32767, indicating a player's spawn height is not fixed and will be determined by surrounding blocks.
Coddy saves the day again 
ty!
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
if (source.typeId !== 'minecraft:player') return;
if (itemStack.typeId === 'minecraft:stick') {
const defaultSpawn = world.getDefaultSpawnLocation();
const topMostBlock = source.dimension.getTopMostBlock({
x: defaultSpawn.x,
z: defaultSpawn.z
});
source.teleport(topMostBlock?.above(), {
dimension: source.dimension
});
}
});```
❤️
why do you eat tables weekly?
they taste good
the texture is outstanding
you should try it sometime
Hey everyone, how to fixed "run failed, no runtime or context available." error when use Script API on Minecraft Bedrock Edition?
yo, it works but it teleports the player to y256 instead of the top most block, is there any way to fix this?
import { world } from '@minecraft/server';
world.afterEvents.playerDimensionChange.subscribe((eventData) => {
const { player, toDimension } = eventData;
if (toDimension.id !== 'minecraft:overworld') {
const overworld = world.getDimension('minecraft:overworld');
const spawnVec = world.getDefaultSpawnLocation();
const topMostBlock = player.dimension.getTopmostBlock({
x: spawnVec.x,
z: spawnVec.z
});
const safeSpawn = {
x: spawnVec.x,
y: topMostBlock?.location.y +1 ?? 70,
z: spawnVec.z
};
player.teleport(safeSpawn, {
dimension: overworld,
keepVelocity: false
});
player.sendMessage('§cReturned to world spawn!');
}
});
Why do that?
I already did this to you.
oh mb
its fixed now, thanks!
oh i just noticed
april fools i guess
oh yeah lol i forgot abt that
They’re alphabetically sorted for neatness 👍
Anyone able to help with optimisation and feedback for my battle system
olleh syug yppah lirpa sloof !
mhm
backwards - hello guys happy april fools !
The files are in battle optimisation also am i the princess varient of you lol im princessTG your just TG so bland 😛 im joking
@prisma shard whos the fool yous the fool happy april fools fool
what
oh my
no my
@leaden elbow so are you able to help optimise?
Hello i want to ask, Can i use python code for addons for my world? My brother know code with python so i am asking 
@prime zenith Can you help me?
no
you can use python to auto generate your addons tho
but not directly use it
^
AI tells to me that coding needs python or something so i don't understand now, python is like language or something
So how do you do that?
I saw ppl use code in addon many times already
addon is made with codes....... ;-; bruh
yes
so how can i do that
codes needs python or smth
or language
not sure what that means
i know JSON tho
I already read that, but there is no python decribed so i asked here if you know how to do that
i need to double jump to work in my addons and they said only script api can do that
I ALREADY SAID.
you can't use python directly in addons.
But can use python to write JSON/JS or auto generate addons
so its not possible to code in addons?
Minecraft only supports Javascript and JSON
ofcourse??
So Code is also python is like javascript?
JSON is a code... Javascript is a code..
^
If you want to make a Double Jump as you said, you can use Javascript and read the article "Intro to scripting"
And detect, if player has jumped, then for the second jump. you can use applyKnockback()
I want to use this but i don't know how to add this code to addon
# Abstract Minecraft API Example
# Assume the Minecraft API provides these methods: `get_player_position`, `set_player_velocity`,
# `on_player_jump`, and `is_player_on_ground`.
# Initialize variables for double jump
max_jumps = 2
jumps_left = max_jumps
jump_strength = 10 # Customize based on the Minecraft API's velocity units
# Event listener for player's jump action
def on_player_jump():
global jumps_left
# Get player's current position and velocity
player_position = minecraft_api.get_player_position() # Placeholder API method
player_velocity = minecraft_api.get_player_velocity() # Placeholder API method
# Double jump logic
if minecraft_api.is_player_on_ground(player_position): # Check if player is on the ground
jumps_left = max_jumps # Reset jumps when on the ground
elif jumps_left > 0:
minecraft_api.set_player_velocity(player_position, (0, jump_strength, 0)) # Apply upward velocity
jumps_left -= 1
# Main game loop (abstract representation)
def game_loop():
while True:
# Listen for jump events
minecraft_api.on_player_jump(on_player_jump) # Bind the jump event to the handler
# Apply gravity (Minecraft should handle this as part of its physics engine)
pass # Gravity logic here if necessary
# Start the game loop
game_loop()
chatGPT right?

please
for god sake
Don't use AI in minecraft scripting
But use if you want to make something Javascript-itself related.
but i don't know how to us python, and AI knows the best
BRO I SAIDDDD, you cant use python in minecraft
😭
yea its the same thing as JavaScript its code you said so
bruh, i think i am cooked
why is script api so hard to learn
i already tried like month ago
to learn script API, you should first complete a javascript course
atleast Learn abbout javascript before scripting
bro doesn't even know that it is a coding language
I know its language, its code using python language or languge like JSON
there are many languages
also molang
but molang is really hard
yes, but, please. Dont put python inside minecraft
Minecraft doesn't support python
there was no point of asking AI to make a double jump with python
Wdym?
Python is code
uh-
why, i need it in my world
OK
I didn't knew you can run other languages in Education Edition 👀
ok
But this isn't the channel for you
This is about Script API (javascript)
js is for when you want to die ts is for when you want to write code 🙏🙏
Then no python please
@oak lynx Can you help me, @prisma shard Doesn't knows python code in MC
I haven't touched python in years
OK
from all the languages I had to use in my life python is in the top 3... worst languages
convert python into js 🤷
but i need it for my world with my friends
OK
firstly, bro says "Yes i need code in world with code Script api"
Then says "finnafinest Doesn't knows python code in MC
"
Bro are you serious? if your gonna code in Script API, you can't use python there..
# Abstract Minecraft API Example
# Assume the Minecraft API provides these methods: `get_player_position`, `set_player_velocity`,
# `on_player_jump`, and `is_player_on_ground`.
# Initialize variables for double jump
max_jumps = 2
jumps_left = max_jumps
jump_strength = 10 # Customize based on the Minecraft API's velocity units
# Event listener for player's jump action
def on_player_jump():
global jumps_left
# Get player's current position and velocity
player_position = minecraft_api.get_player_position() # Placeholder API method
player_velocity = minecraft_api.get_player_velocity() # Placeholder API method
# Double jump logic
if minecraft_api.is_player_on_ground(player_position): # Check if player is on the ground
jumps_left = max_jumps # Reset jumps when on the ground
elif jumps_left > 0:
minecraft_api.set_player_velocity(player_position, (0, jump_strength, 0)) # Apply upward velocity
jumps_left -= 1
# Main game loop (abstract representation)
def game_loop():
while True:
# Listen for jump events
minecraft_api.on_player_jump(on_player_jump) # Bind the jump event to the handler
# Apply gravity (Minecraft should handle this as part of its physics engine)
pass # Gravity logic here if necessary
# Start the game loop
game_loop()
uhhh, this is AI?
Yes
Don't expect me helping you
its python code
you can't do code python?
its language for code
NO
that's not the reason I don't want to help you.
OK
I know how to code python, it's literally in my bio.
Ohh, where i can ask code in addons?
praying that the beta tomorrow makes getBlock() not useless
what update
Umm, nah.
we get a beta every Wednesday
I need double jump in my world
but i don't know how to code
like, what changes will be done to make the getBlock() not useless
then learn????????
This server is for learning
I was supposed to type getBlocks() but autocorrect exists
make getBlocks() return blocks itself not locations?
yes 🗣️
wiill be cool then 🗣️
Can you give me a way to learn code in addons?
wiki.bedrock.dev
I tried 2 months ago and not working
learn basic JavaScript -> read Minecraft script API docs -> make scripts
wait is it possible to get like all the typeIds/permutations that are in a specific region?
i don't know
but i can try
getBlock().
........................
*without crashing
Guys
You're a confusing guy, you don't know js, but will help someone?
THATS what i am saying 😭
he is really ocnfusing
GUYS
GUYS
GUYSvv
GUYS
GUYS
I thought its the advice to start learnig code jS
i think....... that guy is making us April Fools???? Check his username!!! i think it is conmaster second alt account!!!!
Ahh, that was a question and it wasn't for you lol.
I know JSON and JS is part of the JSON
and?
he can kiss me if he wanted 😘
;-;
you think I don't notice lol?
anyone knows the performance impact of this?
damn
I'm just playing along, in the first place who tf has a joined date of 2021 who doesn't know addons?
fr
PRETTY much like getBlocks() I guess but a lil bit faster
wait how u see join date
Or getBlock()
Minimal its the fastest way we got to search for blocks
Stop fuckin spamming
sorry, but who doesn;t know addons, gives advice, i am confused
cuz I had this algo going over all block types and getting their positions with getBlocks() and it might be faster if I could filter out what typeIds to check first
Depends on the scale, if thats more than 50 blocks then its notecible and if thats more than 200 than there is brutal difference
that's the fun part it does.
aw hell naw ConMaster? you fooled us, very badly.....
The area is actually large.
you mean, "you fooled me"??
we talking about millions
Only some of you, i am really sorry but i have to
Did you know already he was ConMaster?
I mean by large is actually large. Like 100x100x100
don't use getBlock() then
yes.
how 😭
And more.
I know
I already saw his account in other channels Soo yeah. I just played along.
i am april fooled 😭
I am so sorry but i have to
okay so right now the plan is simple
- I filter out what typeIds are in an area using containsBlock()
- I iterate over filtered typeIds with getBlocks() to get an area of typeIds and positions
then I run some compression stuff and send it to my DB
i hate April fools
so all of these Drama, putting Python inside minecraft, ..... i am laguhing right now
NO WAY THEY ADDED COMMANDS WITHOUT NAMESPACES OMG
a week ago
Python is so disgusting 🤮
uhh what?
yes.
so real
April fools 🤯
You did a very good acting, lmaaoo, who is your brother you said, who knows python
NO WAY...
is there a faster way to do this?
bruh you made us april fooled too
nah this is actually a real question
I mean, you could try it rn
Its slow and i think there is no better way, yet
i am still shocked how conmaster fooled me
bro is a magician
who is your brother
that knows python
lol
someone threaten mojang to add these things:
- no namespace commands
- XUID
- working getBlocks()
Like I want to make a server network using just bds cuz I am mentally insane
Stop already, the joke already dried out.

you're not mentally insane.
i have getBlock() better version
prove it 🗣️
#1067535608660107284 message
I think getBlock works as intended, but i would also like to have getBlockPermutation() without creatin block instance in JS
okay but i am working on a server network purely in bds
Well I use express.js for some stuff
Whats your specific need case for searching for that specific block?
getBlock is fine getBlocks isn't
I need to save player islands (skyblock) to an external database
So you are saving all blocks, or only one kind of blocks?
all blocks and the islands are bigger than 64x so structures won't work
okay but what do I do with the structures? I already tried getPermutation or whatever the method was
I can't just send a structure through rest api
Ohh, so you have to save that to DB and not just MC world cache
yeah I will probably use mongodb
well then getBlock is only way and still incomplete
if i could suggest then try using custom client to join and extract structures via it
its the fastest way
getBlock is not even providing all NBT information
only few components
okay but wouldn't first filtering what block types are in an area then using getBlocks to get all positions of specific typeIds
I thought you want to save all blocks no matter what
that saves all the blocks
like I filter out what typeIds aren't in the area
/**
* @param {Vector3} location
* @param {Dimension} dim
* @returns {Promise<Block>}
* await getBlock(loc, world.getDimension('nether'))
* getBlock(loc, world.getDimension('nether')).then(block => {})
* Gets a block from any dimension & location in the MCworld asynchronously
*/
export async function getBlock(location, dim = world.getDimension("overworld")) {
let block, { x, y, z } = location;
const getBlock = dim.getBlock.bind(dim, location);
try { if (!(block = getBlock())) throw null; else return block }
catch {
dim.runCommand(`tickingarea add circle ${~~x} ${~~y} ${~~z} 0 "${x},${y},${z}"`);
let remove = () => dim.runCommand(`tickingarea remove "${x},${y},${z}"`);
return new Promise(async resolve => {
system.runJob(function* () {
let trials = 1e3;
do {
block = getBlock();
if (!--trials) yield void remove();
} while (!block);
remove();
return resolve(block);
}())
})
}
};
SIgma Ultra Pro Max++ getBlock()
wait I had a prototype somewhere
If there are only some of them then yea, filtering helps
export function blockVolumeToBlockTypeIdArray(blockVolume: BlockVolume) {
const blockArray: { blockId: string, position: Vector3 }[] = []
const span = blockVolume.getSpan()
const totalSize = span.x*span.y*span.z
for (const id of blockTypeIds) {
for (const location of dimension.getBlocks(blockVolume, { includeTypes: [id] }).getBlockLocationIterator()) {
blockArray.push({ blockId: id, position: location })
}
if(totalSize==blockArray.length) break;
}
return blockArray
}
eww
So you want to filter air blocks basicly right?
If i could suggest, then avoid runJob and use own impl, with Date.now then you can boost up the synced execution
so true.
not recommended for marketplace addons but for local usage is alot faster
no i want to filter out blocks that aren't in the area the code I sent above iterates over all typeIds in the game but I can use containsBlock to only iterate over ids that are present on the player island
Interesting idea, i think at this point its just speculation if to use getBlock, but i would try to do performance tests to decide
I mean my performance tests made getBlock look really bad
yea, i think so
so I'm willing to try a lot of stuff
Yea we need improvement for getBlocks() so we know what blocks are where
like bds performance is great actually
I just need a few little things and it will be enough to run actual servers on it
function is not mine tho, btw how did u get the name lol
What name?
like user name?
yes

First thing i did, was creating existing works like, "Dexter Everyday" then just replace some letters and add weird Capital letters in the middle, thats whole story
my god that is horrifying
why
You maybe talking to a child, so lighten up your language a bit
alright sorry
how do I get all death cause in entity die
wdym? entityDie event fires for all causes except forced removal
get the cause property from the event
ok let me check
Was it event.damageSource.cause?
@honest spear with?
How can i add code python in addon
you don't
OK
thx I got it working
How can I give a block a unique identifier and then use it like an entity with a dynamic property?
just code it
That question is kinda random, maybe share your end goal and let us help you figure it out
well its used alot i guess, you definitely should cache the value in JS if used alot
yeah i should

the lag is no more
though i actually didnt cache the value
since the property can be updated by players mid game
(this is just an excuse, i was just lazy)
((im not used to caching))
(((I am not used to use Script API anymore))), i should fix that
rip
use python
How can i use python in script api?
OK
doesn't minecraft china have a python api or something like that
yes they use python
they have script api too?
Yes
that is cool
#1356632769035243550 Can anyone help?
Its not called "Script" due to "javascript" btw
ok
can anyone help me? #1356632769035243550
Helloo
Can I detect an enderman teleporting before and after?
ionknow
i meant script api as of the same one we have
no, I said they use python
that doesn't mean they have mainstream bedrock's scripting api
they have their own thing that only uses python iirc
no JS
@honest spear do not use python ever it is a bad code to use outside of learning it is absolutly terrible to use and is a leading cause to high electricity prices avoid python
Can you pls write for me
cuz like i'm not learning JS for this
Ah yes, Python—the true villain behind global energy crises. Forget inefficient data centers or industrial power consumption; it's those pesky print("Hello, World!") scripts driving up electricity bills worldwide. Next thing you’ll tell me is that JavaScript is responsible for climate change. Truly, we must return to writing everything in hand-optimized assembly to save the planet.
|| ~ By Someone, Somewhere ||
Ohh, ok
Why this code doesn't work?
import time
# Define parameters for double jump
MAX_JUMPS = 2
JUMP_STRENGTH = 10
jumps_left = MAX_JUMPS
# Event handler for jump action
def handle_jump_event():
global jumps_left
# Check if player is on the ground
if minecraft_api.is_player_on_ground():
jumps_left = MAX_JUMPS # Reset double jump when touching the ground
elif jumps_left > 0:
# Apply upward velocity for the jump
minecraft_api.set_player_velocity(0, JUMP_STRENGTH, 0)
jumps_left -= 1
# Game loop
def game_loop():
# Bind the jump event to the handler
minecraft_api.on_player_jump_event(handle_jump_event)
while True:
# Simulate a game loop with minimal functionality
time.sleep(0.05) # Tick rate (replace with Minecraft's game tick logic if necessary)
# Start the game loop
game_loop()
where script API
it throws syntax error
Under no circumstance for any reason should anyone ever use python python is a bad language and its power consumption is extremely high and because of ppl who used it for servers the power req to keep them is extremely high
I see no scripts and no snakes, so that is invalid python and not a script
Find a python
i want doublt jump in my world to work
but it doesn't
@honest spear im sorry ill help you with javascript but im not helping you write python python is to dangerouse of a language to use
OK
All hello world applications will take over the world.
Can you help me wioth my addon code?
Skynet told me
I don't know how to fix it
wdym?
@honest spear tonight we can talk add me
minecraft_api, a library so advanced that it doesn't even exist yet. If we could get this to work, we might just revolutionize Minecraft modding… or crash the game instantly. 😎
OK
wdym?
#someonehelpme
OK, do you have also problem with python
No #1356632769035243550
😭🙏
js python interpreter?
I got you
OK
Just wait a few years
Im gonna make a c++ interpreter in js
People will think its fast but its gonna be extremely slow
Its gonna compile to Mcssembly (pronounced Macsembly or just mc sembly)
Which then is gonna be interpreted
I think im onto something here
Just like python
@honest spear if you need help i cant help til tonight
Will you make the js python interpreter?
Python?🐍
nah i deleted interpretter
I won
@spring axle will probably hate that I say this. But I think we're targetting for June-ish for scripting v2? But definitely give the team a break if it slips a month or seven. 🙂
Hate as in he wants it earlier or hate beacuse he wants it to be brewed for more time?
smokeystack can u help me
As long as Navi suffers...fine by me.
I just don't like putting pressure on the dev teams by publicly stating dates that might still be fuzzy.
Totally understand. Thanks for the estimate
can u help me
How to register custom components with @minecraft/server release?
I can't find startup event in system
What version?
1.18.0
Continue using worldInitialize before event.
deprecated
Yes, it will be deprecated if you decide to update to 2.0.0
I can't compile with worldInitialize
I'm making a long-term support map, I can't use the beta package.
Then like I said, continue using worldInitialize before event.
Like I said, continue using worldInitialze before event.
@distant gulch Please open a post with your code and the compile error.
worldinitialize is in world.beforeEvents, not system
quick question, how do i view how much lag my addon creates?
profiler
thank
yea profiler really helps
i would also suggest using MC debugger extension so you can see the statistics at the runtime
I would determine the offset of the ray's intersection with the player's position. If, say, the player's "head" starts at ~1.4 blocks up when standing straight, then you can determine a headshot by seeing if the y-offset is greater than 1.4 blocks from the player's y-coordinate
Mame sure to check sneaking
.
My approach would be to get the player head to entity head vector, and compare it with the player's direction vector using the dot product.
get entity from ray can give you exact location, so get head location and do a distance calculation
something like this maybe
isHeadShot = V0 dot V1 < .75 + .15(distance/100)
Are there changelogs for the scripting api?
Yes.
Where?
In the same place as normal changelogs.
I was kinda hoping for something more condensed but alright
It’s been awhile since I’ve touched addons and wanted to know if the stuff I’ve been missing have been adding
not the movement itself but the momentum?
if a particle is spawned on a player can it access player related queries?
like player.spawnParticle
Just tried this out and they can't access player related variables unfortunately
hey guys, do you think using js const startTime = Date.now(); const time = Date.now() - startTime is more efficient than using system.runTimeout? in the case that I need too many of them
When is scripting v2 expected to come out? Soon or later?
@neat cypress
How long did you run it to get those results?
just a few seconds
i could run it for a few minutes but i was just super lazy
oh
how do i correctly subtract the value from a dynamic property (it’s int)
uhm, .getDynamicProperty()?
Get the dynamic property first 🤷
const value = World.getDynamicProperty('value') ?? 50;
World.setDynamicProperty('value', value - 10); // return 40;```
aight thanks
lol i thought he meant how to GET the value
mb
Hey, is it possible to change the name of a spawned npc using scripts ?
If yes can anyone tell me how or link documentation ??
Please ping me if you do
get npc component
Can you tell me more ??
Are there documentation for this ?
What I am aiming for is to show specific text above the npc's head
Kind of like a chat thingy
Also, there's a limit of amount you can display in npc's head/name tag.
Only 32 chars
It can't be bypassed ?
Even with \n ?
no.
Okay, thanks 👍
My Script API is okay but the way it displays the title is not very good so I have to fix my script to make it work more stable.
You could if its positioning thats the issue use json ui to move it
hi steve
Fixed biome title, Now only fixed dimension title left
can I connect the debugger to a remote server or it must be at same machine? also is mandatory to have a client connected?
Mojang claims it can connect to remote servers provided you know how to setup a tcp server. You can connect the debugger to a BDS
but how do I define the server IP?
"localRoot": "${workspaceFolder}/behavior_packs/Inner_BP/",
"port": 19144
No preview today.
previews are the only thing that give me motivation on Wednesdays
I should try finishing my block saving function 🗣️
If mojang adds beforeEvents entityHitEntity, I'll let the kids in my basement go out.
does anyone know how to bypass this
urh
chicken jockey
Well, preview this week is Thursday and it will try to be on Tuesdays from now on.
I gave up on entityHitEntityBeforeEvent and just block entity_hit damage on everything
just imagine the possibilities
i did this
makes sense
I can just imagine people will be forced to learn scripts
its better than doing it manually with JSON
uh
should be
learning javascript is fast, people are either lazy, or just slow learner which I respect, and people who are doing for the sake of friends
anyone here actually codes in js/ts outside of script api?
not me
idk what i should use for my db connection prisma is cool but mongoose also looks like a decent option
speaking of this
that is practically a bug
it affects all the damages, even enchantments and mace damage
Don't inform Mojang.
lmfao
Just shhh

-# if they actually fix that i will go insane
-# please dont do it mojang, its my last hope
-# me who tagged a mojangster here.
how
i will throw tomatoes at you
uhh anyone knows something really technical about dimension.getBlocks()?
does adding the exclude types filter make it faster or slower if i can add all the types i dont want there and include all the types i want?
p sure it makes no difference
everything makes a difference when talking about millions of blocks 🗣️
i dunno how the API works but
im p sure excludeTypes filter is just
equivalent to javascript native filters
(hopefully)

it usually gets a huge spike when i open it cuz it does a lot of calculations on startup to avoid doing them later
should be considered as a bug
bruh
public* blockVolumeToBlockTypeIdArrayWithSaveBlocks(blockVolume: BlockVolume) {
console.log(`Starting to save blocks`)
const filteredBlockIds: string[] = []
const time = system.currentTick
const span = blockVolume.getSpan()
const totalSize = span.x*span.y*span.z
let i = 0;
for(const id of blockById) {
if(dimension.containsBlock(blockVolume, {includeTypes: [id]})){
filteredBlockIds.push(id)
yield;
}
}
for (const id of filteredBlockIds) {
i++
for (const location of dimension.getBlocks(blockVolume, { includeTypes: [id]}).getBlockLocationIterator()) {
this.vectorTypeIdArray.push({ blockId: id, position: location })
yield;
}
if(totalSize==this.vectorTypeIdArray.length) break;
}
console.log(`Found ${this.vectorTypeIdArray.length} blocks out of ${totalSize} in ${i} iterations, Time: ${system.currentTick - time}`)
const uniqueIds = [...new Set(this.vectorTypeIdArray.map(item => item.blockId))];
console.log(`Unique block IDs: ${uniqueIds.join(", ")}`);
}
oh bruj
this is just not possible
yea, i already said you better use custom client
Script API is not build for these kind of stuff
nah the bootup spike is just a second of like 30ms when nobody is on the server
hmm
900 ticks to save 64x384x64 is really bad
first i wanted to check how bad it would be
yea
yea, all right
and it somehow found more blocks than there are in the area 💀
turns out dimension.containsBlock is really slow
i expected it to be at least a little bit better than getBlocks
well you are calling it for every type id, its slow when you call it that many times, but it loops the same blocks many times
it has to visit each block x times
i wonder if there could be done some optimalizations
probably yeah
but i doubt they will change much
easiest would be restricting the list of checked ids to obtainable blocks (but thats use case specific)
Well i could optimize it for you but create post and explain me your goal more for what you do in Script API side
i dont think its possible to make it fast enough i will check endstone docs to see if it can save block areas
Well i could try at least, but if you don't want then all right
like what i am trying to do is to save an area of blocks to a format i can store in a database
I need more of context code, please create a post so we don't spam here
but i already have some optimalization in mind


