#Script API General
1 messages · Page 36 of 1
I see thanks
You're welcome
How i use the script debugger bots?
I'm asking the after events you used not the before event.
But what he gave should work
Anyone know what the script Watchdog settings are by default on Realms? The value of the timeout specifically
Or perhaps more generally: If anyone knows what the default timeout setting might be on BDS.
Seems to be 10 seconds (10000 ms) as of 1.21.43
It is
#script-watchdog-hang-threshold=10000
# Sets the watchdog threshold for single tick hangs (default = 10000 ms).
Do I separately make a dynamic property for every location that I store in item or just one property
The best way depends on what the item does. It depends on the maximum number of locations you're going to have and how often you are going to update them.
I would say in most cases one property per location is better.
Hmm probably 12 locations max, and they don't update frequently cause to change the loc player needs to delete it first then put location they want
Oh. It doesn't really matter then, one property will work and is probably easier to code
idk made it work by making it a function
and running said function
Hello!
Does the playerInteractWithEntity event require the minecraft:interact component in the entity's behavior?
Thanks!
if you use afterEvents then yes, but you can do it without components
can anyone help me? maybe this is oot, but i want to ask how to connect LoginSecurity / AuthMeReloaded plugin to MYSQL database. i have node for my server and i have website with DirectAdmin panel. I've tried connecting it properly, but the plugin is giving an error, and the log says "plugin cannot connect to database"
completely the wrong place to ask lmao
it says the knockback is not a function, which i don't understand why
target.applyKnockback(player.location.x, player.location.z, 8, 0.1)```
Send full code
aight, gimme a sec
const Runner = system.runInterval(() => {
const players = world.getPlayers();
for (let player of players) {
let target = player.dimension.getEntities({location: player.location, excludeNames: [ player.name ], maxDistance: 8, closest: 1});
target.applyKnockback(player.location.x, player.location.z, 8, 0.1)
}
})```
well technically this isn't the full code, but i shortened it down to be able to be sent here
Idk what's problem
can't apply knockback to non-player
use applyImpulse i think or wtv its called
I made an entity that stomp attacks and I want to make the players get knocked away if they are within 10 radius from the entity should I use apply knockback or create explosion?
getEntities() returns Array despite closest: 1.
It also had a possibility of empty Array
you're basically calling Array.applyKnockback, which of course, doesn't work
i tried adding [1] and even with mobs nearby, it said it wasn't a function, which is odd
use 0 for the first element in the array
Array[0]
Is there a function that lets me check the specific family of an entity
import { world } from '@minecraft/server';
world.afterEvents.entityHitEntity.subscribe((event) => {
if (event.damagingEntity.typeId == 'mz:smile') {
const victim = event.hitEntity;
const victimFamily = victim.getComponent('minecraft:type_family');
if (victimFamily != 'demon') {
victim.applyImpulse()
}
}
});
This is my code so far the goal is:
I made an entity that stomp attacks and I want to make the players get knocked away if they are within 10 radius from the entity.
I don't know if I did something wrong
I'll just set the impulse later but is the code correct?
seems like to be
Wait, take alook at your component https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/entitytypefamilycomponent?view=minecraft-bedrock-stable
type_family class
Thanks but I just realized I don't need it cause I already set it up on the behavior.hdon file
Is it possible to import other files into the javascript that minecraft uses? I'm trying to import a json file that I custom made, but it's importing as ___.json.js, lol
You cant import json.
aight ty
hmm that would be nice wouldn't it
sigh lemme guess? We have to choose between lore limit increase or this?
no no no no. If we add importing JSON, we will decrease the lore limit to 7 characters
LGTM. Ship it.

