#Script API General
1 messages Β· Page 81 of 1
why is player now wrong: const attacker = event.player;
You run a script it's quite like the same
is it?
I don't have any
didn't you install the package?
gotta agree
probably the error is the type of "attacker"
yea but I get the type completion addTag
nvm
but how do I define the entity?
in entityHurt
I use damage source: const attacker = lol.damageSource
It is telling you that attacker might not be an Entity instance
check if it actually exists
if (attacker instanceof Player)
ohh
damageSource.damagingEntity
thank you guys
so when youi setup a playerselector in custom commands how do you get the player that the user selected in the command
Yo @dusky flicker
system.beforeEvents.startup.subscribe((init: StartupEvent) => {
init.customCommandRegistry.registerEnum("mcbepm:rankenum", ranks);
init.customCommandRegistry.registerEnum("mcbepm:addremove", [
"add",
"remove",
]);
const rankCommand: CustomCommand = {
name: "mcbepm:rank",
description: "Remove or set player ranks.",
permissionLevel: CommandPermissionLevel.Admin,
mandatoryParameters: [
{ type: CustomCommandParamType.Enum, name: "mcbepm:addremove" },
{
type: CustomCommandParamType.PlayerSelector,
name: "mcbepm:player_select",
},
{ type: CustomCommandParamType.Enum, name: "mcbepm:rankenum" },
],
};
init.customCommandRegistry.registerCommand(rankCommand, changerank);
});
function changerank(origin: CustomCommandOrigin, addremove: any, player_select: Player, rankenum: any): CustomCommandResult {
(origin.sourceEntity as Player).sendMessage(addremove + player_select.name + rankenum);
if (addremove === "add")
{
player_select.setDynamicProperty("mcbepm_rank", rankenum.toString());
return { status: CustomCommandStatus.Success };
} else if (addremove === "remove")
{
player_select.setDynamicProperty("mcbepm_rank", "");
return { status: CustomCommandStatus.Success };
} else {
return {
status: CustomCommandStatus.Failure,
message: `Invalid add/remove option: ${addremove}`,
};
}
}
``` this doesnt return the player for some reason but everything else does. the player is as undefined
?
How can I make it so if I'm on a specific slot and I have a specific scoreboard number a command happens I made a post about it if you want to send it there https://discord.com/channels/523663022053392405/1370824217725239418
I thought PlayerSelector just returns the name anyway?
Nvm, it does return Object
PlayerSelector returns Player[] because you can use selectors such as "@a" which is multiple targets and it doesn't matter if in the command you actually used a name or a one-target selector, it will always return an Array of Player instances. So the way you should do this is
player_select.forEach(player => {
player.setDynamicProperty("mcbepm_rank", rankenum.toString());
})
and the same for the remove function.
Also if you are using typescript which is literally to help you with typings, at least put all the typings correctly instead of just doing any for almost all parameters
This should be like this:
function changerank(origin: CustomCommandOrigin, addremove: string, player_select: Player[], rankenum: string){}
Yeah, that makes sense looking more into the command
import { system, CustomCommand, CustomCommandParameter, CustomCommandParamType, CommandPermissionLevel, CustomCommandOrigin, CustomCommandResult, Player, CustomCommandStatus } from "@minecraft/server";
/**
* Handles the `/namespace:test <target>` custom command.
*
* Sends a test message to all selected target players, indicating the sender's name.
*
* @param {CustomCommandOrigin} origin - The origin of the command, which includes the sender information.
* @param {Player[]} targetPlayers - Array of players selected by the player selector argument.
* @returns {CustomCommandResult} - The result of the command execution, including message and status.
*/
function handleTestCommand(origin: CustomCommandOrigin, targetPlayers: Player[]): CustomCommandResult {
const senderName = (origin.sourceEntity as Player)?.name ?? "Unknown";
for (const player of targetPlayers) {
player.sendMessage(`[Test] This message was sent to you by ${senderName}`);
}
return {
message: `[Test] Sent message to ${targetPlayers.length} player(s).`,
status: CustomCommandStatus.Success,
};
}
system.beforeEvents.startup.subscribe((object) => {
const slashCommands = object.customCommandRegistry;
/**
* Registers the `/namespace:test` command at server startup.
*/
slashCommands.registerCommand(
{
name: "namespace:test",
description: "An example for making a custom slash command",
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [
{
name: "target",
type: CustomCommandParamType.PlayerSelector,
} as CustomCommandParameter,
],
optionalParameters: [],
} as CustomCommand,
handleTestCommand
);
});
how to check if player is op (in 1.21.80)
anyone
only in 2.0.0-beta
yeah im using that ver
so use player.isOp()
ohh i thought it was removed
It will be in the next release most likely. Be mindful that it doesn't work well on Realms. Which is why they are refactoring it. Too many underlying conflicts of interest between local, BDS, Realms, etc when handling permissions.
player.permissionLevel is a thing in beta or no? cus i saw someone refer that here and he said it works but i dont think so
That's for custom commands.
Documentation for @minecraft/server
First time seeing this error
how do i get the direction the player is walking in even if they arent facing it
basically wanna get the direction the player is walking
player.inputInfo.getMovementVector()
i got it already thank though
import { InputButton, ButtonState, Player, world, system, EntityHealthComponent } from "@minecraft/server";
// Map to track players' blocking and last hit times
const playerStates = new Map();
const BLOCK_WINDOW = 500; // ms window for a parry
const BLOCK_CHECK_INTERVAL = 5; // ticks (0.25s)
world.beforeEvents.entityHurt.subscribe((event) => {
const { hurtEntity, damageSource } = event;
if (!hurtEntity || hurtEntity.typeId !== "minecraft:player") return;
const player = hurtEntity;
const state = playerStates.get(player.id) || {};
const now = Date.now();
if (state.isBlocking) {
// Parry condition: recent block and timing
if (now - state.blockStart <= BLOCK_WINDOW) {
// Cancel damage
event.cancel = true;
// Optional: push attacker back
if (damageSource.damagingEntity) {
const attacker = damageSource.damagingEntity;
const direction = {
x: attacker.location.x - player.location.x,
y: 0,
z: attacker.location.z - player.location.z,
};
const length = Math.hypot(direction.x, direction.z);
attacker.applyKnockback(direction.x / length, direction.z / length, 1);
}
player.runCommandAsync("say Parried!");
} else {
// Blocking but not timed for parry
event.damage = event.damage / 2; // Reduce damage
player.runCommandAsync("say Blocked!");
}
}
// Save the time they were hit
state.lastHitTime = now;
playerStates.set(player.id, state);
});
system.runInterval(() => {
for (const player of world.getPlayers()) {
const state = playerStates.get(player.id) || {};
const isSneaking = player.isSneaking;
// Start or update block
if (isSneaking && !state.isBlocking) {
state.isBlocking = true;
state.blockStart = Date.now();
}
// Stop block
if (!isSneaking && state.isBlocking) {
state.isBlocking = false;
}
playerStates.set(player.id, state);
}
}, BLOCK_CHECK_INTERVAL);
sb told me change it to .js
and then when i did
this is what it send in game
..
thanks
so to get the player would I just do ```ts
const player = player_select[0] as Player;
wrap it in ```
there is no beforeEvents.entityHurt
only an after Event
not YET
Has anyone used debug shapes in the most recent preview? It does not appear to work for me on Android.
How to change the player's camera direction to the opposite of the current direction?
player.teleport(player.location, {
facing: -getViewDirection
})```
teleport the player to the opposite of view direction
ig
How to set player on fire without player.json?
facing got renamed to facingLocation
theres meathod for that
seton fire or something
Found it. setOnFire
Hey am I insane or why does getBlocks not have a location parameter?
That would be the first parameter, in volume.
Update your typings?
It takes BlockVolume now
Can you give an example? Like I want it to detect at a player's location
The long solution:
import { BlockVolume } from "@minecraft/server";
function getBlockAroundPlayer(player,blockId,size=10) {
const loc = player.location;
const searchVolume = new BlockVolume({
x: loc.x - size / 2,
y: loc.y - size / 2,
z: loc.z - size / 2
},{
x: loc.x + size / 2,
y: loc.y + size / 2,
z: loc.z + size / 2
})
return player.dimension.getBlocks(searchVolume,{
includeTypes: [ blockId ]
})
}
The short solution:
const blockBelowPlayer = player.dimension.getBlock(player.location).below()
ty
....
That was a example code
Ik
yo @prisma shard
or @random flint
can one of you help me fix this
the parry doesnt cancel damage
and blocking doesnt stop players m1 or dmg once they are holding block and it doesnt stop players from hitting them
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
Is this AI? π
You can't cancel damage only with ScriptAPI
I wish we could tho ππ
You will need the "minecraft:damage_sensor" component on the player (or other actors) to disable the damage.
do you get what im tyring to do tho?
so do i do it with java script instead of type script
Yes, I do, and logically this looks like it would do what you want. To double-check with you: You are receiving the "Parried!" message when you parry an attack, right? It's just not cancelling damage
yep
and im recieving the block message as well
the only thing it does other than them messages is knock up the attacker
which i also dont like
If you don't want the attacker to receive knockback, then remove the attacker.applyKnockback call in your parry logic
As for cancelling the damage, it's a tad trickier. Prefacing with this: The best way is to modify the player's behavior. Does your project's goal support that?
wait what do you mean by that
ok i just took this out
const attacker = event.damageSource?.damagingEntity;
if (attacker) {
const knockback = getKnockbackDirection(player, attacker);
attacker.applyKnockback({x: knockback.x, z: knockback.z}, 1.0);
}
was this what you were saying?
I mean editing the player's definition so that we can cancel damage. Some creators don't like doing this, because it makes their behavior pack incompatible with other packs that also modify the player's definition; Minecraft can only apply one definition to an entity.
In the behavior pack, look in the "entities" folder and see if they have a file named "player", or something along those lines.
(The file name does not guarantee this though, best way is to open every one and see if any definitions use the "minecraft:player" identifier)
That's the one. You can use that as a base, then
Seems kinda big though, haha, let's see what we're working with
Oof, five thousand lines
five thousand? holy
Bad news, what I was about to suggest is not super compatible with this player definition. There are 61 damage sensors in this file already; in whatever way the author set up the different variants, they are more like micro-states on the player
hmm
Still possible technically, just really tedious to go edit
so this blocking/parry system wont work basically
You might be able to append the logic I was about to suggest onto each damage sensor, but there's no telling if that would bust the other logic that's in there (since damage sensors can only trigger one event per tick)
It would require a much finer understanding of how this add-on is set up to do correctly
so theres no other way?
There are the less pretty options.
- You could give the player Resistance V when they activate a sneak, but of course that's heavily abusable.
- You could try healing the player back for the damage they were dealt, but of course the player could die in that strike.
- You could try placing another entity on top of the player when they sneak, so any attacker hits that instead. Probably would not work too well while moving.
I'm trying to think of some others
THE MASSAHEX
As well as the effects screen.
AHHHHHHHHHHHHHHHHHHHHHHHH
Yes
Search #1067869374410657962 for something related to modifying the display of effects on the hud screen
Ofc you coul always just turn the resistance ui element into a shield icon in the middle to represent blocking
It'd be cool
I'm not certain that this is relevant to their question, though. They need a way to prevent the player from being hurt when a parry activates
Yes I know
But I also know his problem
I've been helping him
mhm
basically i want it so if you crouch like a mili sec becfore they hit u its a parry which deflects all dmg
and if your holding block it makes u unable to hit and make it so you deflects dmg as well
but also like a block bar so if you holding it it can be broken
So you would be fine using resistance as long as the ui with the resistance icon doesn't show up?
im fine with anything as long as it works
Alr
is there a way to grab which language the player has selected through script api
No.
yo @sharp elbow
π«‘ What's up
whats outdated about it?
how abt this one
oh nvm
its also outdated
this one is to @distant tulip
export const quests = [
{
id: "pirate_slayer",
name: "Pirate Slayer",
description: "Kill 5 Pirates.",
entityType: "op_asa:kaizoku",
killGoal: 5,
rewardXP: 100
},
{
id: "pirate_hunter",
name: "Pirate Hunter",
description: "Kill Pirate Bandit.",
entityType: "op_asa:kaizoku4",
killGoal: 1,
rewardXP: 150
}
];
try it and see
Is their anyway i can detect a headshot?
hmm
what will be the tag i have to give myself to start it
since the npcs
are not available rn
zombie_slayer
???
Is the profanity filter global?
Does it filter all text?
Even server messages?
Like world.sendmessage
pretty sure theyre tied to json ui?
i dont remember exactly though
Ok if so then good because I want people have the option to have it on or off. I know in settings there is a setting to turn off the profanity filter as far as I know.
It seems to filter cuss words in the chat menu but not the chat display in the hud screen.
It could be because I'm using a custom json ui for the hud_screen for the chat
yeah
if youd like to force it you can edit some json ui
i think its like
"profanity_filter": boolean
something like that
on a label
Iβm gonna ask the lovely community of amazing developers.
I tried to make a block logging script that records every block, broken or replaced and then admin can go to an area and roll back those changes
(the commands for this or in a separate file)
However, this script absolutely murders the world dynamic properties string length, and Iβm not sure of a more optimized way to handle this
i think you could make it so it only stores the surface blocks that players can see/destroy/modify
so youre saving everything in one dynamic property ?
Where i can find people who want to make commissions
-# not here
read the rules
I can make one
Try saving it to two different dynamic properties, one for placing, one for breaking
Another optimization would be not using JSON.stringify, custom serialization and deserialization would be more efficient on space
Based on what you are doing, and the large amount of data that will be involved, I can suggest the following:
[STORE DATA]
|
[CHUNK JSON] β Split into 30KB parts
|
[SET EACH CHUNK] β myDB/key/0, myDB/key/1, ...
|
[UPDATE POINTERS] β Track chunk keys
[GET DATA]
|
[LOAD CHUNKS] β myDB/key/0 ... N
|
[REASSEMBLE JSON]
|
[PARSE VALUE]
[DELETE DATA]
|
[FIND CHUNKS VIA POINTER]
|
[DELETE CHUNKS]
|
[REMOVE POINTER]
I ended up using an external database
Something called Superbase
Still though the data is super large, in like a few minutes with 20 players it hit 200kb
Maybe like 10 minutes
I have it auto delete logs older than 48 hours
I donβt want to do that but itβs whatever
Yea, the data you are recording is very large. You are very limited on that aspect. Using an external database is probably your best bet. Pretty certain my suggestion would suffice too, but the world size would grow large very quickly lol.
Yeahhhh
The system is needed though, itβs for a Minecraft 1.7.3 beta recreation server
Feel free to join and gawk at at haha
play.betafied .net
@remote oyster
erm Supabase*
I stole it from you actually!
bahaha
its very nice tbf
very easy to use
and
its free 500,000,000 character storage
Yeah dude I love it
I only need it for that anyways everything else is is on the world
you can also use it for bans if u want
and use a discord bot to add to it
and use the new asyncBeforePlayerJoin event
Got a link to this? I'm looking at the docs and don't see it.
its in server-admin
it is under @minecraft/server-admin
its quite nice
Ah, thanks
I'm curious, does it work on Realms? I know they have that module enabled in Realms.
yes
π
well it should
transferPlayer works on realms so
but yeah pretty much you can make them wait
Yea that works but the others don't. So its hit and miss.
it waits until whatever you need is fetched
it should work one singleplayer too
This event is fired before a player joins the world. Unlike other before events, this event is a before event that you can delay several ticks by not resolving the promise returned in the subscribe function. If the promise is rejected, the client is rejected.
That's very nice!
If I am on specific slot and I have a specific tag how do I make it so it does a command
how do you clear all dynamic properties anywhere?
including offline players
is it even possible?
im not sure if you can do that
If they are set to a player object then you can't remove it unless they rejoin. Otherwise, the only other way would be to modify the world data file.
Or make the code backward compatible so that when they join again you automatically handle it as needed.
For your World itself you can use getDynamicPropertyIds which will return an array of dynamic property identifiers. From there, just loop through them and set them to undefined to clear them.
Actually no, even better you can use clearDynamicProperties for the World which will loop through the dynamic property identifiers and clear them for you with no extra code needed.
It only impacts those made by the behavior pack.
That is, quite literally, what I have been working on for the past week.
Yes, you will indeed have to make a custom serialisation method. If you use an external database, it'll still mean that data grows to be quite large.
Here's my serialisation function:
/**
* Serialises the key for the block event.
* @param time The unix time of the block event.
* @param blockLocation The location of the block.
* @returns The key in string form.
*/
private serialiseKey(time: number, blockLocation: DimensionLocation): string {
const base64Time = Utility.compressNumber(time)
const blockX = Utility.compressNumber(blockLocation.x)
const blockY = Utility.compressNumber(blockLocation.y)
const blockZ = Utility.compressNumber(blockLocation.z)
const blockDimension = Utility.compressDimension(blockLocation.dimension.id)
if (
BLOCK_EVENT_PREFIX.includes(".") ||
base64Time.toString().includes(".") ||
blockX.toString().includes(".") ||
blockY.toString().includes(".") ||
blockZ.toString().includes(".") ||
blockDimension.toString().includes(".")
) {
system.run(() => world.sendMessage("Areas: Something has gone very wrong with the database, please notify the developer. Full stop found."))
throw new DatabaseInvalidCharacterError('Invalid character "." found in key.')
}
// console.log("Compressed " + base64Time + " original: " + time )
// Must all be strings
const key = `${BLOCK_EVENT_PREFIX}.${base64Time}.${blockX}.${blockY}.${blockZ}.${blockDimension}`
return key
}
This is the git repository for the addon:
https://github.com/Aevarkan/Areas
I don't mind you having a look, but please don't take the whole addon. I'm sure you know this already though π .
That code was from the BlockDatabase class in this file: https://github.com/Aevarkan/Areas/blob/main/src/library/classes/BlockDatabase.ts
I managed to get the records to be around 50 - 100 bytes, so 1MB should be able to store around 10 000 records.
ive been wondering, does entityExplosion damage type cause more durability damage than other types on shields?
its quite unknowable since explosions can damage shields in 1.21.80, but entityExplosion damage type was always able to damage shields durability before the change
what do i use instead of playerSpawn in 2.0.0-beta?
world.afterEvents.playerSpawn.subscribe should still work. That's what my experimental addon is using.
Straight from my addon:
// Grabs a player's name when they spawn in
world.afterEvents.playerSpawn.subscribe(event => {
Areas.Database.Names.savePlayerRecord(event.player)
})
does this only grab name as a string?
It's from a class:
/**
* Saves a players name and id for viewing later.
* @param player The player to save.
*/
public savePlayerRecord(player: Player) {
const playerId = player.id
const playerName = player.name
const key = `nameRecord.${playerId}`
world.setDynamicProperty(key, playerName)
const idKey = `nameRecordId.${playerName}`
world.setDynamicProperty(idKey, playerId)
}
also do u not see this
It's that I bit at the start, that's what was removed.
oh im so lost man
all im tryna do is define player bro π
why they changing all ts
IPlayerSpawnAfterEventSignal got removed, but that's a different class to PlayerSpawnAfterEventSignal
world.afterEvents.playerSpawn.subscribe(data => {
const player = Areas.Database.Names.savePlayerRecord(data.player)
so what am i doing wrong
i dont understand the new shit
playerSpawn hasn't changed.... Must be an issue with your database.
dont have a database
Your line of code above insinuates you use one.
what's the issue you're dealing with and what's leading you to believe it's playerSpawn that's causing it?
yeah i just took what he gave me
I probably shouldn't have shown you the code from my addon, that's my custom class.
Areas.Database.Names is completely custom.
You can do
world.afterEvents.playerSpawn.subscribe(event => {
savePlayerRecord(event.player)
})
function savePlayerRecord(player: Player) {
const playerId = player.id
const playerName = player.name
const key = `nameRecord.${playerId}`
world.setDynamicProperty(key, playerName)
const idKey = `nameRecordId.${playerName}`
world.setDynamicProperty(idKey, playerId)
}
the npm saying smt about it leavnig
leaving
Show your code
you can ignore that one then. As someone previously mentioned, it's just a name change and doesn't actually affect your code
js
import { world } from "@minecraft/server";
import { getScore } from "./config";
world.afterEvents.playerSpawn.subscribe((data) => {
const player = data.player
console.warn("text")
player.runCommand(`scoreboard players add @s season_one 0`)
if (getScore(player, "season_one") === 0) {
world.scoreboard.getObjective("season_one").setScore(player, 1);
world.scoreboard.getObjective("superj_ticks").setScore(player, 0);
world.scoreboard.getObjective("dash_ticks").setScore(player, 0);
world.scoreboard.getObjective("shoot_ticks").setScore(player, 0);
player.runCommand(`say joined first time test`)
}
})
i used this before
now it no longer works
is "text" getting printed?
nope
thats why im so confused
omfg
wait
LMAO
im not running the file in my main file
i might be stupid
welp, that would probably do it
π π
Forgetting the import? That's a classic, I do that all the time π .
i was so confused
heya
can i dm you?
.?setScore
Sure! I got your DM.
...
someone wanna try this?,
#1370349334016561253 message
That reminds me i need to to make 2.0 components
Video?
why is first line wrong? ``` form.show(player).then(res => {
if (res.canceled) return;
const [text, action, deleteBtn] = res.formValues;
if (!isNew && deleteBtn) {
ui.buttons.splice(index, 1);
player.sendMessage(`Β§cButton ${index + 1} deleted.`);
} else {
if (!text) return player.sendMessage("Β§cButton text is required.");
const newBtn = { text, action };
if (isNew) ui.buttons.push(newBtn);
else ui.buttons[index] = newBtn;
player.sendMessage(`Β§aButton ${isNew ? "added" : "updated"}!`);
}
saveAllUIs();
editButtonList(player, name);
});```
omg, I fixed a major issue in my code just by moving something from an independent system.run into my main function that also runs in a system.run, but the first one ran before the function's system.run
I don't see anything that's obviously wrong with any of those lines you've sent. It seems like the error is from something else further up; the RawMessageError is telling me that's likely the case.
My guess is that something is wrong with the other elements, like title, button, or any of the other methods, from the FormData group of classes.
I will recode everything π
I don't want to fix 126 files each over 500 lines of code π
Easy mistake to make
can we read the inside of the bundles now?
yes.
is there an event for when an entity gets loaded and unloaded?
ill check it
EntityLoad
EntityRemove
how do i make a line break on /kick
Use \n with your string.
common mistake
Try `line 1
Line 2`
Show your code. You are doing something that is causing it to not interpret the string the way you want it to.
can I do smth like this in with custom libaries?
Yes.
"metadata": {
"exports": {
"@easy": "scripts/extension/gravel.js"
}
}
right?
and in my tsconfigs
but its still not working
as far as TypeScript Compiler converts those paths, it is okay
am just doing normal /kick
no runCommand
If you need multi-line kick messages, you have to use runCommand
And combine it with enters instead \n
As in using the in-game function command? Are you not using a script? If so, then that would be the first issue.
what I do is to create a seperate package.json in a folder and just npm i ./folder. The name of the package.json will be used as the module name. It does require a bundler tho
if i do this:
const item = new ItemStack('osuea:rod_tier_two', 1)
how do i add lock in inventory keep on death etc?
yall am I doing this right (apparently not, but I should have fixed it) ```js
import { system, world, CommandPermissionLevel, CustomCommandParamType } from "@minecraft/server"
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
customCommandRegistry.registerCommand({
name: "dev:test",
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [{ name: "target", type: CustomCommandParamType.PlayerSelector }]
}, ({ sourceType, sourceEntity, sourceBlock }) => {
target.sendMessage(Success!)
})
})```
using @minecraft/server 2.0.0-beta
or do I have to use the alpha (fixed, yes I do)
nvm figured it out
hold on let me set my manifest to use an absurd script version so it yells at me and tells me what the right alpha is
alright I'm getting somewhere
I did NOT think that custom commands were moved to the base game already
but it seems to work to an extent
this will be very useful for me 
alright how do I put a defined parameter into the command callback
WHY IS MY CROSSHAIR A SPLASH POTION OF POISON NOW??????
thats pretty neat btw
its called a bug
-# which should've been fixed in preview
neat, I love making a bp/rp that completely destroys the textures
I made an rp and then like 50% of all the button textures were shifted (I think) and I didn't change any of them
anyway this is the thing I actually want to know
this is what I have now but target isnt defined for some reason js customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, cheatsRequired: false, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `dev:target`, type: CustomCommandParamType.PlayerSelector }] }, ({ sourceType, sourceEntity, sourceBlock }) => { target.sendMessage(`Success!`) })
is their a way i can detect if a player preses a button like f on their keyboard?
no
tf, this use ai?
no?
I'm just shit at js
please
just tell me how to use the parameter in my function
but why you add cheatsRequired, if you not using ai?
because bridge. says its valid
bruh
and minecraft doesnt yell at me
just add args
this is what I have now but target isnt defined for some reason js customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }] }, ({ sourceType, sourceEntity, sourceBlock },target) => { target.sendMessage(`Success!`) })
it's that simple?
but it isnt in the destructuring
how does that wor- whatever
I'll try it
this is what I have now js import { system, world, CommandPermissionLevel, CustomCommandParamType } from "@minecraft/server" system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => { customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, cheatsRequired: false, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }] }, ({ sourceType, sourceEntity, sourceBlock, initiator }, target) => { target.sendMessage(`Success!`) }) })
bruh
nothing
you can try this thoo,
#1370349334016561253 message
i give example on commands.js
here's what happened (ignore the resource pack thing idk how to fix it it happens every time I join a world now)
send main.js
your "add an argument" thing didnt work
import { system, world, CommandPermissionLevel, CustomCommandParamType } from "@minecraft/server"
system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => {
customCommandRegistry.registerCommand({
name: `dev:test`,
description: `Tests if this is working!`,
cheatsRequired: false,
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }]
}, ({ sourceType, sourceEntity, sourceBlock, initiator }, target) => {
target.sendMessage(`Success!`)
})
})```
thats it
on 3.0.0-alpha
why you use alpha version?
because it can't use the custom commands on the current beta, I tried already ._.
Then you messed up.
???????????????????????? how???
maybe I tried importing an invalid package due to bridge's autocompletions but damn
I'll try the beta again
Nah, you're wrong, in the latest version now, using the beta version, there is already a custom command
ok it does work on the current beta
i thing cheatsRequired property will already on 3.0.0?
but I still have the issue of not being able to use the parameters in the callbackfn
mc doesn't yell at me for using it so I'm keeping it.
okay
i went back to beta
how do I use the custom command parameters in the callbackfn
please
it's all I want to know
When is the next major update for scriptAPI?
Idk.
Have you read the docs?
this is JavaScript. Not typescript. And i already forgot where to find the other docs that aren't learn.microsoft and bedrock.dev
all the docs I find are in TypeScript
I DON'T KNOW HOW TO USE TYPESCRIPT!!!!! I CAN'T JUST CONVERT THEM LIKE THAT
Yeah you can.
you can use ai
I was trying so hard to not get mad but now I'm getting mad again because all you can tell me is to "use ts or convert it" and I can't do either. It's truly not that simple. I'm an incompetent idiot who can't goddamn convert two languages because I don't remotely know how one of them works. Is it really too hard to ask just to give me direct js instructions???

I would rather not.
But you literally can convert it...
Is it really too hard to read the docs?
You can literally just...remove the types.
Typescript is just JS...with types.
Or just learn TS.
you need to learn js again
I self taught myself mostly by looking at other scripts
._.
????
that barely makes sense to me
and I want my command to be in all one nice function, like I have been doing, instead of other object consts
which right now- js system.beforeEvents.startup.subscribe(({ customCommandRegistry }) => { customCommandRegistry.registerCommand({ name: `dev:test`, description: `Tests if this is working!`, cheatsRequired: false, permissionLevel: CommandPermissionLevel.Any, mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }], }, ({ sourceType, sourceEntity, sourceBlock, initiator }, target) => { target.sendMessage(`Success!`) }) })Looks like this. How is it so hard to get help here?
I very simply can't figure out how to use the custom command paramater "target" in the callbackfn.
that's all I want to know at this moment.
Thank you.
I would highly suggest reading this doc.
already did
like five times
still can't figure it out
what is alpha even for?
Literally nothing useable.
it's multiple annoying objects and no javascript
bruh it's not that hard
Why are you so allergic to multiple objects? Especially when you yourself do not understand the basics of JS you cannot be complaining.
Learn the basics, then read the docs.
To my adhd brain, I like defining the least number of things possible and condensing my code as much as possible
(which is why I also like destructuring so much and want everything in the custom command to be in one function)
function(player: Player, item: ItemStack);
by reading that you already know that you need a player class instance and an ItemStack one, ez
You might want to run away from JavaScript then. It's all about objects.
You cannot be holding yourself to this standard when you do not even understand or grasp the concept. It's like a student trying to simplify a matrix equation when they don't even know how to add or multiply them.
i know, and I can use them (mostly) fine but would rather not if I can have everything directly in the definition function
yeah, sure, so I just suck at this. Haven't I clarified this many times before? I'm trying.
Does apply knockback work on other entities
no
How can I create a dash skill of my entity using the dataDrinvenEntity?
Detect the event -> applyImpulse on the entity.
Does apply impulse works like tp or like knockback cause I don't want the entity to phase through blocks?
like knockback
it's basically identical to knockback
Thanks
I still get target is not defined!!!!!!!!! HOW. DO. I. DEFINE. THE target PARAMETER. AS. A. VARIABLE. I. CAN. USE. ```js
function test(target) {
system.run(() => {
target.sendMessage(Success!)
})
}
customCommandRegistry.registerCommand({
name: `dev:test`,
description: `Tests if this is working!`,
cheatsRequired: false,
permissionLevel: CommandPermissionLevel.Any,
mandatoryParameters: [{ name: `target`, type: CustomCommandParamType.PlayerSelector }],
}, test(target))```
#1067535608660107284 message
that's typescript.
So use an online tool to convert it to JavaScript. It has JSDOCS for you to read to better understand how to use registerCommand
I did my best to do what I count as "converting" some typescript to javascript but they look like they do the exact same thing and the js doesn't work.
Then you implemented that code incorrectly because it's already been tested on my end and confirmed working.
like dude how does this convert to js cleanly, the parameters aren't even remotely the same
where does it even pick up "targetPlayers"
You really don't know JavaScript do you?
you weren't here before were you
even then I don't have the frickin typescript code to convert to javascript in the first place, and if I try converting my current javascript to typescript it says "cannot use import outside of a module" or "system is not defined"
You have the code. I linked it above. Which contains written comments and jsdocs that explains what it is doing and how it works in the most simplest form possible.
fine, I'll try converting your code and working from there
Make sure you read it and study it so you learn from it. Otherwise it's all for not and you gain nothing.
so what I learned is that I need to have the origin parameter included as the first parameter in the function, it must be a seperate function, every parameter in the custom command probably has to be in order in the function args and don't need their name to match, and the namespaces must all be the same throughout the entire behavior pack, selector arguments must be iterated through.............................................. ok.
now I know.
Now I can continue what I wanted to do for this whole entire day. Which is make very simple custom commands instead of using a message prefix based system.
thanks for this though.
Doesn't have to be a function, but I find that it helps to keep it cleaner looking. That's mostly personal preference.
I still prefer using prefix messages over registerCommands. At least until they do something with namespaces.
Which they have.
it doesnt clear player properties though
No, only for world. Can't clear them from a player unless the player is online. Only other option is to edit the saved world file using an NBT editor of your choice and manually removing them. Otherwise, don't store on players and do so in the world using player id as the key for the value(s).
alr
speaking of DPs, what is the good way to cache them into memory?
I use pointers to keep memory usage low, storing only small amounts of data directly. The pointers allow me to quickly look up and retrieve the full data when needed.
may i ask how large the datas are?
My use case isn't large but it can get large if I wanted it to. Just haven't had the need to and in either case, I wouldn't want to impose on memory since it's limited.
i see, thanks
might have to start caching DPs into memory for performance since the current one uses world.getDynamicProperty() in runInterval
How to make someone stuck in first-person with only script API?
how do i stop people from opening chests, barrels, flipping trap doors etc
2.0.0-beta
nvm figured it out
Hey is there some way to have a branching command (like /fill) so I can make a setDynamicProperty command and let it set all 3 types of dynamic property seamlessly
or do I just have to put in a dreadful amount of logic like I do with message prefix based "commands" ._.
...or just make 3 different commands
after finally learning how to get them to run I'm on a roll with them but this gives me pause
-# I already tried registering an Enum with the different parameter types but that went about as well as you'd probably expect
For now I'll just make 3 different commands until I get an answer that would change it
Is there any way to kick the owner without bds with custom message?
Not sure what you're meaning by branching commands. If you're referring to subcommands, like how for the scoreboard command there's /scoreboard objectives and /scoreboard players, then they're not possible.
#1354481778278273246 message
its not working too, I did everything right... I think
"compilerOptions": {
"module": "ES2020",
"target": "ES2021",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true,
"baseUrl": "./scripts",
"rootDir": "./scripts",
"outDir": "./scripts",
"preserveConstEnums": true,
"experimentalDecorators": true,
"paths": {
"@easy": ["./scripts/extensions/gravel.js"]
}
},
"exclude": ["node_modules"],
"include": ["scripts"]
}
my file has a ts and a d.ts file
wait a god damn minute.
why does effectType from EffectAddBeforeEvent give translated strings as effectType
uhhhh????????
So my script can't run /allowlist on BDS, this is due to the permission level I am sure... so how do I make it so the command is run from the console permission level?
pretty sure any console level commands can only be executed in console
You can supposedly elevate the script to be able to use those
op-permission-level = 4
hmmmm never tried scripting in BDS before, so im honestly not sure
will this be fine?
try catch try catch
well how about this
1000 ms Hang lmao im gonna kill my pc
you can add a limit
are you for real , or a joke to crash my game
like i mean, i never used while (true ) so
for real
you can use a for loop if you think that's unsafe that much
bascialy im loading the chunk , but sometime it say error not loaded chunk, so when you fillBlocks again, it works the second time, and if it doesnt, again dooing works on the third time
this while loop is doing the same thing, but it'll stop checking for it when the function will be run successfully
if you would like to rate limit it, you can use:
const MAX_ITERATIONS = 3
for (let i = 0; i < MAX_ITERATIONS; i++) {
try {
system.runJob(fillBlocks(player, chunks, blockId, {}, count))
break
} catch {}
}
what if i want to do if first time fails, when its gonna start second filll, do waitTicks
like waitTicks on each iteration
what's the function/event called?
const MAX_ITERATIONS = 3
for (let i = 0; i < MAX_ITERATIONS; i++) {
try {
if (i > 0) system.waitTicks(1)
system.runJob(fillBlocks(player, chunks, blockId, {}, count))
break
} catch {}
}
i is a number of current attempt
β
can be spoofed
yeah, pretty easy to spoof
yep
cubecraft was using it at some point in there ban system, you can bypass that, not sure if they still using it
why would ever someone use this instead XUID
π
They still get around that just by mass producing accounts.
she is using it for some DB as a PK afaik
i dont have the db yet
is this good?
uiBuilder.register.actionformdata("main", "menu", (player, form) => {
form.title("Menu").body("lol why do u read this?")
.button("Test")
.button("Close");
return async (response) => {
switch (response.selection) {
case 0:
runCommand(player, "say lol");
break;
case 1:
player.sendMessage("BYE!");
break;
}
};
});
So someone sent me a script to set a scoreboard depending on what slot you are on here it is ```js
import { world, system } from "@minecraft/server";
const slotObjective = world.scoreboard.getObjective("slotValue") ?? world.scoreboard.addObjective("slotValue", "slotValue");
system.runInterval(() => {
for (const player of world.getPlayers()) {
const currentSlot = player.selectedSlotIndex;
const lastSlot = player.getDynamicProperty("lastSelectedSlot")
if (lastSlot !== undefined && currentSlot !== lastSlot) {
const score = slotObjective.getScore(player) ?? 0;
const d = currentSlot > lastSlot ? 1 : -1;
slotObjective.setScore(player, score + d);
}
player.setDynamicProperty("lastSelectedSlot", currentSlot);
}
});
the scoreboard objective name, the addObjective part should be the same because the code checks if objective exists, if it doesn't then it creates it to not cause issues
if you are 100% sure the objective will exist then you can remove ?? world.scoreboard.addObjective("slotValue", "slotValue"); if you don't want to cause confusion
Thanks I was asking cause there was two slotValue's in the addObjective
the second slotValue is for the display
its not an event listener.
ItemInventoryComponent
I cant find a doc on it rn
like how you get any component on an item
I forgot :<
look around.
its should be just inventory
in the changelog.
dang, thanks VoidCell
Is it possible to make me a script to increase the percentage of monstersβ respawn?
like java
respawn, do you mean spawning?
or spawning another one after death?
is there a method to execute
/event command
triggerEvent()?
Method triggerEvent in Entity class
Do you need docs?
oh my god scripting is so weird
can you check if the error is a unloadedChunkError
catch (error) {
typeof error === UnloadedChunksError
}```
that?
error instanceof ...
oh okay
pfft lol it spammed my chat
try {
player.dimension.fillBlocks(blockVolume, block, blockFillOptions)
} catch {
try {
for (let i = 0; i < 3; i++) {
if (i > 0) system.waitTicks(1)
player.dimension.fillBlocks(blockVolume, block, blockFillOptions)
break;
}
} catch (e) {
if (e instanceof UnloadedChunksError) {
world.sendMessage(`[WorldEdit] Failed to fill blocks for now, Chunks have been loaded now, Please try the same command again. For some reason, If it fails, It works the second time.`)
}
}
}
this is my try{} catch{} try{} catch{} spagghetti code
π i wanna run that sendMessage only 1 time
i think its for the iteration
I thought they added damage cancelation vai script api
How would I make it so if I'm on a specific slot it constantly does a command
import { world, system } from "@minecraft/server";
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
if (player.selectedSlotIndex === 1) {
player.runCommand(`say slot 1`);
}
}
}, 20); // run every 20 ticks
Thank you
moving from ! to slash commands is crazy
cuz now i have so much more boilerplate π
Yes, that's what I was talking about, and that's what I thought. At least there's enums. Thanks for the answer
It has much more built-in error handling and in-command autocompletions/parameter names. I think it's for the best that prefix based message commands be migrated to the new custom commands
It'll take a while, sure, but it's much better (and can also be used in /execute afaik)
no i agree
it took me like an hour or two to migrate
And I'm terrible at js but good thing most I need to do it copy-paste the callbackfn into the new custom command, link all the parameters, set up success/fail and returning messages, then remove the now unneeded error handling... still a lot but whatever
A worthy sacrifice to make
i mean most of my commands are admin only
Sure so you don't need as much error handling (is what I assume you need)
But otherwise I'm not sure what makes that different
Baaad idea lol
nuh uh i am a peak dev
Make sure the first parameter in the callbackfn is ALWAYS the origin parameter
That was my big mistake yesterday
i know
And nobody told me that was the issue I was having ._.
docs on this are kinda eh rn
I agree β οΈ
now i just need a decent version of getBlocks()
Was that removed?
Or changed?
I don't quite remember that method anyway
Hold on going afk Minato can probably help
nah it just returns positions of blocks instead of blocks
that what i love about jayly ones
most of the time there is examples
i use jayly docs
cool
getting a script to run bds in terminal was peak π
wait how does the operator permission work?
i have operator and i cant use commands with CommandPermissionLevel.Admin
Because it's GameDirector for operator players
docs say "Any operator can run this command, but NOT command blocks."
Idk then. Maybe it's trying to run in read-only, in which, wrap the code in a system.run
nah the commands just dont show up
If the commands don't show up at all then your entry script failed to load because there's a fatal syntax error
commands with any permissions show up
Yeah just set it to GameDirector please
Until Mojang fixes Admin
I guess
yeah changed it
Aight
i mean i have command blocks disabled so it doesnt really matter
Sure
Which one?
That looks like it may be related, for BDS that is, the configuration in server.properties when setting op-permission-level either 0 to 4 or simply not defining it at all. Try setting it between 2-4 and see if that resolves it.
This issue with permissions between BDS, Realms, etc, is partly why I believe they are removing isOp() and taking a different approach.
Operator Permission Levels (op-permission-level) β Minecraft Bedrock Dedicated Server
The op-permission-level setting in server.properties determines the default permission level assigned to players when using the /op command. This affects which commands they can use unless explicitly set in ops.json.
Level 1 β Basic Commands
Allows only non-destructive, informational, and communication-related commands. Ideal for minimal permissions.
Level 2 β Game Management Commands
Adds access to gameplay-related commands such as gamemode changes, teleporting, and giving items. Suitable for creative players or minor helpers.
Level 3 β Moderation Commands
Grants access to moderation tools like kicking and banning players. Useful for server moderators or staff.
Level 4 β Full Administrative Access
Provides full access to all server and management commands. Intended only for server owners or trusted administrators.
time to copy paste this to my docs if that's ok (with credits ofc)
hmm time to figure out if loading all the auctions to ram is better or calling the api
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const player = event.player;
const block = event.block;
if (block.typeId !== "minecraft:frame") return;
const inventory = player.getComponent("inventory")?.container;
if (!inventory) return;
system.run(() => {
inventory.addItem(new ItemStack("minecraft:emerald", 1));
block.setType("minecraft:air");
})
});
How to get the item inside of the item frame?
I had this problem and fixed it by doing .setOp(true)
^
im not sure if theres any component related with item frames
i might be wrong though
Any other way to do it?
I tried breaking the item frame and getting the entity, but no items dropped.
yeah im not sure either, sorry
Alright.
this is kinda a wierd one, if I remember right you can use the Block.getItemStack but you will be unable to detect if the item is an item frame in an item frame or a glow item frame in a glow item frame.
Not sure if it's been answered, but how do I spawn custom entities in the latest beta2.0 1.21.80 stable version?
I don't think the Dimension.spawnEntity function has changes between 1.0 and 2.0
it has between 1.21.70 and 1.21.80
Argument of type '"floating:text"' is not assignable to parameter of type 'VanillaEntityIdentifier'.
is that a type error?
I might've just accidentally discovered a fix but not sure yet as it's not showing a syntax error. The issue is custom entities aren't in VanillaEntityIdentifier because they're not vanilla
yeah, someone mentioned this error too before
kinda odd
what version of the npm package are you using?
so 2.1.0-beta.1.21.90-preview.25?
so the solution here is this, ```ts
(some_variable as Dimension).spawnEntity<"my:custom_entity">("my:custom_entity", { x: 0, y: 0, z: 0 });
cc @deep yew and @shy leaf
hmm

