#Script API General
1 messages · Page 75 of 1
Yes
what kind of big changes does it have?
How can I get traits?
what?
these things from blocksjson "traits": { "minecraft:placement_position": { "enabled_states": ["minecraft:vertical_half"] }, "minecraft:placement_direction": { "enabled_states": ["minecraft:cardinal_direction"], "y_rotation_offset": 180 } }
why
because I need it
which information
the rotation
block.permutation.getState("minecraft:vertical_half")
I need some help
step 1: go to #1067876857103536159
step 2: ask there
if hes asking here, assume he asking how to get the states through script api...
turns out that was the case, if you read above.
make a post about it, and tell people what the issue is
I did
alr
Can someone give me an example for how to set particle colors using MolangVariableMap.setColorRGBA()? I'm having trouble actually changing the color value. Here's what I've got so far:
{
"format_version": "1.10.0",
"particle_effect": {
"description": {
"identifier": "structool:outline",
"basic_render_parameters": {
"material": "particles_blend",
"texture": "textures/particle/particles"
}
},
"components": {
"minecraft:emitter_rate_instant": {
"num_particles": 1
},
"minecraft:emitter_lifetime_once": {
"active_time": 1
},
"minecraft:emitter_shape_point": {},
"minecraft:particle_lifetime_expression": {
"max_lifetime": 1
},
"minecraft:particle_appearance_billboard": {
"size": [0.2, 0.2],
"facing_camera_mode": "rotate_xyz",
"uv": {
"texture_width": 16,
"texture_height": 16,
"uv": [6, 11],
"uv_size": [1, 1]
}
},
"minecraft:particle_appearance_tinting": {
"color": [1, 1, 1, 1]
}
}
}
}
Attempting to set color like this:
molang = new MolangVariableMap().setColorRGB("minecraft:particle_appearance_tinting",{ red: 1, green: 1, blue: 0, alpha: 1 });
overworld.spawnParticle("structool:outline", location, molang);
"minecraft:particle_appearance_tinting": {
"color": [
"variable.<name>.r",
"variable.<name>.g",
"variable.<name>.b"
]
}```
```js
const molang = new MolangVariableMap();
molang.setColorRGB('<name>', { red: 0, green: 0, blue: 0 });
Dimension.spawnParticle('<id>', location, molang);```
Mmm now they're flickering
Got it working thanks 👍
It was because I was expecting setColorRGB() to return the molang map but it's just void
Was in the script v2 video on the creator channel
anyone knows what is the difference between applyImpulse and applyKnockback?
knockback is affected by side effects such as the knockback resistance from netherite armor
Speaking about this subject, I just posted a question about it. But since it’s more a discussion based subject rather than a question it might be more fitting for this chat. I am trying to find the best way to smoothly adjust the player position by applying momentum. https://media.discordapp.net/attachments/1361837344755552469/1361837346198257944/Minecraft_2025-04-16_00-50-44.mp4?ex=6800355d&is=67fee3dd&hm=ca2762aafacf9e0f1b4bd0f3e8b5ecf7f9b98aecae238dbb37d38c6a5f2bfb2a&
this is what I got so far using applyKnockback.
that is really nice
That's really smooth.
I'd be curious if it can be done better.
It’s certainly usable but it is a bit jittery and player movement is not completely predicable. This is more apparent when actually playing of course.
I can see how the jitters would be bothersome.
Huh? No
It doesn’t change current event firing; it just adds extra events and how data is handled when the world is first loaded up
So we can get before entity hit?
no
I don’t see how that’s related to the world loading… if you’re asking if it’s still possibly being added, then yeah, no reason it can’t be added
entityHurt beforeEvents would be really nice
Yar
modifying damage would be great for configuration menus
please Mojang i beg you 
Took me 2 days to realize that my code wasn't working because I used inventory.length and not .size 😔
Thats why you should use Typescript 
its just util for lsp, js with jsdocs would work as well
Mmmm Typescript 
Weird when people try to act like a language is superior to others
Try using assembly next time
It's way better
Minor oversight. Bro did not read the docs.
Oh im just joking
It was muscle memory 😭
🙏 Muscle memory backfired.
but rust is superior than typescript
Binary on top
Why would I ever give attention to a language named after old and errodded metal smh
whst language
const objectiveNames = ["money", "top]
system.runInterval(() => {
for (const objectiveName of objectiveNames) {
const obj = world.scoreboard.getObjective(objectiveName);
if (!obj) continue;
for (const player of world.getAllPlayers()) {
const realScore = obj.getScore(player.scoreboardIdentity);
if (realScore === undefined) continue;
world.scoreboard.setScore("fake_" + player.name, objectiveName, realScore);
}
}
}, 100);
Error:
native variant type conversion failed. Function argument [0] expected type: ScoreboardIdentity | Entity | string at <anonymous> (index.js:31)
error is at obj.getScore() line
how to fix it?
chek for null
seems like player.scoreboardIdentity is returning undefiend
Is it possible to suppress vanilla blocks loot?
haha.
nyeh heh heh
I wonder if they're changing how API world loads work to prepare for dimensions and custom biome generation through scripting

why would they implement those via scripting
Guys, how do I specify the players if they accept string[] in PlayAnimationOptions
using player.id does nothing
I don't trust you, is that a genuine question or nah? 🤔
did you try there name?
can entities not be tamed by non-player entities via scripting?
Can entities tame other entities in the first place?
I don't think non-player entities can tame other entities
no effect 😭
hmm
I don't think that's taming, that's leashing onky
Oh, actually nvm, .name work, a mistake on my end 💀
Weird choice to use player name moyang
Providing the player instance imo would be better. hopefully changed in Scripting v2
Zombie apocalypse oh no.
yeah, it's unique to that entity.
I am tired of begging
Im going insane asking for this
it change from world to world
You're probably looking for "XUID"
💀
If I'm not mistaken it's supposed to be consistent across worlds but there are instances where it could change out of nowhere
oh so it's not as reliable as player.name
Tbf, even the player's name can't be reliable because it can be changed at any time. I still prefer the player's id
What are you trying to do
If your trying to grab offline scores and names I have a system for that
A advanced custom scoreboard class used to help Creators manager their scoreboards easier. - BubblesToGo/ScoreboardClassMCBE
is there an event for when an entity dies?
Hey for some reason onTick is not invoking on my custom_component. The block has tick component. loop, etc.
OnPlayerInteract is working...
Not sure why at all. I figured if OnTick wasnt working, onPlayerInteract wouldnt either.
Try adding the tick component to your block
https://learn.microsoft.com/en-us/minecraft/creator/reference/content/blockreference/examples/blockcomponents/minecraftblock_tick?view=minecraft-bedrock-stable
Im not sure, but it is needed
can 2.0.0 be used on realms?
Yes
The tick component is on my block. I can place my block via command, or by hand. and onTick invokes.
BUT it is not invoking onworldload.
Yet the onPlayerInteract works...
So the custom_event is registering properly. But the blocks onTick specifically. is not working. Even with the block tick component
@wary edge Hey! Any idea why a blocks custom_component may not register onTick, when the world is loaded!
So you place your block down then rejoiend the world?
yes
to be more specific. I am placing a block in v1.0.0
loading the world again with the pack on v1.1
exact same block
but with a custom_component
the custom_component is registaering properly. because onPlayerinteract worls
That seems like a bug.
damnnnn. ive noticed it a few other times in other instances as well. For example. i spawn a bunch of single blocks, via feature rules. All of the blocks work with onPlayerInteract. But only half or so are invoking OnTick. Should i make a ticket
Yeah, onTick has a 50/50 chance of actually ticking when placed via world gen.
This is a known thing? so it is a bug? any work arounds? maybe just respawning the block when in loaded distance
I know random tick still works so you could random tick and set the block again.
Good idea ty
Hey would this delete any dynamic property that has the string Voter:"random like a player id"
world.getDynamicPropertyIds().forEach((id) => {
if (id.startsWith(`Voter:`)) {
world.setDynamicProperty(id, undefined)
}
})
Can someone explain this error? [Scripting][error]-TypeError: not a function at <anonymous> (chat_cmds.js)
Side note, how to you add a new line on discord?
is there a way to make a custom projectile entity to rotate to the player view?
im using this
let launchVel = 5;
const velocity = player.getViewDirection();
let headLoc = player.getHeadLocation();
const proj = player.dimension.spawnEntity('ultra:revolver_bullet', {
x: headLoc.x + velocity.x,
y: headLoc.y + velocity.y,
z: headLoc.z + velocity.z
});
const projComp = proj.getComponent('minecraft:projectile');
if (projComp) {
projComp.shoot({
x: velocity.x * launchVel,
y: velocity.y * launchVel,
z: velocity.z * launchVel
});
}```
tried the methode that uses animations but it just rotate to the x axis for some reason
Yes.
Does anyone know how to increase the scale of an entity via script? 😔
ty
Not possible...
Scale's value property is read-only
It doesn't work.
Tho you could try it.
I may be wrong tho... :)
Only using entity events
You're adding velocity to head that's why.
Elaborate
With component_groups changing minecraft:scale you can scale the entity up. But with scripts I don't know
I don't need to elaborate, you're adding the value of the head and the value of the view direction of olayer
Arent they the same? (Idk nothin about how vel work)
Noo?
let launchVel = 5;
const view = player.getViewDirection();
const head = player.getHeadLocation();
const entity = player.dimension.spawnEntity('minecraft:snowball', { ...head, y: head.y + 0.1 });
const projectile = entity.getComponent('projectile');
projectile.shoot({ x: view.x * launchVel, y: view.y * launchVel, z: view.z * launchVel });
how to get a player from playerid
getPlayers()
ill check it out
It was working normally with arrows then when I switched to custom projectile it broke
it's entities animation then
Not the scripts...
interface EntityQueryOptions {
closest?: number;
excludeFamilies?: string[];
excludeGameModes?: GameMode[];
excludeNames?: string[];
excludeTags?: string[];
excludeTypes?: string[];
families?: string[];
farthest?: number;
gameMode?: GameMode;
location?: Vector3;
maxDistance?: number;
maxHorizontalRotation?: number;
maxLevel?: number;
maxVerticalRotation?: number;
minDistance?: number;
minHorizontalRotation?: number;
minLevel?: number;
minVerticalRotation?: number;
name?: string;
propertyOptions?: EntityQueryPropertyOptions[];
scoreOptions?: EntityQueryScoreOptions[];
tags?: string[];
type?: string;
volume?: Vector3;
}
i dont see id
Tried the suggested methode from the bot but it worked as the vid I sent so I wanted to know if I can fix it w modifying the script
ummjs for (const player of world.getPlayers()) { if (player.id === id) {} }
will getEntity work?
wouldnt it be better than whatever
this is
I just suggested
thanks tho
Should I ask in entities channel?
Resources packs is better.
Try checking arrows animation and models.
Other question, how can I make the proj go straight?
wdym straight?
Like doesnt go down like an arrow
Not affected by gravity
Like a bullet
put high velocity or make it don't have gravity in Entities file
Didnt think of that lol
Other other question, how can I modify its speed?
Wait nvm
the velocity in scripts
The variable you just made here.
Was gonna say if I do that then it will fall near the player but I can just disable gravity in entity file
Ty for your help
I finally started using the new custom command APIs. I really hope they come around to fixing the command descriptions, and adding the ability to type the command without the namespace
they said they might look into allowing the commands without namespace for none marketplace content
? Are you implying that they intended it only for marketplace use?
no, if they ever allowed custom commands without namespace, they will enforce the namespace to the marketplace guideline
give me a sec to look for navi comment
Oh you were just talking about the namespace requirement
yep
possible, using events only.
like "group_0" has the scale 0.1
"group_1" has the scale 3
"group_2" has the scale 7
etc, and via scripts, u activate those events by just entity?.triggerEvent('event:id');
does script api has isRiding an entity?
ridingOn component
no, but u can detect it by getting the riding component
getComponent
player get this component when he is riding somthing?
okey tysm
player?.getComponent('minecraft:riding') ig
How to set item in hotbar with "Item Lock" and "Keep on Death"?
'minecraft:riding'
const smth = inv.getItem(slot*);
smth.lockMode = 'inventory';
<slot|item>.lockMode = "inventory"
<slot|item>.keepOnDeath = true
Thanks
"inv" being a variable that stores the container class.
const inv = player.getComponent('inventory').container
Ok, thanks
Documentation for @minecraft/server
What's the problem with the description?
is there any good reason why BlockComponentPlayerPlaceBeforeEvent doesnt fire if you have a block that has an item?
can i lock chests using script api or like cancel the chest ui
Player interact with block before event
#1361731327145021500 message
Ahh, I also wish they'll add rawtext, I have send a message about that before lol
I want translation key on item Lore 😔
iirc the % works
Didn't confirmed it yet tho.
I'm starting to be a bit OA in making these custom commands better and easier for me to add instead of manually adding registerCommand().
I keep getting undefined from this, I am trying to target a certain entity and find out if it's holding an item. I've tried several different ways from the wiki to try and target the item, but nothing is working, any ideas what I'm doing wrong:
for (const entity of world.getDimension("overworld").getEntities({
families: ["cnb_ppl_emitter"]
})) {
const entityId = entity.id;
const equippable = entity.getComponent('equippable');
console.error(equippable)
if (!equippable) return;
const mainhand = equippable.getEquipment('Mainhand');
console.error(mainhand)
if (!mainhand) return;
if (mainhand.typeId === `cnb:cnb_ppl_particle`) {
const lore = mainhand.getLore()[0];
if (!lore) return;
//...
Unfortunately the 'equippable' component is disabled in entities.
The best thing you can do is the hasitem command or molang query in animation controllers
Ooooh ok Thank you, makes sense. Is there a way to figure out what item an entity is holding?
Oooooh ok
Wait... why did you change your name again? Hahha
Like a tag handoff through a function kind of thing?
I haven't changed it since April 1
yeah.
And it's better if you use animation controllers or function to run the command.
Not thru scripts.
Yeah i think its possible and needs script but you need some JSON along
Oh ok, I haven't talked with you since then. I assume, though it must have been something before since it used to be a reference to "Filipino" in some way as your bio says.
Ok, duly noted, thank you!
I haven't changed my bio, only my name lol...
And you'll be surprised at me having a blank display name lol
💀
nvm, just did it.
bro just changed his name llmao
What the what??? lol
uh
I hate not having one Soo yeah, I'll be reverting it.
Debug scripts bot not working :((
haha, Aaah there we go. That's the one I know. Anyway, thank you! I should have thought of that solution sooner.
Just one by one read your script.
hey coddy you free?
can u respond in DMs
Y...?
If you.. could help with making a addon....
i need some help w/ scripts
Hmm any ideas on how to unpack the lore? I have the item number stored in it. Maybe I can use the getcomponent(“inventory”) somehow?
itemStack.getLore()
Hmm ok thank you I’ll try it.
Did anyone answer you?
No but I can answer myself. It's because the scripting API is a total mess
how to disable watchdog
Don't
im working on a Chess AI
it does require a lot of computation power lol
im aware of the problem
Chess? Shyt I got PTSD on that
I encountered the same thing some days ago, it seem that block placer component only triggers the after event, do you need beforeevent for something specific?
so how to bypass the watchdog lol
i know its not a good practice but thats how chess engine works
The only knowledge i am bot sure to share lol
How much spike hangs do you get
Iirc there is a watch dog event under system.beforeEvents
Should be watchDog
system.beforeEvents.watchdogTerminate.subscribe?
Probably, try and see
for some reason when I add this event to the script it straight up wont load
I already imported from "@minecraft/server"
is it only in experimental?
running on stable
to alter the blockstate thats being place and prevent it from being placed when theres no solid block behind
also checking for a block face is solid is absolute garbage, such a basic thing and yet not decent way to do it (efficently)
was this reported? dont even know wheer this stuff could be reported
similar to .getRedstonePower() not returning power when block is next to a redstone block... scripting api is really a mess seems amateurish too there are way more of these quirks
you can do some stuff with itemuseon
not alter the blockstate part tho
actually no. even if you use that event the block still gets placed
so you do stuff twice if you for example place a block with item used
huh, well shit
lol
and cant even remove the block placer compoent as i need an item for 2d sprite and other item components stuff
and dont get me started on all the events.. if you add beforePlayerPlace component the player will swing its hand when clicking on the block empty handded... for some reason
Scripting is a mess indeed
and the onUseOn will make the hand swing ALL the times regardless of what player does. no context whatsoever...
not just scripting.
Ask the game for a minecraft:white_wool[color=red]
ah yes red wool that is....
oh animal mob family? yes that just contains goats
hardened clay? yup thats terracotta...
mob family? that has abunch of stuff including armor stand and NOT goats...
and why need for family whenthere are tags..
sorry for the rant but thisis all BS
Hey @spring axle , sorry for the ping.
Can you guys do something about this?
I am referring to the block placer component, It doesn't trigger BeforeEventPlayerPlaceBlock or Custom Components, it will be cool if it did or if not possible altar the placed block in the itemUseOn event? Either way we really need something done regarding this
You should upvote the bug report (I think @open urchin made one). He's already aware of this in the OSS.
To Do (Reopened)
Unresolved
I haven't made a bug report for it not working at all on BDS/Realms
fixed in custom components v2
the arm still doesn't swing though
fixed the whole bug or just stuff you replied to?
I haven't tested replace_block_item yet
the client clearly isn't recognising that the player has placed the block so it's not fully fixed but at least the code in beforeOnPlayerPlace is running
makes building with the blocks difficult since too many get placed
what
the issue that has been fixed is beforeOnPlayerPlace being broken (not ever triggering) on BDS
ah, you were talking about BDS
it is still broken with replace_block_item
How can i link my TS file to JS ?
the TS shows error when JS file is not open at the same time + the typings in JS don't show when TS file is not open at the same time
Whent i use getComponent()? it returns a bool?
/**
* @type {import("yourfilepath").yourinterface}
*/
const yourVariable = yourDatatype
something like:
/** @type {import("./BattlePassTypes").reward[]} */
const rewards = [
{
//assume a rewards object here
}
]
yo thank you very much!!!!
What component are you trying to get?
item cooldown
itemStack.getComponent('minecraft:cooldown')?.getRemaingTicks
is the component valid in that instance?
Wdym?
does the item have a cooldown component to begin with?
so then do isValid checks before trying to do anything with it 🤷
Ok thnk
i mean you can create your own events but they will be fired from existing components or events

Can anyone tell me why trying to set an entity enum property isn't working in this script?
theEntity.setProperty('wfir:prop', 'east')
It's trying to change the value of this property in the BP:
"properties": {
"wfir:prop": {
"type": "enum",
"values": ["north", "south", "east", "west", "up", "down"],
"default": "north",
"client_sync": true
}
}
I know the script is running, because there's another property that it's setting just fine. It's just the enum property that's causing problems. It stays the default and using setProperty doesn't seem to change it.
This doesn't seem to work with entities since items are equipped to hand once given to them. And it doesn't seem like there's a way to unpack Lore within their container. Maybe I'm missing something though, here's my code just incase:
const { container } = entity.getComponent('inventory');
console.error(container)
const itemStack = container.getItem(0);
console.error(itemStack)
const mainhand = itemStack.getLore()[0];
console.error(mainhand)
if (!mainhand) return;
I figured it out. setProperty value applies on the next tick, not the same tick.
How do I access the name of a block in scripting? For example, I'm after Oak Stairs, not minecraft:oak_stairs.
You can just convert it using a function. Split the words by _ and then capitalize the start of each word.
export function getItemName(item) {
return item?.nameTag ??
item?.typeId.replace(/.*(?<=:)/, '').replace(/_/g, ' ').replace(/(^\w|\s\w)/g, m => m.toUpperCase());
}
In 2.0.0 you can access the localization key if that helps.
That's probably what I want... how do I access that key?
i think it's preview only
Any idea where the documentation is for it?
is there a way to add features to vanilla biomes?
pretty sure ive seen addons do it, even if i imagine they were using hacks likespawning entities and such
what is the goto way?
This is a #1067869232395735130 question.
ah so this must mean there is a proper way of doing it nice
you can't get the entities' main hand item at the moment
you can only get their inventory
how could i check if a entity a player kills has over 80 health to then drop an item?
Yeah... That's what I thought. Too bad, I found another way anyway, thank you. Np
If player killed a mob that's over 80 health?
Current health or max health?
max, so anything that spawns with 80 health or up. trying to make it just bosses(and allowing it to include add on bosses) but excluding iron golem?
i think thats the only none boss type mob that spawns with over 80?
get the health component and check if their max health is greater than 80
Documentation for @minecraft/server
to exclude the iron golem, just check if the typeId of the entity is not iron golem.
Thank you!
Like how you did the inanimate object?
ye
no
Honestly sounds silly but I just want to ask:
Is it useless to just get the block permutation of each block in a structure and take a specific coordinate and use the structure blocks' relative locations to set each block using commands or scripts?
And if I wanted to use it for more controlled structure placement/animation, would it then be okay?
That would be slow, can't you just do it in one structure save?
I know it would be slow, but I was just wondering if it'd be better that way if you'd want it slow. Purposefully slow wouldn't hurt the server with more complex structures, even custom sized ones, I'd assume
I'm trying to get the block a player is looking at but it seems to be getting the wrong block
const blockRaycast = player.dimension.getBlockFromRay(player.location,player.getViewDirection());```
when i use the code it does not return the block that the player is looking at
pls help
oh wait nvm i fixed it
i was using the position of the feet 😆
getBlockFromViewDirection...?
i did not know that was a thing
now you know
people dont have autocomplete xd
ye its possible, but I mean word.after - beforeEvents. thtas prob impossible
yeah beforeEvents is impossible.
afterEvents are posible, if you need, i can give you my custom event script
yea
okay
u need?
yes
tho its incomplete
export class EntityHurtBeforeEventSignal extends EntityHurtBeforeEvent {
/** @type {Map<(data: import('@minecraft/server').EntityHurtBeforeEvent) => void>} */
listeners = new Map();
constructor() { }
subscribe(cb) {
const id = system.currentTick;
this.listeners.set(id, cb);
return id;
}
unsubscribe(id) {
return this.listeners.delete(id);
}
run(data) {
for (const cb of this.listeners.values()) {
cb(data);
}
}
}```
class EntityHurtBeforeEvent {
// properties
/**
* @type {boolean}
*/
#cancel = false;
get cancel() { return this.#cancel };
set cancel(v) {
if (v == true){
// code here to 'cancel'
}
return this.#cancel = v;
};
/**
* @type {number}
*/
damage;
/**
* @type {import('@minecraft/server').EntityDamageSource}
*/
damageSource;
/**
* @type {import('@minecraft/server').Entity}
*/
hurtEntity;
constructor(data) {
this.damage = data.damage;
this.damageSource = data.damageSource;
this.hurtEntity = data.hurtEntity;
}
}
const entityHurtEvent = new EntityHurtBeforeEventSignal();
WorldBeforeEvents.prototype.entityHurt = entityHurtEvent;
world.afterEvents.entityHurt.subscribe((ev) => {
const data = new EntityHurtBeforeEvent(ev);
entityHurtEvent.run(data);
data.cancel = true;
if (data.cancel) {
// code here to cancel
}
})```
ohhh
// Usage
world.beforeEvents.entityHurt.subscribe((event) => {
const { damage, damageSource, hurtEntity } = event
event.cancel = true;
})
import {} from "@minecraft/server";
declare module "@minecraft/server" {
interface WorldBeforeEvents {
readonly entityHurt: EntityHurtBeforeEventSignal;
}
export class EntityHurtBeforeEventSignal extends EntityHurtAfterEventSignal {
private constructor();
subscribe(
callback: (arg0: EntityHurtBeforeEvent) => void,
): (arg0: EntityHurtBeforeEvent) => void;
unsubscribe(
callback: (arg0: EntityHurtBeforeEvent) => void,
)
}
export interface EntityHurtBeforeEvent extends EntityHurtAfterEvent {
cancel: boolean;
readonly damage: number;
readonly damageSource: EntityDamageSource;
readonly hurtEntity: Entity;
constructor(data: EntityHurtAfterEvent);
}
}```
Typescript for custom Events
for typings
I use it everytime but I can't import it
oh, its bcoz to make sure it doesnt conflict with JS
I dont think you can import TS directly in JS
typescript is so much easier
why do I see in libaries ts files
patchy api
mc bedrock api
but I think it does smth
forms.js
forms.d.ts
but is it possible to make world.afterEvents.LOL
// for example, lets say this file is called "functions.js"
export function test() {
}
import { test } from './functions'
test()
With the new way minecraft load its world how can i make it run like so with worldLoad but i dont see how can someone show me an exemple
wdym?
When you import code from another file, it imports the entire file. If you are invoking anything in the scope of that imported file, that is your problem
e.g.
# a_thingy.js
import { world } from "@minecraft/server";
// This line may throw in 2.0 when this file is imported
const overworld = world.getDimension("overworld");
export function init() {}
# main.js
import { init } from "./a_thingy.js"
init();
import {world} from "@minecraft/server"
world.afterEvents.worldLoad.subscribe( () =>
World.sendMessage("test")
})
import "file.js"
import { test } from "./function.js"
test()```
okay if the line with the const overworld cause problem how can i solve it ?
You need to write more import-friendly code. I can only offer suggestions if you can share what error you are getting
Global variables.
let dimension;
world.afterEvents.worldLoad.subscribe(event => {
dimension = world.getDimension("overworld");
})```
global variables fix the overworld constant issue
which returns a have not required priviliges error
This works. That pattern can get repetitive, however. I would personally place those dimensions into another module that can be imported from elsewhere
anyone know how to make VS Code use globally installed types
npm i -g <package>
ye, I know how to install it
Oh if you mean make the VSCode 'use' globally installed type, just install it globally without opening any folder. Then you can use typings in any folder
but vsc isn't detecting that
I'm having the same problem lmao
I just realized
Does anyone know why my globally installed types don't work?
does anyone knows if Mojang has any plans to make scripts able to intercomunicate with scripts from other add-ons?
would be extremely useful
you can do that withscript eventss
yea
wait, how?
there is scriptEventRecieve event
trigger event and listen to the event
/scriptevent se:example
but I cant like:
addon 1 with an input
addon 2 with the function, returns the result to addon 1
u can also filter based on source
wdym
and import files from other addons
why not just put the file on that other addon too
acts like import
u can pass basic string args
because if I needed to update the file I would have to update it in all projects
instead of just one
how?
oh, can you getDynamicProperty between different addons? because iirc dynamic property saves in UUID, and different addon has different UUID
Well this is where libraries come in.
YES
Yeah
thats it
lol
^
I wanted to make a library for my projects
🙂 I recommend learning how to publish libraries to NPM and utilise that.
I've done so with my adk-scripts-server library.
u will need to sync that across packs
i see
by the way
is constant arrow function better than functions
I have no idea where to begin with lol, can you point me to a starting point, please?
but like how do you use this on a minecraft addon
but u will need to install lib to every project
And then bundle it.
npm i <package>
import {} from "@your/package"
you use like that in your addon
import your custom lib
I never knew this was possible lol
I'm going to check more about this
if any of you guys have any tips or idk, youtube tutorials or websites that teach this it would be extremely useful
How to make your own NPM package (Step-by-Step) 📦
🧠 Resources
tsconfig.json and tsup.config.ts: https://gist.github.com/notunderctrl/e1f51dc0207d2ba19e723be71b5eecec
🌐 Important links
Discord: https://ctrl.lol/discord
Github: https://github.com/notunderctrl
Patreon: https://patreon.com/UnderCtrl
Buy me a coffee (one-time donation...
but either way thank you all very much for all the info!!
If anyone knows anything about this, let me know
how do i modify the durability of an item using scripts?
get the durability component.
Documentation for @minecraft/server
I recall them removing support for it a while ago. Don't ask me when 😅. @honest spear may know? Hopefully I'm not confusing myself with something else entirely 🫡
it doesnt seem to be workin
import { world } from '@minecraft/server';
import { hasLoreInHeldItem } from '../../../utils/utils.js';
const potato = true
function tryApplyReinforcement(player) {
if (!hasLoreInHeldItem(player, 'reinforced')) return;
if (potato) {
const inventory = player.getComponent('minecraft:inventory')?.container;
if (!inventory) return false;
const selectedSlot = player.selectedSlotIndex;
if (typeof selectedSlot !== 'number') return false;
const item = inventory.getItem(selectedSlot);
const durability = item.getComponent('minecraft:durability');
console.log(durability.damage)
durability.damage -= 1;
player.playSound('random.orb');
player.onScreenDisplay.setActionBar('§r[§bReinforced Item§r]');
}
}
world.afterEvents.playerBreakBlock.subscribe(({ player }) => {
if (player?.isValid()) {
tryApplyReinforcement(player);
}
});
world.afterEvents.entityHurt.subscribe(({ damageSource }) => {
const attacker = damageSource.damagingEntity;
if (attacker?.isValid() && attacker.typeId === 'minecraft:player') {
tryApplyReinforcement(attacker);
}
});
set the item back in the slot to save the changes made to the itemstack.
oki
There is no way, VSCode has deprecated this feature but you can change the path to the directory where globals are installed to be at the parent folder for your projects in that case it works as intended
inventory.setItem(selectedSlot, item)
put it after the changes
looks like sprunkles suggested the same 2 mins ago.
tysm!
ah mb, i didnt see that
its alr
Make a check for zero durability.damage (because if you try to set it less than zero you will get an error). and I also think it would be better to increase durability in percent, not just by one
And remove this useless line
tysm!
how to make floating text?
The easy way is to use an entity with a nameable component: always_show to true.
- A custom entity is preferable. But that'll require a resource pack to be rendered correctly.
- A vanilla entity could work without any new resource pack, but you'll be editing a vanilla file.
I did it
why Math.clamp() isnt a thing
Shouldn't be hard to implement using max() and min()
ikr
but why it isnt just a native method
const clamp = (val, min, max) => Math.min(Math.max(val, min), max)```
we have to do this for clamp
atleast even a 1 line matters
Math.clamp() would be lot simpler
Math utils class
where
*make
lol
Is not a big problem...
You can actually delay players' clients to update their surroundings lol.
By overloading the client by sending and using player.spawnParticle, you can have them see a few seconds ago in the past.
Other player's perspectives would be normal. And it doesn't have any significant impact on TPS
Oh wait i must check out minecraft/math
now add lerp :))
what is the error ?
world.getAllplayers()return an array of all online players... basically[ player, player, player ]
You fed that to the objective.getScore()... it doesn't want array
change questScore === 1..9999999 to questScore >= 1
?
thanks
Is it bad to have lots of global properties on a world?
I'm not sure if there is such thing as badly polluting the global scope
Mb I'll make a post
i was saying 1.99999 is weird as he used it on the code
^
uhh
type error not a function: const dimension = world.getDimension("overworld");
is world defined?
import { world, system } from "@minecraft/server";
The line before it?
show the full code
static generatePlotArea(plot) {
world.getDimension("overworld");
what does this throw in V2 if it is in the global scope
interesting... 🍿
it would just throw a privilege error no?
const dimension = world.getDimension("overworld");
const startX = plot.pos1.x;
const startZ = plot.pos1.z;
const endX = startX + plot.size - 1;
const endZ = startZ + plot.size - 1;
const y = PlotAPI.baseY;
for (let x = startX - PlotAPI.roadSize; x <= endX + PlotAPI.roadSize; x++) {
for (let z = startZ - PlotAPI.roadSize; z <= endZ + PlotAPI.roadSize; z++) {
const inPlot = (x >= startX && x <= endX && z >= startZ && z <= endZ);
const isEdge = (x === startX || x === endX || z === startZ || z === endZ);
const block = dimension.getBlock({ x, y, z });
if (!block) continue;
if (inPlot) {
block.setType(PlotAPI.groundBlock);
if (isEdge) {
const fenceBlock = dimension.getBlock({ x, y: y + 1, z });
fenceBlock?.setType(PlotAPI.fenceBlock);
}
} else {
block.setType(PlotAPI.roadBlock);
}
}
}
}```
in a class
not sure
Where are you calling the method
wdym?
where are you calling class.generatePlotArea()
Is it on early execution scope?
"whats that"
lol
yea
Have you tried system.run()
no
The same thing but fancier
hmm? no
system.run evaluate the call to the next tick
world load wait for the world to actually load
await null;
NO
now here: PlotAPI.createPlot("plot_" + Date.now(), player.name, pos1, pos2);
ive heard someone say not to use that.
They still exit early execution. And getDimension should work regardless
or nvm
i doubt that
🥀
they are just mad;
sure...
I shall test if remembeh.
-# And win this 1:00 am issue later
what's that
make a quest tsystem
class to make plots
okay
and why is it gone?
i miss read done with gone
"Max verstappen" 🙏 😭
brainrot final boss
How do i make a function act like callback with properties
Visual example pls because my brain can't comprehend the ambiguity
detectJump((player) => {
console.log(`${player.name}`)
})
of what
here i want to get the player property
whereAs the detectJump is a function
and it will act like callback
How do i
make it a variable?
variable = function ((player) => {
player.jump();
}
function detectJump(callback) {
// code
callback(/* params */)
}
welp
There are apparently no errors in your code. Mojangs don't like that.
-
callbackArray
-
detectJump(callback)
- callbackArray.push(callback)
-
the jumping logic
- gather value to pass:
info - callbackArray.forEach
- callback(info)
- gather value to pass:
lol, you jumped in without knowing the context
is that gud or nah
i think u lost
You win this time
import { system, world } from "@minecraft/server";
console.warn(`world loaded at ${system.currentTick}`);
try {
world.getDimension("overworld").runCommand("say Hello World!");
console.warn(`world.getDimension() at ${system.currentTick} with no errors`);
} catch (error) {
console.warn(`world.getDimension() at ${system.currentTick} with errors`);
console.warn(error);
}
try {
system.run(() => {
world.getDimension("overworld").runCommand("say Hello World!");
console.warn(`system.run() at ${system.currentTick} with no errors`);
});
} catch (error) {
console.warn(`system.run() at ${system.currentTick} with errors`);
console.warn(error);
}
world.afterEvents.worldLoad.subscribe((event) => {
console.warn("World Initialized");
world.getDimension("overworld").runCommand("say Hello World!");
});
Yay.
function detectJump(callback) {
world.afterEvents.playerSpawn.subscribe((event) => {
const { player } = event;
callback({ player: player })
})
}
What did you want to know?
You're adding new listener everytime you run that
How do i pass the properties of the events, to the function ?
you can create a const outside the event callback then update the const with the data
we were arguing if system.run skip early execution
So that the properties of the event inside function, can be used in the callback like that:
detectJump((event) => {
const player = event.player
})```
How
const Listeners = []
function detectJump(callback) {
Listeners.push(callback)
}
system.runInterval(() => {
for (let player of world.getAllPlayers()) {
if (player.isJumping && player.isOnGround) {
for (let callback of Listeners) {
callback(player)
}
}
}
})
function detectJump(callback) {
let player = undefined; world.afterEvents.playerSpawn.subscribe((event) => {
const { source } = event;
player = source;
});
player.jump();
}
Thanks
there's playerButtonInput afterEvent
the Detect Jump is a example-
autojump exists
player.jump() ???
also why set player undefined?
event listener inside a function without unsubscribe
sound like a bad idea
One way road
well, the game crashing is the unsubscribe
how
Some of my global types do work for some reason tho
can we export global part
That's not 1.999 it's 1..999
-# blind?
I forgot, high serty.
What is the best way to visualize a shrinking border?
- Singular Particle Walls (billboard)
- Individual particle effects
- Custom Barrier Blocks
- Other method haven't listed
Thank you.
particles is better imo...
Can you send me an example of creating a manifest.json file for the script. I can't find it anywhere and I can't do it, it gives an error
tho not individual, just use one particle where it adjusts in xyz
-# not advertising...
The last time I tried to access this it was removed, that's why I asked
Thanks again
Ohh I changed the repo that's why
from com_project into manifest_generator lol
lol
I already have a particle set up, but I cannot spawn outside of loaded chunks. Did you just spawn it in whenever the player got close?
yes
how do i make vsc auto compile
tsc --watch will compile automatically when files change. If you use package.json in your project then you can add that as a script:
"scripts": {
"watch": "tsc --watch"
}
Then excute in your terminal npm run watch. Or just execute the command itself, but that script is good to have if others contribute.
Is there an entity animation event thing that can be triggered to make player swing it's hand?
hello, you knew how I can put my effects in percentage from 1 to 100% then make it so that when I put the scoreboard streng to 5 it gives 5% easily
Oh srry
is there a way to load/unload chunks?
EntityHitEntity and EntityHitBlock
And no it can't detect hitting the air, either animation controllers or use old versions of script.
which I doubt you wil
I examined myself wrong. I want to trigger the player swing animation
If I wanted to do this I would just raytrace with item use event
playing the animation? If that's what you meant, then no. It uses the variable.attack_time value to show much swing it plays, since it doesn't have value obviously the attack animation don't play.
So there's no way to make the player hand animaution play at will?
ticking areas?
recreate yourself, or create new animation and copy the attack animation and instead of using variable.attack_time use entity properties, the value is from 0.0 to 1.0
wait, lemme look
I have the hardcoded values made by Minato before.
{
"format_version": "1.8.0",
"animations": {
"animation.steve.swing": {
"loop": true,
"animation_length": 0.2917,
"bones": {
"rightArm": {
"rotation": {
"0.0": [0, 0, 0],
"0.0833": [-5.41199, 23.06265, 5.38894],
"0.125": [-13.31634, 36.7612, 56.32978],
"0.1667": [-58.11073, 6.44931, 8.72102],
"0.25": [-28.77157, -5.28699, -10.94791],
"0.2917": [0, 0, 0]
}
},
"leftArm": {
"rotation": {
"0.0417": [-8, 0, 0],
"0.1667": [-16, 0, 0],
"0.2917": [-8, 0, 0]
}
},
"body": {
"rotation": {
"0.0417": [0, 0, 0],
"0.1667": [0, 7.5, 0],
"0.2917": [0, 0, 0]
}
}
}
}
}
}```
y'know how to use Blockbench right?
Can addons modify the player like that tho? I thought we couldn't alter vanilla stuff
Can
- Entities
- Certain Items(Any food items or those found in the windowsapp folder)
- Entity loot tables
- Features
- Feature Rules
- Biomes
Can't
- Blocks
- Block loot tables
- Items not found in the windowsapp folder
- Dimensions
.
Let me clarify, addons for the marketplace, I thought there was a policy where vanilla stuff shouldn't be overwritten and in my understanding to add an animation I would need to overwrite something no?
why are you overwriting it?
You can just add animation in the animations folder and play it using the playanimation command or playAnimation() API in scripts
Oh I see I see
I barely did anything outside of scripting, I need this because the interact events are so dumb and either always play the swing anim unconditionally or just don't play it at all
is there any way to check the effect of a potion itemStack?
const effectName = item.getComponent('potion').potionEffectType.id
[Scripting][error]-TypeError: cannot read property 'subscribe' of undefined at <anonymous> (main.js:556)
world.beforeEvents.worldSave.subscribe(() => {
i guess you can using tickingareas?
will have to look into it
it has no native method for add ticking areas
you do
runCommand(`add tickingarea ~~~ true`)```
smth like that it was
how will i remove it
"worldSave" isn't correct
It's saying that worldSave is undefined
/ not correct
worldSave doesnt exist?
It's not a thing
There's worldLoad in 2.0.0-beta, but no worldSave
If you're using AI. I suggest using Mistal AI's Le Chat
It doesn't make stuff up (most of the time)
Yes, I tried to add something in cpt, cpt is corrupted.
Guys Help
How can I create a ItemStack with a Specified Potion, Like a regeneration potion??
Wait that doesn't exist in the 2.0.0-beta.. do I need to use the newest beta for experimental
🤷♂️
I dont know which versions are experimental or stable :(
2.0.0-beta = experimental
1.18.0 = stable??
Well, im using the 2.0.0-neta and installed the npm of it but it doesnt gets shown
maybe the npm is wrong, i got:
@minecraft/server-ui@2.0.0-beta.1.21.70-stable
@minecraft/server@2.0.0-beta.1.21.70-stable
wait
ughhh
I see it
Still thanks for helping
Heh, it's always been a static method. Everyone falls for that
I'm currently storing logs for my chestlog addon in global properties, 1 property per chest. How bad is this, and is there a better way to store it? It's on a realm or I'd store it externally...
how do i cancel whatc dog thing with script
system.beforeEvents.watchdogTerminate.subscribe(data => {
data.cancel = true
})
thx serty
how
just say how
just dont write a namespace
^facts
that's it...?
i think
doesn't it return an error when you don't write a namespace?
it does
then how did you do that
ok ima reveal the method
u just do this
const command = {
name: "hello::::world",
description: "bruh",
permissionLevel: 0
}```
and make the colon invisible
good to know.
A partial subcommand technique
wtf
how tho
just do
/effect : invisibility infinite 0 true
Does that automatically get parsed to be invisible?
uhh
im too stupid
wouldn't that mean you'd have to make a command for each effect
or you change the glyph texture?
ig you did...
but wouldnt you still need to type ::::
yes
People playing on their phones will thank you.
they sure will
is chatSend not a stable thing?
No.
Have a beta-api pack read it and pass it through script event to your stable api pack 💀
Wait you might have told actually the real way to do this
cool
Ah, yes, the obviously redundant and ridiculously stupid concept is being approved. I'm so proud of myself
Set a players hunger, is that something accessable through the components?
no it isn't possible with scripts
however you can add the saturation effect or hunger effect to the player
saturation might heal them up to full hp tho
Thank you
Yes, Thank you
how do I import a ts file
declaration files
Aww men, someone said it before me :(
this is real?
what?
try reading typescript
yes its real
Do you have a example on how its done?
import {
system,
world,
} from "@minecraft/server";
system.beforeEvents.startup.subscribe((init) => {
const helloCommand = {
name: "creator:hellocustomcommand",
description: "Celebration super party hello",
permissionLevel: 0,
optionalParameters: [{ type: 1, name: "celebrationSize" }],
};
init.customCommandRegistry.registerCommand(helloCommand, helloCustomCommand);
})
function helloCustomCommand(origin, celebrationSize) {
world.sendMessage("Hello Custom Command!");
if (celebrationSize) {
system.run(() => {
for (const player of world.getPlayers()) {
player.dimension.createExplosion(player.location, celebrationSize);
}
});
}
return {
status: 0,
};
}
from https://github.com/microsoft/minecraft-scripting-samples/blob/main/custom-commands/scripts/main.ts
Seems to not roll any dice for me
but why herobrines chestui is using typescript or why patchyapi is using typescript?
your probably looking at the type bindings
if u can't import it
Which helps you see how functions are used
How to write a high-quality TypeScript Declaration (d.ts) file
ohhhhh
thx
And btw, you tried it on phone?
I need to be on the beta 😔
i thought you are into something, lol
scuffed is an understatement
lol I can import ts files
you are talking about minecraft or third party software
When i break a block how can i test if the crop was fully grown or not
Permutation
growthState
myb the max growthState is 7
Check if its 7 so that can u know if its fully grown
So block.permutstion.growth() ?
no
My intrnet bkx broke so doin this shit on phone is aids rn
no
block.permutation.getState('..')
ya i was talking abt that lol
It doesn't work like a PC, it doesn't have the same effect
And yes, I used the font and 4 :
Says getState of undefined im lost
block.permutation.getState('growth') === 7
@dawn zealot
console.error(JSON.stringify(block.permutation.getAllStates()));
Check the state block has.
getAllStates is undefined
i remember u as i seen you as a Command guy somewhere, Osuea
?
idk ignore it
Then the block isn't defined.
But it is
Get it using block property in playerBreakBlock event
Or getBlock() if outside event
Pretty sure your just trying to detect growth when broken
world.beforeEvents.playerInteractWithBlock.subscribe(({ block, player }) => {
console.error(JSON.stringify(block.permutation.getAllStates()));
});```
Okay, why not just send the code
Its on my pc
My wire to my internet box broke waiting to get replaced
So using data
noo? brokenBlockPermutation you mean?
oh yeah
block.permutation()
and brokenBlockPermutation property
Isnt it same thing it returns?
4k quality
and what does it return?
17k subs and no screenshot button
Cannot read property getAllStates of undefined at anon
Internet box broke bud, no need for the comment
apologies sire
block doesn't exist anymore, that's why I said use brokenBlockPermutation
console.error(JSON.stringify(brokenBlockPermutation.getAllStates()));
What?
block property dont exist anymore?
There difference with block and block property my guy.
Read first...
Same error
Try this @dawn zealot
But what if its broken
its a afterevent
I only need broken
just try it first pls?
brokenBlockPermutation exists, it's separate to the block property
Still undefined
Are you sure you're editing the right file? Are you sure that the block has permutation?
Never been aware of that
Its wheat and yeah
Since in the first place it should work, you can't tell me otherwise since I'm literally using it rn.
try sendMessage() to actually check if you're editing right file.
what is your version
Bro i am😭
and are you using the beforeevent
then what the fuck.
Yeah
code?
2.0.0-beta
before or after? Pls one answer.
It would be block.getAllStates()
Cant provide it from my pc as my internet box broke, im using data atm
no.
It's under permutation, pls read docs first.
👆
I already said
no
source?
... before event
And? Doesn't change the fact it's under permutation not block my guy.
I'm talking about this lol
that ain't valid lmao
Right do how am i supposed to test if its broken if im using interact event then
huh
block.permutation.getAllStates() not block.getAllStates()
show me in the docs where thats stated
excuse me, what?
He told me to use playerInteractWithBlock event
Thats what i asked in the first place😭
You guys are making Coddy frustrated
Just answer directly
Why argue
Ohh no someone didn't read docs
lol
"" show me in docs where its stated ""
Like literally?
That just for testing lol
You asked me for my source and I gave you one, now... Give me yours for saying block.getAllStates()?
Right... so then how do i test if the crop was fully grown when broken..?
what's the id does console returns for the growth?
world.afterEvents.playerBreakBlock.subscribe((event) => {
const { player, brokenBlockPermutation } = event;
console.log(JSON.stringify(brokenBlockPermutation.getAllStates()))
})```
since the console will return list of permutation available on blocks, if you find one use it in getState('<name>')
{"growth":0}```
{"growth":5}
Then use growth.
block.permutation.getState('growth') === <value>
Use a beforeEvent, if the growth is below 5, then use event.cancel = true
I don't think he's canceling it, he just needs to check if it's in that state before broken.
Ty.
Np, dont worry about these other trolls, sometimes they feel like they are inherintely better than others for no reason
brokenBlockPermutation is not in the before event in V2
ohh shit, I'm scared...
bro asks for source and gave him and I'm the one who's wrong? Oh noo.
guys I'm bored what to code
Tbh, I talked to you properly but I guess you took it seriously? Then it's not my fault lol
Why are you being such a ass, just help the guy. Stop trying to bait me into a arguement thanks
-# that what he did
if you say sooo...
why is the item undefined?
try {
const currentId = event.itemStack?.typeId;
console.warn(`[setItem] Used item: ${currentId}, target: ${itemId}`);
if (currentId === itemId) {
func();
}
} catch (e) {
console.warn(`[setItem] Error: ${e}`);
}
};
anyway @dawn zealot brokenBlockPermutation is in the afterevent
sorry about the misinformation
just the debug version
I got it ty👍
I do have another question tho
wait, I can use the this. in the function() right?
Is their an efficient way to check like lets say a 3x3 area around the broken crop instead of typing out each coordinate?
sure
make an array of all directions eg
const directions = [
{x:1,y:0,z=0},
{x:1,y:0,z=1},
{x:0,y:0,z=1},
{x:1,y:0,z=0},
{x:-1,y:0,z=0},
{x:-1,y:0,z=-1},
{x:-1,y:0,z=1},
{x:1,y:0,z=-1},
]
loop through them and add them to your block location
Oh god lmao
world.afterEvents.playerBreakBlock.subscribe(({ block, player }) => {
const { x, y, z } = block.location;
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
for (let dz = -1; dz <= 1; dz++) {
}
}
}
});```
-# oof, lag will say hi to you...
i mean... you could simplify that
const offsets = [];
for (let dx = -1; dx <= 1; dx++) {
for (let dz = -1; dz <= 1; dz++) {
if (dx === 0 && dz === 0) continue; // skip center
offsets.push({ x: dx, y: 0, z: dz });
}
}
-# not referring to what coddy sent
I guess it would be better, if I just make this into a class. Tbh
I get it but i dont rly understand how to use it
Is there a place for all afterEvents and beforeEvents?
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.WorldAfterEvents.html
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.WorldBeforeEvents.html
Thanks!
the links I sent u are not beta btw
you are fast
light speed
I literally had those 2 tabs already opened lol
lol
Yk the thing u sent above how do i like use it?
add them to your block location and get those blocks
const allClaims = getAllClaims();
let insideClaim = null;
for (const [name, claim] of Object.entries(allClaims)) {
if (
hasFlag(claim.flags, CLAIM_FLAGS.LOG_ENTRY_EXIT) &&
isPositionInBoundary(claim.start, claim.end, { x, y, z })
) {
insideClaim = name;
break;
}
}
export function isPositionInBoundary(pos1, pos2, target) {
const [xMin, xMax] = pos1.x < pos2.x ? [pos1.x, pos2.x] : [pos2.x, pos1.x];
const [yMin, yMax] = pos1.y < pos2.y ? [pos1.y, pos2.y] : [pos2.y, pos1.y];
const [zMin, zMax] = pos1.z < pos2.z ? [pos1.z, pos2.z] : [pos2.z, pos1.z];
return (
target.x >= xMin && target.x <= xMax &&
target.y >= yMin && target.y <= yMax &&
target.z >= zMin && target.z <= zMax
);
}
For a claims plugin that logs whenever someone enters a claim, is this bad practice? I'm using some code from this chat way back. This runs on the playerButtonInput afterEvent so I'm not sure if this is bad... like I get tons of claims will cause issues, but say like 30 claims
import { world } from '@minecraft/server';
world.afterEvents.playerBreakBlock.subscribe((event) => {
const { brokenBlockPermutation } = event
if (brokenBlockPermutation.type.id !== "minecraft:wheat") return;
if (brokenBlockPermutation.getState('growth') !== 5) return
const blocks = getHorizanal3x3Blocks(event.block)
for (const block of blocks) {
//...
}
})
function getHorizanal3x3Blocks(block) {
const { x, y, z } = block.location
const blocks = [];
for (let dx = -1; dx <= 1; dx++) {
for (let dz = -1; dz <= 1; dz++) {
if (dx === 0 && dz === 0) continue; // skip center
Blocks.push(block.dimension.getBlock({
x: dx + x,
y: y,
z: dz + z
}))
}
}
return blocks
}
I feel like I'm always reading the wrong docs, but is there a reason I can't use this on the beta? I just want to check if a player is in creative
(I'm running this inside the before block break event)
world.beforeEvents.playerBreakBlock.subscribe(e => {
const player = e.player
const player = e.player.getGameMode()
})```
Thank you! I'll give it a go
any example using getBlocks method?
Not working