function getAllEntities(options) {
let all = []
for (let id of ["overworld","nether","the_end"]) {
all = all.concat(world.getDimension(id).getEntities(options))
}
return all
}
Ia there a method for world.afterEvents.dataDrivenEntityTrigger.subscribe to make my mob apply impulse to target when my mob specific event is active
Documentation for @minecraft/server
Just applyImuplse or knocback to the entity.
Yeah I mean on a target of my mob when event is active
I try to do this target=entity.target
But not working?
Are you using beta apis?
Any content log?
I'm am not
There you go.
best way to detect the player that threw a projectile (when it has spawned, not when it has hit something)?
What beta version should I use then?
Theres only 1.
im worried getting the nearest player is not reliable enough cos sometimes it's not correct when i've tried
Um what is it?
And what Minecraft version it works
honestly just imported a json file anyways by just copying the whole thing and assigning it to a var lmao... a little cursed but it works so 🤷♂️
export const jsonObject = {
"a": {
"z": 1,
},
"b": {
"z": 2,
},
}
Oh shesh I misunderstood you I thought u say if I use Minecraft/server beta
world.afterEvents.projectileHitEntity.subscribe((data) => {
let projectile = data.projectile;
let isAbility = projectile.getDynamicProperty("isAbility")??false
why do i get Failed to call function 'getDynamicProperty'
Full error message
comes from line isAbility
this isnt the full file so
nothing else is relevant
Is the projectile valid
Entity is not valid
No way
You need to set the value of "destroyOnHit" (or whatever it is) in the projectile component to false
its not custom projectile if you meant that
but its okay
i found a new fix
So that the projectile is not destroyed upon collision and destroy it manually after executing the code
why do i get this humongous stack of slowdowns when i /reload
Lol 5 milliseconds. I wouldn't call it a "slowdown". This means you are running complex code at the beginning of loading scripts
do slowdowns from the same script stop showing up after a certain point if it calls for a slowdown multiple times
because i do not run anything complex specifically at the beginning of loading scripts
more like i run complex systems all the time
my pack is filled with loops at intervals of 1-2 ticks
Well that's your problem. Warnings do eventually stop showing up for the same script if they get triggered too many times. This message is warning you that your loops are lagging the game.
what do i do if i do need these loops tho ,,
You can change them so they run faster. What kinds of things do they do? Why do they need to run every 1-2 ticks?
this one is probably the most resource intensive one
yes this one is every 20 ticks but it's complex
i need to check what claim a player is in
system.runInterval(() => {
let dimension = world.getDimension("overworld")
const enderPearls = dimension?.getEntities({
location: { x: 0, y: 64, z: 0 },
maxDistance: 88 * 1.5,
type: "minecraft:ender_pearl"
});
const players = dimension?.getEntities({
location: { x: 0, y: 64, z: 0 },
maxDistance: 88 * 1.5,
type: "minecraft:player"
});
const allEntities = [...(enderPearls || []), ...(players || [])];
for (const plr of allEntities) {
const check = BlockVolumeUtil.intersects({ x: plr.location.x, z: plr.location.z },
{
from: { x: spawnArea.xMin, z: spawnArea.zMin },
to: { x: spawnArea.xMax, z: spawnArea.zMax }
})
if (check && (plr.typeId == "minecraft:player" ? (plr.getDynamicProperty("spawntag") ?? 0) > 0 : true == true)) {
let spawnLocation = { x: 0, y: 66, z: -1 };
let playerLocation = plr.location;
let teleportVector = {
x: spawnLocation.x - playerLocation.x,
y: 0,
z: spawnLocation.z - playerLocation.z
};
let length = Math.sqrt(teleportVector.x ** 2 + teleportVector.z ** 2);
let normalizedTeleportVector = {
x: teleportVector.x / length,
y: teleportVector.y,
z: teleportVector.z / length
};
let teleportDistance = -1;
let teleportX = playerLocation.x + teleportDistance * normalizedTeleportVector.x;
let teleportY = playerLocation.y;
let teleportZ = playerLocation.z + teleportDistance * normalizedTeleportVector.z;
while (
teleportX > spawnArea.xMin && teleportX < spawnArea.xMax &&
teleportZ > spawnArea.zMin && teleportZ < spawnArea.zMax
) {
teleportX += teleportDistance * normalizedTeleportVector.x;
teleportZ += teleportDistance * normalizedTeleportVector.z;
}
system.run(() => {
Frozen.Flag("Spawnglitch", plr);
plr.teleport({ x: teleportX, y: teleportY, z: teleportZ });
plr.runCommandAsync(`inputpermission set @s movement disabled`);
system.runTimeout(() => {
plr.runCommandAsync(`inputpermission set @s movement enabled`);
}, 20);
});
}
}
}, 1);
anti-spawnglitch stuff
tp ender pearls to be land outside of spawn
system.runInterval(() => {
for (const player of world.getPlayers()) {
const playerClass = player.getDynamicProperty("class");
if (playerClass === "bard") {
const inventory = player.getComponent("inventory");
const heldItem = inventory.container.getSlot(player.selectedSlotIndex);
try {
if (heldItem.typeId === "minecraft:iron_ingot") {
const team = player.getDynamicProperty("team");
for (const target of world.getDimension(player.dimension.id).getEntities({type: "minecraft:player",maxDistance: 16, location: player.location})) {
if (target.getDynamicProperty("team") === team) {
target.addEffect("resistance", 100, {
amplifier: 0
});
}
}
}
} catch {}
}
}
}, 1);
passive buffs for faction members (there's more to it than this but its all just repeated if statements
Wait, why do you use system.run inside of system.runInterval
Without being able to run the whole addon I can't tell you what is slowing you down the most, but you have a lot of loops inside loops and loops running in parallel. There are also more efficient ways to check land claims, especially if you have many of them.
how can I have a simulated player equip a shield using getComponent("equippable"):setEquipment(offhand) i tried it but it didn't work.
Is there a...onxpgranted perhaps? Theoretically...if I wanted to double the xp someone gets from doing an action(editing vanilla files is not possible due to smelting and other sources). I can't also just double the xp amount after each xp spawned.
copy pasted from another place i’ll remove that ty
you don’t use colons in js to call methods
try something like Entity.getComponent("equippable").setEquipment(EquipmentSlot.Offhand, new ItemStack("minecraft:shield", 1))
not sure if it’s actually like that im not on pc atm
runInterval and wait for xp increase
Yeah that was my original thinking.
an event for it would be nice
Do you mean xp from experience orbs explicitly or in general whether it be from orbs or commands
how would you prevent it from detecting the added xp to achieve the result of doubling as an increase tho
updating the old xp variable you saved
okay but if ur gonna check for xp increases in intervals like every 1 or 2 ticks
that’s not going to prevent it from detecting the manual addition as increase
manual addition?
he said he wants to double all the xp a player gets, no
no that should prevent it
Just a quick one. How would I go about something like this
./HC items 100 (would multiply the 100 by 8 giving an output of “800 gt”)
And
./HC gt 80 (would divide the 80 by 8 giving an output of “10 items”)
if a player gains a xp, add +a more xp
what should i don’t understand what you meant by updating the old variable
by detecting the xp change you mean detecting if the amount of experience a player has has been changed since last iteration?
exactly, so if u add any amount to xp it will trigger the interval to update oldxp again
oldxp -1
xp 0
add 2 to xp -> oldxp becomes 2
because xp changed, add the amount changed, xp becomes 4 -> okdxp becomes 4
because xp changed AGAIN (by 2), add the amount changed, xp becomes 6 -> oldxp becomes 6
and so on….
i think it wiuld get stuck in a loop like this
no?
he said he wanted to double all the amounts of xp given
that what i did
so it would detect +10, then give another 10, and giving this 10 would also detect the amount to be changed again and get stuck in loop
no you added it once but you don’t include logic to add the change in amount
i did...
oh wait right
i thought about implementing it a bit differently but now i inderstand why with ur logic it would work
yeah
i was going to update oldxp before adding the doubled amount
you need to keep track of the amount added,, so yeah
is there any way to run a custom command using a command block... i thought chatSend would work for some reason lol
Scriptevent?
ty, got it working
oh wait i didn't use colons though mb
lua getting through my head
but hold up. What I found weird is that the simulatedplayer not showing the equipment which it is odd
oonly armor not shields, fireworks, etc...
What does apply impulse do?
Does it do knockback
Yes
import { world } from '@minecraft/server';
world.afterEvents.entityHitEntity.subscribe((event) => {
if (event.damagingEntity.typeId == 'mz:stomp1') {
const victim = event.hitEntity;
const attacker = event.damagingEntity;
if (victim && attacker) {
const attackerPos = attacker.location;
const victimPos = victim.location;
const direction = {
x: victimPos.x - attackerPos.x,
y: 0,
z: victimPos.z - attackerPos.z,
};
const magnitude = Math.sqrt(direction.x ** 2 + direction.z ** 2);
const normalizedDirection = {
x: direction.x / magnitude,
y: 2,
z: direction.z / magnitude,
};
const strength = 5;
const knockback = {
x: normalizedDirection.x * strength,
y: normalizedDirection.y * strength,
z: normalizedDirection.z * strength,
};
victim.applyImpulse(knockback);
}
}
});
Why is my knockback not working cause I made my boss summon another entity to do the attacking which is called mz:stomp1 and after 0.1 seconds that entity disappear is that the reason why my knockback system is not working?the entity disappears before the script runs
Wait I check it
Is this valid in runJob? I genuinely don't know how to use this thing.
system.runJob(function* test() {
yield
});```
Wow I never see the things like this
add a () after the function definition
so it's like
system.runJob(function*(){}())
you gotta call it to get the generator which the runJob uses
Thank you
Does anyone have a better idea than this
What is better to use apply knockback or apply impulse?
Depends on the tasks
Well my goal is this
A boss that stomps and knockbacks players away from it
applyKnockback at least because applyImpulse does not work on players
I see thanks I'll try and change this code that I made
import { world } from '@minecraft/server';
world.afterEvents.entityHitEntity.subscribe((event) => {
if (event.damagingEntity.typeId == 'mz:stomp1') {
const victim = event.hitEntity;
if (victim) {
victim.applyKnockback(0, 0, 0, 10, 0);
}
}
});
I tried simplyfiying the code to just make the players upwards but it doesn't work can you see why?
Because you need to carefully read the documentation
you have more parameters for the method than it should have
Oh I see I thought there is a y value hahaha thanks
just delete one zero
directionX, directionZ, horizontalStrength, verticalStrength
yeah
Ill try it now
verticalStrength has an exponential graph
not linear
you should take this into account
So I should add at least a little bit value to the directions or the horizontal strength?
i think maybe
Thanks
applyKnockback is cursed
but suitable for single hits
It still doesn't work I tried it 😭
code
import { world } from '@minecraft/server';
world.afterEvents.entityHitEntity.subscribe((event) => {
if (event.damagingEntity.typeId == 'mz:stomp1') {
const victim = event.hitEntity;
if (victim) {
victim.applyKnockback(1, 1, 10, 5);
}
}
});
My entity is using area attack does that count as entity hit?
yes.
However no
Then why doesn't this work? 😭😭
I tested this not long ago, and it doesn’t work very well here either.
use entityHurt instead then.
Can I be able to detect the attacker?
yes.
Okay I'll try
import { world } from '@minecraft/server';
world.afterEvents.entityHurt.subscribe(({ damageSource, hurtEntity }) => {
if (damageSource.damagingEntity.typeId == 'mz:stomp1') {
const victim = hurtEntity;
if (victim) {
victim.applyKnockback(1, 1, 10, 5);
}
}
});
It is working sometimes and sometimes not but for other entities there are times it gets delayed also for player
in a entityhurt event how do i get how much damage is getting dealt
There is a damage argument you can use
how?
thanks
Can you check the reason here serty
i needed it so i could make a damage indicator
Bro you're making slime addon
ye
In this script it is throwing this error :
[Scripting][error]-TypeError: cannot read property 'typeId' of undefined at <anonymous> (win/smile.js:5)
Read the error
I think the reason is it is checking entities that got hurt that was not cause by the damaging.entity?
Right!
(begrudgingly new at scripting)
How does one set up an addon to begin using scripts?
(please do correct me if I am wrong)
- add a script module in the manifest (of the behaviour pack only)
- also add a decency for @minecraft server (for some reason...)
- create a folder for scripts
- make a main.js file (to 'subscribe' whatever scripts that needs to be subscribed in the game for your addon to work)
then make whatever script files you need... right?
( and unless need be, you do not have to enable Beta API to do scripting in general?)
(and those who may be more of a hobbyist or a dabbler, could they skip the npm setup?)
that sadly does not answer the question.
That only spoonfeeds how to make a script file that spams "Hello World"
And not how said script file can be applied to anything in a addon.
Namely, subscribe a different script file for a block event (ex. a player interacts with "Block X" while holding an axe, and it is replaced with "Block Y". aka a stripped log event)
It talks about the base. How to connect the script. This site also has a little more about scripts. To connect 1 more file you need to learn import in js. The documentation itself, which describes all the methods and capabilities here
The link provided sadly does not explian how to import js files. Not even contain a link to it.
It just lists a whole bunch of information. None of which is helpful to explaining how to solve the question.
a russain doc... why?
Imma rather leave this channel.
Seems like it does not help at all with a person looking to learn.
And not be sent on goose chases while at it.
Auto translation. I have already changed the link
Well, or I can help you with writing a script, just explain what you need

I would go to mcpedl, go to scripts section and download anything that catches your attention
Then open those files and try changing things around
That helps with codon
codon?
I'll have a look, thank you.
that is the slowest way of learning
uh, just to make sure
const slot = inv?.getSlot('Mainhand'); is how i can get itemStack slot, right?
isn't getSlot argument an index
i want to replace the itemStack, not detects it
just like slot?.setItem(new ItemStack(,,,))
no that return the slot
use getItem
also it uses an index (number)
i cant replace the item using getItem
i had to use getSlot
why not
world.afterEvents.playerInteractWithEntity.subscribe(({target: entity, itemStack, player}) => {
const inv = player?.getComponent('minecraft:inventory')?.container;
const slot = inv?.getSlot('Mainhand');
if (entity?.typeId === 'my:entity') if (itemStack?.typeId === 'minecraft:raw_iron') slot?.setItem(new ItemStack('minecraft:raw_copper', 1));
})```just replacing the item after interacting with the entity, after interacting with it, it will replace the item that u are holding with another item.
const slot = inv?.getSlot(player.selectedSlotIndex);
i mean why do you even need to get the slot
just set it directly
?
how?,,
setItem() getItem()
ah, i thought theres a better way
inv?.setItem(player?.selectedSlotIndex, new ItemStack('minecraft:raw_copper', 1));.
I didn't mean to send that
how do I make something in a script run through a command?
i want it to when a person is standing in a certain area it runs a script. but in a command block so it doesn't cause lag with system run interval
Has anyone got any ideas?
I’m not the best at this lol
Elaborate, explain what you mean
What am I supposed to think of when you say "./HC gt 8"
You should read his mind, that's obvious
Yeah my bad
how do I use script events?
/scriptevent namespace:id message
A new version 1.18.0-beta has been released for documentation. There's nothing new there...
Nvm
Nothing new in changelog 1.18.0-beta
oh, it wasn't working because I misspelt it
Yeah yeah I now understand
Ok well
My idea is to make a command to calculate the amount of time X amount of items will add up in a hopper counter. Or if you specify the amount of game ticks it will tell you how many items you need to got that time
So the math for that is this
Items > game ticks
[items] x8 = [game ticks]
game ticks > items
[game ticks] ÷8 = [items]
Well, let's start with the fact that custom commands are impossible
No it’s not? My addon literally uses ./ for everything
//Command
player.sendMessage(`Game ticks: ${itemsCount*8}`);
// Another Command
player.sendMessage(`Items: ${gameTicks/8}`);```
Thx
You're welcome
You can't trust anyone, not even documentation
Is it possible to spawn a mob tamed to the player
yes
function spawnTamedEntity(entityId, location, player) {
let entity = player.dimension.spawnEntity(entityId, location)
entity.getComponent("tameable")?.tame(player)
return entity
}
You're a little late ;)

import { world, system } from '@minecraft/server';
import { tameableMobs } from 'api/utils/lists'; // Corrected import path
function spawnMob(player, entityName, isMountable) {
const location = player.location;
const dimension = player.dimension; // Get the player's dimension
const entity = dimension.spawnEntity(entityName, location); // Spawn the specific mob
// Tame the entity to the player
const tameableComponent = entity.getComponent("tameable");
if (tameableComponent) {
tameableComponent.tame(player);
}
const type = isMountable ? "Mount" : "Pet";
player.runCommandAsync(`tellraw @a {"rawtext":[{"text":"Your ${entityName.replace("lycanite:", "")} has been bound, you will now find it in your ${type} Manager."}]}`);
return entity; // Return the entity
}
world.afterEvents.itemUse.subscribe(event => {
const player = event.source;
const item = event.itemStack;
const itemId = item.typeId;
const mobs = tameableMobs[itemId];
if (!mobs) return;
const mob = mobs[Math.floor(Math.random() * mobs.length)];
spawnMob(player, mob.name, mob.is_mountable);
// Remove the soulstone from the player's inventory
player.runCommandAsync(`clear @s ${itemId} 1`);
});
i tried it but the mob dosent spawned tamed
How did you test its tameness?
Well, then most likely it cannot be tamed, because getComponent() gives undefined, because the mob does not have a component
i hit an entity and it didnt start attacking it
however when i hit it it dosent attack me
2 secs
Your entity code
wait nvm its attacking me
i tried using entity events aswell but it didnt work
wait now its tamed
gimme a sec
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36m<REPL0>.js[0m:[33m2[0m:[33m30[0m - [31merror[0m[30m TS2792: [0mCannot find module 'api/utils/lists'. Did you mean to set the 'moduleResolution' option to 'nodenext', or to add aliases to the 'paths' option?
[7m2[0m import { tameableMobs } from 'api/utils/lists'; // Corrected import path
[7m [0m [31m ~~~~~~~~~~~~~~~~~[0m
ESLint results:
<REPL0>.js
1:17 error 'system' is defined but never used @typescript-eslint/no-unused-vars
The import seems to be correct
uh,
if (count % 20 === 0 && entity?.isValid() === true) has a log inside the unloaded chunks
how can i force it to work on the entity only when the chunks are loaded?, using blocks right?
const block = entity?.dimension.getBlock(entity?.location)
if (count % 20 === 0 && entity?.isValid() && block?.isValid() === true) { ,,, }?
alr its working ty
uh, i just make it right while asking
How do I detect if block has been destroyed by explosion?
how can i create a modded scoreboard
world.afterEvents.blockExplode
Documentation for @minecraft/server
world.beforeEvents.playerLeave.subscribe(({ player }) => {
let inv = player.getComponent("inventory").container;
let invMap = []
let invSize = inv.size
for (let i = 0; i < invSize; i++) {
invMap.push(inv.getItem(i))
}
let effects = player.getEffects();
let armor = player.getComponent("equippable").getEquipment;
let dimension = player.dimension;
let loc = player.location;
let name = player.name;
if ((player.getDynamicProperty("spawntag") ?? 0) > 0) {
system.run(() => {
let entity = dimension.spawnEntity("tr:combat", loc);
let container = entity.getComponent("inventory").container
invMap.forEach((value,index)=>{
if (value instanceof ItemStack) {
container.addItem(value);
}
})
let HeadArmor = armor(EquipmentSlot.Head);
let ChestArmor = armor(EquipmentSlot.Chest);
let LegsArmor = armor(EquipmentSlot.Legs);
let FeetArmor = armor(EquipmentSlot.Feet);
if (HeadArmor) container.addItem(armor(EquipmentSlot.Head));
if (ChestArmor) container.addItem(armor(EquipmentSlot.Chest));
if (LegsArmor) container.addItem(armor(EquipmentSlot.Legs));
if (FeetArmor) container.addItem(armor(EquipmentSlot.Feet));
entity.nameTag = `§c${name} §7[Combat-Logger]`;
});
}
});
what does the error mean
THERE IS AN IMPOSTER BETWEEN US!
why do i have to run /reload every time i start up my world
if i don't the bp doesn't take efffect
can functions run with runJob returns values somehow?
This usually happens because your initialization logic is expecting the world to be more loaded than it is.
What do the content logs say?
Anyone down to work with me on learning to use Script API to the fullest extent?
You can wrap them in a promise to make them a regular async function. What kind of value do you want to return?
How can I disable block from dropping loot if it was blown up by explosion?
Like TNT do
What's the difference between system.run, system.timeout, system.waitTicks, etc?
remove the block from the effected blocks array and set it to air
how do i set a player's view direction
tp
system.runTimeout calls your callback function after a specific number of ticks. system.run does it as soon as possible (usually the same tick or the next tick). system.waitTicks is used in async functions to wait a certain number of ticks.
i'll try to check that the next time i rejoin
without overriding velocity
Is it possible to make it using world.afterEvents.blockExplode?
beforeevent
not possible
Can I ask what the difference between async and regular commands are?
And do I just do runInterval at 0 to make something constant?
I want to search the nearest block of a certain in an area, of all the blocks of that id
ok how to set view direction tho
do i need to use commands
Their location
Like detect id there are logs in a cube around a certain location
Return true or false depending on that
asynchronous functions will not block the rest of the thread from running, hence the name asynchronous, it will not be in sync with the rest of your code
Alr, when does that come in useful?
in scenarios where you want to wait before executing something without also waiting for the other things to execute
and there's some things that will take a lot of time to process and sometimes you wanna handle those asynchronously
to prevent other things from slowing down
in other programs api requests are commonly asynchronous, because otherwise the rest of ur code would be blocked from running further until a response is given
How many jobs can I have running at a time?
difference between runCommand and runCommandAsync?
hit.setRotation({x: -180, y: hit.getRotation().y})
why does this not do anything
Some commands take more time to run than others. runCommand will block the script engine until the command returns. runCommandAsync returns a promise that resolves when the command is done so you can keep running other code.
when i apply the rotation through .teleport it works perfectly fine
but not this way
Thanks @jolly citrus
thanks
ur welcome
One last question for everyone for at least 3 minutes
What's the diff between applyImpulse and applyKnockback
I've never used applyImpulse
and am not even sure how to
Because I use applyKnockback to create dashing
applyImpulse is only applicable to entities that are not players, applyKnockback is the opposite
Ah
idk about the values though
Alright
it works a bit differently
Works for me
Thanks
Can I use runInterval(() => {
blah blah blah
}, 0);
For a constant run?
Yeah, that would run it every tick. Just make sure you actually need to run your code every tick and can't get away with a longer interval. This is one of the most common performance issues.
anyone has an idea why the getEntitiesFromRay doesnt work properly in this case?
export default function ({block}) {
const state = block.permutation.getState('minecraft:cardinal_direction')
let direction = {}
switch (state) {
case "north":
direction = { x: 0, y: 0, z: -1 };
break;
case "south":
direction = { x: 0, y: 0, z: 1 };
break;
case "west":
direction = { x: -1, y: 0, z: 0 };
break;
case "east":
direction = { x: 1, y: 0, z: 0 };
break;
default:
break;
}
const entities = block.dimension.getEntitiesFromRay(block.location, direction,{maxDistance:10})
console.warn(entities.length);
for (const entity of entities) console.warn(entity.distance);
}```
It's broken for players
Is it possible to detect if the player is walking forward or backward?
Check their movement and the direction they are facing.
How can I do this? I'm a beginner in the subject
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
let { forward, right, backward, left } = direction(player);
let text = ''
if (forward > 0) {
text = 'forward';
} else if (left > 0) {
text = 'left';
} else if (right > 0) {
text = 'right';
} else if (backward > 0) {
text = 'backward';
} else return;
player.sendMessage(text);
}
})
function direction(player) {
let velocity = player.getVelocity();
let viewDirection = player.getViewDirection();
let viewDirMagnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
let normalizedViewDir = { x: viewDirection.x / viewDirMagnitude, z: viewDirection.z / viewDirMagnitude };
let forwardVelocity = (velocity.x * normalizedViewDir.x + velocity.z * normalizedViewDir.z);
let rightVelocity = (velocity.z * normalizedViewDir.x - velocity.x * normalizedViewDir.z);
let backwardVelocity = -forwardVelocity;
let leftVelocity = -rightVelocity;
forwardVelocity = Math.round(forwardVelocity * 100) / 100;
rightVelocity = Math.round(rightVelocity * 100) / 100;
backwardVelocity = Math.round(backwardVelocity * 100) / 100;
leftVelocity = Math.round(leftVelocity * 100) / 100;
return {
forward: forwardVelocity,
right: rightVelocity,
backward: backwardVelocity,
left: leftVelocity
};
}```
This works very fine to me.
Thnk u
Btw soon this would be useless cause there's a more accurate way but it's currently in preview
It can detect wasd up and down button even if we disabled it's movement
Oh, that's great. I'm waiting.
Can you make double jumps with script api?
Well, specifically air-jumps (as many as I want to add)
Less about that now
is there any way i can append the contents of an array to the bottom of another array?
More about how to detect when an elytra is being used
front or back, not bottom
you mean back right?
In javascript, if I remember correctly, there's something called push for an array
yes
const array1 = [1,2,3]
const array2 = [4,5,6]
array1.push(...array2) // [1,2,3,4,5,6]
thats what is so weird
this is what i used:
var vanillaEquippableIds = [
...
]
export const mBEquippableIds = [
vanillaEquippableIds.push(mBTypeIds)
]```
wdym
and you need to spread the mbTypeIds (assuming it's also an array)
oh wait what
wtf
what are you even doing there lmao
the "..." was just so that i didn't have to copy all the contents of the array
ah right
well
first, you're not even correctly pusing mBTypeIds onto vanillaEquibbableIds. right now you're pushin the entire array onto it, instead of it's items
second, that will put it int vanillaEquippableIds, not your new array
i see
use this
import { mBTypeIds } from "./mBTypeIds.js";
var vanillaEquippableIds = [
// ...
]
export const mBEquippableIds = [
...vanillaEquippableIds,
...mBTypeIds
]
that will spread both arrays into the new one
Guys, why is the server-net module* only for BDS?
Did U find the reason for my code?
If you don't have internet, you won't be able to use it.
Mvm
And maybe some data can be read by the person who created the addon, and this already looks like a virus
hmmm okay
how would i applyImpulse an entity towards the player?
let strength = 2
player.applyKnockback(direction.x, direction.z, strength, direction.y*strength)
how about applyImpulse? that's applyKnockack, which doesn't work for items as i tried
code
Do you need an item lying on the ground to be attracted to the player?
entity.applyImpulse(-player.getViewDirection())```
do you perhaps know the formula?
Apparently I should still give people this function.....
the applyknockback earlier?
function getDirection(vector1, vector2) {
let distance = Math.sqrt((vector1.x-vector2.x)**2 + (vector1.y-vector2.y)**2 + (vector1.z-vector2.z)**2) || 0.001
let direction = {
x: (vector2.x-vector1.x)/distance,
y: (vector2.y-vector1.y)/distance,
z: (vector2.z-vector1.z)/distance
}
return direction
}
What means of sqrt?
square root of a number.
Oh
are there any functions i can use to find out the performance ?
let lastDate = Date.now()
let TPS = 20;
system.runInterval(() => {
itemMechanics()
const currDate = Date.now();
TPS = tickspeed * 50 / (currDate - lastDate) * 20
lastDate = currDate
console.error(TPS)
}, tickspeed
)
i used this it prints 0
currDate - lastDate is in milliseconds so you need to / 1000 to convert to seconds
0/1000 is still 0
also no one test performance in seconds
unless you are a python user
they're calculating ticks per second
what is your tickspeed variable set to?
0 i made it 1 so it got fixed
:l
is it somehow possible to detect if the player after joining is valid to hear sounds?
i want to play a sound after joining but i need to use a timeout
because sounds are played after rendering the world. The player is valid after joining
uh
if (eEntity?.typeId?.startsWith('exe:')) return; shouldn't work on entities that starts with 'exe:' right?
it works on them, somehow
correct
Yeah, nothing too crazy tho
No I guess? Since we can't even detect sound in the first place
i thought of a variable or a method to detect that
And what is it?
system.runInterval(() => {
count++;
let slots = 0;
const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
for (const entity of world.getDimension(dim).getEntities()) {
if (entity?.typeId === 'my:entity' && entity?.isValid()) {
const dim = entity?.dimension;
const loc = entity?.location;
const entities = dim?.getEntities({location: loc, maxDistance: 18});
entities?.forEach((eEntity => {
if (eEntity?.typeId.startsWith('exe:')) return;
}));
};
};
});
});```this is all
i only thought that a variable or method existed.
i tried catching and tryTeleport
but both execute without errors
so i guess it isnt possible
Did you try to run a code to entities that starts with exe?
if (eEntity.typeId.startsWith('exe:')) {
console.error('bruh');
}```
literally bruh
uh, can i use this entity?.dimension.getEntities({location: loc, maxDistance: 1, type: '' ← ←}); to make it not working for a specific entities?
cuz that return thing isn't working, somehow
world.afterEvents.playerSpawn.subscribe(data => {
if (!data.initialSpawn) return
data.player.playSound("soundName")
})
hmm,
@warm mason return is not returning in my script
Do console.warn(eEntity.typeId)
what?
why did you send me a script for checking if the player joined
Well, you need to play the sound when you join
i asked for a method or variable to check if the player is able to hear sounds
yuh, but with a delay
This one doesn't exist
For what
players dont hear anything when they join
after some time they start to hear
or render the game
playerSpawn - event when a player spawns. He can do anything
Well, you can set the delay for a second just in case
yeah i can, but i want it to be delay to the time the player can hear
sometime the device can lag and take more than a second
Well it doesnt work like that.
AfterEvents.PlayerSpawned(({ player, playerJoined }) => {
if (!playerJoined) return;
player.hud.setTitle(
titleGreeting,
{
subtitle: subtitleGreeting,
fadeInDuration: 10,
fadeOutDuration: 10,
stayDuration: 20 * 10
}
);
player.playSound("random.levelup");
});
this is what i use
OK I'll check it out
the sound is not being heard
if (eEntity?.typeId?.startsWith('exe:')) console.warn('isWorking'); is working
What is "playerJoined"?
a property
but return is not
it's initialSpawn
He uses his mega library
Ok
true
Might have to extend the durations
Have u tried extending it?
what do you mean by extending it?
Like 30 40
the delay? as in system.runTimeout?
Fade delay
Ok, u can try runTimeout on playSound
i did
and it works
but it is risky
depends on how much time it takes the device to render the game
i guess will need to stick with timeouts
system.runInterval(() => {
count++;
const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
for (const entity of world.getDimension(dim).getEntities()) {
if (entity?.typeId === 'my:entity' && entity?.isValid()) {
const dim = entity?.dimension;
const loc = entity?.location;
const entities = dim?.getEntities({location: loc, maxDistance: 18});
entities?.forEach((eEntity => {
if (eEntity?.typeId.startsWith('exe:')) console.warn('a'); ← is warning
if (eEntity?.typeId.startsWith('exe:')) return; ← isn't returning
eEntity?.addEffect('nausea', TicksPerSecond * 10, {amplifier: 0, showParticles: false});
}));
};
};
});
});```*why?*
how do you know it isnt returning?
lemme edit it really quick
the entity that is starts with exe: is getting the effects too
Just put them inside of {}, there fixes your problem
The warning shows up right?
yes
erm
you first check if the entity is my:entity
like if (!eEntity.typeId.startsWith('exe:')) { effects }?
is that correct?
it is
What's wrong here?
const playerGrab = world.getPlayers()
playerGrab.forEach((e) => {
if (e.isGliding) {
if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 8) {
e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
world.scoreboard.getObjective("doubleJump").addScore(e.source, 1);
e.runCommand("clear @s elytra");
system.runTimeout(() => {
e.runCommand("replaceitem entity @s slot.armor.chest elytra");
}, 2)
}
}
})
There's two things
It checks the entities, if the entity exists another array of entities but certain distance but it checks if entities have id starts with exe:
So I don't think he did something wrong here. He also said that the warning shows up it just doesn't return
addScore(e, 1)
warn is warning when it found an entity that starts with exe:
but it's not returning, and keep giving them the effects
Oh, yeah, forgot this isn't an itemUse
Thanks!
Is that the only thing wrong?
I already told you just put them inside of {}
I'll try it
if (!eEntity.typeId.startsWith('exe')) {
}```
stills giving them the effects
startsWith is broken
I'll use other method
later
I don't think it's really broken, if yes try eEntity.typeId.includes('exe:')
not working either
I'll try the other method later.
it will work, 100%
system.runInterval(() => {
count++;
const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
for (const entity of world.getDimension(dim).getEntities()) {
if (entity?.typeId === 'my:entity' && entity?.isValid()) {
const dim = entity?.dimension;
const loc = entity?.location;
const entities = dim?.getEntities({ location: loc, maxDistance: 18 });
entities?.forEach(eEntity => {
if (eEntity?.typeId.startsWith('exe:')) {
console.warn('a');
return;
}
eEntity?.addEffect('nausea', TicksPerSecond * 10, { amplifier: 0, showParticles: false });
});
}
}
});
});
I just realized, the return is almost equivalent to continue in your case
entities?.filter(eEntity => !eEntity?.typeId.startsWith('exe:'))
.forEach(eEntity => {
eEntity?.addEffect('nausea', TicksPerSecond * 10, { amplifier: 0, showParticles: false });
});
The continue if for a loop
And certainly they're not the same
true
Continue skips the rest of the code in the current iteration of a loop and moves to the next iteration while return exits it early and immediately
yeah
i said that return in that case is like continue
i never said that return is continue
.
I gave an explanation to that, before you said it's almost a 1:1
Nah it's good, everything's good
i will remake it once again, its really bugged,
I'm having trouble here
I want something to be active for every player
but this isn't doing that
const playerGrab = world.getPlayers()
playerGrab.forEach((e) => {
The inputs I have in the forEach function aren't being run constantly
or maybe just aren't beiing run on the players in the world
This code should run one time for each player. Do you have it in a loop?
What am I doing wrong? I want to read some permutations from block before it explodes but I'm getting this error:
[Scripting][inform]-Detected bomb: {"x":3,"y":69,"z":-422}
[Scripting][inform]-test: undefined
[Scripting][error]-TypeError: Native variant type conversion failed. Function argument [1] expected type: number | boolean | string at <anonymous> (atomic_bomb/atomic_bomb_explosion.js:110)
Here is my code that goes under world.beforeEvents.explosion.subscribe(explodeEvent => {
// Trigger an explosion if the bomb block has been blown up
const impactedBombBlocks = explodeEvent.getImpactedBlocks().filter(b => b.typeId === blockID);
system.run(() => {
if (impactedBombBlocks) {
for (let i = 0; i <= impactedBombBlocks.length; i++) {
// const block = explodeEvent.dimension.getBlock(impactedBombBlocks[i]);
const block = impactedBombBlocks[i];
// const { x, y, z } = block.location;
const { x, y, z } = block.bottomCenter();
console.log(`Detected bomb: ${JSON.stringify(block)}`);
const blockCardinalDirection = block.permutation.getState('minecraft:cardinal_direction');
console.log(`test: ${blockCardinalDirection}`);
const entityRotationPermutation = 'nubs:rotation';
// create rotation table for entities
const cardinalToRotationTable = {
'north': 0,
'south': 2,
'west': 3,
'east': 1
};
// remove block
block.setPermutation(BlockPermutation.resolve("minecraft:air"));
// kill dropped loot
const drop = explodeEvent.dimension.getEntities({ type: 'item', closest: 1 })[0];
drop.kill();
// spawn entity
explodeEvent.dimension.spawnEntity(`${entityID}`, { x: x, y: y, z: z });
// find summoned entity
const entity = explodeEvent.dimension.getEntities({ type: entityID, closest: 1 })[0];
// set entity properties for correct rotation
entity.setProperty(entityRotationPermutation, cardinalToRotationTable[blockCardinalDirection]);
}
}
})
block.permutation.getState('cardinal_direction');
is it in system.runInterval()?
It still gives me undefined
Whats line 110?
This one:
entity.setProperty(entityRotationPermutation, cardinalToRotationTable[blockCardinalDirection]);
It causes errors because blockCardinalDirection is undefined
Not all blocks have a cardinal direction.
The block I'm checking for should
Other blocks might be impacted.
Doesn't const impactedBombBlocks = explodeEvent.getImpactedBlocks().filter(b => b.typeId === blockID) filter it?
(const blockID = 'nubs:atomic_bomb_block';)
One sure fire way is log the type id in each loop 🙂 .
what's its all states look like in script?
Theres your issue.
uhm, that block instance turns air inside the system.run
thats why its typeId is air and has no cardinal_direction
world.beforeEvents.explosion.subscribe(explodeEvent => {
// Trigger an explosion if the bomb block has been blown up
const impactedBombBlocks = explodeEvent.getImpactedBlocks().reduce((array, block) => {
if (block.typeId !== blockID) return array;
return array.concat({ block, permutation: block.permutation })
}, []);
//if length is !0
if (!impactedBombBlocks.length) return;
const dim = explodeEvent.dimension;
system.run(() => {
const entityRotationPermutation = 'nubs:rotation';
const cardinalToRotationTable = {
'north': 0,
'south': 2,
'west': 3,
'east': 1
};
const query = { type: 'item', closest: 1 };
for (let i = impactedBombBlocks.length; i--;) {
// const block = explodeEvent.dimension.getBlock(impactedBombBlocks[i]);
const { block, permutation } = impactedBombBlocks[i];
// const { x, y, z } = block.location;
const { x, y, z } = block.bottomCenter();
console.log(`Detected bomb: ${JSON.stringify(block)}`);
console.log(`test: ${JSON.stringify(permutation.getAllStates())}`);
// create rotation table for entities
const cardinalToRotation = cardinalToRotationTable[permutation.getState('minecraft:cardinal_direction')];
// remove block
block.setType("air");
query.location = { x, y, z };
// kill dropped loot
const drop = dim.getEntities(query)[0];
drop?.kill();
// spawn entity
const entity = dim.spawnEntity(entityID, { x, y, z });
// set entity properties for correct rotation
entity.setProperty(entityRotationPermutation, cardinalToRotation);
}
})
});
```idk if the `drop.kill()` would work properly tho
If not, I expect that drop.remove would
Thank you, that perfectly works!
that was indeed it; i'm trying to load the container of a block that has not yet been loaded at the top of a script, how do i fix it tho
Ah, no I dont. Would the easiest way to loop just be something like this?
server.runInterval(() => {
code here
}, 0);
No, if I put it in one, will it be fixed?
And can I put 0 as the interval, or does it need to be 1
✅
Alright bet, thanks!
0 and 1 are the same. They both run every tick. The only difference is that 0 starts running on the current tick and 1 starts on the next tick
Ah, I see
Thanks
I'm making a combat system
I've made two moves for a sword, double jumps, dashes, teleports
Very fun
uh, is the world.getDimension({ matchAll('all 3 dimensions') }) a thing?
i mean is it a better way to get all 3 dimensions at once?
cuz i wanna get all 3 dimensions without putting it inside of a loop
is playerInteractWithBlock the only event called when a player right clicks a chest
or bed etc
This isn't working:
system.runInterval(() => {
playerGrab.forEach((e) => {
if (e.isGliding) {
if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
world.scoreboard.getObjective("doubleJump").addScore(e, 1);
e.runCommand("clear @s elytra");
system.runTimeout(() => {
e.runCommand("replaceitem entity @s slot.armor.chest elytra");
}, 2)
}
}
})
}, 0)
Is this something wrong with this code?
I'm gliding, and nothing is happening
system.runInterval(() => {
world.getAllPlayers().forEach((e) => {
if (e.isGliding) {
if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
world.scoreboard.getObjective("doubleJump").addScore(e, 1);
e.runCommand("clear @s elytra");
system.runTimeout(() => {
e.runCommand("replaceitem entity @s slot.armor.chest elytra");
}, 2)
}
}
})
})```
What did you change?
What was changed?
Oh you changedfor getAllPlayers
I had it as getPlayers
Oh yes, I never added that to showcase
You also removed the 0 in the system.runInterval
does that also make it every tick>
?*
yes
is there any better way to const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
for (const entity of world.getDimension(dim).getEntities()) { get all 3 dimensions without putting it inside of a loop like that?
no
Hmm, this is frustrating, it's still not working
const playerGrab = world.getAllPlayers();
system.runInterval(() => {
playerGrab.forEach((e) => {
if (e.isGliding) {
if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
world.scoreboard.getObjective("doubleJump").addScore(e, 1);
e.runCommand("clear @s elytra");
system.runTimeout(() => {
e.runCommand("replaceitem entity @s slot.armor.chest elytra");
}, 2)
}
}
})
playerGrab.forEach((e) => {
if (e.isOnGround) {
world.scoreboard.getObjective("doubleJump").setScore(e, 8);
}
})
playerGrab.forEach((e) => {
if (e.isOnGround) {
if (e.isSneaking) {
if (e.isJumping) {
e.applyKnockback(e.getVelocity().x, e.getVelocity().z, 7, -0.4);
}
}
}
})
})
This is what I currently have @warm mason
And all my other code outside of this segment works
But this isn't running anything
system.runInterval(() => {
world.getAllPlayers().forEach((e) => {
if (e.isGliding) {
if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
world.scoreboard.getObjective("doubleJump").addScore(e, 1);
e.runCommand("clear @s elytra");
system.runTimeout(() => {
e.runCommand("replaceitem entity @s slot.armor.chest elytra");
}, 2)
}
}
})
playerGrab.forEach((e) => {
if (e.isOnGround) {
world.scoreboard.getObjective("doubleJump").setScore(e, 8);
}
})
playerGrab.forEach((e) => {
if (e.isOnGround) {
if (e.isSneaking) {
if (e.isJumping) {
e.applyKnockback(e.getVelocity().x, e.getVelocity().z, 7, -0.4);
}
}
}
})
})```
does container.addItem() return undefined if the item wasn't able to be added for reasons such as the container being full?
Most likely yes
does it return the itemstack or undefined if it was full
i feel like it would return it back if it couldn't be added
i'm going to try that first
weird that the documentation doesn't include which one is returned when
I think it will increase the itemStack that ended up (for example 3 stones + 3 stones = 6 stones)
The scoreboard value could be wrong. In fact, it's not a great idea to use a scoreboard for this at all. What exactly are you trying to do? Let a player boost without using a firework a certain number of times while gliding?
No, I'm trying to create a double-jump
When you press space in air, it glides
I want it to boost you up with knockback
remove your elytra
and give it back
I have the scoreboard so they can only airjump 8 times
Does applyKnockback not work when gliding? Either way I think the issue here is that you're only doing the knock back if the player is sneaking, jumping and on the ground. Don't you want !e.isOnGround?
No, that part is the dash
world.getAllPlayers().forEach((e) => {
world.sendMessage("loop works");
if (e.isGliding) {
if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
world.scoreboard.getObjective("doubleJump").addScore(e, 1);
e.runCommand("clear @s elytra");
system.runTimeout(() => {
e.runCommand("replaceitem entity @s slot.armor.chest elytra");
}, 2)
}
}
})
This is the double jump
Can someone help me with this error: "[SCP-Project Orgon BP - 1.0.0] - [main.js] ran with error: [SyntaxError: Invalid Redefinition of lexical identifier at clicks/lever.js:37]
No
I thought case was their own pieces of code so I didnt know if they could be accessed outside of each case
is it possible switch cases arent block independent unless you wrap them with {}
have you tried
//logic
}
case 'south': {
//logic
}
}```
no
Why use switch/case if there is if/else
Easier for me
Moreover, your code is quite monotonous, it is easier for you to substitute variables than to write a separate piece for each case
Oh it is because i redeclared it
in js inside a switch statement all case blocks share the same scope unless explicitly wrapped in their own block (using {})
so that is invalid redefinition of the variable
keep in mind a scope can access the parent scope variables but not the other way around
Ive only just started script API a week ago so I'm very new
I believe most langaues yes.
yeah
i can't speak in general
just use if/else and be happy
I thought that was the case but I don't really use switch cases often
you did the same thing
i said they share the same scope
Use if/else - no no no
suffer with switch/case - yes, that’s our opinion.
Idk what coding scope is
Switch is easier for me cus it's less time consuming
he didn't even get into the weird part of switch statement
let a = 1
let a = 1
// Dublicate variables
{
let a = 1
}
{
let a = 1
}
// Not dublicate
Yes, especially that break at the end
and one field for all cases
Very convenient
what des this do?
dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);
});```
my brain just auto type
const h = help=="hi"?"2":help=="hello"?"":undefined
idk what system,run is for
It delays the code inside of it until the next game tick
it is kinda "useless" outside before events
It's main use is in before events, yes
100,000 messages!