huh?
well, assuming your using typescript
its the typescript syntax for a type parameter/argument.
Types which take parameters
I just don't understand it yet
exactly. I just don't see why this simple function needs it and not just keep the old logic
but maybe it's a pre-fix for something later
it could be an oversight from devs
the reason its like that is for the completions here.
yes see I understand why I need to put the type parameter, because of syntax error. It's not a vanilla entity. I just don't understand the need for it in general
better dx
though 90% of the time it seems to me its more likely your spawning a custom entity
could have just dimension.spawnEntity("oraria:hitbox_connector" as any, location);
looks more neat
you can but thats less correct from a type pov, its side stepping the problem instead of solving it.
you could also just use <string> as the type parameter which would be looser I suppose.
yo @fallow carbon can you help me
if you state your problem instead of asking people to help you
basically im trying to make a leveling system that connects to different npcs for questlines and quest for players im making one piece and trying to do different quest for islands
this the script i have so far but nothing works
my bad
unless you can be more specific, error messages or something else I'll have to pass
theres a error ingame saying something about a typeId
when rightclicking on the npd
npc
so we are supposed blindly fix it? without knowing the problem ?
if you can provide the error
it would help
also the stack trace would be helpful
To know why the error is caused we need to see the code.
no you didnt?
world.afterEvents.playerInteractWithEntity.subscribe(event => {
const player = event.player;
const npc = event.target;
if (!npc.hasTag("quest_giver")) return;
const state = getPlayerState(player);
if (state.quest) {
player.runCommand(`say Β§cYou are already on a quest.`);
return;
}
// Find available quests for player's level
const availableQuests = quests.filter(q => q.minLevel <= state.level);
if (availableQuests.length === 0) {
player.runCommand(`say Β§eNo quests available at your level.`);
return;
}
const quest = availableQuests[Math.floor(Math.random() * availableQuests.length)];
state.quest = quest;
state.kills = 0;
player.runCommand(`say Β§bQuest Accepted: ${quest.name} - ${quest.description}`);
});
there nothing related to typeId
hmm
either the error is somewhere else
so what is the problem
idk try.
do you know how to see your content log @fresh current?
on minecraft?
yes
yea
wanna join vc
no
no
so when you open the game go in settings > creator > and enable content log gui
also put log level to info
mhm
thats the thing
that says
typeId when i try interacting with the npc
but
im doing homework rn so
thanks for your unaccommodating
theres a copy button or screen shot the error
you cant expect anyone to spoon feed you without even knowing where your mouth is
not spoon
just because we are unavailable to join a voice channel does not mean we aren't trying to assist you, its sometime a challenge but the process of gathering information and using that to form an answer is sometimes required (like in this case) and is not something we can do without your assistance, please keep in mind we have no obligation to assist you but are doing so anyways.
1 sec
this is also with the ui im making
an dthis happens when i right click the npc
so the error is happening in index.js at line 144
and the file that you sent only has 94 lines
index is my other file
yeah so if you read the error it explains where the error is coming from
Is there a method to check if the held item (itemStack) is a block?
Sounds like you need a library
Make a function with all minecraft block id and return if given id is in the list
This will be a huge library
typeId will return undefined if nothing is in your main hand.
yeah I'll just redesign the idea cause this is too much lol
thats a whole another script
try using getComponent('minecraft:equippable') instead of getComponent(EntityComponentTypes.Equippable)
the thing is
thats not what im trying to fix
thats a whole other system script
the script im trying to fix is the leveling system
then why did you send it π
because
he tlaking abt line 44
144
but that ha nothing to do with what im trying to fix
???
You can see if it resolves to a block type using the provided blocktypes.get (I think that's what it is) method. If it does it's a block
your content log error says index.js:144
you have an error in your code
omg yes
ill try that
if (event.player
.getComponent(EntityComponentTypes.Equippable)
.getEquipment(EquipmentSlot.Mainhand)?.typeId == "op_asa:cola") {
put this in your line 144 and see if it fixes
interesting
BlockTypes.getAll().some(t => t.id === item.typeId) works perfectly, thank you!
Might be worth putting these in a set to avoid iterating it each time but you would have to compare
oh will do
This ain't the place for that.
if your not calling it super often you could just do this.
function isItemStackABlock(itemStack: ItemStack): boolean {
return BlockTypes.get(itemStack.typeId) !== undefined;
}
(untested)
Is it possible for me to change the state of my block when hit by a wind charge like it happens with vanilla doors?
Not exactly because of the wind charge but also because of its explosion
.getEquipment(EquipmentSlot.Mainhand)?.typeId == "op_asa:cola") {
this is where ternery operator ? is much helpful
function isItemStackABlock(itemStack) {
try {
BlockPermutation.resolve(itemStack.typeId)
return true;
} catch { }
return false
}
that effectively does the same thing but requires a try catch?
not sure what your wanting me to see @prisma shard
yes, it does, but it does make use of try-catch which may not be desirable
ok π
both works
and it just seems to be an error on yours
when there is no item in mainhand
hmmm ? doesnt fix it
mine does'nt do anything with the mainhand so thats likely an issue in your testing code?
ok, here is my test and its results.
function a_isItemStackABlock(itemStack: ItemStack): boolean {
return BlockTypes.get(itemStack.typeId) !== undefined;
}
function b_isItemStackABlock(itemStack) {
try {
BlockPermutation.resolve(itemStack.typeId);
return true;
} catch {}
return false;
}
system.afterEvents.scriptEventReceive.subscribe((e) => {
if (e.id !== "f:test") return;
const items = ItemTypes.getAll().map((item) => new ItemStack(item, 1));
let s1 = Date.now();
let blockCount = 0;
let itemCount = 0;
for (const item of items) {
if (a_isItemStackABlock(item)) {
blockCount++;
} else {
itemCount++;
}
}
let e1 = Date.now();
let s2 = Date.now();
let blockCount2 = 0;
let itemCount2 = 0;
for (const item of items) {
if (b_isItemStackABlock(item)) {
blockCount2++;
} else {
itemCount2++;
}
}
let e2 = Date.now();
world.sendMessage(`a: ${e1 - s1}ms, b: ${e2 - s2}ms`);
world.sendMessage(`blocks: ${blockCount}, items: ${itemCount}`);
world.sendMessage(`blocks2: ${blockCount2}, items2: ${itemCount2}`);
});
function isBlock(itemStack) {
try {
BlockTypes?.get(itemStack?.typeId) !== undefined;
}
catch {
return false;
}
}```
try catch fixes it
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const a = player.getComponent(EntityComponentTypes.Equippable).getEquipment(EquipmentSlot.Mainhand)
console.warn(`fetchbot: ${isItemStackABlock(a)}`)
console.warn(`mine: ${isBlock(a)}`)
}
}, 20)
function isItemStackABlock(itemStack) {
try {
BlockPermutation.resolve(itemStack.typeId)
return true;
} catch { }
return false
}
function isBlock(itemStack) {
try {
BlockTypes?.get(itemStack?.typeId) !== undefined;
}
catch {
return false;
}
}```
heree's mine tested code
eh yours is better method
i'll replace your func with mine is it okay lol
I'm having a hard time figuring out how BlockTypes can be undefined for you because its exported from @minecraft/server
I don't like it when things break and start working and I don't understand why.
lol
in the function with BlockPermutation its because the resolve method will throw if it fails and in the isBlock i'm not sure since I haven't seen any errors on my end.
i need some real help in json ui :c
already asked in json ui channel, no help, so depres π π₯
please have patience, you asked just a few minutes ago and it seems like the json-ui channel is less active than this one (json-ui is perhaps more niche). it might be better form if you try and work it out on your own for a while, look at some tutorial, the bedrock.dev wiki, etc. and document what you have managed to work out and ask for guidance from there π
function isUnderground(player) {
if (player.dimension.heightRange.min > player.location.y) return true;
if (player.dimension.heightRange.max < player.location.y) return false;
let block = player.dimension.getTopmostBlock(player.location)
if (player.location.y >= block.y) return false
while (!block.isSolid && block.y > player.dimension.heightRange.min) {
if (player.location.y >= block.y) return false
block = block.below()
}
return true
}```
can anyone fix this function, It return error cannot read property 'y' of undefined, when going down the void
there are lots of y here
which line does the game say the error is on?
function isUnderground(player) {
try {
if (player.location.y < player.dimension.heightRange.min) return false;
if (player.location.y > player.dimension.heightRange.max) return false;
let block = player.dimension.getTopmostBlock({x: player.location.x, z: player.location.z });
if (!block) return false;
if (player.location.y >= block.y) return false;
while (!block.isSolid && block.y > player.dimension.heightRange.min) {
if (player.location.y >= block.y) return false;
block = block.below();
if (!block) return false;
}
return true;
}
catch {
return false
}
}```
I dont know but i am in love with try catch lmfao
Check if block is valid before checking for it's y
mkay
you should try and fix it, just relying on try-catch is opening you up to more issues down the road because an error is happening causing unexpected behavior
okay i am trying
-# jk with the trycatch
Yea, don't put a bandaid on it. That bandaid will eventually fall off π
there is a hole in the wall, lets paint over it π
well that one is valid if its a drywall
I mean, you should prob fix the hole first though π
it sounds like your bounds check is perhaps not correct then
comical method of covering the brick wall with a conveniently large canvas to hide a suspiciously hammer shaped hole
Validate the object before accessing the properties or methods in the object.
im going to crashout if i see another try catch
try {
crashout;
} catch {
discord.delete();
}
herobrine
funni how i realized it was a different code causing the error
Help me what is the name of the event player break block
Is it possible for me to change the state of my block when hit by a wind charge like it happens with vanilla doors?
world.afterEvents.playerBreakBlock.subscribe((event) => {
const { block, player } = event;
})
.isOp() isn't working in a dedicated server?
you need to make op level 4 in server.properties
there's no option for that
it's a bedrock edition or bds
don't use it
it'll be removed soon
I think it's already deprecated
I know it will be changed into something like player.PerrmissionLevel. However, I am lazy to change it into admin tag method for temporary
Additionally, the op level permission in custom slash command is also not working. It doesn't detect operators
How to make real time system also date month year
Jokes on you I'm coding using termux >:)
world.beforeEvents.chatSend.subscribe((event) => {
const { sender, message } = event;
if (message === "!data") {
const now = new Date(Date.now());
const day = now.getDate();
const month = now.getMonth() + 1;
const year = now.getFullYear();
sender.sendMessage(`${day}.${month}.${year}`);
}
});
is that what you meant?
use some function to check if player is an admin
const isAdmin = (/** @type {import("@minecraft/server").Player} */player) => {
return player.isOp()
}
π
will this work in bds?
isOp does not work correctly in BDS
use a tag or wait for new permission system
normally in the client world, we could use the reload command. However, we couldn't execute it and it said it doesn't meet the permission level to run it
you have to use reload via server's process (terminal)
at this point, you should use some tag to recognize an permitted user
rip
or you can always wait for new permission system
is there any way to change the permission level of an op in bds though?
but I don't know if you would like to wait for it
op-permission-level property in server.properties
highest value is 4
it doesn't exist
or should I put it myself?
it does exist, documentation does not include this
no problem
You can put it anywhere you want to? I usually pick something random at least 50,000 blocks away from (0,0) so it doesn't conflict with other add-ons and players aren't likely to find it accidentally
do you put it below the normal Y level? like the level the endsgone platform spawns
how big is the void there from 0,0 to the islands?
What's the beta version of server ui in Minecraft 1.21.80
2.0.0-beta
Help me fix code
No
Why?
Open a forum in #1067535382285135923 where you can share your code and explain what the issues are. Then wait and see if anyone responds.
I posted it now can anyone help me
Is chatSend still beta?
still beta
awh
ask again when gta 6 is out
how do I change the name of a player?
you can edit the nametag property.
you have to edit the chat message with beforeEvent chatsend I believe.
override message
cancel event and send new one
import { world } from "@minecraft/server"
world.beforeEvents.chatSend.subscribe((eventData) => {
eventData.cancel = true
world.sendMessage(`${player.name}: ${message}`)
})
nameTag
but yeah, that's how you do it
import { world, system, BlockPermutation, EntityDamageCause, EffectTypes, ItemStack, Component } from "@minecraft/server";
import { MinecraftEffectTypes } from './vanilla-data.js';
import { Perlin } from './perlin.js';
//FADED BUD: BEGIN
world.afterEvents.worldLoad.subscribe((initEvent) => {
initEvent.blockComponentRegistry.registerCustomComponent('deep_end:on_fall_on_faded_bud', {
onEntityFallOn(arg) {
if (arg.fallDistance >= 1) {
arg.entity.addEffect(MinecraftEffectTypes.Levitation, 9, {
amplifier: 50
});
arg.entity.addEffect(MinecraftEffectTypes.SlowFalling, 140, {
amplifier: 1
});
}
}
});
});```
[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at <anonymous> (deep_end_custom_block_components.js:5)[Scripting][warning]-Component 'deep_end:on_fall_on_faded_bud' was not registered in script but used on a block
So, apparently worldInitialize was deprecated
but I get these errors trying to update to worldLoad
what version are you using?
My @minecraft-server in the manifest is 1.19.0 and I'm on stable 1.21.80
what do I use for v2 components?
@tight bloom , I recommend to start porting everything to ScriptV2. https://learn.microsoft.com/en-us/minecraft/creator/documents/scriptingv2.0.0overview?view=minecraft-bedrock-stable Mojang has provided documentation on how to upgrade your scripts.
It seems that custom components v2 are only functional on preview?
Nope! You can use it in Stable via the experimental toggles.
Wait, really?
is there something new to put in the manifest? i can't find it in the docs page
You need two toggles enabled:
- Custom COmponents V2
- Beta APIs
I have that on the world
but the custom v2 component returns
| deep_end:faded_bud | components | deep_end:on_fall_on_faded_bud | child 'deep_end:on_fall_on_faded_bud' not valid here.
Can you open a post and post your Script and Block code?
will do
oh, I missed it