#Script API General
1 messages ¡ Page 18 of 1
git gud
I mean it works just fine (ignore the fire, I keep doing my particle tests using one of my blocks that explode on contact)
top block always have more weight
let say we have
[
red,
green,
blue
]
the script should mix the colors like red3 + green2 blue*1
that is almost what the beam particle is doing in that equation
check the view direction, if that works for you
updated it a few minutes ago so several instances of the same color would still increase it's value
Can we prevent players from equipping netherite armor?
Is there a way to cancel minecart chest inventory?
Access to?
I mean the only thing I can think of is disabling it entirely through json file (not sure if that's possible)
Does interactWithEntity not work?
Is there a before event?
I must have missed it if there is now
Oh wait
I'm sorry I meant hit
I guess we do have that
Dang that's funny
Does anyone know why sometime, it say log that it cannot get location?
Lots of time it works, but sometime it say this for no reason. How to fix?
whatcha trying
Whatever you're getting the location from is undefined
It just effect entity in 10 block on fire. But sometime it doesn't work for no reason
post code
But I don't understand, how?
Something like a raycast can return undefined result if it didn't find anything. Check if things are there or not. Share code?
e.itemComponentRegistry.registerCustomComponent("evo:ember_blitz", {
onUse(e) {
const player = e.source;
const xyz = player.location;
const dimension = player.dimension;
player.startItemCooldown("custom", 20);
player.playSound("mob.blaze.breathe");
let nearbyEntities = dimension.getEntities({
location: xyz,
maxDistance: 10,
excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
});
nearbyEntities = nearbyEntities.filter(entity => entity !== player);
nearbyEntities.forEach(entity => {
entity.setOnFire(7, true);
entity.runCommandAsync("effect @s wither 5 1");
entity.runCommandAsync("particle evo:ember_blitz ~~~");
});
}
});
which line is the log pointing at?
The }) below particle command
This hapens when the entity handle is invalid. So in js, the object apears normal but there is no entity that it actually represents. This can happen when you execute something on an entity that has already been despawned. You can check if the handle is valid with entity.isValid()
isnt that line 58
Same with container slots btw
ohh, but I still don't understand, how is entity despawn? In picture, pig is close and not despawn
im assuming setting them on fire kills the entities and fails to run commands
Yes sorry,, it is the forEach(entity) line
But entity is not set on fire?
or
It was just an example, there could be other reasons for it having an invalid handle. For exaple if the chunk is not loaded. But thats not the case here... you must be missing something
wait
Yes is very confusing
If I do in a group of pigs, sometimes one pig will do error but others will work fine. I don't understand
hmmm
e.itemComponentRegistry.registerCustomComponent("evo:ember_blitz", {
onUse(e) {
const player = e.source;
const dimension = player.dimension;
player.startItemCooldown("custom", 20);
player.playSound("mob.blaze.breathe");
let nearbyEntities = dimension.getEntities({
location: player.location,
maxDistance: 10,
excludeTypes: ["minecraft:item", "minecraft:xp_orb"]
});
nearbyEntities.forEach((entity) => {
if (entity == player) return;
entity.setOnFire(7, true);
entity.runCommandAsync("effect @s wither 5 1");
entity.runCommandAsync("particle evo:ember_blitz ~~~");
});
}
});
can you try this
Ok
Are there any molang queries (except for q.scoreboard) that I can change using scripts, for player or item to be specific
So I want to dynamically change my elytra's color but idk how to except with using queries but idk which query to use since idk what can I change about the elytra or the player that the queries can detect
i dont think theres a direct molang query that can change the elytras color dynamically
maybe use animation controllers?
Does anyone know of an app to take a picture of my map?
Same, I've found it's great for understanding theory of algorithms and such. I wouldn't personally use it to write code though as that'd make tracing bugs a nightmare
Blocktopograph maybe?
fun fact: blocktopograph is a popular application and it is developed by my friend đ
blocktopograph in outdated long ago
who is your friend
which version of blocktopograph?
Aw bro, don't I know blocktopograph is outdated a long ago?
I meant that, my friend has updated the blocktopograph completely to the latest version.
.
When the owner was discontinuing, he handovered the app to my friend. Because its source code. And can be lead by public.
.
my friends name is "NguyenDuck"
he is in this server
alr
that not the original creator
but it seem his version is the latest
https://github.com/NguyenDuck/blocktopograph/releases/tag/v0.0.1-dev.10032024
Yes, I said his version is latest
And I already said he's not the original creator
"When the original owner was discontinuing, he handovered the app to my friend. Because its source code. And can be lead by public."
Does anyone know how to add money to a button, for example there are 10 buttons, if you press any button it will show money and the money will increase
how do we use PlayerInputPermissions class?
try this one```js
async function moneyForm(player, money = 0, formValues = [-1, true]) {
const moneyValues = [5, 10, 20, 50]
const form = new ModalFormData()
form.dropdown(Current Money: ${money}\n\nMoney Value, moneyValues.map(String), formValues[0])
form.toggle("Add / Remove", formValues[1])
const res = await form.show(player)
if (res.canceled) return
formValues = res.formValues
money = formValues[1]
? money + moneyValues[formValues[0]]
: money - moneyValues[formValues[0]]
return moneyForm(player, money, formValues)
}
Ohh thank
here's another onejs async function moneyForm(player, money = 0) { const values = [-50, -20, -10, -5, 0, 5, 10, 20, 50, 100, "Done"] const form = new ActionFormData() form.body(`Current Money: ${money}\n\nMoney to contribute:`) values.forEach(n => form.button(`${n}`)) const res = await form.show(player) if (res.canceled) return const value = values[res.selection] if (value === "Done") { //code player.sendMessage(`Money: ${money}`) return } return moneyForm(player, money + value) }
Do you think its good to use typescript?
Yes
think its an option or more of a necessity?
optional
script-api mainly uses js files
TS needs to be compiled into JS anyway
For me, a necessity
for precision
Using typescript is the best thing you can do to write good code and save yourself time, I would never consider making an anything in plain JavaScript now that I know typescript but if you don't already know JavaScript then it will be twice the frustration.
Start with JS and learn typescript when you feel like you know the basics
Wdym?
to reduce errors
Is there a way to automatically connect to a websocket?
Like in the background esk way
No. The game will only accept the command if the player types it in
Damm
Why?
prob security reasons
;/ Hmmm
ty guys using ts đ
function getItemCount(player, itemId) {
if (!itemId) return 0;
let itemCount = 0;
const inventory = player.getComponent( "inventory" ).container;
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem( i );
if (item?.typeId == itemId) itemCount += item.amount;
};
return itemCount;
}
system.afterEvents.scriptEventReceive.subscribe((event)=>{
const {id: text, sourceEntity: player} = event
const Score = `money` //name objective
const item = `minecraft:emerald` //typeId item
const count = getItemCount(player,item)
if(text == "gwim:open") { //detect when use text run code
const Deposit = new ModalFormData()
.title(`Deposit`)
.slider(`Select Amount Of Emeralds To Deposit\nCurrent: ${count}\nChoose: `, 1, 64, 1)
Deposit.show(player).then(async (rs) => {
const { canceled, formValues } = rs;
if (canceled) return;
const [a] = formValues;
if (a > count) {
player.sendMessage(`Quantity must not exceed the number of items available`);
player.playSound(`note.harp`,{pitch:1,volume:1});
return
}
player.runCommandAsync(`scoreboard players add @s ${Score} ${a}`);
player.runCommandAsync(`clear @s ${item} 0 ${a}`);
player.sendMessage(`Deposited, +${a}$`);
player.playSound(`random.orb`,{pitch:1,volume:1});
})
}
})
i tried this but it didn't work :(
what modules do i need to import into my manifest ?
if possible can someone make this into a full addon and send it ??
also the /scriptevent gwim:open doesn't work :(
i want it to work in npc as well
and if i right click a stick then also the ui opens
any errors?
Debug result for [code](#1067535608660107284 message)
Compiler found 6 errors:
[36m<REPL0>.js[0m:[33m20[0m:[33m24[0m - [31merror[0m[30m TS2345: [0mArgument of type 'Entity' is not assignable to parameter of type 'Player'.
Type 'Entity' is missing the following properties from type 'Player': camera, inputPermissions, isEmoting, isFlying, and 23 more.
[7m20[0m Deposit.show(player).then(async (rs) => {
[7m [0m [31m ~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m24[0m:[33m15[0m - [31merror[0m[30m TS2365: [0mOperator '>' cannot be applied to types 'string | number | boolean' and 'number'.
[7m24[0m if (a > count) {
[7m [0m [31m ~~~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m25[0m:[33m20[0m - [31merror[0m[30m TS2339: [0mProperty 'sendMessage' does not exist on type 'Entity'.
[7m25[0m player.sendMessage(`Quantity must not exceed the number of items available`);
[7m [0m [31m ~~~~~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m26[0m:[33m20[0m - [31merror[0m[30m TS2339: [0mProperty 'playSound' does not exist on type 'Entity'.
[7m26[0m player.playSound(`note.harp`,{pitch:1,volume:1});
[7m [0m [31m ~~~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m31[0m:[33m18[0m - [31merror[0m[30m TS2339: [0mProperty 'sendMessage' does not exist on type 'Entity'.
[7m31[0m player.sendMessage(`Deposited, +${a}$`);
[7m [0m [31m ~~~~~~~~~~~[0m
``````ansi
[36m<REPL0>.js[0m:[33m32[0m:[33m18[0m - [31merror[0m[30m TS2339: [0mProperty 'playSound' does not exist on type 'Entity'.
[7m32[0m player.playSound(`random.orb`,{pitch:1,volume:1});
[7m [0m [31m ~~~~~~~~~[0m
There are no errors from ESLint.
no :(
function getItemCount(player, itemId) {
if (!itemId) return 0;
let itemCount = 0;
const inventory = player.getComponent( "inventory" ).container;
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem( i );
if (item?.typeId == itemId) itemCount += item.amount;
};
return itemCount;
}
system.afterEvents.scriptEventReceive.subscribe((event)=>{
const {id: text, sourceEntity: player} = event
const Score = `money` //name objective
const item = `minecraft:emerald` //typeId item
const count = getItemCount(player,item)
if(text == "gwim:open") { //detect when use text run code
const Deposit = new ModalFormData()
.title(`Deposit`)
.slider(`Select Amount Of Emeralds To Deposit\nCurrent: ${count}\nChoose: `, 1, 64, 1)
Deposit.show(player).then(async (rs) => {
const { canceled, formValues } = rs;
if (canceled) return;
const [a] = formValues;
if (a > count) {
player.sendMessage(`Quantity must not exceed the number of items available`);
player.playSound(`note.harp`,{pitch:1,volume:1});
return
}
player.runCommandAsync(`scoreboard players add @s ${Score} ${a}`);
player.runCommandAsync(`clear @s ${item} 0 ${a}`);
player.sendMessage(`Deposited, +${a}$`);
player.playSound(`random.orb`,{pitch:1,volume:1});
})
}
})
This is a modified script ig
I want it so that if a player right-clicks a stick or interacts with an npc (npc has the following command "/scriptevent gwim:open")
What i want is that a form opens, with a slider in increments of 1 upto 100
If playwr selects a amount and clciks the deposit button, then the amount is added to the "Money" scoreboard
If player has less emeralds than the amount selected then it shows an error
(emerald are the currency that you deposit)
send full code
import { world } from "@minecraft/server"
world.afterEvents.itemCompleteUse.subscribe(yef => {
if (ev.itemStack.typeId == 'av:armor_potion') {
yef.source.runCommand('function armor_potion')
}
})
If i drink the potion why doesn't work the function
"yef" , "ev"
Oh okay thanks
Yup still not working even i changed it
import { world } from "@minecraft/server"
world.afterEvents.itemCompleteUse.subscribe(yef => {
if (yef.itemStack.typeId == 'av:armor_potion') {
yef.source.runCommand('function armor_potion')
}
})
Is there any wrong with my code?
import { world } from "@minecraft/server";
world.afterEvents.itemCompleteUse.subscribe((yef) => {
if (yef.itemStack.typeId === 'av:armor_potion') {
yef.source.runCommandAsync('function armor_potion');
};
});```
Any errors?
const heatexplode = {
onHitEntity: target => {
const hitEntity = target;
const onfire = hitEntity.getComponent("minecraft:is_ignited");
if (onfire) {
onfire.applyDamage(20);
onfire.extinguishFire(true);
}
else {
hitEntity.setOnFire(10);
}
}
}
Hi. If I wanted to damage entity on fire, what should I edit from this code?
check dm
I get the idea of browsing 'is_ignited' tag from that 'getComponent' but no idea of testing it
Im guessing there are no known bypasses?
How can I do something like this?
hust download addon for hook
They are not that good quality and neat
I don't think that the "eventData.blockTypeRegistry.registerCustomComponent" works anymore.
Does anyone know a solution?
Change blockTypeRegistry to blockComponentRegistry.
player.inputPermissions() anyone know how to use it
True
is it possible to get the collision box of an entity? for context i'm trying to detect if an entity touched a side of a wall
hi, what are the advantages of using ts over js? in what cases it's more reasonable to use ts?
Type safety, easier collaboration
player.inputPermissions.cameraEnabled = boolean;
player.inputPermissions.movementEnabled = boolean;
thx
i see, thanks
Thank you, it works!
is there a way to set stuff in players armor slots with the inventory for loop check?
Anyone know how youâd go about making a player slow fall through a block
Like a web perhaps...
yeah exactly lol
I know of no components for that.. ancient mojang secret.. but if I had to make one.. I'd put a web inside of a block entity that can breath in blocks with no collision that did not move...
that is where I would start
That sounds nice but then the texture
player may see the web once inside tho. Texture the entity block thingy. and if for a custom world with NO webs... we ll, invisible the web texture
other idea, is to play with trying to figure out how they do the web. maybe it's a slow looping tp down pixel by pixel for each entity in web
Sure there is no way with apply knockback and a repeating timer until out of the block
block would need to check for entities within it's borders and do stuff to them
or entity
If entity.location === block.location possible?
no... block has no decimals.. would need some vector math... block has block.center and you can range out from there to check.
do test by putting your creative self in a block and getting the locations
build a chat command to show you
oh and also that statement would not work because those are object pointers, not values
an idea.. if the collision for the block was in permutations, such that an onStepOn, would release the collision and tag them... just a badly fleshed out idea
and you have to make sure breathable
const areSameLocation = Object.values(entityLocation).map(Math.floor).every(
(value, index) => value === Math.floor(Object.values(blockLocation)[index])
if (areSameLocation) {
}
no more decimalsđ
yes (not in the version that you coded)
but not always accurate depending on negative and positive coords. I'd take the center of the block to be safe
math.abs?
I cannot explain the details, I've just had to deal with working around that fact a lot.
not actually becouse negative cords are accurate too becouse the block is in negative but also the player so it does always get it right
best to demonstrate for yourselves by going to 0,0 and the blocks around it and getting the information to make sure your calcs ring true
I'd rather truncate the center of the block
x0 y0 z0 is a block the blocks nearby are all different, and math.floor always rounds lower so if 1.9 it will round it to 1, and -2.9 will be rounded to -2
its the same thing
I added the different functions to the players location in my F3 info pack.
When I am dead center in the block, rounding has me at same x,z, but when I shift over a tiny bit, rounding shifts me completely as on another block, tho technically I am on both.
I need to test from positive side...
what does this error mean? note i havent touched script api since 1.12.0-beta 1.21.0 rn im on 1.13.0-beta
rn its 1.14 beta for minecraft and 1.15 beta for preview
it tells me the available ones r 1.13.0-beta and 1.2.0 or 1.20.0-alpha i forgot which 1
but that wouldn't explain my error anyway
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]
Hey guys! Check this out đ
https://discord.com/channels/523663022053392405/1279200325643010138
any idea why this doesnt work still no errors. everthing but changing the permutation is working
im working on addon setup for bds server, and for some reason my server won't recognize my addon inside the servers dev beh and res folders
is there somewhere i need to specifiy something?
nvm ill follow protocol info
recognized packs kind of file
awh ok thx
found it thx at the bottom didn't see lol
world.afterEvents.itemUse.subscribe((data) => {
const item = data.itemStack;
const player = data.source;
const cooldown = item.getComponent("minecraft:cooldown");
if (item.typeId === "bm:strength_mirror" && cooldown.cooldownTicks == 1800 && cooldown.getCooldownTicksRemaining(player) == 1800) {
player.runCommandAsync("/function strength_effect");
cooldown.startCooldown(player);
}
});```
for some reason the script doesnt work
unless i remove the
```&& coolddown.getCooldownTicksRemaining(player)``` part
though i need that part so the item cant be spammed
Can anyone help
if you console warn that part, what shows up?
how do i do that, could you show me an example
console.warn(coolddown.getCooldownTicksRemaining(player))
and just chuck it before the if statement
ok, thanks
[Scripting][warning]-1148
[Scripting][warning]-1138
i keep getting these numbers that count down from 1800, but in ticks i think
Well that sure doesnât equal 1800, thatâs for sure
it starts at 1800 and anytime i click it throws a different number, but its desecnding
sorry, i think i changed the code, i removed the 1800 and changed it to zero
Throw a msg inside the last block to make sure it made it inside the last if.
Also, you are setting the state to a constant number, did you confirm that it was not already 1, maybe a log message on that too as the msg inside the last if block.
No the default is 0 I had a message in the block the last attempt and it was fine I'm not sure what's going on with it. I have a question thing open but I've not gotten anywhere since
I'm just try to even get the perm to change. It's not the full code I'm trying to do it's just a test for now
Did you say you have a post for this? Not sure if that is waht you meant.. if so, link? if not, can you make one and load your test pack. I can load it and trouble shoot it.
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]
Installation for @minecraft/server-ui
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]
Using .teleport, what do I have to input in the teleportOptions dimension property? I'm trying to tp a player to the End and can't figure out what needs to be inputted
world.getDimension()
That worked, thanks!
import { world, system } from "@minecraft/server";
function initializeScript() {
console.warn("da script has bean initialized");
}
function repairItemDurability(item) {
if (item && item.getComponent) {
const durability = item.getComponent("durability");
if (durability && typeof durability.damage === "number" && durability.damage > 0) {
const maxDurability = durability.maxDurability;
durability.damage = 0;
item.setComponent("durability", durability);
return true;
}
}
return false;
}
function scanAndRepairInventory(player) {
if (player && player.getComponent) {
const inventory = player.getComponent("inventory");
if (inventory && inventory.container) {
let repairPerformed = false;
for (let i = 0; i < inventory.container.size; i++) {
const item = inventory.container.getItem(i);
if (repairItemDurability(item)) {
repairPerformed = true;
}
}
return repairPerformed;
}
}
return false;
}
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
scanAndRepairInventory(player);
}
}, 1);
world.afterEvents.itemUse.subscribe((event) => {
repairItemDurability(event.itemStack);
});
world.afterEvents.itemUseOn.subscribe((event) => {
repairItemDurability(event.itemStack);
});
initializeScript();
can anyone tell me why this isn't working?
Debug result for [code](#1067535608660107284 message)
Compiler found 0 errors.
ESLint results:
<REPL0>.js
11:19 error 'maxDurability' is assigned a value but never used @typescript-eslint/no-unused-vars
Debug result for [code](#1067535608660107284 message)
Compiler found 0 errors.
ESLint results:
<REPL0>.js
11:19 error 'maxDurability' is assigned a value but never used @typescript-eslint/no-unused-vars
Um is it possible to make the armor enchant even your already wearing it?
yesh
I try every command and it didn't work i guess its a script
can i set runInterval time with decimal point like this system.runInterval(() => { }); }, 16.67)
no the game ticks are 20 per second you cant add decimals, if you type 1.9 it will run on tick 2
ty đ
is there a better way to make an in-game timer?
he's having a problem where the time desyncs by going a little bit faster than normal
Timers module
setTimeout(), setImmediate(), and setInterval() simple replica for Minecraft Bedrock Edition script APIs (experimental).
Usage
import { setTimeout } from "./timers.js";
setTimeout(() => {
console.log("Hello World");
}, 1000);
Compile & Test
Compile only
tsc
Unit test (include tsc)
npm run test
that is
donât think that will work
you should need the timers.js file
i saw minato doing some thing with timers he probably knows
i think setTimeout should work
can you elaborate
it will run things like console.warn) in non ticks, but ingame action will be ran always in ticks
setTimeout(()=>{
}, 10)
idk if that works but this should be a 10ms timeout
I think I havenât updated the file
Can I just say a quick giant thank you to you sir! Your resources are absolutely amazing!
wait is that a new thing on script?
Itâs a JavaScript thing not a Minecraft thing
really?
setTimeout exist in js?
i thought its in only script api
Are you being real?
system.runInterval(() => {
seasonHandler()
const worldTimer = world.scoreboard.getObjective(`WorldTimer`);
const seconds = worldTimer.getScore('seconds');
worldTimer.setScore('seconds', seconds + 18)
}, 20)
function seasonHandler() {
const worldTimer = world.scoreboard.getObjective(`WorldTimer`);
const seconds = worldTimer.getScore('seconds');
const allPlayers = world.getPlayers();
if (0 <= seconds && seconds < 48592800) {
allPlayers.forEach(player => {
player.sendMessage('1')
});
} else if (48592800 <= seconds && seconds < 97601600) {
allPlayers.forEach(player => {
player.sendMessage('2')
});
} else if (97601600 <= seconds && seconds < 146188800) {
allPlayers.forEach(player => {
player.sendMessage('3')
});
} else if (146188800 <= seconds && seconds < 195481200) {
allPlayers.forEach(player => {
player.sendMessage('4')
});
} else if (seconds === 195481200) {
worldTimer.setScore('seconds', 0)
}
}``` seasonHandler doesnt work ;-;
how can i fix it?
when sending the code please do
'''js so the code gets colors
oh ty
are you sure 195481200 is a number that 18*x can reach?
specifically does the function run or its a problem that runs not as intended?
Just not running season handler
idk the code is fine, but i can get you a better version to stop using scoreboards that are trash
Better version?
yeah your method is not good scoreboards arent useful, and minecrat has its own time so you dont have to calculate it with a scoreboard
I want make custom time
i dont want use worldTime
why?
worldtime is too fast
wdym you can change the ranges for seasons
if i will use world time i can calculate day hours or minutes?
system.runInterval(() => {
const time = world.getAbsoluteTime() // 1 minecraft day is 24000 tick || 20 minutes = 24000 ticks
const days = time / 24000 //transforming ingame ticks into ingame days (20 minutes)
const dayranges = [
{ max: 30, message: '1' }, //every 600 minutes season changes
{ max: 60, message: '2' },
{ max: 90, message: '3' },
{ max: 120, message: '4' }
]
for (const range of dayranges) {
if (days < range.max) {
player.sendMessage(range.message) //sending the message for the season number that we are in
break
}
}
}, 20)
ty
world.afterEvents.itemUse.subscribe((event) => {
const source = event.source;
const heldItem = event.itemStack;
if(heldItem.typeId !== 'rq:scrub_sponge') return;
const target = source.getEntitiesFromViewDirection()[0];
const {x, y, z} = source.getViewDirection();
const shootStrength = {x:x, y:y, z:z};
const projectileEntity = source.dimension.spawnEntity("minecraft:snowball", source.getHeadLocation());
const projectile = projectileEntity.getComponent("projectile");
projectile.owner = source;
projectile.shoot(shootStrength);
}
});```
anyone know how to amplify the speed of the projectile?
I'm not sure that you can? Right now you are attempting it in an afterEvent which I would imagine the projectile is already gone and reached its destination. I know this is the case for the projectile event. If you were to manage this behavior in some kind of beforeEvent I think it would result in the same way since the restrictions of read-mode, pushing you to offset the change.
Based on that, and without looking over the docs, I'm simply gonna say no on this.
Suggestion for @idle dagger
Description
A simple to use command creator.
Parameters:
info(Object): An object containing the information about the command.name(string): The name of the command.description(string): The description of the command.is_staff(boolean, default: false): Indicates if the command requires staff privileges.
Example usage
commandBuild.create(
{
name: 'getCommands',
description: 'Get a list of all commands registered',
is_staff: fa
```...
I see, thank you for the response
Suggestion for @idle dagger
Description
Calculate distance
Credits
These scripts were written by GlitchyTurtle32
You could do it if you spawned it, but I don't think that is your goal.
does spawning it by itemUse not count?
It's different. In your case it's the afterEvent. The projectile is already shot. In a beforeEvent you are restricted by read-only mode. When you offset it using something like system.run() the results are practically the same as witnessed in the afterEvent.
This is more of what I was talking about when I said "spawn":
const location: Vector3 = { x: 0, y: -59, z: 0 };
const velocity: Vector3 = { x: 0, y: 0, z: 5 };
const arrow = world.getDimension('overworld').spawnEntity('minecraft:arrow', location);
const projectileComp = arrow.getComponent('minecraft:projectile');
projectileComp?.shoot(velocity);
guess that means I should take a break from coding
been going for a few hours nonstop now
thank you visual1mpact for the feedback
Yea, unfortunately, I don't believe it's possible to accomplish your goal right now simply because of the restrictions in beforeEvents which is really what you need.
have u tried multiplying the shootStrength?
system.runInterval(() => {
const time = world.getAbsoluteTime() + 6000; //adjust time to match the sun position
const days = Math.floor(time / 24000); //total days passed
const date = {
year: Math.floor(days / 360), //current year (365 days) //1 year is 120 hours of playing
month: Math.floor((days % 360) / 30), //the month of the year (0-12 i think)
day: days % 30, //the day of the month (0-29)
hour: Math.floor((time % 24000) / 1000), //the hour of the day (0-23)
minute: Math.floor(((time % 24000) % 1000) / (1000 / 60)), //the minute of the hour (0-59)
second: Math.floor((((time % 24000) % 1000) % (1000 / 60)) * (60 / (1000 / 60))) //the second of the minute (0-59)
};
world.getAllPlayers().forEach(player => player.onScreenDisplay.setActionBar("----------\n" + Object.entries(date).map(([key, value]) => `${key}: ${value}`).join("\n") + "\n----------"))
})
this is the best you can find for ingame date @distant gulch
script team just limited it by only read json file
I kind of tried that and it said something about invalid because I'm multiplying a vector with regular multiplication
How can I get the velocity of a player?
Is it possible to test the enchants of two items and then transfer those enchants to a single item?
function shootProjectile(entity, projectile, power) {
const headLoc = entity.getHeadLocation();
const viewVector = entity.getViewDirection();
const direction = { x: headLoc.x + viewVector.x, y: headLoc.y + viewVector.y, z: headLoc.z + viewVector.z };
const vel = { x: viewVector.x * power, y: viewVector.y * power, z: viewVector.z * power };
const projectileEntity = entity.dimension.spawnEntity(projectile, direction).getComponent('projectile');
projectileEntity.owner = entity;
projectileEntity.shoot(vel);
};
world.afterEvents.itemUse.subscribe((event) => {
const source = event.source;
const heldItem = event.itemStack;
if (heldItem.typeId !== 'rq:scrub_sponge') return;
const target = source.getEntitiesFromViewDirection()[0];
shootProjectile(source, 'minecraft:snowball', 1);
});
try that
I will try this out, thank you for the help Ash
import { world, Player } from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe((initEvent) => {
initEvent.itemComponentRegistry.registerCustomComponent('bm:magic_mirror', {
onUse() { }
});
});
world.afterEvents.itemUse.subscribe((data) => {
const item = data.itemStack;
const player = data.source;
const cooldown = item.getComponent("minecraft:cooldown");
console.warn(cooldown.getCooldownTicksRemaining(player))
if (item.typeId === "bm:strength_mirror" && cooldown.cooldownTicks == 1800 && cooldown.getCooldownTicksRemaining(player) == 0) {
player.runCommandAsync("/function strength_effect");
cooldown.startCooldown(player);
}
});
Can anyone help, the command wont run unless i remove && cooldown.getCooldownTicksRemaining(player)
Try >= 0 instead of == 0
Okay
Okay, it works but the item can be constantly spammed, even with the cooldown in effect
Then use <=
ok
is it possible to get/use a value from the lang file?
hmm, if i do that, then it doesnt work at all, wierd
not get, you can just translate
you can use raw text from the lang file in a sendMessage
the same thing as the tellraw command
how so?
like this?
world.sendMessage(item.minecraft:stick.name)
it takes a raw message, which is an object with these properties i think
{
rawtext?: RawMessage[];
score?: RawMessageScore;
text?: string;
translate?: string;
with?: string[] | RawMessage;
}
so that would be like this?
world.sendMessage({tanslate: "item.minecraft:stick.name"})
ah, i see
can i define a raw message in a string?
like
const myMessage = {
translate: "myWord.word1"
}
yep it worked
great, i haven't use it before, so i wasn't sure
?
Yes almost everything is possible with script api
But I want to combine two items like an anvil
You can do it but you canât change anvil behavior , you might need a custom block with custom ui
I have a problem
I don't know how to combine the enchantments of items in slots 1 and 2 into an anvil
What is the format for getBlocks' 'filter' parameter?
keeps telling me that the object doesn't have a native handle despite my syntax looking correct
oh nvm
.getComponent('minecraft:equippable').getEquipment(EquipmentSlot.Mainhand)
Why isn't this working on my custom entity? getComponent is returning undefined even though there is item visible in the entities hand?
equippable only works on players
ok, anything I can do to get the item in the entities hand?
does it have inventory component?
yes
try that one then
Inventory is different than equippable for entities
You'll have to use execute command with the hasitem operator
If I set it to 1 size and check what item is there, it returns undefined. My plan is to save the item in the entity inventory and use replaceitem to make it appear that the item is in hand
failing that, I'll save the item data as a dynamic property
got it working, ty
nice
Read the docs if you know JavaScript then itâs easy
Dm me I can help you after 20:30
Ok
But What is the time there?
19:32
Ok
Calling all scripting Gods... https://discord.com/channels/523663022053392405/1279491485343027313 conundrum!
import { world, Player } from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe((initEvent) => {
initEvent.itemComponentRegistry.registerCustomComponent('bm:magic_mirror', {
onUse() { }
});
});
world.afterEvents.itemUse.subscribe((data) => {
const item = data.itemStack;
const player = data.source;
const cooldown = item.getComponent("minecraft:cooldown");
console.warn(cooldown.getCooldownTicksRemaining(player));
if (item.typeId === "bm:strength_mirror" && cooldown.cooldownTicks == 1800 && cooldown.getCooldownTicksRemaining(player) == 0) {
player.runCommandAsync("/function strength_effect");
cooldown.startCooldown(player);
}
});
The script wont work, no errors given, but when i remove the && cooldown.getCooldownTicksRemaining(player), the script works, but the problem is the player can spam the item
Consider opening a post then
ok
import { GameMode, system, world } from "@minecraft/server";
import { PlayerServer } from "api/@minecraft/Main";
world.beforeEvents.playerPlaceBlock.subscribe((eventData) => {
const { player, block, permutationBeingPlaced: { type: { id: typeId } } } = eventData;
const playerServer = new PlayerServer(player);
if (playerServer.getPlayerProperty("adminPermissionModifyBlocks", true) && player.getGameMode() == GameMode.creative)
return;
if (player.location.x <= 100 && player.location.x >= -100 && player.location.z <= 100 && player.location.z >= -100) {
eventData.cancel = true;
return;
}
if (typeId == 'minecraft:lava' && JSON.stringify({ x: Math.floor(player.location.x), y: Math.floor(player.location.y) - 1, z: Math.floor(player.location.z) }) == JSON.stringify(block.location)) {
eventData.cancel = true;
return;
}
if (typeId == 'minecraft:slime' && JSON.stringify({ x: Math.floor(player.location.x), y: Math.floor(player.location.y) - 1, z: Math.floor(player.location.z) }) == JSON.stringify(block.location)) {
system.run(() => {
player.applyKnockback(0, 0, 0, 2);
player.runCommandAsync("give @s slime")
});
const xBlock = block.location.x
const yBlock = block.location.y
const zBlock = block.location.z
system.runTimeout(() => {
player.runCommandAsync(`setblock ${xBlock} ${yBlock} ${zBlock} air`)
}, 10)
return;
}
eventData.cancel = true;
});
Why does this script work on a regular world but not on Realms?
if I had to guess.. does it have something to do with js import { PlayerServer } from "api/@minecraft/Main";what is that?
a folder(?
content log??????
with @minecraft and no ./ offset ref?
guess is possible...
I think maybe, the folder needs to be within the scripts folder for realms
mmm đ¤
so bundle for a realm deploy
maybe the mc engine accepts that syntax
on your local pc, it can maybe pull from anywhere... I have not tested the limits of that, just guestimating
if you want your library code all in one place, may need to have a bundler for the deployment so the references within other systems are correct.
please help me check my post
the best way to get floating texts, is invisible entitys?
I don't do forms yet... so can't help. Have you checked the resources, I know some people have done example or library code over there for forms... Or wait unil a forms person sees your post and helps.
Most likely.
I'm using custom components through scripts, but I have a doubt about if there is a way to add a condition to make the block interact or not
because when it was done through molang using the triggers events and events, the same was achieved with a âconditionâ.
No
You can use if statements then return but it will still swing your arm
well I found a workaround and basically recreated what would happen when placing another block in any direction, not ideal but it works :/
(should do it with a switch case)
Ah so your issue is when interacting trying to place a block right?
as such my problem is not being able to block interactions at will, as it was possible to do before, so as such I am trying to overcome this impediment somehow
Unfortunately a before event to cancel intearction is not on the roadmap:
https://discord.com/channels/523663022053392405/1279085286193762385
However in this post I did link to a feedback post on the official discord to add an interactable component again
Uff
my dream right now
or...
beforeOnPlayerInteract(event) {
if (not condition) { event.cancel }
Ideally it would be
if(not condition) event.cancel
use block.above/below/north/east/south/west
they're faster calls than if you were to do block.dimension.getBlock(...)
yes
ty <3
not sure if someone's answered you already, but changing the durability damage value does not affect the initial item itself, only the item object. So you need to set the container item afterwards to the item with the repaired durability. its also not necessary to set the component back after, you can just return after damage = 0. I would return the repaired item itself (or undefined if already repaired/no durability). then you can set the container item after in the inventory if it returns an item stack
thank you :>
how would people do that swiping attack?
like the dark souls kind
is it possible to disable the left click attacks?
i dont think so
ive seen this in a few addons, maybe try to check out the greatswords from the fortify addon by weejuice
hmmmmm
ty
Hey guys how to I run a command in the scripting api? Since I am not finding any way to
player.runcommand
or dimension.runCommand works as well
Which imports?
Can you give an example file? My autocompletetions only show Dimension.call/caller etc
you have to get a player object or a dimension from the world
world.getDimension("overworld").runcommand()
or player.dimension.runCommand
Oh
yeah you need to get a player or a dimension to run this method on, you can't just type Player.runCommand("kill @s") and expect it to work
Is the items normal seems all the sword and weapons to me don't take any damage by breaking blocks only by hitting an entity like zombie etc. do i need a script for this?
Yes
You have some example of it?
my library has a custom component for it
How do I log the potion effect inside of a cauldron?
I dont believe you can, you can only set the potion effect
Hey guys is there any way to cancel damage applied to my entity in scripting api since there isn't beforeEvents.entityHurt or can I get the amount of damage applied to my entity through world.afterEvents.entityHurt.subscribe((event) => {
const damager = event.damageSource.damagingEntity
const damaged = event.hurtEntity
if (damaged.typeId == 'space:siren_head'' && damager.typeId != 'minecraft:player')
const damageAmount = event.damage after this how do I get the amount of damage applied?
});
You cant cancel damage
Then how to get the amount of damage that was applied?
Try healing after getting damage
Through event.damage then what?
But I need to get the amount applied so I can heal with amount of damage applied to my entity
entityHurt event has a damage property, if I remember correctly
Yes Ik but how do I actually get it using event.damage then after event.damage what do I do?
you use that damage value
its a number
Does it return the number after const ifk = event.damage?
It wojt work though if the entity dies
Hey can someone give an example of using event.damage?
@ivory bough so
Grab health component -> add the damage amount back
I don't think grabbung health component would work
I need to do it through world.afterEvents.entityHurt.subscribe and event.damage
Does this work?
world.afterEvents.entityHurt.subscribe((event) => {
const damager = event.damageSource.damagingEntity;
const damaged = event.hurtEntity;
const damageAmount = event.damage;
if (damager.typeId != 'minecraft:player' && damaged.typeId == 'space:siren_head') {
world.getDimension("overworld").runCommandAsync("effect @e[type=space:siren_head] instant_health 1 ${damageAmount}");
return;
} else {
return;
}
});
Then how
That's not the problem I just need to know how much is the damage applied
give me a sec
yeah that work
@distant tulip this script?
yeah
how do i detect whether an item is dropped by a player?
you can't directly, in #1067535712372654091 someone made a script
i see, thanks, i think i can find the post
that's dumb. whose idea was this?
hi, jayly docs give skeleton as example for applyKnockback but from my testing it only works on player.. is it the same for everyone?
Status effects and enchantments are so hardcoded, it's the final frontier for data-driven content
@wary edge Sorry for the ping
With a script. Is it possible to do something like this?
function mergetest(player, slot1, slot2) {
const inv = player.getComponent("minecraft:inventory").container;
const item = inv.getItem(slot1);
const items = inv.getItem(slot2);
var encid = "none";
var itemenchant = false;
try {
const enchantments = items.getComponent("enchantable").getEnchantments();
if (enchantments.length > 0) {
encid = enchantments.map(e => ({...e, type: e.type.id}))
itemenchant = true;
}
} catch (error) {}
if (itemenchant == true) {
const ench = item.getComponent("enchantable");
ench.addEnchantments(encid.map(e => ({ ...e, type: new EnchantmentType(e.type) })))
}
console.warn("test")
inv.setItem(slot1, item);
inv.setItem(slot2, new ItemStack("minecraft:barrier", 1));
player.sendMessage("§aMerge Successful.")
player.playSound("random.anvil_use")
player.runCommand(`clear @s barrier`)
}
Digging in the book. It doesn't work when there is a spell that is not printed. How can I solve this?
May ask if the adk-lib is an item?
It's a library, not an item
import { GameMode, system, world } from "@minecraft/server";
import { PlayerServer } from "api/@minecraft/Main";
world.beforeEvents.playerPlaceBlock.subscribe((eventData) => {
const { player, block, permutationBeingPlaced: { type: { id: typeId } } } = eventData;
const playerServer = new PlayerServer(player);
if (playerServer.getPlayerProperty("adminPermissionModifyBlocks", true) && player.getGameMode() == GameMode.creative)
return;
if (player.location.x <= 100 && player.location.x >= -100 && player.location.z <= 100 && player.location.z >= -100) {
eventData.cancel = true;
return;
}
if (typeId == 'minecraft:lava' && JSON.stringify({ x: Math.floor(player.location.x), y: Math.floor(player.location.y) - 1, z: Math.floor(player.location.z) }) == JSON.stringify(block.location)) {
eventData.cancel = true;
return;
}
if (typeId == 'minecraft:slime' && JSON.stringify({ x: Math.floor(player.location.x), y: Math.floor(player.location.y) - 1, z: Math.floor(player.location.z) }) == JSON.stringify(block.location)) {
system.run(() => {
player.applyKnockback(0, 0, 0, 2);
player.runCommandAsync("give @s slime")
});
const xBlock = block.location.x
const yBlock = block.location.y
const zBlock = block.location.z
system.runTimeout(() => {
player.runCommandAsync(`setblock ${xBlock} ${yBlock} ${zBlock} air`)
}, 10)
return;
}
eventData.cancel = true;
});
Why does this script work on a regular world but not on Realms?
Consider opening a post
does applyImpulese work on minecarts
||```js
const a = []
a.push(a)
Is this normal? Player with spectator gamemode can be killed with kill @e
not script related, but it sure looks like bug
Works as intended
Oh okay, I'm literally PLAYING Minecraft for the first time
Not sure if I can say this the way I want but is it possible to make a block drop items based off its permutations and have them triggered individually and keep data on the block with said perms? I have a block that when an item is used on it it changes permutations but I want to be able to get the item back either when broken or interacted with again with the same item
maxDistance is radius?
yes
Why ?
minDistance is rm
sadly no
đŚ
hmm, i know theres a way to make a method not throw an error, but i cant seem to remember, theres no problem in the script fiile, except when the conditions for the if statements arent met. can anyone show how its done
try {} catch(e) {}
and you shouldn't have to use that
write your code so that you don't get errors
im not to sure, but it has something to do with "?"
also, the code works as intended, its just that when its check the player for a specific component and the component isnt there, it gives an error
What component are you looking for?
you mean like player.getComponent()?.dosomething
const comp = player.getComponent("comp")
if (comp) {
//do codes
}
if it errors, then it isn't working as intended lol
but anyway either of those ^^ should work
thats what i meant, the question mark thingy, so it can throw an undefined instead of the error
thanks yall
It throws an error if you attempt to access a property or method from getComponent() that returns undefined since whatever property or method you are attempting to access does not exist. It won't throw if the component is undefined. It simply returns undefined.
So like Gega demonstrated, you can conditionally check if it's defined or not defined before accessing the component.
Example 1 (Ternary Operator):
const comp = player.getComponent("comp");
const message = comp ? "Component is defined" : "Component is undefined";
console.log(message);
Example 2 (Logical OR Operator):
const comp = player.getComponent("comp");
const defaultComp = "default";
const effectiveComp = comp || defaultComp;
console.log(effectiveComp); // Logs "default" if comp is undefined
Example 3 (Logical AND Operator):
const comp = player.getComponent("comp");
comp && console.log("Component is defined"); // Logs message only if comp is defined
Example 4 (Nullish Coalescing Operator):
const comp = player.getComponent("comp");
const fallbackComp = "fallback";
const finalComp = comp ?? fallbackComp;
console.log(finalComp); // Logs "fallback" if comp is undefined or null
Example 5 (typeof Operator):
const comp = player.getComponent("comp");
if (typeof comp !== "undefined") {
console.log("Component is defined");
} else {
console.log("Component is undefined");
}
I usually like to specify that it's checking for undefined, which can help with numbers & booleans, where false or 0 will also cause the undefined behaviour to run
const comp = player.getComponent("comp");
const message = comp !== undefined ? "Component is defined" : "Component is undefined";
console.log(message);
and maybe strings
is "" counted as false?
ah yes it is
better readability as well
the only ones that wouldn't need that are the typeof and nullish coalescing operator
yes
that's not the same as undefined though
There are many ways to do it. Really just comes down to knowing what your code is doing, and understanding what it could possibly do under circumstances and how you select to handle the conditions best suited for the environment.
you should always check what the function return in the
getComponent will never return those
found better neovim alt 
is it better to detect if the typeId is player or use instanceof Player?
playerid is better imo
tbh it doesn't matter
alright then
no termux i hoop...
One notable difference is type assertion. Using player instanceof Player hints to Intellisense that your class is a type Player.
In my event subscriptions meant to affect only players, I filter out non-players using !(player instanceof Player) for that reason. From that line onward VSCode knows I am working with a player. This does not happen with player.typeId != 'minecraft:player'
Only other way I know to assert it as Player is to copy the entity instance from the function parameters. (e) => {const player = (e.sourceEntity as Player); ...}
Does anyone know if we can grab player skins on bds?
only bdsx
Only with a bds mod
Oooo ok
plugin*
same thing
not really
i mean you need to make a mod to retrieve that data from the server
ÂŻ_(ă)_/ÂŻ
"plugin" is just what mods for servers are called
modification
forge modifies always the game
forge it self is a mod...
data pack in java it's like an addon
forge is the modloader but sure its a mod
you get my point
alr
dimension. what he said
cause it's getting the entities of the dimension
take the first element
I wonder how world.getEntities sorts. I assume it is by distanceâand the location defaults to the world origin
Loading order?
Idk sorry
How should it emitâone particle, halfway in between? Or a line of particles between two coordinates? If so, how many? Or should it be "x number of particles" per block? There are lots of ways to emit a particle between two points
Any particle between these two block
message.js(29,35): Operator '+' cannot be applied to types '{ x: number; y: number; z: number; }' and '{ x: number; y: number; z: number; }'.
wdym i cant add numbers with numbers??? whats the point of numbers then???
that is an object
function vector3add(a, b) {
return {
x: a.x + b.x,
y: a.y + b.y,
z: a.z + b.z
};
}
Is SpawnParticle for js or ts?
So how to use spawnparticle js?
Documentation for @minecraft/server
I couldn't understand it even though I looked at it from here.
so instead of { x: x, y: y, z: z - 1 }; could i use,
block.location = z - 1 ; đ
pretty much im trying to add 2 block positions together
The example is right there
@burnt remnant
But for ts
Then transpile it to JS
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
Theres minimum difference between js and Ts syntax
Its only a problem if you dont code and just copypaste
There are differences. Like TS does add language features (enums and decorators).
Yes but its still being js
how can i fix this? just a generic decriment stack
idk how to convert it to js
Then use a website
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
yeah i got it do i import the function the same way as i do other js?
ItemUseOn before event returns block before or after use?
Try it, and see
so why doesnt it work?
let { block } = e;
let target = {
x: block.x,
y: block.y,
z: block.z - 1
};
block.dimension.getBlock(target).setType("minecraft:oak_planks");
target.y + 1
if(target.typeId === "minecraft:oak_log"){
block.dimension.getBlock(target).setType("minecraft:oak_planks");
target.y + 1
if(target.typeId === "minecraft:oak_log"){
block.dimension.getBlock(target).setType("minecraft:oak_planks");
target.y + 1
if(target.typeId === "minecraft:oak_log"){
block.dimension.getBlock(target).setType("minecraft:oak_planks");
target.y + 1
if(target.typeId === "minecraft:oak_log"){
block.dimension.getBlock(target).setType("minecraft:oak_planks");
target.y + 1
}
}
}
}
currently it only works up to the first set type oak planks, after that nothing happens
Thats a whole load of nested code
thats just the simplified version
a loop where it keeps executing the same code infinitely until the if statement fails was something i thought of initially but idk how to do that
but im guessing the target.y+1 is the problem since thats when its stops
can someone tell me why this dont work?
const item = new ItemStack("minecraft:potion{Potion:swiftness}", 1)
item.nameTag = "§l§bPotion of speed"
thatâs not how you create a potion. This is https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server_1_14_0_beta.ItemStack.html#createPotion
Do items that have the minecraft:damage component take durability when used to attack by default?
Yes
Why?
I'm surprised the game does the work for you
Instead of handling all that manually with a script
With a custom component
Only breaking blocks does that
can i set player speed using script? Not effect
so why doesnt it work
let targetblock = {
x: block.x,
y: block.y,
z: block.z - 1
}; block.dimension.getBlock(targetblock).setType("minecraft:oak_planks");
targetblock.y + 1
if(targetblock.typeId === "minecraft:oak_log"){
block.dimension.getBlock(targetblock).setType("minecraft:oak_planks");
its not adding + 1 to y
You are adding it, but not setting it back
so, targetblock = targetblock.y + 1 ?
Can do a few things-
targetblock.y++;
targetblock.y += 1;
targetblock.y = targetblock.y + 1;
hmm still doesnt seem to work
let targetblock = {
x: block.x,
y: block.y,
z: block.z - 1
};
block.dimension.getBlock(targetblock).setType("minecraft:oak_planks");
targetblock.y = targetblock.y + 1
if(targetblock.typeId === "minecraft:oak_log"){
block.dimension.getBlock(targetblock).setType("minecraft:oak_planks");
targetblock.y = targetblock.y + 1
if(targetblock.typeId === "minecraft:oak_log"){
block.dimension.getBlock(targetblock).setType("minecraft:oak_planks");
targetblock.y = targetblock.y + 1
if(targetblock.typeId === "minecraft:oak_log"){
block.dimension.getBlock(targetblock).setType("minecraft:oak_planks");
targetblock.y = targetblock.y + 1
}
}
}```
you nested your if statements when they shouldn't be nested
i.e., since you nested your if statements, if the targetBlock is not an oak_log, the rest of the code will not run
but i want these if statement to run only if the previous one has
all if-ing the same tho
targetblock.typeId doenst exists..
litterally is:
let targetblock = {
x: block.x,
y: block.y,
z: block.z - 1
};
redundancy
whaaatt
so it can add +1 every time the if statement runs so the height gets higher
but yeah, targetBlock.typeId doesn't exist
I did a lot of that this week :]
let targetBlock = block.dimension.getBlock({ x: block.x, y: block.y, z: block.z - 1 });
if (targetBlock.typeId === 'minecraft:oak_log') {
targetBlock.setType('...');
}
posted a thread on all this 2 hours ago, ive been working on this for 6 hours đľâđŤ
ok see what you are doing. going upp and seeing if same for a vein miner?
perhaps a loop
pretty much,like a tree capitator, but instead of breaking the block, i want it to be planks
pereferably infinite but im sure thatll be a horrible idea, so up to 30 blocks since mega taiga trees can go up to 25
yeah ik
a loop can do however many and stopp when not a log
yeah when coming up with the idea i had loops in mind but realised i know 0 about loops
im surprised i made it this far
is easy!
const targetblock = {
x: block.x,
y: block.y,
z: block.z - 1
};
for (let current = 0; current < 4; current++) {
const currentBlock = block.dimension.getBlock({ x: targetblock.x, y: targetblock.y + current, z: targetblock.z });
if (currentBlock.typeId === "minecraft:oak_log") currentBlock.setType("minecraft:oak_planks");
else break;
}
and that also works with height?
It adds one to the y direction every time the loop runs
And if the block above is not planks, it will stop the loop
that is not as much as i thought it would take
One wayjs let more=true; do { block.dimension.getBlock(targetblock).setType("minecraft:oak_planks"); targetblock.y = targetblock.y + 1; if (targetblock.typeId != "minecraft:oak_log") more=false; } while (more)
for more than 4
so you want to go out in all directions
make functions for x y and z with a parm of what to add... so either 1 or neg 1 and call that for each side
or one function if can use eval
thank you everyone for the help, i really appreciate it. i wouldve started to lose hair
wouldn't work
targetblock.typeId
targetblock would be a vector
not a block
entity.getComponent("movement").setCurrentValue(speed);```
No idea about if his code works as intended or not. I did not analyze it. I was just putting it in a loop per how he did it with giving him more than 4. Based on this #1067535608660107284 message. But looking at it, you are right.... but I have a feeling he figured that part... out I hope.
ah right
What would the easiest way be to see what's causing a script delay error at world load?
it doesn't work anymore
what do you mean anymore
what do you guys use for scripting?
I generally use bridge but Its been some time since I last made addons so there might be better alternatives rn
oh well so you set up the manifest manually?
can i change item name using script?
Guys, if I use Minecraft:tick_world to keep an entity "loaded" can I access it's inventory even when on unused chunks?
<ItemStack>.nameTag = '...'
% is omitted when i getting lore how do I solve it?
Did you download my pack?
I put the adk- but still not working
Yea i did
Any content log?
Lets open a post and post your item code there in #1067869136606220288
How can I stop a cooldown?
if youre talking about item cooldown, get the cooldown component and current tick, and then set the cooldown with the said tick
doesnt works
youre putting it inside runInterval or loop, right?
The Problem is, that .cooldownTicks is read-only
theres a thing that allows you to set cooldown for category
and how can I do that?
The player class have startItemCooldown method. This allows you to set cooldown of an item by category with specific ticks you want.
If my script is teleporting an entity at a specified location. How can I continue doing that after the world reloads?
youd need something that can store the data for teleporting even after it reloads
maybe dynamicProperty?
So I'm still kinda new to that. Would it be the world dynamic property or the entity dynamic property?
i think that would be your choice
And I believe we would have to stringify it
It stores vec3? I need to check that
Awh thx
Idk why you want to use bdsx after the pdb getting removed but here it is
Awh I see
People saying endstone?
I haven't looked into that
Does anyone know how I would go about making a leap ability? I'm looking at applyImpulse but not too sure how to apply it in the direction the player faces
applyImpulse doesnt work on players
alternatively you can use knockback, along with player.getViewDirection()
ok thank you!
have a look online as their is a couple methods
just search for how to print % in string js or smth
it has to do with the way the game is coded I think
% is used for translation keys
tbh idk
it's an issue with js itself I believe
actually wouldn't say it's an issue it's just how js formats stuff
Use %%
It's dumb, but it worked for me.
do arrays not react reactivly in classes?
Elaborate
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]
Installation for @minecraft/server-ui
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]
nvm i fixed my problem
#debug-playground :D
Sorry
Does onUseOn method for ItemCustomComponent work on custom blocks or not? I heard it has issues
Yes if the custom block does not have the interact component
Ohhh, okayy. Thankss!
Endstone is good
Guys 2 questions
What's the maximum amount of dynamic properties an item can have?
What's the max length of a string that can be stored in a dynamic property?
Guys is there a limit on how many participants can be in an objective? Talking about scoreboards
does EntityLifeTimeState not work?
what you need it for?
does it matter? im just testing
nice
Howâd you edit the ground entity? Or did you just summon a new one?
i have this method on my Entity
mc.Entity.prototype.isMoving = function() {
let v = this.getVelocity()
if (v.x != 0 || v.y != 0 || v.z != 0) return true
return false
}
how do i detect the head movement?
because this one only detect the velocity or the "entity" movement
Well you have to check head rotation difference every tick tho
well yeah, but how do i check it at different tick when the usage of isMoving is inside of runInterval?
owh i know, nvm
So I come back after a couple weeks to make a new project and now my auto completions for VScode and Bridge donât work and Iâm not getting any debugging from Minecraft either. Is there something I missed?
It's not usable so ignore it. Back before they made everything in that event read only you could use that to modify who received the broadcast from that event or not.
can i change the item entity amount without converting it to an itemStack and back to an entity?
how can i get slot1 item?
How do you solve this?
how does line 10 in main.js look like?
import { world, ItemStack } from "@minecraft/server";
world.beforeEvents.worldInitialize.subscribe((eventData) => {
eventData.itemComponentRegistry.registerComponent("fm:on_use", {
onUse(itemEvent) {
if (itemEvent.item.typeId === 'fm:magic_wand') {
itemEvent.source.runCommand(summon zombie ~~~);
}
}
});
});
the command is not surrounded by quotes
oh, it's surrounded by back ticks
It has quotes but it doesn't appear on discord
it's registerCustomComponent not registerComponent
Now this error occurred.
itemEvent.itemStack.typeId
not itemEvent.item.typeId
Thanks, it worked
how can i get items amount?
itemStack.amount
and for related stuffs,
itemStack.isStackable
itemStack.maxAmount
how work server net module?
what mean "dedicated server"?
bds
Does anyone know how to make a command constantly be active if the player is on the ground and when you're in the air it stops?
I've been trying to make a script for it but nonetheless haven't figured one out
system.runInterval(() => {
world.getPlayers().forEach((player) => {
if(player.isOnGround){
player.runCommand("say you are on ground") //you can use @s for self
player.dimension.runCommand("say you are in:" + player.dimension.id) //run in dimension... can also use world.getDimension("overworld")
}
})
},1 /* interval in ticks */ )
"minecraft:damage_sensor": {
"triggers": [
{
"on_damage": {
"filters": [
{
"any_of": [
{
"test": "has_dynamic_property",
"subject": "self",
"operator": "=",
"property": "protection",
"value": 1
},
{
"test": "has_dynamic_property",
"subject": "self",
"operator": "=",
"property": "protection",
"value": 1
}
]
}
],
"event": "test"
}
}
]
}
},
Does anyone knows how to test dynamic property in player.json
I don't believe you can.
Gonna have to use tags I think.
Dynamic properties are exposed only via scripting.
You could copy it over to entity properties, through Entity.prototype.setProperty.
Smart
Thanks đđ
Whatâs the difference between using a custom component and using a plain script?
Like for example on_use replacement
Hi, does anyone know how to open an interface with an item using scripts?
plain script is like telling the game "hey if this happens, do this"
custom component is closer to "injecting" the functions into items & blocks
but its no different in the end
its just that custom components have more functions
you can go for the one you find the best
Iâve been told that custom components are âfasterâ when it comes to individual item/block stuff
oh yeah also that
idk if its true though
#1067535608660107284 message
nice
is there a way to check how long the player has been sneaking without runInterval?
without runInterval
not really related with scripting but is player.json required for that in BPAC
or do i just need RP AC and BP AC for this
i havent used it for so long i forgot
well, that's an animation controller
Why is this happening?! If my code contains the entity "n:iruka"
My code:
// npc interact
mc.world.afterEvents.entityHitEntity.subscribe((data) => {
const player = data.damagingEntity;
const damaged = data.hitEntity;
if (player.typeId === "minecraft:player" && damaged.typeId === "n:iruka")
iruka(player);
player.runCommandAsync("camera @s set minecraft:free ease 1 in_out_expo pos ~~3~-5 rot 25 0")
player.addTag("inUi")
})
you need to wrap if statement with {}
it only checks and affects iruka(player) but not the other two rn
Oh, okay
Anyone have any idea how I could save an item in my inventory? Like a shulker full of stuff?
How did you get your health bar like that?
did getEquipment get deprecated?
No
Lots of things are still in beta
Wdym? It's stable
They may be in a diff mc version
Guess I messed up somewhere else. But my pack I posted 3 weeks ago is now broken and it used that class. That one was using a full release version of the api as well so idky it broke
I'm trying to figure out how to run a command as soon as the player has loaded the world and not before, like it happens with playerSpawn event
the message appears even before the world loads, when I'm in the loading screen
this way it is not possible to execute the camera command precisely, I think there is a way to trigger the commands only when the player is actually in the world and not in the loading screen
I probably solved it via query.is_in_ui. Thanks.
can you help me fix this script?
Debug result for [code](#1067535608660107284 message)
Compiler found 2 errors:
[36memojis.js[0m:[33m130[0m:[33m10[0m - [31merror[0m[30m TS2540: [0mCannot assign to 'message' because it is a read-only property.
[7m130[0m data.message = Object.keys(emoji).forEach(key => data.message = data.message.replaceAll(`${key}`, emoji[key]))
[7m [0m [31m ~~~~~~~[0m
``````ansi
[36memojis.js[0m:[33m130[0m:[33m59[0m - [31merror[0m[30m TS2540: [0mCannot assign to 'message' because it is a read-only property.
[7m130[0m data.message = Object.keys(emoji).forEach(key => data.message = data.message.replaceAll(`${key}`, emoji[key]))
[7m [0m [31m ~~~~~~~[0m
ESLint results:
emojis.js
2:7 error 'Commands' is defined but never used @typescript-eslint/no-unused-vars
You are attempting to modify message in the chatSend event which is currently not modifiable. The developers have made it read only. What you will want to do is cancel the event, and instead send the message by looping through all players in the world.
Modify the message by storing it in another variable.
ty
Is possible to have armour in hand and put trim?
wdym?
People can buy armour trim in my world, is possible to habe select trim, than the ore and put it on armour that player is holding?
You understand?
How to do?
wait for an expert
Hahaha, okay
sorry ain't that good with java script either lol
Ja is very hard
ikr
maybe I am just a idiot
c++ made me think coding is easy lol
It take me long time to learn code
c++ is harder than js lol.
that is what I was thinking
where to see document for component
I see people use .container and .currentValue when get component. But I check doc and don't see ?
u will have to look for that component's documentation then, for example I am guessing this is what ur looking for: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/entityinventorycomponent?view=minecraft-bedrock-stable
Nope
Thank you very much đ
you think?
i find it quite the opposite lol
c++ is def better when it comes to making stuff
but i find javascripts better in terms of difficulty
its easy to learn for most people, and i think thats why they chose javascripts for scripting
i see
Anyone know a way to test if the player is riding another entity using scripting?
Thanks
Anyone know a way to use an arrow runtime identifier without it dropping an arrow when you touch it?
When the projectile lands, make it detect the player in a farther range and despawn it before giving them an item
I need the player to be close and the arrow to respawn in order for the rest of the mechanics to work. Is there a way to make it identify as an arrow that was shot with infinity?
Technically I could run a command when it is picked up to automatically clear it but I was hoping there was a way to prevent it altogether
Is there anyway to check if the dropped entity is a specific item? (For example, chest)
Without actually testing for it's name
entity item component
didn't know there's such a component, thx
How to detect if player hold nothing?
It say "undefined" and say error in console log all time if I hold nothing
Show your code.
Does anybody know how I can make a command activate when on air? and where I'm specifically looking at
Raycast
Can you make the player swing by having a tag or is it not possible
Animation?
Read the docs
Is possible to put armour trim on item player is holding?
Using title
Is it possible to make a script where when a player is outside of the sun he takes damage but doesn't set on fire
Does anyone know why the first command executes without detecting the item in the second hand?
world.beforeEvents.worldInitialize.subscribe((eventData) => {
eventData.itemComponentRegistry.registerCustomComponent("fm:on_use", {
onUse(itemEvent) {
const mainHandItem = itemEvent.itemStack;
const offHandItem = itemEvent.itemOffhand;
if (mainHandItem.typeId === 'fm:magic_wand' && offHandItem?.typeId !== 'fm:avada_kedrava') {
itemEvent.source.runCommand('function extrair');
}
if (itemEvent.itemStack.typeId === 'fm:fire_wave') {
itemEvent.source.runCommand('function fire');
}
if (itemEvent.itemStack.typeId === 'fm:expecto_patronum') {
itemEvent.source.runCommand('function patronum');
}
if (itemEvent.itemStack.typeId === 'fm:thunder_search') {
itemEvent.source.runCommand('function light_ray');
}
if (itemEvent.itemStack.typeId === 'fm:levitate_search') {
itemEvent.source.runCommand('function levitate');
}
if (itemEvent.itemStack.typeId === 'fm:time_search') {
itemEvent.source.runCommand('function skip');
}
}
});
});```
itemOffHand doenst exist.
You need to get the player equipment component to get the item equipped on off hand
how to play animation when player interact
How do I run a function when closing the form?
Interact with item, block or entity?
Hellooo. I am trying to simply have my custom block be destroyed. if the block underneath it, is suddenly air.
I was thinking maybe having a custom_component (tick) on my blocks. subscribe to this. and constantly check the block below. if block == 'minecraft:air' destroy block?
Does this seem like a valid approach. maybe there is something more simple. Like a direct placement_rule component?
and maybe i can exclude air?
I would just like the block to destroy, instead of float. if the block below is destroyed
^^ custom_components. But i was hoping for maybe a more direct approach
because the player playsound only plays the sound for the player
dimension playsound plays it for everyone
why isn't it just in the Entity base class
because if it was, it would only play the sound for the entity?
What use does that have
no one would hear it but the entity
can you confirm this?
So basically you're telling me only that player can hear the sound and not other players?
When ever I call the player playsound
player.playSound only play sounds to a specific player, I think you mean dimension.playSound?
Also playing sounds to an entity makes no sense, they can't hear anything
Wasn't aware the sound wasn't broadcasted to everyone around the player
Makes sense then
Any good methods to make an addon the most efficent/performance friendly as possible?
When an addon gets really big, it obviously depends on how it's made/structured but what good practices are there
I've used prototype, and for loops, and stuff like that for minor help.. but because we only have one thread is there much we can do?
Use the debugger extension and the script profile, it helps showing the performance difference
I've seen the auto debugger running finds minor issues at start up, but running seems fine normally
On pc can I actually see a graph?
I'll try looking into this more thx
Oh thats cool
How do I identify if there are mobs around in 5 blocks distance to execute a command?
toTp.clearVelocity();
toTp.teleport({ ...entity.location, y: entity.location.y + 0.2 });
when running this using system.runInterval, why does it teleport entities perfectly to everything except players? When teleporting to a zombie, pig, etc, even when moving at high speeds, it's perfectly cantered but when entity is a player, it can't handle even a slight movement, it always lags behind by a lot
redatone components, huh?
I've been thinking about doing a write up of this recently. The debugger and script profiler are very helpful for figuring out bottlenecks if you're already having issues.
More generally for performance you want to
- don't use Armor Stands for anything
- avoid using
runCommand/runCommandAsyncat all if possible. - avoid using scoreboards for storing any type of data unless you are showing that value in a scoreboard to the player
- cache or memoize everything you can, there are a lot of things (like world.getPlayers or entity.getComponent) that people don't realize are native calls that take significantly longer than referencing an array.
- in most cases you should only have one subscription to each event type in your entire addon
- think hard about using any runIntervals, use the longest interval you can, not everything needs to run every tick
If you're looking for more general advice on maintainability of a large addon, use typescript and eslint, write lots of game tests and avoid modifying any of the prototypes from @minecraft/server
Yeah I break some of these rules lol. I try native as much as possible etc..
Why scoreboards tho, I use a custom database script and it seems fine?
Works great, just the amount if calls
I use cache as much as possible
Dynamic properties works as well, I like I could cross save between addons
With scoreboard
Only reason I stay scoreboard method
Scoreboard operations take about 30-40% longer than the equivalent dynamic property operations.
Dang that's crazy
If that's the case...
I might go back to dynamic properties, I need some solid evidence and someone to show tests
That would be so cool
Speed tests
Scoreboards are good for cross-addon storage if that's something you need admittedly.
I have a performance test framework that I'll share when I get home later tonight.
What types of damage ignore the shield apart from magic and override?
ramAttack, contact
and prob anything that arent entityAttack and entityExplosion
yall know why my decorators are showing up in my compiled js? i just migrated my code from using experimental decorators to the newer stage 3 decorators. do they not get "dumbed down" anymore? i dont think my tsconfig is too weird either.
{
"compilerOptions": {
"module": "ES2020",
"target": "ES2021",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true,
"declaration": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"paths": {
"@/*": ["./packs/BP/scripts/*"]
}
},
"exclude": ["node_modules"],
"include": ["packs/BP/scripts"]
}
Is possible to put armour trim on item player is holding?
nvm figured out its an esbuild issue
Ok
is there a module that checks whether the player stopped hitting a block?
if (!(
player.hasTag("soldier") ||
player.hasTag("elite") ||
player.hasTag("general") ||
player.hasTag("overlord") ||
player.hasTag("king") ||
player.hasTag("emperor") ||
player.hasTag("dragon") ||
player.hasTag("eld-dragon") ||
player.hasTag("demi-god") ||
player.hasTag("god") ||
player.hasTag("eld-god"))) {
player.sendMessage(`§l§dHCV KitPvP >> §cYou need to be soldier rank or higher to claim the kit`);
} else if(
player.hasTag("soldier") ||
player.hasTag("elite") ||
player.hasTag("general") ||
player.hasTag("overlord") ||
player.hasTag("king") ||
player.hasTag("emperor") ||
player.hasTag("dragon") ||
player.hasTag("eld-dragon") ||
player.hasTag("demi-god") ||
player.hasTag("god") ||
player.hasTag("eld-god")) {
claimKit(player)
}
When i have the solider tag this works but with any other tag i cant run the claimKit function
DEAR GOD
you can just
do for loop with an array

explain?
instead of checking for every single tags
you can do
const tags = [ "soldier", "elite", ... ];```
its all in a case so the first tag "soldier" gets removed
and then do
for (let i=0; i<tags.length; i++) {
if (player.hasTag(tags[i]) { break; }
//code
}```
its the best to do this for the sake of performance and utility
use
.every
array method
const tags = [ "soldier", "elite", ... ];
if (tags.every(tag => player.hasTag(tag))) ...
wouldnt u want to use tags.some not .every?
not even. its just way more concise and maintainable
how many javascripts functions have i missed atp
many, likely
oh yeh, mb
.some for OR, .every for AND
x, y, z, dx, dy, dz selectors in commands
so if i do { x:1, y:1, z:1 }, it includes entities that are inside the cube with volume of 1 centered on the location?
sorry ive never used those target selectors in my life so i dunno much lol
can i use functions in constants like this?
const object = {
"onSneak": function(player) {
player.sendMessage("test")
}
}
object.onSneak(player)```
because when i tried it, player is said to be undefined
well
the player is actually and literally undefined
you could wrap object.onSneak(player) in world.getAllPlayers().forEach()
the one on the bottom is how i'd used it/typed it out, i did use the object in a getPlayers
Correct
player was still undefined tho
the location defines one corner, and the volume specifies the distance along each axis
oops, i directed it to the wrong string, lemme test it again
There was nothing wrong with the code in the first place
i just did a typo on "emeperor" which messed up everything
live skull reaction

me when "minecraft:soul_torch" is not included as a passableBlock in raycast options đż
HMRM
ahh so I just can't seem to detect a decorated pot with getBlockFromRay period
thought I just did something wrong
const hitBlock = block.dimension.getBlockFromRay(block.south(1).location, {x: 0, y: 0, z: 1}, { maxDistance: range - 1, includePassableBlocks: true, excludeTypes: ['minecraft:soul_torch'], includeTypes: ['minecraft:decorated_pot'] });
it just doesn't detect it at all :]
gotta love it
center the ray
block.south(1).center()
or bottom center
reminded me of when i tried to detect double chest by shouting a ray between the tow
turns out the collision box have a gap
How do I identify if there are mobs around in 5 blocks distance to execute a command?
getEntities with location and distance
what component trigger onCompleteUse?
i believe its for stuff like food
nope
"minecraft:use_modifiers": {
"use_duration": 0.5,
"movement_modifier": 0
},
trigger when use_duration is complete
yeah
but not only food