who was the message to get the channel over 100k
mine :)
Crazy works
unless someone deletes a message >:)
can you not say stuff like that please @distant gulch
Why
It's been like this for a long time
it’s not relevant or appropriate
Maybe mine didn’t update yet
How is it inappropriate if it's a name but wtv
If I had a nickel for every time someone said 100k messages, I'd be able to buy a house
we will get 100000 message that claim the 100000 message someday
fellas we just hit 100k messages
Context is very valuable, and the context behind that specific name is inappropriate.
By the way, this is the most popular development channel
Willger
I think it'd be different if the name was something common like "john"
The kid named "Script API General"
Just what happened a couple of weeks ago?
...
so a few messages over
but this is all the message including those in the threads
how many messages could threads realistically take up
yeah
can't search in posts yet
Willing to bet 50% of the messages arent scriptapi related.
most of the stuff here are general js
We have between 10! & 11! messages in this channel 
All messages from the main development posts < messages from the main post script API
we have over 3,628,800 messages
500,000 in the offtopic channel
I was joking because 10 factorial is 3628800
9.06475! (or Γ(10.06475) )
I think this channel would show if it was over 200k messages
or does it cut off at 100k+
It cuts off
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]
So uh fixed the bug that broke it by wrapping it in {} and it does calculate correctly I'm just having trouble making it a toggle
The Lever
The Third Block
hmmm
Oh wait nvm my dumby self just set both of them to the same state 😭
But also swapped the way the toggle worked hence why it didn't place redstone on the first press
How do you get the name of a chest when it has already been placed?
unlucky lol
?
If a script has a custom component for a block using the interaction function.
Is there a way that allows the player to place a block while looking at this block instead of attempting the interaction which would fail anyways?
use playerInteractWithBlock
And read this -> https://discord.com/channels/523663022053392405/1309136217996005377
so replace "onPlayerInteract" with "playerInteractWithBlock"?
sadly, doing so broke the code.
The interaction fails and the block still attempts interactions instead of placing a block.
show code
No unfortunately.
this is the version with the "playerInteractWithBlock" in place of "onPlayerInteract"
This is why I asked to confirm.
I would not know otherwise what it means to "use playerInteractWithBlock"
world.beforeEvents.playerInteractWithBlock.subscribe(data => {
// Code
})
If the interaction is successful, then enter data.cancel = true
that breaks the script.
And remember about the privilege system in beforeEvents
How did you use it
"[Scripting][error]- TypeError: cannot read property 'registerCustomComponent' of undefined ..."
By replacing "worldInitialize" with "playerInteractWithBlock" as you demonstrated.
world.beforeEvents.worldInitialize.subscribe(eventData => { ...
world.beforeEvents.playerInteractWithBlock.subscribe(data => {...
because that's how you need to use it.
And the eventData vs data difference also causes errors.
This is not a custom component
The thing is I intended to use it as a custom component for the block.
So I can assign this script to selected blocks. Not all blocks....
This is the event that is called when the player clicks on a block
You can't use this as a custom component.
by giving I will give you an example
world.beforeEvents.playerInteractWithBlock.subscribe(data => {
let block = data.block
let player = data.player
let item = data.itemStack
if (!data.isFirstEvent) return
if (block.typeId != "wiki:my_block") return
if (item?.typeId != block.typeId) return
//If the code has reached this point, then the interaction is successful
//Cancel the block installation event (if there is one)
data.cancel = true
//system.run is needed to maintain privileges
system.run(() => {
block.setType("stone")
})
})
@pallid portal
welp...
if I set that to the block in question. It just turns the block into stone when the player tries placing the same block on it...
And it does not work with the axe.
Not only that, it still has the same issues as the previous version. Player is prevented from placing a block on them because the script attempts the interaction and failing.
I do recall a bug with the scripts where the interaction prevented players from placing blocks on them.
so it might be that?
Well.. I should give up helping newbies with scripts. I'm not that patient for this
Sorry, I can't help you..
And I am sorry for being clueless.
I do appreciate the help all the same.
Like I said lol.
We just need an interactable component and the issue could be solved. cough https://discord.com/channels/1138536747932864532/1263209224805159043
(mini rant at Mojang)
That is ironic how when this addon used HolidayCreatorFeatures. Players were able to place blocks and still do the interaction.
So much for the scripts being better when this feature depricated.
It is technically better in terms of more capabilities. It's just missing a conditional is all.
More options but at the cost of removing features many addons relied on....
Like, I wager 99% of HCF events are made better. The only one that really "suffered" was interaction.
Lesson learned, don't rely on experimental.
That's okay dudee... Rest for now
Also the HCF removal thing is a long time ago and you still can't get over it?
Nope.
More like. When one wants to make something that is arbituarily similar to vanilla minecraft.
Mojang be like: "nope"
Because sure, people can make a pig dance, a block change colour when you step on it, or make a cake explode by feeding it to a rabbit.
But heaven forbid they want to use a feature that is not available in normal minecraft, nor in the stable features...
If everyone could simply make their own games by learning how to code. 99% of the Minecraft playerbase would have left a long time ago.
😹
If you don't know how to do something in Minecraft, it doesn't mean it's impossible to do, it means you're not smart enough to figure out how to do it.
Not really.
It was a thing for years. And the change brought more annoying issues than improvements.
Here comes the yapping ughh
I very much disagree, as someone who has been making addons since 2020 this is such a new era.
If you don't want to learn then don't, if you hate things because of the issues leave, if you hate it don't complain you hate it... You'll never learn if you don't want to learn, learn to adapt in the environment
I'll see myself out....
@pallid portal
what seem to be the problem?
what are you trying to do
Fortunately, with this new era, beta features are shipped in small quantities making it much easier to ship to stable 🙂 .
-# deferred and editor mode
Completely different things and you know it. Those two explicitly are preview only so we dont have a hcf repeat.
yeah i guess so
long story short.
I am trying to revive an addon that relied on block events (interact, destroy, and placing)
Since the old events were deprecated. I have begrudgingly turned to scripting.
The interaction aspect of the customcomponents in this case proved problematic because blocks using onPlayerInteract also prevents the player from placing blocks on them.
Because the game attempts interacting with the block, fails, and also fails to place the block.
can you send your block json file
By all means. I dont mind.
The "wood_log" is the block using the custom component.
And the "stripped_interact" is the script.
The component is meant to let the player interact with the block while holding axe to turn it into a different block.
Essentially replicating the vanilla mechanic of stripping log blocks.
But the issue here is the interaction component prevents players from placing blocks on them.
what can i do to reduce lag in my scripts?
Use the script profiler to see which parts are taking the most time.
okay
are you using beta api
so I just do /script profiler start in chat?
I tried avoiding experimental features. But if need be, I can enable it.
try this out
the script is sadly not linked to the block.
So the script is seemingly running but is not responding to the block it is supposed to respond to.
The block in question now lets the player place blocks on it. But it is because it does not have the interaction function that does the log stripping.
now?
if that didn't work try this
Man you should've seen coding in 2018
Does anyone know if there is a way to stop a Bedrock server using script or run the / commands that would normally be available in the game itself?
is there an event for detecting when a entity’s/player’s inventory is updated/a new item is received
no
any good way to implement that then
runtInterval is your only choice
I tried saving player inventories in a map and updating every 2 ticks checking for any changes but it’s quite slow
even with 1 player in the world it gets slowdowns constantly
5-7ms
sadly, all of these options have not worked.
They do give a hint at something that should work though.
Because the goal is for these blocks to have this interaction but also allow players to place blocks on them.
I'll tinker with things some more.
Can someone help on how to achieve an entity that takes the texture of the ground and makes it as it's own I saw this entity named Ignis that summons blocks that takes the texture of the ground sadly the addon developer used an obfuscater tool to make the code unreadable so I don't know how he did it
Not possible with scriptapi to my knowledge.
I think that's not a script API thing more like a resource packs
But I'm not sure of it
the way others do it is using items equipped in hand of a custom entity
idk then
that should have worked
Is it possible to check the weather via script? For example, when it's raining and I use an item, it sends a hi in the chat.
or is it not possible?
What you can do is use https://stirante.com/script/server/1.15.0/classes/WeatherChangeAfterEvent.html and set a dynamic property to the world to store the current weather.
Documentation for @minecraft/server
Guys, does anyone know if it's possible to do a structure load, and after a few seconds it disappears and the world returns to its original state?
This is stable?
Yes.
Is this something I can do?
world.afterEvents.itemUse.subscribe((e) => {
if (e.itemStack.typeId == "minecraft:anvil") {
e.source.applyKnockback(e.source.getViewDirection().x, e.source.getViewDirection().z, 0, -Infinity);
}
})
is it possible to get the itemstack that is placed on an item frame
wouldn't you be able to do that in the entity's own json file?
As a behaviour.
I can't do it
I'm unable
I don't know if it's in the behavior file or in the animation
in this case, I want the entity to rotate the entire body towards another entity
just to confirm.
A behaviour like this is not it?
yes
import { world } from '@minecraft/server';
world.afterEvents.entityHurt.subscribe(({ hurtEntity, damageSource }) => {
const attacker = damageSource.damagingEntity;
if (attacker?.typeId == 'mz:stomp1') {
hurtEntity.applyKnockback(0, 0, 10, 1);
}
else if (attacker?.typeId == 'mz:stomp2') {
hurtEntity.applyKnockback(0, 0, 1, 10);
}
});
How can I make the knock effect like an explosion where the entity is knocked away from the source
requires math.
Can you like give me a pointer and I do the coding
nope
||im bad at math||
Oh okay
How do I create a Vector 3
Do I just make an array then have the three values listed?
like const myArray[x, y, z]
Would that automatically be a Vector 3?
its an object with 3 properties
x, y z
not an array
create an object.
you dont know what an object is?
I want to utilize player.teleport()
And I need a vector 3. I can't just put in x, y, z
What do I need to make that vector 3 with my own x,y,z coords
{x: blah, y: blah, z: blah}
{x: 0, y: 0, z: 0}
assuming xLocation and the rest are defined, yes.
np
Can I send video here related to scripting?
new illager
Anyone know how to achieve this?
Seems more of a #1067869022273667152 question.
It's just an entity that holds an item specifically a block then position the item so it looks like full blcok
I actually have pre-made models and animations, I can send you if you want
do anyone know how to make a script where someone places a block, it disappears without using custom blocks?
Yes plss
There is a tutorial on YouTube which cancels the block upon placing it
I can't understand the logic on how it works though if it is an invisible entity that holds the item block which positions it or scales it to look like a full block, how does it take the item from the ground?
Using scripts I guess?
When you summon the entity, it takes the block id below it then put into it's hand using replaceitem command, then despawn after a few seconds
-# based on what I seen in the video
It's not really complicated to understand
Now I get it so the full block appearance mainly relies on the animation thanks
I'll try and create this script
You don't need to change anything in model and animations it's already fixed to looks like full block
Just apply the model and the animations to the entity
could you tel me the youtube channel if it’s possible?
import { world, system } from '@minecraft/server';
world.afterEvents.entitySpawn.subscribe(({ entity }) => {
if (entity.typeId === '<mob typeid>') {
const block = entity.dimension.getBlock(entity.location);
entity.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 ${block.below().typeId}`);
system.runTimeout(() => {
entity.remove();
}, 2 * 20); // 20 ticks = 1 second
}
});```
I'm sorry I can't find it but do you know the basics of scripting API?
oh no i mean the process of doin this
Wym by disappear?
like breaks the block
It would not place at all?
So example I have grass block, I right click instead of placing it on ground it won't at all?
um i mean i want so that whenever someone places a block, after 5ish sec, it would break automatically
but without using custom blocks
I found it search for minedev studious check the vid about script API basics he used that as an example when you placed a block it instantly disappears
tysm!
@dim tusk , Is it possible to make a form that when pressing a certain button it registers a custom component for the player?
Wym custom components
I'm not English, could you tell me aje es wym?
it means What you mean..
for example changing the hitbox with a custom component from player.json
No, you can't change hitbox with scripts only
I did a explosion-like knock back effect before
Might have the files around if you haven't done it yet
I discovered something with the playerButtonInput in the 1.21.60+
When the player has the option to hold down to sneak or click once to sneak thingy when you activate click once to activate the class things it's not pressed anymore.
world.afterEvents.playerButtonInput.subscribe(({ button, newButtonState, player }) => {
console.error(button, newButtonState, player.name);
});```
but tbh it kinda makes sense cause the player is not holding it anymore the game does not you soo...
Let it slide I guess?
When does it say "Released"?
So when the player has the click once to sneak options for Android devices, it sends the pressed then released message after that
Instead of pressed till player untoggle the sneak button
But I said, it kinda makes sense cause the game is the one who keeps pressing it, not you lol
well yeah that makes sense
though
in this case it's the buttonState, not the input state
so it should be pressed
and not release until toggled again
So we could say a 🪲?
yeah probably
Hmm, let's just wait for other geniuses opinion
Do you mind telling me why you're trying to make Minecraft calculate Infinity?
well Bridge. told me it was an option, and I'd rather make that the answer than 99999. I assumed it would work the same as putting "infinite" in a /effect lol
There's a slight difference between using infinite in duration and infinite in the calculation of a vector.
'sides, I'm not even sure why you need 99999 for knockback anyways, that's just overkill.
const deathMessages = {
"fall": "%s hit the ground too hard.",
"drowning": "%s drowned.",
"fire": "%s burned to death.",
"fire_tick": "%s was on fire.",
"lava": "%s tried to swim in lava.",
"explosion": "%s blew up.",
"explosion.player": "%s was blown up by %a.",
"magic": "%s was killed by magic.",
"projectile": "%s was shot by %a.",
"melee": "%s was slain by %a.",
"thorns": "%s was killed by thorns.",
"falling_block": "%s was squashed by a falling block.",
"anvil": "%s was squashed by a falling anvil.",
"cactus": "%s was pricked to death by a cactus.",
"void": "%s fell out of the world.",
"lightning": "%s was struck by lightning.",
"suicide": "%s took their own life.",
"starvation": "%s starved to death.",
"freeze": "%s froze to death.",
"poison": "%s succumbed to poison.",
"wither": "%s withered away.",
"custom": "%s died."
};
world.afterEvents.entityDie.subscribe((data) => {
/**
* @type {Player}
*/
let plr = data.deadEntity;
if (plr.typeId == "minecraft:player") {
let lasthit = plr.getDynamicProperty("lasthit")??null;
let plrName = `§c${plr.name}§4[${(plr.getDynamicProperty("deaths") ?? 0) + 1}]§e`
plr.setDynamicProperty("spawntag", 0);
let team = FindPlayerTeam(plr.name);
if (team && team != null) {
freezeDtr(team, 1800000);
removeDtr(team);
}
plr.runCommandAsync(`inputpermission set @s camera disabled`);
plr.runCommandAsync(`inputpermission set @s movement disabled`);
plr.setGameMode(GameMode.spectator);
plr.setDynamicProperty("deathbanexpiry", Date.now() + 3600000);
plr.setDynamicProperty("deathbanuntil", 3600000);
plr.setDynamicProperty("pvpimmunity", 0);
let deathCause = data.damageSource.cause || "custom";
let killer = data.damageSource.damagingEntity;
let deathMessage = deathMessages[deathCause] || "%s died.";
if (killer && killer.typeId == "minecraft:player") {
killer.setDynamicProperty("kills", (killer.getDynamicProperty("deaths") ?? 0) + 1);
let killerName = `§c${killer.name}§4[${(killer.getDynamicProperty("kills") ?? 0) + 1}]§e`
world.sendMessage(deathMessage.replace("%s", plrName).replace("%a", killerName));
} else {
if (lasthit != null) {
let killer = world.getPlayers({name: lasthit})?.[0]
if (killer) {
killer.setDynamicProperty("kills", (killer.getDynamicProperty("deaths") ?? 0) + 1);
let killerName = `§c${lasthit}§4[${(killer.getDynamicProperty("kills") ?? 0) + 1}]§e`
deathMessage = deathMessage.replace(".","") + ` thanks to %a.`
world.sendMessage(deathMessage.replace("%s", plrName).replace("%a", killerName));
} else {
world.sendMessage(deathMessage.replace("%s", plrName));
}
}
world.sendMessage(deathMessage.replace("%s", plrName));
}
plr.setDynamicProperty("deaths", (plr.getDynamicProperty("deaths") ?? 0) + 1);
system.runTimeout(() => {
plr.teleport({ x: -1117.5, y: 38, z: 108.5 });
}, 5);
}
});
why is the message being sent twice
if (lasthit != null) {
let killer = world.getPlayers({name: lasthit})?.[0];
if (killer) {
killer.setDynamicProperty("kills", (killer.getDynamicProperty("deaths") ?? 0) + 1);
let killerName = `§c${lasthit}§4[${(killer.getDynamicProperty("kills") ?? 0) + 1}]§e`;
deathMessage = deathMessage.replace(".", "") + ` thanks to %a.`;
world.sendMessage(deathMessage.replace("%s", plrName).replace("%a", killerName));
} else {
world.sendMessage(deathMessage.replace("%s", plrName));
}
}
world.sendMessage(deathMessage.replace("%s", plrName));
You have 3 here... And how does the very bottom message trigger?
Spent the last half hour debugging something.... switched a this to a the in a lore line and it fixed itself 💀
It's when the dead is not player, I guess you could put it inside of else of the (lasthit != null)
Databases 
if (lasthit != null) {
}
} else {
world.sendMessage(deathMessage.replace("%s", plrName));
}
Bro said "I ain't dealing with this crap"
fr
i see it now i forgot to wrap it in an else, thank you
spawn an invisible armorstand, get block at feet, run command replace the item on hand, play animation make the item look bigger, applyImpulse
You have achieved it?
Why is this error occurring?
const replacements = [
{
id: "minecraft:wooden_sword",
lore: ["Line 1", "Line 2", "Line 3"]
},
{
id: "minecraft:apple",
lore: ["Just one line"]
}
]
mc.system.runInterval(() => {
for (const player of mc.world.getPlayers()) {
const inventory = player.getComponent("inventory")?.container;
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
if (item === undefined) continue;
if (item?.typeId == replacements.id) { // LINE 21
item.setLore(replacements.lore);
inventory.setItem(i, item);
}
}
}
});
Make sure the file is updated
For example, write console.warn("the file has been updated")
What do you mean?
And don't forget that replacements is a list and not an object
So it would be better to do this:
const replacements = {
"minecraft:wooden_sword": ["Line 1", "Line 2", "Line 3"],
"minecraft:apple": ["Just one line"]
}
mc.system.runInterval(() => {
for (const player of mc.world.getPlayers()) {
const inventory = player.getComponent("inventory")?.container;
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
if (item === undefined) continue;
if (replacements[item.typeId] != undefined) { // LINE 21
item.setLore(replacements[item.typeId]);
inventory.setItem(i, item);
}
}
}
});
i want to load some blocks in the world and save them in a variable as my scripts starts up. how do i prevent this from throwing errors when i first join the world (meaning the area is yet to be loaded)
Wait for playerSpawn or just catch the erros
If the area is not loaded then getBlock will simply return undefined, so you just have to wait for it to return Block
it dose throw errors as far as i remembered
If he is beyond the boundaries of the world (for example at 500 altitude) then yes
let me try to make sure
This is probably about the fact that if you receive a block object and try to use it after unloading it, you get an error

