#Script API General
1 messages · Page 60 of 1
1.11.0 was playerInteractWithBlock stable then?
deepseek is better at it sometime, even if it is not trained
but it is better to just l"earn" to read the docs
I used to use it Solve problems I don't know about and create scripts regularly. But it's different. 🤣
Thank you brother for the recommendation. 🥰
import { world, BlockPermutation } from "@minecraft/server";
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const { player, block } = event;
player.sendMessage({
translate: "Interacted with %1 block at %2",
with: [
block.typeId,
`X:${block.location.x} Y:${block.location.y} Z:${block.location.z}`
]
});
});
deepseek one have a privilege problem, but yeah
-# %1 %2 is that a thing?
One message removed from a suspended account.
how to your train deepseek?
no
i didn't, it is kinda up to date
You can't train it unless you are familiar with the documentation.
To teach you must learn to be a teacher.
This is my search history.
brother I don't just use AI, I search for what I need.
Sup guys
How to spawn an entity using dimension.spawnEntity behind a block and also triggering one of the entity's event
get block location -> spawn entity -> trigger event on the entity.
I recommend reading the docs on spawnEntity since it returns an Entity instance in which you can use triggerEvent.
But I didn't understand the location one inside the the parentheses
oh i misunderstood srry
how to handle removing experience? No matter what i do it doesnt go down in levels it just emptys the bar
elaborate
I think its pretty clear.
but i didnt understand
im doing player.addexperiance(-1) but in game my level never goes down it will go down to exactly level 3 with an empty xp bar but never go down to level 2
you will need to make it do that yourself sadly.
thats annoying. do yk how the levels scale? is it like 8 * level = xp for next level or something like that?
ive made a method in a class for this exact thing.
I rather teach you how to make it, rather than just giving it to you
i just want the algorithm for the scaling of the levels i can do the code
you dont even need that, I didn't.
but if i want to go from level 3 (28xp) and then go to level 2 (16xp) i dont want to just jump to level 2 i want to go to 27xp, 26xp, 25xp all the way down and to do that i need to know what the max is for each level
check when your xpEarnedAtCurrentLevel is at 0, add the xpNeededForNextLevel minus the amount being taken away and remove 1 level.
if your bar is not empty, just remove the xp normally.
its fine
you will need to check if xpNeededForNextLevel - Amount is less or equal to 0 rather than just checking if the xpEarnedAtCurrentLevel is 0.
np.
getComponent returns EntityComponent and VScode doesn't know that you get EntityInventoryComponent, so it only shows methods that are available on all components
how come it works in my other addon tho?
bcoz you put container?
Maybe VScode can analyze code. I don't know the details.
Are you using the Beta APIs?
yes
If you're using stable, you'll need to typecast. If you're using beta, you don't.
I installed 1.18.0-beta's autocompletions
typecast 🔥
okay then.
I guess he installed 1.0.0 type definition library
Stable or Beta modules?
Stable
You need to typecast.
getComponent('cooldown') as ItemCooldownComponent
As an example.
Th is an typecast
I tried that before but it says it only works in TypeScript
Then use TS.
Idk how to
world.afterEvents.dataDrivenEntityTrigger.subscribe(eventData => {
let eventName = eventData.eventId;
let EventEntity = eventData.entity;
if (eventData.eventId.startsWith('level_')) {
console.warn(eventName);
let EntityItem = EventEntity.getComponent('equippable').getEquipment('Offhand');
const durability = EntityItem.getComponent('durability');
durability.damage = 1;
}
})
you can use instanceof in an if statement
why wont this damage the item?
You have to set the item back.
?
ohh
i guess he selected old version
of the scripting engine
const inv = player.getComponent(EntityInventoryComponent.componentId)
if (inv instanceof EntityInventoryComponent) {
//...
}
use enums instead of static fields of classes 😭
can we get armor component of an item?
do getEquipmentSlot
or you have to call setItem function
O shi this actually works what da heil
as i know it's impossible now. you have to make map(enum or can be object) manually
Now how do I get an item in the mainhand
It's possible with commands
container.getItem(player.selectedSlotIndex)
Where the hell is the player variable coming from
then where the hell is the container variable coming from
here's the another.
entity.getComponent(EntityComponentTypes.Equippable).getEquipment(EquipmentSlot.Mainhand);
The another is more work
ye it's working for non-player entities
this only works for players
Is data store possible
for non-player entities you can just do container.setItem(0) iirc
I'm talking about sending data to a website or an API either through an http request or sum
And reloading it back
only possible in BDS, you can use post and get request
What is BDS
could you please google it 😭
bedrock dedicated server
Oh that
before you ask, please google it first..
how do i repair an item?
on mainhand?
You're wrong about that part bud.
change the damage of the item.
const equippable = player.getComponent('equippable');
for (const item of ['Offhand','Mainhand']) {
const durability = item.getComponent('durability');
durability.damage = 0;
}```
doesnt allow - values
wdym , if i set damage to -1 its error
obviously.
you can have damage of -1?
no right?
DAMAGE.
tf
0 damage means fixed.
so i cant say i increase by 1
For example I have the max durability of 100, and the damage is 1, means my item's durability is 99
if the damage is 0, means it's full durability
it's literally in the name DAMAGE
finally
you could've just answered him but you did not.
Is it possible to detect a block in a certain radius
entity detect blocks around it?
yes.
Ye I tried using /execute if blocks but that only detects if all blocks in the radius are like that, and idk if there is a way with script API
you can
do ```js
for (const location of Dimension.getBlocks(new BlockVolume({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }))) {
const block = Dimension.getBlock(location);
// ...
}
make a list of location of the entity.
(this function should be getBlock bcz the parameter is not array)
but beware that it will cause a lot of tp docps
I'm not done.
I want to make it so it checks in a radius if it contains a block not a single area or like that
getBlock will not cause critical performance issues
my worldedit placement's speed is 250k/sec
you can handle 10k blocks in a tick without lag.
-# runJob exists.
getBlock takes less resources than setBlockPermutation
so it can be more higher than 10k blocks in a tick
-# what a genius!
Ye but I'm not trying to detect a singular block but a block in a radius
he did this
do ```js
const volumeStart = { x: 0, y: 0, z: 0 };
const volumeEnd = { x: 10, y: 10, z: 10 };
const blocks = Dimension.getBlocks(new BlockVolume(volumeStart, volumeEnd), { excludeTypes: ['minecraft:air'] }, false);
for (const location of blocks.getBlockLocationIterator()) {
const block = Dimension.getBlock(location);
// ...
}
wth is that
better version of getBlock
better version ig
common sense exists genius?
since you're on PC why not help him instead 😜
Will that be able to detect if it contains a block not if the whole area is the same block
the filter argument is not optional
possible
Like detecting if a string contains a letter but it's a block being detected in a radius
I have to help the guy in the vc
You didn't import BlockVolume didn't you?
then I can say... Skill issue
sample
that's why there's an error
nice nesting.
But would it appear around the block relative to it's position
I want the detection range relative to a blocks position
you should do it in runtInterval, get the location around the player and put it in the array and sue that for location check.
^
I'm not understanding
This is what I want to be done
(Detect if an iron door block is contained in the radius of 2 blocks from a block that is being clicked on)
oh it's a block detecting another blocks?
Yes
still the same, use runtInterval
wait. I'll try to give a sample.
But the block would be static right?
And how do you cancel an interval
I tried using
const interval = system.runInterval
system.clearRun(interval)
but it doesn't work
And is it possible to cancel a timeout?
This works with the normal JavaScript interval but not with mcs system
That's valid one how it won't work.
And what I want fully to happen is
Detect in a radius of 2 away from the original block being clicked on if the radius contains a iron door block go back to the original block and then run a command
?
world.beforeEvents.playerInteractWithBlock.subscribe(({ block, player, dimension }) => {
if (block.typeId === 'minecraft:grass_block') {
const centerLoc = block.location;
for (let dx = -2; dx <= 2; dx++) {
for (let dy = -2; dy <= 2; dy++) {
for (let dz = -2; dz <= 2; dz++) {
const nearbyBlock = dimension.getBlock({ x: centerLoc.x + dx, y: centerLoc.y + dy, z: centerLoc.z + dz });
console.error(nearbyBlock.typeId);
}
}
}
}
});```
just do let x = centerLoc.x - 2
sigh I love nesting
x <= centerLoc.x + 2
use the exact position instead of the delta position
so you can just simply do getBlock({ x, y, z })
Hmm.
world.beforeEvents.playerInteractWithBlock.subscribe(({ block, dimension }) => {
if (block.typeId !== 'minecraft:grass_block') return;
const { x: cx, y: cy, z: cz } = block.location;
for (let x = cx - 2; x <= cx + 2; x++) for (let y = cy - 2; y <= cy + 2; y++) for (let z = cz - 2; z <= cz + 2; z++) {
const nearByBlock = dimension.getBlock({ x, y, z });
if (nearByBlock !== undefined) console.error(nearByBlock.typeId);
}
});```
BEST READABILITY 👍
sarcastic?
for real.
What would be the necessary extensions for script API auto completions on visual Studio Code
no extensions
install node js and any package you want types auto completions for
How
which part
NodeJS download is easily accessible to find online
And you can then just run "npm i @minecraft/server" in your terminal to install the packages to your current directory
world.afterEvents.playerBreakBlock.subscribe(({ player, brokenBlockPermutation }) => {
console.error(brokenBlockPermutation.type.id);
});```
Sorry what?
ahh for the custom items. Why? They already have a built-in properties
also they have different names it's minedBlockPermutation instead
is there a parameter that can allow for a custom death message?
I don't wonna make a custom script that deletes this one and replaces it yada yada yada
is it possible to make a block change the state based on biome?
You can summon a dummy entity to query the biome. Then relay that info to scriptapi.
maybe with player, execute function and script queries, bcs I'm making a custom grass that will replace the default grass, so this isnt a option bcs of lag
sad
not 100% perfect but disable showDeathMessages gamerule, send your own message then enable it again
is there any way to block invis skins?
turn on "only allow trusted skin"
dimension.spawnEntity("space:anomaly", block.location);
How to spawn my entity behind the block?
define the "block" and "behind the block"
?
The block variable is defined somewhere in the code
How to spawn my entity behind the block?
is not clear
where is the block
what "behind the block" mean? relative to what?
Relative to block's local cordinates
^^^-1
And the block is from blockRayCastHit
^^^-1 is not block relative
blockface location relative to block.center?
perhaps...
it is relative to the block origin 0 0 0
well, im not the inquiree ;-;
Yes
hitLocation + block location + ray direction normalized
what if it's like a slab, should it relate to the viewvector of the player?
it is a log iirc
I am detecting logs and want to spawn an entity behind that log so that the player cannot see it
ok, relative to player view
try this?
Ok
not sure about the normalized part
sense the block can get to √(1²+1² + 1²) = √3 thick, depending on the vector
Wait but the hit and block location is same
they are not
Why can't user import addons, when he clicks to install the addon, the addon doesn't go into Minecraft Bedrock.
#add-ons
can someone help me fix the error?
[Scripting][error]-Unhandled promise rejection: Error: Invalid amount. Amount must be greater than 0 and less than 256.
const form = new ModalFormData()
.title(`§6Refine ${inputItem}`)
.slider("§fSelect amount to refine:", 1, maxRefinable, 1, maxRefinable);
form.show(player).then((response) => {
if (response.canceled) return;
let amountToRefine = response.formValues[0];
let removed = removeItem(player, inputItem, amountToRefine);
if (removed === 0) {
player.sendMessage(`§cError: Failed to remove ${inputItem}!`);
return;
}
idk where the error is from so maybe this could be too
function giveOrDrop(player, itemType, amount) {
const inventory = player.getComponent("minecraft:inventory").container;
while (amount > 0) {
let stackSize = Math.min(amount, 64);
let itemStack = new ItemStack(itemType, stackSize);
let leftover = inventory.addItem(itemStack);
if (leftover) {
player.dimension.spawnItem(leftover, player.location);
}
amount -= stackSize;
}
}
Wait but what if I just add +1 to the z of the block's location and spawn it in using summon ${blockLoc.z}
try something like this
import { world } from '@minecraft/server';
const dimension = world.getDimension(...)
const blockHit = dimension.getBlockFromRay(...)
const location = addVectors([
blockHit.faceLocation,
blockHit.block.location,
normalizeToSqrt3(rayDirection)
])
const entity = dimension.spawnEntity('id', location)
function normalizeToSqrt3(vector) {
const length = Math.sqrt(vector.x ** 2 + vector.y ** 2 + vector.z ** 2);
if (length === 0) return { x: 0, y: 0, z: 0 };
const scaleFactor = Math.sqrt(3) / length;
return {
x: vector.x * scaleFactor,
y: vector.y * scaleFactor,
z: vector.z * scaleFactor
};
}
function addVectors(vectors) {
return vectors.reduce((sum, v) => ({
x: sum.x + v.x,
y: sum.y + v.y,
z: sum.z + v.z
}), { x: 0, y: 0, z: 0 });
}
rayDirection is the ray direction
what is maxRefinable
wait
ensure it is valid
sry my inetert bugged out
let maxRefinable = Math.min(itemCount, maxAffordable);
let maxRefinable = Math.min(itemCount, maxAffordable);
log that to console and see it value
error doesnt allow it
Wdym?
move the line before the itemstak one
huh
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id == "space:peek") {
let loopStart = { x: 1, y: 0, z: 10 };
let loopEnd = { x: 3, y: 1, z: 0 };
for (let player of world.getAllPlayers()) {
const playerPos = player.getHeadLocation();
let logFound = false;
for (let x = loopStart.x; x <= loopEnd.x; x++) {
for (let y = loopStart.y; y <= loopEnd.y; y++) {
const direction = { x, y, z: loopStart.z };
const blockRaycast = player.dimension.getBlockFromRay(playerPos, direction, { maxDistance: 40 });
let block = blockRaycast?.block;
if (block && block.typeId === "minecraft:oak_log") {
let blockLoc = block.location;
let blockk = blockLoc.z;
blockk = blockk + 1;
world.getDimension("overworld").runCommandAsync(`summon space:anomaly ${blockLoc.x} ${blockLoc.y} ${blockk} facing @a`)
world.getDimension("overworld").runCommandAsync("tag @a add tree");
logFound = true;
console.log(`found at ${blockLoc.x}, ${blockLoc.y}, ${blockLoc.z}`)
break;
}
}
if (logFound) break;
}
if (logFound) return;
}
}
});
Any suggestions improving this?
Performance and if there's a better way to do it
does it make lags?
No
I am asking if there's a better way of detecting logs
Or the raycast
do you know what direction is?
It's player's view direction
x, y, z values are must be from -1 to 1.
It seems wrong
I'm wondering how it works
🤔
How
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id !== "space:peek") return;
const loopStart = { x: 1, y: 0 };
const loopEnd = { x: 3, y: 1 };
const z = 10;
outerfor: for (let player of world.getAllPlayers()) {
const playerPos = player.getHeadLocation();
for (let x = loopStart.x; x <= loopEnd.x; x++)
for (let y = loopStart.y; y <= loopEnd.y; y++) {
const direction = { x, y, z };
const blockRaycast = player.dimension.getBlockFromRay(playerPos, direction, { maxDistance: 40 });
let block = blockRaycast?.block;
if (!block || block.typeId !== "minecraft:oak_log") continue;
const blockLoc = block.location;
world.getDimension("overworld").runCommand(`summon space:anomaly ${blockLoc.x} ${blockLoc.y} ${blockLoc.z + 1} facing @a`);
world.getDimension("overworld").runCommand("tag @a add tree");
console.log(`found at ${blockLoc.x}, ${blockLoc.y}, ${blockLoc.z}`);
break outerfor;
}
}
});
alr this is my best.
(to avoid gc, i could do pos caching. but i didn't. it's not required)
idk
what limit scriptEventReceive is? When it actives 46 functions it starts bugging
Is there any way to force an entity into a specific target?
hmmm this is new to me, what does Player.hideAllExcept do?
Hides all HUD except
view_entity.applyDamage(50, {
damagingEntity: {
"damagingEntity": player,
"cause": "entityAttack"
}
}) this has an error in it i believe its to do with the cause
but reading this i think i messed alot up
dont use strings for cause
or damagingEntity
just do:
view_entity.applyDamage(50, {
damagingEntity: {
damagingEntity: player,
cause: "entityAttack"
}
})
ah i see thanks
np
Entity.applyDamage(50, { damagingEntity: player, cause: 'entityAttack' });```
O thanks
Is air not detectable by getBlockFromRay?
I wanted to get the location of something 3 blocks infront of me. Tried to stick to blocks.
it returns undefined
There's really no way to get the coords of where you're looking 3 blocks infront?
How to get the feet location(starting point of collision box) of my entity
// block variable = block
if (typeof block == undefined || block) {
const blockLoc = block.location;
console.log(`block loc= ${blockLoc.x}, ${blockLoc.y}, ${blockLoc.z}`);
};
nono, how would you get the location if the block is undefined?
you can't.
Ah then idk there's no way
i don't think "air" would work
entity locations are centered from the bottom by default
so just use entity.location
is it possible to summon entity in a unloaded chunk?
Is the dynamic property addon specific, file specific or world specific?
i believe they're saved under pack uuid
i might be wrong
if not possible, ping me with a "no" please
how would u like, disable equipping, in certain circumstances, lets say player dynamic property lvl = 1, disable equipping dia chestplate (with lores and properties on it)
thanks
addon & world
per world, saved under the addon uuid
How do i detect when a player interacts with a custom block?
Afaik there is no "minecraft:interactable" component and when i use world.beforeEvents.itemUseOn [... code ...] this only works if i can actually use the item and doesn't depend on the block
Use custom components for your custom block.
you need to keep checking every tick for item in player's chest, then you can use if statements to check if it matchs the lore, properties and player has lvl 1, if it does have the lore and player is lvl 1, it will remove that item then add it back to player's inventory
ping me if you want a code example
thx
i meant if lore n properties are available, how to put it back to inv with the same lore n properties, and yes ill appreciate a example code
system.runInterval(() => {
for (const player of world.getPlayers()) {
const inv = player.getComponent("inventory").container
const equippable = player.getComponent("equippable")
const chest = equippable.getEquipment("Chest")
if (chest.typeId === "minecraft:diamond_chestplate" && chest.getLore().includes("lore") && player.getDynamicProperty("level") == 1) {
inv.addItem(chest)
equippable.setEquipment("Chest", null)
}
}
})
alright, appreciate that!! thanks!
im still confused on what runJob is for, can anyone explain
Generator function
Runs generator functions
Which pause execution till the next tick if you do yield;
let say you have a function that does to much stuff and the game lag if you run all that at once
import { system, world } from "@minecraft/server";
anyName()
function anyName() {
let task = 0;
while (task < 100000) {
task++;
//...
world.sendMessage(`task reached: ${task}`);
}
world.sendMessage("job complete");
}
what we can do is convert it to a generator function
function* anyName(){}
and use yield to devide the function into sections. the game will execute the code untill it hit a yield, pause and continue when there is a place in the tick to run.
so something like this:
import { system, world } from "@minecraft/server";
system.runJob(anyName());
function* anyName() {
let task = 0;
while (task < 100000) {
task++;
//...
world.sendMessage(`task reached: ${task}`);
yield; // pause execution and continue on the next time the game is free
}
world.sendMessage("job complete");
}
why do we need it?
the best thing about runJob is that it can run multiple times in a tick. and that make it way faster then any alternative
Thank you
Is there a way to use use permutationToPlace to set multiple permutations to be placed
import { BlockPermutation } from "@minecraft/server";
const permutation = BlockPermutation
.resolve("minecraft:your_block_id")
.withState("state1_name", value1)
.withState("state2_name", value2)
.withState("state3_name", value3)
.withState("state4_name", value4);
isnt that for setPermutation?
hmm?
doesnt .resolve() only work for setPermutation?
resolve and withState both return a permutation
and permutationToPlace take permutation
import { BlockPermutation } from "@minecraft/server";
const permutation = BlockPermutation.resolve("minecraft:your_block_id", {
name: value,
name2: value2
})
yikes, i felt like i am messing something
lol, you good man?
anyone know how to temporarily disable fall damage for the player?
effects
ok
how do I make a fillable item?
item dynamic properties, and Item Lore to display the current value
or like the bucket, different items for every "state"
Is it possible to detect if the player riding an entity is trying to move?
When you click on a daybed a message appears above your hotbar, however, this message appears to be different from the others. Is it possible to show the player a message with a similar ui?
const inputInfo = player.inputInfo;
const movement = inputInfo.getMovementVector();
const riding = player.getComponent('riding')?.entityRidingOn;
if (riding && (movement.x !== 0 && movement.y !== 0)) {
// ...
}```
Not using beta
Use getVelocity then
Yeah... The problem is that I'm making a flying vehicle and I'm trying to detect if the player is moving or not so I can stop the vehicle
When the vehicle is moving, the player's velocity is the same as the vehicle
then you don't have a choice, that's the most accurate thing you could do in stable.
This is what I'm doing rn```js
const { x, y, z } = pilot.getViewDirection();
const v = vehicle.getVelocity();
const abs = Vector.abs(v);
const h = abs.x + abs.z;
vehicle.applyKnockback(x, z, h ? h * (abs.x > 0.1 && abs.z > 0.1 ? 0.8 : 1.1) : 0, y < 0.25 && y > -0.4 ? 0.022 : (y / 3) + 0.05);
It works but only in a straight line
If I move in a diagonal direction, the vehicle never stops
system.runInterval(() => {
let players = world.getAllPlayers()
for (let player of players) {
const item = player.getComponent("minecraft:inventory").container.getItem(9);
if (!item?.typeId === "minecraft:diamond") {
player.runCommandAsync('camera @s fade time 0 2 0 color 0 0 0');
}
}
}, 20)
Why this doesn't work?
If I don't put ! , this works but if I put ! it doesn't work anymore
item?.typeId !== 'minecraft:diamond'
in that case, just use applyImpulse
applyImpulse doesn't modify the velocity?
iirc it adds that value to your current velocity
Then its the same that I'm doing now
I dunno what's your plan tbh, maybe you could use Entity.clearVelocity() first.
I'm trying to make the entity move when the player is holding the movement buttons
As I said before, this only works for straight lines but for some reason it never stops moving in diagonal directions
Does anyone have an example how to apply knockback sideways? Like push the player to the right
I'm really bad at math
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id == "space:sign1") {
for (const entity of world.getDimension('overworld').getEntities({ type: 'space:anomaly' })) {
const messages = [
"I see you, watch your back,",
"You walked past me twice already,",
"I like how you panic, when you realize you’re not alone,",
"Your footsteps aren’t the only ones here,",
"You blinked, I moved closer,",
"I know where you'll go next,",
"You are not alone,"
];
const random = Math.floor(Math.random() * messages.length);
const location = entity.location;
const vector = { x: location.x, y: location.y, z: location.z + 2 };
const block = entity.dimension.getBlock(vector);
const player = entity.dimension.getEntities({ type: 'player', closest: 1, location: entity.location })[0];
if (block) {
block.setType("standing_sign");
const signComponent = block.getComponent("minecraft:sign");
signComponent?.setText(`${messages[random]}, ${player.name}`, SignSide.Front);
signComponent?.setText(`${messages[random]}, ${player.name}`, SignSide.Back);
world.getDimension("overworld").runCommandAsync("event entity @e[type=space:anomaly] despawn");
}
}
}
});
it says error expecting , on line 113 and line 113 is });
Yo
I'm revamping my bliss addon
So i kinda added two new abilities
Phase, and another
Anyway, does anyone know how i'd let a player walk thru blocks?
I don't mind using player.json
idk try asking in #1067869022273667152
You can't.
unless you're in spectator or teleport
other than that? No.
How fast scripts 2.0 execute is?
depends how complex your script is
depend on mojang dev
How do I make a skyblock island generator?
Does anyone have an idea?
like oneblock, it generates a random block after breaking?
or a whole skyblock island terrain you want to generate? (you can do this using worldedit)
No
A random island for each person
like a whole skyblock island terrain you want to generate?
just do it with worldedit! if you want to do it
you can copy the skyblock island using a worldedit addon and paste it many time as you want
oh a island for each person?
then you can use playerSpawn event for each player and whenever they join, you can generate each island for them and teleport them to the each island
you can edit the overworld file to make everything void, so it looks like actual "sky"block
Thought so too
Well, is there anyway to make tamed zombies and skeletons?
Like they can't and won't target you
Even if you attack them
entity.json editing
mobs
what 😭
that's easy
just edit this and place it in bp/entities/zombie.json
Aight but, i gotta do it for Skeletons, endermen, wardens, and a whole lot more
well you have to
but after you do 1 time you just have to copy paste
But i have to find the vanilla file, find where to place it, then place it, then save it.
That isn't an easy task when dealing with many files
So i said, i would make a python script. I forgot to add "to automate this process" (my bad), but you get the point, right?
world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
const block = data.block;
const player = data.player;
const inventory = player.getComponent("minecraft:inventory");
const heldItem = inventory.container.getItem(player.selectedSlot);
player.sendMessage(
`${player.name} interacted with block at ${x}, ${y}, ${z} while holding ${heldItem.typeId}`);
});```
can someone tell me what wrong with this code because i tried it and also it looks fine but it just not working also there is not errors or warns
.selectedSlot => .selectedSlotIndex
nope still not working
Also
world.beforeEvents.playerInteractWithBlock.subscribe((data) => {
const block = data.block;
const player = data.player;
const inventory = player.getComponent("minecraft:inventory");
const heldItem = inventory.container.getItem(player.selectedSlotIndex);
const {x, y, z} = block.location;
player.sendMessage(
`${player.name} interacted with block at ${x}, ${y}, ${z} while holding ${heldItem.typeId}`);
});```
Idk abt the indentation cuz i am on discord mobile rn so yea, but it will work
Any content logs?
i just turns on the logs the problem was on the coords i forget them
hi here. Is it possible to detect biomes?( if player is in specific biomes)
If anyone has an idea please tell me
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]
import { BiomeTypes, system, world } from "@minecraft/server";
function getBiome(location, dimension) {
let closestBiome;
for (const biome of BiomeTypes.getAll()) {
const biomeLocation = dimension.findClosestBiome(location, biome, { boundingSize: { x: 64, y: 64, z: 64 } });
if (biomeLocation) {
const dx = biomeLocation.x - location.x;
const dy = biomeLocation.y - location.y;
const dz = biomeLocation.z - location.z;
const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
if (!closestBiome || distance < closestBiome.distance) closestBiome = { biome, distance };
}
}
if (!closestBiome) throw new Error("Could not find biome within the given location");
return closestBiome.biome;
}
const player = world.getPlayers()[0];
system.runInterval(() => {
const biome = getBiome(player.location, player.dimension);
player.onScreenDisplay.setActionBar(biome.id);
});```
You need to remember that the more checks you do the more tps drop it gives.
and this isn't 100% accurate.
How can I run a realms 24/7?
Couldn't it be done with something like a fake player?
I guess you could have a realm bot or something stay in the sever
The real question is why
I use phone and for me realms is cheaper and more convenient
Sure, but why keep it open 24/7
To synchronize world time with world time in minecraft
import { world, system } from "@minecraft/server";
import { ActionFormData, ModalFormData } from "@minecraft/server-ui";
system.runInterval(()=>{
world.getPlayers().forEach(player=>{
const hour = world.getDynamicProperty("hour");
const min = world.getDynamicProperty("min");
const sec = world.getDynamicProperty("sec");
player.runCommand(`title @s actionbar ${hour}:${min}:${sec}`)
if (player.hasTag("worldtime")) {
wtime(player)
player.removeTag("worldtime")
}
})});
system.runInterval(()=>{
const sec = world.getDynamicProperty("sec");
const s = sec + 1
world.setDynamicProperty("sec", s);
}, 20)
system.runInterval(()=>{
const hour = world.getDynamicProperty("hour");
const min = world.getDynamicProperty("min");
const sec = world.getDynamicProperty("sec");
if (sec == undefined) {
world.setDynamicProperty("sec", 0);
}
if (min == undefined) {
world.setDynamicProperty("min", 0);
}
if (hour == undefined) {
world.setDynamicProperty("hour", 0);
}
if (sec >= 60) {
const m = min + 1;
world.setDynamicProperty("min", m);
world.setDynamicProperty("sec", 0);
}
if (min >= 60) {
const h = hour + 1
world.setDynamicProperty("hour", h);
world.setDynamicProperty("min", 0);
}
if (hour >= 24) {
world.setDynamicProperty("hour", 0);
}
})
system.runInterval(()=>{
const hour = world.getDynamicProperty("hour");
const min = world.getDynamicProperty("min");
const sec = world.getDynamicProperty("sec");
const time = Math.floor((hour * 1000) + (min * 1000 / 60) + (sec * (1000 / 3600)))
if (time >= 6001) {
const realtime = time - 6000
world.setTimeOfDay(realtime)
}
if (time <= 6000) {
const realtime = time + 18000
if ( realtime < 24000) {
world.setTimeOfDay(realtime)
}
}
})
After setting the game clock with the world time, I can synchronize the world and game clock with this code.
don't put the world dynamic property inside of for each of players and Date.now() exists accurately
the formatting hurts me
Plus game code can be slowed down by internal processing- which, may not seem like much, but over the course of days, weeks, months it would build up substantially
system.runInterval(()=>{
let date = new Date();
let hour = date.getUTCHours();
let min = date.getUTCMinutes();
let sec = date.getUTCSeconds();
const time = Math.floor((hour * 1000) + (min * 1000 / 60) + (sec * (1000 / 3600)))
if (time >= 6001) {
const realtime = time - 6000
world.setTimeOfDay(realtime)
}
if (time <= 6000) {
const realtime = time + 18000
if ( realtime < 24000) {
world.setTimeOfDay(realtime)
}
}
})
This really works better, it's great
Does the navigator work in scripts?
Does "getProperty()" work with molang variables like "is_casting" or "variable.attack_time"?
Those are not properties.
Is there a way to query those in script API?
hmm
Is there another way to check if the behavior 'minecraft:behavior.summon_entity' is active?
Might be able to rig something up with BP animations/animation controllers, but I dunno if it works for all variables (it does work for attack time, at the minimum)
If you set an entity property at the same time the component is added (using component groups) you can test that via scripts
not that it has the component, but that it is actively casting
same as the 'query.is_casting' molang expression
could use the casting component to set a property with a timer and then have it expire at the same time the animation ends
How do I detect if a mob has items in its hand?
Not with scrips
Oh no
you can't because the equippable component is disabled for mobs yet it only works for players
The best you could do is this.
function holdingItem(entity) {
const command = entity.runCommand('testfor @s[hasitem={item=<id>,location=slot.weapon.mainhand}]');
if (command.successCount > 0) return true;
else return false;
}```
Oh, thanks
Installation for @minecraft/server-gametest
Beta API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
When using playSound, do I need to specify the volume and pitch to match how the sound is listed on the wiki?
Or can I omit the sound options and it will default to those values anyway?
Yep.
Nice, thanks for the quick reply 👍
How would one applyKnockback an entity to a specific coordinate?
probally not good for alot of uses but theirs also
function getEntityHeldItem(entity) {
for (const itemType of ItemTypes.getAll()) {
const command = entity.runCommand(`testfor @s[hasitem={item=${itemType.id},location=slot.weapon.mainhand}]`);
if (command.successCount > 0) return itemType;
}
return ItemTypes.get("minecraft:air")
}
just looping through every item id lol
This is bad actually
there's a lot of ids that it will take 2-3 seconds to get the ID
I mean yes it will work but not that fast.
What are my eyes seeing
Oh no definitely
Its a horrible idea
Im just stating that, that can be dne
bro tries to detect what item entity is holding.
Testfor command wasnt removed?
No?
Why would it be?
I remember something like that, maybe delulu
Can an ItemStack be stored in a dynamic property on a player?
Is there not a work around? I have a trash can block the remembers the last disposed item incase the player accidentally bins something. Problem is, anyone that interacts with it will receive that item even if they weren't the one who put it in
Could using a WeakMap work perhaps?
Use a entity container to store the latest item that every player discarts(?
You can set dynamic properties on items, use it to set the owner of the item
When a player discarts an item find if theres an item that the player own in the container yet, if it is just replace the slot, that way it will be 1 slot for every player
And if too many players discarts items and exceeds the container size delete the oldest item
||(It will be more realistic if you cant take trash from other players 👀)||
that's.... Stealing right?
world.beforeEvents.worldInitialize.subscribe(eventData => {
eventData.blockComponentRegistry.registerCustomComponent('cobblemon:leaf_decay', {
onRandomTick: (e) => {
const { block } = e;
if (leafBlocksSet.has(block.typeId)) recalculatePersistence(block);
}
});
});
world.beforeEvents.worldInitialize.subscribe
why is this an error?
it worked perfectly before
What version are you on?
what's the error, exactly?
oh.
Wait iirc it's under the system now since the beforeEvents worldInitialize is removed
js line 18
ignore
It's the above code
what's line 18, he can't just magically guess it.
cannot read property subscribe
Yeah it's removed already. Change it to js system.beforeEvents.startup.subscribe
ok wait
-# I think.
[Scripting][error]-ReferenceError: 'system' is not defined at <anonymous> (components/blockComponents.js:18)
[Scripting][error]-Plugin [Cobblemon - 1.0.0] - [main.js] ran with error: [ReferenceError: 'system' is not defined at <anonymous> (components/blockComponents.js:18)
]
import { system } from "@minecraft/server";
Nuh uh
import { world , system } from '@minecraft/server';
I sent you the fix
Yup
ok
if that didn't work do startUp other than that... I dunno anymore lol
same error
ok
import { world , system } from '@minecraft/server';
import { berryManager } from '../classes/berryManager';
//block components
const blockComponents = [
{
id: "grlab:apple",
code: {
onPlayerInteract: (data)=>{
berryManager.interact(data.block, data.player);
},
onRandomTick: (data)=>{
berryManager.tick(data.block);
}
}
}
];
let reload = 0;
system.beforeEvents.startUp.subscribe((data)=>{
//reload is needed to stop crashes
reload = reload + 1;
if (reload > 1) return;
for (const comp of blockComponents){
//register the component
data.blockComponentRegistry.registerCustomComponent(comp.id, comp.code);
}
});
Yo does know how I'd detect swapping, say helmets?
See, i add a set of 10 hearts when a player has a crown on their head (elected leader)... i want to remove these extra hearts when he isn't wearing that item anymore
nah.
best you could do is check if he's wearing it or na.
Well, I'd say using itemUse
I used the afterEvent for enchanting and i was testing enchanting armor
And it swapped
then how you'll check they wear it thru inventory?
Assuming delaying the check till the next tick and checking if they have the crown in their hand if they have it in their head slot before the system.run?
Could work
I'll test and see
you could make your own event using interval
the player can just open inv and change it
yeah, that's why I said this.
is server-net activated on realms?
no
is there a isSolid?
In beta.
thx
function randomSafeTeleport(player) {
const x = Math.round((Math.random() - 0.5) * -600);
const z = Math.round((Math.random() - 0.5) * 400);
let y = undefined;
for (let i = 60; i < 320; i++) {
if (world.getDimension('minecraft:overworld').getBlock({x,y:i,z}).isSolid &&
world.getDimension('minecraft:overworld').getBlockAbove({x, y:i, z}) == undefined) {
y = i + 1;
break;
}
}
if (y) player.teleport({x,y,z})
else randomSafeTeleport(player)
}
Your block is undefined.
How do I add an enchantment to my item? I'm trying to add curse of vanishing but I'm not sure exactly how the .addEnchantment syntax needs to be
Is there any better way to get a few blocks forward from view direction im tryna make an apply knockback in the direction your facing but its prety buggy
some times sending me in the oposite direction
usually when im looking abit lower it sends me back and when look higher sends forward
and the knockback when tryna go diagonal is a bit off
x, y, and z axis?
Yeh
i'm asking
wdym?
Y axis i always want to go up
not down
applyKnockback({ x: view_location.x, z: view_location.z } , 2)
y is up and down
ye?
but i dont want to change the y so i dont use it
i got it fixed at 2
?????
? you know how the lifeboat feather works
it flings u forward and up
thats what im tryna get
is there a better way to force load chunks than with a temporary ticking area? I'm using it to load structures
you can turn it off in chat settings, not sure if there's another way
hide with json ui!!
guys, what version of script was equippable disabled to mobs.
how can i test the depth of a water block to know if its full?
isWater && !isWaterlogged
Check the block state. Liquid depth.
how is the sintaxis?
block.matches(`minecraft:water`,{liquid_depth:15})like this?
Hello Guys
Quick question
Is it possible to remove the Animation when Closing and Opening a Action or Modal form UI?
I want to make a thing where the "UI" updates itself, but the animation is really annpying
#1067869374410657962
try checking Herobrine's Chest UI
... is this the only solution
he did that.
Yeh
there's no way to actually removed that since it's server side.
unless Mojang added client, probably
someone know?
the right sintaxis
i also tried with "withState" but neither work
go open a world try checking the states it accepts in setblock or fill command
/setblock water[] or /setblock flowing_water[]
The state is "liquid_depth" I just don't know what's the sintaxis to check for that specific state
Block.permutation.getState('liquid_depth')?
I was wondering where this thread went for the last few days. It really should be a channel.
They don't like lurkers.
How?
they didn't, discord only count up to 100k in threads status
world.afterEvents.playerJoin.subscribe((eventData) => {
const now = new Date();
const localHour = now.getHours();
let greetingMessage = null;
if (localHour >= 5 && localHour < 12) {
greetingMessage = "The sun rises, but the shadows grow longer...";
} else if (localHour >= 12 && localHour < 17) {
greetingMessage = "The midday sun is harsh, but something stirs in the distance...";
} else if (localHour >= 17 && localHour < 20) {
greetingMessage = "The evening grows dark, and something watches you...";
} else {
greetingMessage = "The night is silent, yet you feel you are not alone...";
}
world.sendMessage(greetingMessage);
});
Why doesn't this work?
try doing a console.log for the hours
console.error(localHours)
to know if it really returns the value required.
guys
my scripts use like 27 entity hurt for weapon ces, what should i do? make every ce a function and run it in one single entity hurt with if or anything else to do?
i didnt think of optimization earlier 😭
Make them a function and run them in one onEntityHurt event. And use switch-case instead of if-else
switch case would run only 1? wouldnt it
so instead if cases for all of em?
what about, making if statements for all, if the dynamic property (enchantment lvl) greater or equal than 1, it runs?
In that case if-else is the solution, try it ig
wouldnt if-else still run only 1?
??
if-else runs only 1 condition, which is correct and true, doesn't it?
i think i only need to use if, nothing else.
I don't get it
If else can run multiple checks via || (or) and && (and) operator
ah nvm
let a = 10, b = 20;
if (a > 5) {
console.log("A is greater than 5");
}
if (b > 15) {
console.log("B is greater than 15");
}
```like this yeah?
Yep
👍
is the new scriptevent method in stable now? If so, how does it work? I'm planning on using it more often after I update to the next hotfix.
I would make an array of objects for each subscribable event. There would be a "condition" property and a "execute" property. Then you can iterate all effects in a loop; you won't have to change any files in hurtEffect.js, just import the array and push to it.
// hurtEffects.js
import {world, EntityHurtAfterEvent} from "@minecraft/server";
/**
* @typedef {Object} HurtEffect
* @property {(e: EntityHurtAfterEvent) => boolean} HurtEffect.condition
* @property {(e: EntityHurtAfterEvent) => void} HurtEffect.execute
*/
/** @type HurtEffect[] */
const HurtEffects = [];
export default HurtEffects;
world.afterEvents.entityHurt.subscribe(onEntityHurt);
/** @param {EntityHurtAfterEvent} e */
function onEntityHurt(e) {
return HurtEffects.find(Effect => Effect.condition(e))?.execute(e);
}
// poisonBlade.js
import HurtEffects from 'hurtEffects';
HurtEffects.push({
condition(e) {
return e.damageSource.damagingEntity.name == "MadBoy";
},
execute(e) {
e.hurtEntity.addEffect("poison", 100);
}
});
damn, smart work, thanks
How can I see the NBT of an item?
It really does return my local hour
Wait now I created a new world and it works now
the api documentation is simultaneously one of the worst, and one of the better documentation I have read in a while.
Which site are you using?
the microsoft api reference
that why we have ton of none official ones
I would recommend:
https://stirante.com/script/
How to make scripts execute very early
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id !== "space:peek") return;
const checkLogs = system.runInterval(() => {
for (let player of world.getAllPlayers()) {
const playerPos = player.getHeadLocation();
for (let x = 0; x <= 3; x++) {
for (let y = 0; y <= 1; y++) {
const direction = { x, y, z: 3 };
const blockRaycast = player.dimension.getBlockFromRay(playerPos, direction, { maxDistance: 20 });
let block = blockRaycast?.block;
if (block && block.typeId.includes("_log")) {
const blockLoc = block.location;
world.getDimension("overworld").runCommandAsync(`summon space:anomaly ${blockLoc.x} ${blockLoc.y} ${blockLoc.z + 1} facing @a log`);
world.getDimension("overworld").runCommandAsync("tag @a add tree");
system.clearRun(checkLogs);
return;
}
}
}
}
}, 10);
});
Is this the correct way of looping my system.runInterval until my condition is met?
world.afterEvents.playerJoin.subscribe((eventData) => {
const now = new Date();
const localHour = now.getHours();
let greetingMessage = "h";
if (localHour >= 5 && localHour < 12) {
greetingMessage = "The sun rises, but the shadows grow longer...";
} else if (localHour >= 12 && localHour < 17) {
greetingMessage = "The midday sun is harsh, but something stirs in the distance...";
} else if (localHour >= 17 && localHour < 20) {
greetingMessage = "The evening grows dark, and something watches you...";
} else {
greetingMessage = "The night is silent, yet you feel you are not alone...";
}
world.sendMessage(greetingMessage)
});
Also why does this only work the first two times the player joins it just doesn't work after that
maybe be just coincidence? try using playerSpawn event instead of playerJoin, and check if initialSpawn = true
playerJoin triggers even if the player is in the loading screen
anyone in here intrested in being a long term dev that will do things free for minecraft bedrock
If you want an add-on made for you for free, you're most likely out of luck. The best thing you can do is watch tutorials and read guides so you can learn how to develop it yourself.
People won't work for free, but you can always offer to pay them to make something for you.
@sick robin
how can i clear a loop for an entity if it is no longer rendered?
nvm i got it
How do I stop a player from picking up items from the ground?
does anyone know why the scale component returns undefined in players and entities
Does the entity JSON have the scale component?
How do you do a side knockback? Using the entity.applyKnockback()
applyKnockback(
directionX: number,
directionZ: number,
horizontalStrength: number,
verticalStrength: number,
)
Play around with it.js const view = player.getViewDirection(); player.applyKnockback(-view.x, view.z, 1, view.y);
If you have two directions that you want knockback to be "sideways" to, you can compute the cross product to find the vector that is orthogonal to both inputs.
Say an action should push the player left from where they are looking. I would convert their rotation to spherical coordinates, then take the cross product of that and the Down vector ⟨0, -1, 0⟩
damn you math...
-# I know it's simple math but I hate it.
Spherical coordinate function:
#1301499373061931119 message
export function Vector3_cross(v1, v2) {
return {
x: v1.y * v2.z - v1.z * v2.y,
y: v1.z * v2.x - v1.x * v2.z,
z: v1.x * v2.y - v1.y * v2.x
}
}
const Forward = toSphericalFromRotation(1, player.getRotation().y, 0);
const Down = {x: 0, y: -1, z: 0};
const Left = Vector3_cross(Forward, Down);
// Left should now be left from facing dir
Although I realize the original spherical coordinate function I wrote isn't very smart with its inputs. Really should be able to pass a Vector2 in there
function DEG_TO_RAD(deg) {
return (deg / 180) * Math.PI;
}
function toSphericalFromRotation(
dist: number,
rot: Vector2
) {
const y_rot = -DEG_TO_RAD(rot.y), x_rot = DEG_TO_RAD(90 + rot.x);
return {
x: dist * Math.sin(y_rot) * Math.sin(x_rot),
z: dist * Math.cos(y_rot) * Math.sin(x_rot),
y: dist * Math.cos(x_rot)
}
}
const Forward = toSphericalFromRotation(1, {y: player.getRotation().y, x: 0});
const Down = {x: 0, y: -1, z: 0};
const Left = Vector3_cross(Forward, Down);
// Left should now be left from facing dir
Why does the game freeze when more than 1 entity activates addRider() at the same time?
use run job
import { world } from "@minecraft/server";
world.afterEvents.entityHitEntity.subscribe(({ source, itemStack }) => {
if (!itemStack) return;
if (itemStack.typeId === "d:cal_on") {
source.runCommand("/playsound knockback @a[x=~,y=~,z=~,r=10]");
}
});```
Am I missing something?
ItemStack doesn't exist in there
use equippable or inventory
const equippable = damagingEntity.getComponent('equippable');
const mainhand = equippable.getEquipment('Mainhand');```
ah ok
also it's damagingEntity and hitEntity are the valid properties
alright
how to use BlockLocation class?
what and why?
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id !== "space:peek") return;
const checkLogs = system.runInterval(() => {
for (let player of world.getAllPlayers()) {
const playerPos = player.getHeadLocation();
for (let x = 0; x <= 3; x++) {
for (let y = 0; y <= 1; y++) {
const direction = { x, y, z: 3 };
const blockRaycast = player.dimension.getBlockFromRay(playerPos, direction, { maxDistance: 20 });
let block = blockRaycast?.block;
if (block && block.typeId.includes("_log")) {
const blockLoc = block.location;
world.getDimension("overworld").runCommandAsync(`summon space:anomaly ${blockLoc.x} ${blockLoc.y} ${blockLoc.z + 1} facing @a log`);
world.getDimension("overworld").runCommandAsync("tag @a add tree");
system.clearRun(checkLogs);
return;
}
}
}
}
}, 10);
});
Is this the correct way of looping my system.runInterval until my condition is met?
Is it possible to have entity json component events call the script API?
There's no custom componnets for entities it seems
Use queue_command and run the scriptevent command
Mount(entity, target) {
const interval = system.runInterval(() => {
system.runJob( function* () { try { entity.getComponent("minecraft:rideable")?.addRider(target) } catch(e) { system.clearRun(interval) } } )
}, 2)
return interval
}
what's wrong?
.
@shut citrus
Can Minecraft Handle this if it's well optimized code?
Its not about th length of code but how much code you run each tick
Okay that's perffect, i just have like 2 intervals with a delay of 30 and 100 ticks
I just realized shouldn't it be system.runJob(anyName()) not a variable call only.
also in the sendMessage maybe you meant task not count?
you are right
tnx
-# edited
How can i detect if a player is in the overworld
it will return one of the dimension ids
overworld: minecraft:overworld
nether: minecraft:nether
end: minecraft:the_end
thx
finally it works
i was doing it with getComponent
dimension isn't a component, it's easy to get confused lol
if you're using vscode, try downloading the node modules, it will show minecraft stuff and make it easier to use
okay
How can I make players immortal?
The player must take damage but not die
And without effect
import { world } from "@minecraft/server";
world.afterEvents.entityHurt.subscribe((event) => {
const { hurtEntity, damage } = event;
if (hurtEntity.typeId !== "minecraft:player") return;
const health = hurtEntity.getComponent("health");
health?.setCurrentValue(health.currentValue + damage);
});
Hmm
What happens if the main player takes 20 damage?
he die 🤷♂️

Isn't it possible to increase the player's health bar with a script?
Make 1000 hp
setCurrentValue
BTW what is the purpose of the "?" after health?
I see this in some codes
if health is defined do what after
if it is not stop there
can be useful if you don't know if a component may or may not be present
sup so i need sum help so a nice guy here gave me a script to a feature i wanted to be in a addon of mine but idk how to make the addon or like put the script into my addon
Create a behavior pack
Then put it in the script file
is it possible to create a trigger box to detect if a player has entered a certain area, or are we forced to check per tick if a player is in a certain area?
import { world, system, BlockVolume } from '@minecraft/server';
system.runInterval(() => {
for (const player of world.getPlayers()) {
const volume = new BlockVolume({ x: 0, y: 0, z: 0 }, { x: 0, y: -60, z: 0 });
if (volume.isInside(player.location)) {
// ...
}
}
});
you are awesome
what is the difference between runInterval and running in the main execution function
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.BlockVolume-1.html
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.BlockVolumeBase-1.html
https://jaylydev.github.io/scriptapi-docs/latest/classes/_minecraft_server.ListBlockVolume-1.html
For more information
runtInterval is a loop imagine a repeating command block
Tho I'm not quite sure what's your question...
in the documentation, they use a recursive function for the main execution of the script
i'm curious if the runInterval would be better optimized
i'm learning how to make scripts for a custom summon directions ¿this is written correctly?
no.
the const one is wrong
const { id, sourceEntity } = data;
if (id === '' && sourceEntity) {
// ...
}```
Are you even sleeping coddy? You are everywhere lol
That's the fun part. I don't
oh your a rare sight
btw
I've seen ppl make functions in variable
how you do it
What is async actually
and whats the differnce with functions
.
like I saw ppl use await async blah blah:
const getBlockFromSurface = //..
await async getBlockFromSurface( );
Meanwhile you can do it with functions:
function getBlockFromSight() {
}
getBlockFromSight()
What does async,? and what is difference comparing to functions
you mean arrow functions or function expression
ah none of that
that not assigning the function to a variable
we are waiting for the function to return a value
can be useful in situation where the function take time to finish
What does async,? and what is difference comparing to functions
look into asynchronous functions and promise
hm
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id !== "space:peek") return;
for (const player of world.getAllPlayers()) {
const playerPos = player.getHeadLocation();
const directions = [
{ x: 1, y: 0, z: 0 },
{ x: -1, y: 0, z: 0 },
{ x: 0, y: 1, z: 0 },
{ x: 0, y: 0, z: 1 },
{ x: 0, y: 0, z: -1 },
{ x: 1, y: 1, z: 0 },
{ x: -1, y: 1, z: 0 },
{ x: 0, y: 1, z: 1 },
{ x: 0, y: 1, z: -1 },
{ x: 1, y: 0, z: 1 },
{ x: -1, y: 0, z: 1 },
];
for (const direction of directions) {
const blockRaycast = player.dimension.getBlockFromRay(playerPos, direction, { maxDistance: 20 });
const block = blockRaycast?.block;
if (block?.typeId.includes("_log")) {
const blockLoc = block.location;
player.dimension.runCommandAsync(
`execute as @a at @s run summon space:anomaly ~${blockLoc.x} ~${blockLoc.y} ~${blockLoc.z + 1} ~ ~`
);
world.getDimension("overworld").runCommandAsync("tag @a add tree");
system.clearRun(checkLogs);
return;
}
}
}
});
How to loop this with system.runInterval until found a log and stop that once found
ohhh nahhh
that's written like:
const getBlockFromSurface = (block) => {
//..
}
async getBlockFromSurface();
nope, that is not valid
thanks\
np
making a function async will not just magically make it more efficient
in fact often it decreases the performance due to the overhead from the promise
almost all that is wrong if i am being honest
This is like...the most...wrong comparison I've seen.
everyone just casually roasted @wheat condor 77Carchi💀
corrected*
big different
-# waiting for dingsel to send his correction so i don't have to
its quite hard to explain it in easy ways tbh but I will try my best
hence why i just told hem to look it up
It does however make you able to write code that is distributed over a longer time and wait for that to finish. You are still making the same amount of calls, you just have the option to distribute them as said without blocking other execution. For example you could place a block in one tick and another block in a different tick. You can wait for the last operation to complete by resolving the promise and using await.
You are not gaining performance because of async/await but you rather "gain" performance because you are doing less in a single tick
yeah, the only way to gain performance using async is to divide the task into a small tasks and run each one after the other by waiting for each one to finish, kinda like runJob
also that is really not the point of async, same thing can be done with runtimeout in a regular function (the only different is that it is impossible to return a value that way)
in general async isn’t about speed it’s about responsiveness
If you're working with something that doesn’t need to finish immediately (like fetching external data or placing multiple blocks over time, waiting for the player response (that is why show function in forms is async))
i tried to explain it the best as i can
how do I open a entity click form when player is sneaking
like clicking a entity while sneaking to open a form?
world.beforeEvents.playerInteractWithEntity.subscribe(ev => {
const { target, player, itemStack } = ev;
if (player.isSneaking && target.typeId === 'minecraft:creeper') {
ev.cancel = true;
// ...
}
});```
ok thx
system.runInterval(() =>{
for(let player of world.getPlayers()){
if(player.hasTag("interact" && !Player.isSneaking )){
interact(player)
player.removeTag("interact")
}
}
function interact (player) {
const gui = new ActionFormData();
gui.button('Jump Up!', 'textures/gui/menu/jump_up_icon')
gui.button('Exit!', 'textures/gui/menu/exit_icon')
gui.show(player).then(result => {
if (result.selection === 1) {
jump_up(player)
}
if (result.selection === 4) {
exit(player)
}
}
)
}
function jump_up(player) {
player.runCommandAsync("event entity @e [family=monkey,c=1,r=5] grlab:to_jump_up");
}
function exit(player) {
player.runCommandAsync;
}
})
is dips below 20TPS normal
How do I cast a ray to check if a block was hit with the desired origin and direction?
Why is MinecraftEffectTypes not working
is it a player?
player or not you could use getBlockFromRay()
Are you bundling the vanilla data module?
is not from an entity
getBlockFromRay(location, direction, options?)
btw it's under dimension.
Foxed it
I found a fix
I needed to use Effects with a get method
Wait nvm
Its not setting the effect
Entity.addEffect('speed', duration * 20, { amplifier: 0, showParticles: false })
im trying to make a function i can run wherever that sets code for effects ill add aditional logic below in each case
Ohh wait its adding it for short sperts only
There we go
Ok what is the method to remove all effects from a player
What is the proper way to clear all effects on minecraft scripts
the only existing one is .removeEffect('<effect>')
Ohh so id need to remove specific effect that might not be a bad thing tbh
So player.removeEffect(effect) assuming effect is a variable
Cause ima create a function that takes in effect
to remove all effects just do getEffects() the get all current effects then get the ID then boom
That confuces me but i dont need to clear all effect i judt thought it was the only way
for (const effect of Player.getEffects()) Player.removeEffect(effect.typeId)```
Give me a reason just 1 reason why anyone would ever do an unsubscribe world event
if you're calling an event inside if an event
Perfomance reasons, for example you only need that event in an specific time frame like an boss fight or minigame
Ohhh so unsubscribe will still show the event just not all the time
unsubscribe unsubscribes from the event or stops the event listener
Is there an event for player moves player hits key or player is in a radius of certain coords
Ohhh i see
There is an input event, but it's only for crouch/sneak and jump
Thats useful still what about if a plater is in radius of certain coords
No direct event for that- you can use an interval and test their coords for that.
Ok so how do i do that then set there value to x y or z
I personally would just use the inbuild api as its better for performance in this case
interval:
dimension.getEntities({ type: "minecraft:player", location: {x,y,z}, maxDistance/Radius: 30})
Tbh I forgot the actual names for these fields, but there kinda like this
Im not on pc rn
system.runInterval(() => {
for (const player of world.getPlayers()) {
const inputInfo = player.inputInfo;
const movement = inputInfo.getMovementVector();
const jump = inputInfo.getButtonState('Jump');
const sneak = inputInfo.getButtonState('Sneak');
const normalizedX = Math.abs(movement.x) > 0.2 ? Math.sign(movement.y) : 0;
const normalizedY = Math.abs(movement.y) > 0.2 ? Math.sign(movement.y) : 0;
if (normalizedY > 0) console.error('forward');
else if (normalizedY < 0) console.error('backward');
if (normalizedX > 0) console.error('left');
else if (normalizedX < 0) console.error('right');
if (jump === 'Pressed') console.error('jump');
if (sneak === 'Pressed') console.error('sneak');
}
});```
Have to factor in view direction if you wanna get accurate direction buttons :(
Tbh all i need is an input to cancel crafting i tried with forms but the code wont run while forms are open so all i needcis to make it so thevplayer can cancel the crafting
@dim tusk so how would i use that all i really need is a way a player can do an imput so i can use that imput to cancel another script i have
What type of input.
As of now there's now way to detect buttons pressed btw.
It doesnt matter sneak works jump works
Any 1 imput i just need a way to cancel scripts by player input
what's your goto solution for connecting a database to a server via the ts api
@dim tusk
I'm asking, what type of input.
Whats possible
like be specific.
using items, using items on blocks, interaction with blocks, movement and camera.
Sneak ets do sneak
Player.inputPermissions.setPermissionCategory(5, false);
You can refer to the values of movements here, just change the 5 with values needed
im using server-net for the http, im also running a express server for a local db so i can export data, it wont send data but no errors
Why is that not in numeric order you know what never mind
Ltho that looks like its taking sneak away
Basicually what i need is to be able to run a function that returns sneak if sneaking so it can set canceled to true and stop the for loop
Well its not a for loop actually
Its a timed loop
player.isSneaking
Thats a valid input? Ok
its true or false
world.afterEvents.playerButtonInput
Thats fine all i need is true or false
Oka
why?
There's a built-in thing already
If you mean just getting the current day do use world.getDay()
It is tick based not time based
nah, getDay returns the current day.
i thought of something like world.getAbsoluteTime() and then each night passes and i add one number to the variable ..
like:
if(world.getAbsoluteTime() == "") {
counter++
}```
Again it’s tick based, if you do /time set 0 the days will return to 0
I really want to know that, is there a significant performance difference between those two methods?
Lets take 5 sleeping players as example, would it lag like crazy on the 1st method?
??
just putting the night time value
and then should it work
Since sleeping takes more than 1 tick you can optimize it by setting the runinterval al 20 ticks and check the sleeping by player.isSleeping == true, then you can optimize even more dividono the players in each tick
Btw the second is the best option
It's a number not string.
Sorry for the confusion but it's not vanilla sleep, sleep.onSleep() runs some necessary code per tick
The day starts at tick 6000
Well if you don’t want lag you should avoid:
Commands
Tags
Scoreboard
If you give me the full code i can optimize it as best as I can
ohhh wait @wheat condor @dim tusk
every minecraft day is 24 000 ticks long
so get currentTick and divide it via 24 000
then maybe that will get number of days
will that work? am i right?
That’s just world.getday()
currentTick doesn't reset?
You need something that counts play time as minutes or as ticks?
how do i use world.getDay() to make the day counter.. that's the question
Ah nvm.
just days
like a night passes == new day
we've to detect when the night passes, so then we can add new day
The code's running smoothly so far, I was just asking that if script event is called on multiple entities at the same tick, would it lag too much?
Well, it depends on what you are doing in the same tick
I see
Thanks for the info, both of you!
let tick = world.getDynamicProperty('tick') ?? 0;
let dayCount = world.getDynamicProperty('dayCount') ?? 0;
system.runInterval(() => {
tick += 1;
if (tick >= 24000) {
tick = 0;
dayCount += 1;
world.setDynamicProperty('dayCount', dayCount);
}
world.setDynamicProperty('tick', tick);
});
maybe i remeber someone made day counter bfore
and how do i show the day
wheres the variable
This shit is random only
umm, dayCount??
so,
console.warn(${dayCount}) ??
Bro how can the tick be 24000
really good explenation
It’s just ChatGPT
understanding how JS handles execution is the key to success
oh hey! can you help me about how can i make a Day Counter?
????
Get current tick and divide it by 24000
ohh
for each player?
then count ticks the are in world
is this script fine ?
let tick = world.getDynamicProperty('tick') ?? 0;
let dayCount = world.getDynamicProperty('dayCount') ?? 0;
system.runInterval(() => {
tick += 1;
if (tick >= 24000) {
tick = 0;
dayCount += 1;
world.setDynamicProperty('dayCount', dayCount);
}
world.setDynamicProperty('tick', tick);
});
is this script fine for what i want
?
could work but definitely not good
its waste of performance
can you improve it
If it’s for the world is just useless math, you just need world.getday()
yeah definitely not lmfao
i just stop reading it once i saw runInterwal thats why i said so haha
Bro just use world.getDay()
bro is just shouting world.getDay()😭 but its not used in this script
bad as well
Why is it?
hear me out
not per player
ahh, the guy who said not to use it, suggests using it.
So you need it per player?
well here is pseudo
If it’s for world it’s fine, else not
sigh why would in the first place I suggested the getDay()
Bro, can yoou please tell me improving the script?? one guy is saying to use world.getDay() or is the script i showed you is it fine??
on-player-join:
player.joinTime = getTime
on-please-leave:
player.totalPlayTime += getTime - player.joinTime
thats the pseudo
use it and code it
each time they play add it to the total time once the left
or server shutdowns
If you need it per player, just add a dynamic property to catch the Eorld.getAbsoljteTime() when the player joins and when the player leaves, then sum it everytime to keep only 1 value and add everytime
Yeah we were thinking the same thing
//save when player join so we can use it later
world.afterEvents.playerSpawn.subscribe((event) => {
const {player,initialSpawn} = event
if(!initialSpawn) return
player.setDynamicProperty("joinTime",Date.now())
});
//save time played in this session + the previous ones
world.beforeEvents.playerLeave.subscribe((event) => {
const {player} = event
const time = getPlayedTime(player)
player.setDynamicProperty("playedTime", time)
});
//get the current time played
world.afterEvents.chatSend.subscribe((event) => {
const {sender,message} = event
if(message != "!playedTime") return
const time = getPlayedTime(sender)
sender.sendMessage(`You played for ${time} seconds`)
});
function getPlayedTime(player) {
const playedTime = player.getDynamicProperty("playedTime")??0
const joinTime = player.getDynamicProperty("joinTime")??0
//Date.now() - joinTime >>> current session time
//Date.now() - joinTime + playedTime >>> current session time + previous ones >>> total time
return Date.now() - joinTime + playedTime
}
so you actually using real time not MC ticks?
I think he wish to count in MC days
oh, i guess he could change it
so you guess, huh, I guess 90% of the script api members don't know diff between word "Script API" and "JavaScript", but you already helped more than enought