#Script API General

1 messages · Page 60 of 1

distant tulip
#

yeah it is, a bit outdated tho

#

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

azure lichen
#

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. 🥰

distant tulip
#
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?

dense wraith
#

One message removed from a suspended account.

distant tulip
#

i didn't, it is kinda up to date

remote oyster
#

To teach you must learn to be a teacher.

azure lichen
#

This is my search history.

#

brother I don't just use AI, I search for what I need.

deep arrow
#

Sup guys

ivory bough
#

How to spawn an entity using dimension.spawnEntity behind a block and also triggering one of the entity's event

wary edge
#

I recommend reading the docs on spawnEntity since it returns an Entity instance in which you can use triggerEvent.

ivory bough
prisma shard
#

oh i misunderstood srry

hot sundial
#

how to handle removing experience? No matter what i do it doesnt go down in levels it just emptys the bar

thorn flicker
prisma shard
#

but i didnt understand

hot sundial
#

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

thorn flicker
hot sundial
thorn flicker
#

ive made a method in a class for this exact thing.

hot sundial
#

could you send it to me?

#

pretty please

thorn flicker
#

I rather teach you how to make it, rather than just giving it to you

hot sundial
#

i just want the algorithm for the scaling of the levels i can do the code

thorn flicker
#

you dont even need that, I didn't.

hot sundial
#

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

thorn flicker
#

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.

hot sundial
#

omg i feel like an idiot

#

i didnt know player had .XpNeededForNextLevel

thorn flicker
#

its fine

thorn flicker
hot sundial
#

i got it working

#

thank you

thorn flicker
#

np.

unique acorn
#

is something wrong here?

#

why isn't autocompletion working properly

warm mason
# unique acorn is something wrong here?

getComponent returns EntityComponent and VScode doesn't know that you get EntityInventoryComponent, so it only shows methods that are available on all components

unique acorn
#

how come it works in my other addon tho?

prisma shard
#

bcoz you put container?

warm mason
wary edge
unique acorn
#

yes

wary edge
#

If you're using stable, you'll need to typecast. If you're using beta, you don't.

unique acorn
#

I installed 1.18.0-beta's autocompletions

errant wadi
#

typecast 🔥

unique acorn
#

okay then.

errant wadi
distant gulch
#

Is that even the right way to get it

wary edge
distant gulch
#

Stable

wary edge
distant gulch
#

Th is an typecast

distant gulch
wary edge
#

Then use TS.

distant gulch
#

Idk how to

fading sand
#
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;
    }
})
thorn flicker
fading sand
wary edge
#

You have to set the item back.

distant gulch
fading sand
errant wadi
#

of the scripting engine

thorn flicker
# distant gulch ?
    const inv = player.getComponent(EntityInventoryComponent.componentId)

    if (inv instanceof EntityInventoryComponent) {
        //...
    }
errant wadi
fading sand
#

can we get armor component of an item?

errant wadi
#

or you have to call setItem function

distant gulch
errant wadi
#

that stupid bridge doesn't know the maps ig

#

this is how the type is defined

fading sand
#

how to get the armor level of an armor?

errant wadi
distant gulch
#

Now how do I get an item in the mainhand

errant wadi
#

container.getItem(player.selectedSlotIndex)

distant gulch
#

Where the hell is the player variable coming from

errant wadi
#

then where the hell is the container variable coming from

distant gulch
#

Huh

#

Oh it's just the entity

errant wadi
#

here's the another.

#
entity.getComponent(EntityComponentTypes.Equippable).getEquipment(EquipmentSlot.Mainhand);
distant gulch
#

The another is more work

errant wadi
#

ye it's working for non-player entities

errant wadi
distant gulch
#

Is data store possible

errant wadi
#

for non-player entities you can just do container.setItem(0) iirc

errant wadi
#

with dynamic properties

distant gulch
#

I'm talking about sending data to a website or an API either through an http request or sum

#

And reloading it back

unique acorn
#

only possible in BDS, you can use post and get request

distant gulch
#

What is BDS

errant wadi
#

could you please google it 😭

unique acorn
#

bedrock dedicated server

distant gulch
#

Oh that

errant wadi
#

before you ask, please google it first..

distant gulch
fading sand
#

how do i repair an item?

errant wadi
fading sand
#

but prob same

dim tusk
#

You're wrong about that part bud.

dim tusk
dim tusk
# fading sand how do i repair an item?
const equippable = player.getComponent('equippable');
for (const item of ['Offhand','Mainhand']) {
   const durability = item.getComponent('durability');
   durability.damage = 0;
}```
fading sand
#

wdym , if i set damage to -1 its error

dim tusk
#

you can have damage of -1?

#

no right?

fading sand
#

ye

#

so

#

how is repair done

dim tusk
fading sand
#

tf

dim tusk
#

0 damage means fixed.

fading sand
#

so i cant say i increase by 1

dim tusk
#

if the damage is 0, means it's full durability

#

it's literally in the name DAMAGE

fading sand
#

hmm

#

thx

errant wadi
#

finally

dim tusk
errant wadi
#

I was watching screenshare, and teaching him how to make rp and bp

distant gulch
#

Is it possible to detect a block in a certain radius

dim tusk
distant gulch
errant wadi
#

you can

dim tusk
#

make a list of location of the entity.

errant wadi
dim tusk
#

but beware that it will cause a lot of tp docps

errant wadi
#

lol

#

um actually

distant gulch
#

I want to make it so it checks in a radius if it contains a block not a single area or like that

errant wadi
#

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.

dim tusk
errant wadi
#

getBlock takes less resources than setBlockPermutation

#

so it can be more higher than 10k blocks in a tick

errant wadi
distant gulch
dim tusk
#

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);
// ...
}

errant wadi
#

wth is that

dim tusk
errant wadi
#

better version ig

dim tusk
#

since you're on PC why not help him instead 😜

errant wadi
distant gulch
#

Will that be able to detect if it contains a block not if the whole area is the same block

errant wadi
#

the filter argument is not optional

distant gulch
#

Like detecting if a string contains a letter but it's a block being detected in a radius

errant wadi
dim tusk
dim tusk
errant wadi
#

but you didn't give it

dim tusk
errant wadi
#

that's why there's an error

dim tusk
#

?

#

?

errant wadi
#

I never used getBlocks before

#

so i don't know

dim tusk
#

Nevermind it's hard to win against someone.

#

sigh

errant wadi
#

😖

#

I only do just 3 loops

#

for (x..
for( y..
for(z..
dimension.getBlock({x, y, z})

distant gulch
#

But would it appear around the block relative to it's position

#

I want the detection range relative to a blocks position

dim tusk
distant gulch
#

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)

dim tusk
distant gulch
dim tusk
distant gulch
#

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?

distant gulch
dim tusk
distant gulch
#

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

distant gulch
dim tusk
# distant gulch And what I want fully to happen is Detect in a radius of 2 away from the origina...
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);
                }
            }
        }
    }
});```
errant wadi
#

just do let x = centerLoc.x - 2

dim tusk
#

sigh I love nesting

errant wadi
#

x <= centerLoc.x + 2

#

use the exact position instead of the delta position

#

so you can just simply do getBlock({ x, y, z })

dim tusk
#

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);
    }
});```
errant wadi
#

BEST READABILITY 👍

dim tusk
errant wadi
#

for real.

distant gulch
#

What would be the necessary extensions for script API auto completions on visual Studio Code

distant tulip
distant tulip
#

which part

deep arrow
#

And you can then just run "npm i @minecraft/server" in your terminal to install the packages to your current directory

north rapids
#

Is it possible to detect which block was broken?

#

Block id to be more specific

dim tusk
north rapids
#

Tysm

#

Is it possible by "on_break" custom component?

dim tusk
north rapids
#

Sorry, I meant the custom component event "onMineBlock"

#

I'm a little rusty with JS

dim tusk
#

also they have different names it's minedBlockPermutation instead

north rapids
#

I didn't know that

#

Tysm

scarlet sable
#

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

silver agate
#

is it possible to make a block change the state based on biome?

silver agate
#

oh, that's rlly sad

#

isnt there any metod?

#

like even to simulate it (idk)

wary edge
silver agate
scarlet sable
unique acorn
# scarlet sable

not 100% perfect but disable showDeathMessages gamerule, send your own message then enable it again

glacial widget
#

is there any way to block invis skins?

random flint
#

turn on "only allow trusted skin"

ivory bough
#

dimension.spawnEntity("space:anomaly", block.location);
How to spawn my entity behind the block?

distant tulip
#

define the "block" and "behind the block"

ivory bough
#

The block variable is defined somewhere in the code

distant tulip
#

How to spawn my entity behind the block?
is not clear
where is the block
what "behind the block" mean? relative to what?

ivory bough
#

^^^-1

#

And the block is from blockRayCastHit

distant tulip
#

^^^-1 is not block relative

subtle cove
#

blockface location relative to block.center?

distant tulip
#

blockface is a string, no?

#

you mean the hitLocation

subtle cove
#

perhaps...

distant tulip
#

it is relative to the block origin 0 0 0

subtle cove
#

well, im not the inquiree ;-;

ivory bough
distant tulip
#

hitLocation + block location + ray direction normalized

subtle cove
# ivory bough Yes

what if it's like a slab, should it relate to the viewvector of the player?

distant tulip
#

it is a log iirc

ivory bough
subtle cove
#

ok, relative to player view

distant tulip
ivory bough
distant tulip
#

not sure about the normalized part
sense the block can get to √(1²+1² + 1²) = √3 thick, depending on the vector

ivory bough
distant tulip
#

they are not

azure lichen
#

Why can't user import addons, when he clicks to install the addon, the addon doesn't go into Minecraft Bedrock.

distant tulip
#

#add-ons

hybrid island
#

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;
    }
}
ivory bough
distant tulip
# ivory bough Wait but what if I just add +1 to the z of the block's location and spawn it in ...

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

hybrid island
#

wait

distant tulip
#

ensure it is valid

hybrid island
#

sry my inetert bugged out

#

let maxRefinable = Math.min(itemCount, maxAffordable);
let maxRefinable = Math.min(itemCount, maxAffordable);

distant tulip
#

log that to console and see it value

hybrid island
#

error doesnt allow it

wary edge
hybrid island
distant tulip
#

move the line before the itemstak one

hybrid island
#

huh

ivory bough
#
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?

errant wadi
#

WDYM "IMPROVING"

#

performance?

#

readability?

#

or something else?

ivory bough
errant wadi
#

does it make lags?

ivory bough
#

I am asking if there's a better way of detecting logs

#

Or the raycast

errant wadi
#

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

#

🤔

ivory bough
errant wadi
#
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)

prisma shard
shut citrus
#

what limit scriptEventReceive is? When it actives 46 functions it starts bugging

wheat condor
empty yoke
#

Is there any way to force an entity into a specific target?

tawny peak
#

hmmm this is new to me, what does Player.hideAllExcept do?

wary edge
jade grail
#

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

night acorn
#

or damagingEntity

#

just do:

view_entity.applyDamage(50, {
        damagingEntity: {
            damagingEntity: player,
            cause: "entityAttack"
        }
    })
jade grail
#

ah i see thanks

night acorn
#

np

jade grail
#

still doent work tho

dim tusk
jade grail
#

O thanks

zinc flax
#

Is air not detectable by getBlockFromRay?

#

I wanted to get the location of something 3 blocks infront of me. Tried to stick to blocks.

dim tusk
zinc flax
prisma shard
#

how to get the entity that was hit by projectile

#

oh i see getEntityHit().entity

ivory bough
#

How to get the feet location(starting point of collision box) of my entity

ivory bough
dim tusk
#

you can't.

ivory bough
#

i don't think "air" would work

night acorn
#

so just use entity.location

stark kestrel
#

is it possible to summon entity in a unloaded chunk?

fallow rivet
#

Is the dynamic property addon specific, file specific or world specific?

stark kestrel
#

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

slow walrus
#

per world, saved under the addon uuid

lethal willow
#

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

wary edge
unique acorn
#

ping me if you want a code example

lethal willow
prisma shard
stark kestrel
unique acorn
# stark kestrel i meant if lore n properties are available, how to put it back to inv with the s...
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)
    }
  }
})
stark kestrel
unique acorn
#

im still confused on what runJob is for, can anyone explain

chilly fractal
#

Generator function

#

Runs generator functions

#

Which pause execution till the next tick if you do yield;

distant tulip
# unique acorn im still confused on what runJob is for, can anyone explain

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

unique acorn
#

Thank you

tidal wasp
#

Is there a way to use use permutationToPlace to set multiple permutations to be placed

distant tulip
tidal wasp
#

isnt that for setPermutation?

distant tulip
#

hmm?

tidal wasp
#

doesnt .resolve() only work for setPermutation?

distant tulip
#

resolve and withState both return a permutation
and permutationToPlace take permutation

warm mason
distant tulip
night acorn
#

anyone know how to temporarily disable fall damage for the player?

distant tulip
#

effects

night acorn
#

ok

scarlet sable
#

how do I make a fillable item?

cold grove
#

or like the bucket, different items for every "state"

knotty plaza
#

Is it possible to detect if the player riding an entity is trying to move?

umbral dune
#

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?

dim tusk
knotty plaza
#

Not using beta

dim tusk
knotty plaza
#

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

dim tusk
knotty plaza
#

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

celest abyss
#
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

knotty plaza
dim tusk
knotty plaza
dim tusk
knotty plaza
dim tusk
knotty plaza
#

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

unique acorn
#

Does anyone have an example how to apply knockback sideways? Like push the player to the right

#

I'm really bad at math

bright dove
#

Hey

#

Is there a jank to listten to block updates ?

ivory bough
#
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 });

chilly fractal
#

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

prisma shard
dim tusk
#

unless you're in spectator or teleport

#

other than that? No.

shut citrus
#

How fast scripts 2.0 execute is?

night acorn
shut citrus
fallow rivet
#

How do I make a skyblock island generator?
Does anyone have an idea?

prisma shard
#

or a whole skyblock island terrain you want to generate? (you can do this using worldedit)

fallow rivet
#

A random island for each person

prisma shard
#

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

prisma shard
# fallow rivet A random island for each person

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

chilly fractal
#

Well, is there anyway to make tamed zombies and skeletons?

#

Like they can't and won't target you

#

Even if you attack them

wheat condor
chilly fractal
#

For player or mobs?..

#

Assuming mobs.. right?

wheat condor
chilly fractal
#

Ah shit

#

Welp

#

I guess I'm gonna need to make a python script

wheat condor
chilly fractal
#

Cuz that's way too many entity files

#

Python

wheat condor
chilly fractal
#

What do you exactly mean?

wheat condor
chilly fractal
#

Aight but, i gotta do it for Skeletons, endermen, wardens, and a whole lot more

chilly fractal
#

Yea

#

That's why i said I'm gonna need to make a python script

wheat condor
#

but after you do 1 time you just have to copy paste

chilly fractal
#

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?

midnight ridge
#
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
chilly fractal
#

.selectedSlot => .selectedSlotIndex

midnight ridge
chilly fractal
#

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

midnight ridge
#

😭 i forget to turn on the logs

#

srr guys

midnight ridge
edgy elm
#

hi here. Is it possible to detect biomes?( if player is in specific biomes)

If anyone has an idea please tell me

gaunt salmonBOT
dim tusk
# edgy elm hi here. Is it possible to detect biomes?( if player is in specific biomes) If ...
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.

fallow rivet
#

How can I run a realms 24/7?

valid ice
#

Use BDS

#

Realms close automatically when nobody is online. No way to turn that off.

fallow rivet
valid ice
#

I guess you could have a realm bot or something stay in the sever

#

The real question is why

fallow rivet
valid ice
#

Sure, but why keep it open 24/7

fallow rivet
#
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)
}
}
})

valid ice
#

Just use javascript's Date.now() method

#

Always runs

fallow rivet
#

After setting the game clock with the world time, I can synchronize the world and game clock with this code.

valid ice
#

Always updates

#

Accurate down to the millisecond

dim tusk
#

the formatting hurts me

valid ice
#

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

fallow rivet
#
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

fallow rivet
#

Does the navigator work in scripts?

digital trout
#

Does "getProperty()" work with molang variables like "is_casting" or "variable.attack_time"?

digital trout
#

Is there a way to query those in script API?

valid ice
#

Nope

#

Client side only

digital trout
#

hmm

Is there another way to check if the behavior 'minecraft:behavior.summon_entity' is active?

valid ice
#

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)

valid ice
digital trout
#

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

valid ice
#

Ah I see

#

That’s a tricky one for sure

slim forum
#

How do I detect if a mob has items in its hand?

dim tusk
slim forum
#

Oh no

dim tusk
# slim forum Oh no

you can't because the equippable component is disabled for mobs yet it only works for players

dim tusk
# slim forum Oh no

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;
}```
gaunt salmonBOT
grave thistle
#

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?

grave thistle
#

Nice, thanks for the quick reply 👍

zinc flax
#

How would one applyKnockback an entity to a specific coordinate?

deep arrow
# dim tusk The best you could do is this. ```js function holdingItem(entity) { const com...

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

dim tusk
#

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.

deep arrow
#

Its a horrible idea

#

Im just stating that, that can be dne

dim tusk
cold grove
#

Testfor command wasnt removed?

deep arrow
dim tusk
cold grove
#

I remember something like that, maybe delulu

deep arrow
#

Delulu frfr

#

Aint we all tho

grave thistle
#

Can an ItemStack be stored in a dynamic property on a player?

grave thistle
#

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?

cold grove
#

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 👀)||

chilly moth
#
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

chilly moth
#

beta

#

@dim tusk

#

1.21.70._

#

?

dim tusk
#

Wait iirc it's under the system now since the beforeEvents worldInitialize is removed

chilly moth
dim tusk
#

what's line 18, he can't just magically guess it.

chilly moth
#

cannot read property subscribe

subtle cove
#

i got no other news than that

dim tusk
chilly moth
#

ok wait

dim tusk
#

-# I think.

chilly moth
#
[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)
]


chilly fractal
chilly moth
chilly fractal
#

Nuh uh

chilly moth
#

import { world , system } from '@minecraft/server';

chilly fractal
#

I sent you the fix

chilly moth
#

ok

dim tusk
#

if that didn't work do startUp other than that... I dunno anymore lol

chilly moth
#

same error

chilly moth
#
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);
    }
});

chilly fractal
#

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

dim tusk
#

best you could do is check if he's wearing it or na.

chilly fractal
#

Well, I'd say using itemUse

#

I used the afterEvent for enchanting and i was testing enchanting armor

#

And it swapped

dim tusk
chilly fractal
#

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

distant tulip
#

you could make your own event using interval

chilly fractal
#

Nah, itemUse is enough

#

I believe.

distant tulip
#

the player can just open inv and change it

chilly fractal
#

True..

#

Hmmm... alright i guess that's my only option. To use interval.

dim tusk
chrome flint
#

is server-net activated on realms?

open urchin
#

no

fast lark
#

is there a isSolid?

wary edge
fast lark
#

thx

fast lark
# wary edge In beta.

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)
}

grave thistle
#

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

jade grail
#

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

jade grail
cold grove
#

i'm asking

jade grail
#

wdym?

cold grove
#

get ViewDirection is a Vector3 so you are missing one axis

#

thats why is buggy

jade grail
#

not down

cold grove
#

applyKnockback({ x: view_location.x, z: view_location.z } , 2)

cold grove
jade grail
#

but i dont want to change the y so i dont use it

#

i got it fixed at 2

jade grail
#

? you know how the lifeboat feather works

#

it flings u forward and up

#

thats what im tryna get

fallow rivet
#

Does anyone know how I can turn this off?

#

Emojimsg

minor horizon
#

is there a better way to force load chunks than with a temporary ticking area? I'm using it to load structures

open urchin
dim tusk
dim tusk
#

guys, what version of script was equippable disabled to mobs.

meager pulsar
#

how can i test the depth of a water block to know if its full?

shut citrus
wary edge
meager pulsar
#

block.matches(`minecraft:water`,{liquid_depth:15})like this?

distant gulch
#

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

dim tusk
#

try checking Herobrine's Chest UI

distant gulch
dim tusk
#

he did that.

dim tusk
distant gulch
#

ugh

#

anyways, thanks

dim tusk
#

there's no way to actually removed that since it's server side.

#

unless Mojang added client, probably

meager pulsar
#

the right sintaxis

#

i also tried with "withState" but neither work

dim tusk
#

/setblock water[] or /setblock flowing_water[]

meager pulsar
dim tusk
meager pulsar
#

Th

#

Thx

small cloak
#

I was wondering where this thread went for the last few days. It really should be a channel.

#

They don't like lurkers.

fallow rivet
chilly moth
#

99999

#

100k msg in Script Api General

#

yeah

distant tulip
#

they didn't, discord only count up to 100k in threads status

ivory bough
#

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?

dim tusk
#

console.error(localHours)

#

to know if it really returns the value required.

stark kestrel
#

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 😭

lofty cape
#

Make them a function and run them in one onEntityHurt event. And use switch-case instead of if-else

stark kestrel
#

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?

lofty cape
#

In that case if-else is the solution, try it ig

stark kestrel
lofty cape
#

??

stark kestrel
# lofty cape ??

if-else runs only 1 condition, which is correct and true, doesn't it?

#

i think i only need to use if, nothing else.

lofty cape
stark kestrel
lofty cape
#

Yep

stark kestrel
#

yeah i was confused when u said else 😭

#

cuz i cant use else in this

lofty cape
#

👍

sage portal
#

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.

sharp elbow
# stark kestrel my scripts use like 27 entity hurt for weapon ces, what should i do? make every ...

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);
  }
});
fallow rivet
#

How can I see the NBT of an item?

ivory bough
#

Wait now I created a new world and it works now

hazy cosmos
#

the api documentation is simultaneously one of the worst, and one of the better documentation I have read in a while.

hazy cosmos
#

the microsoft api reference

distant tulip
#

that why we have ton of none official ones

wary edge
hazy cosmos
#

What would y'all suggest.. thank you

#

wow that's much better

shut citrus
#

How to make scripts execute very early

cold grove
#

what

#

🤔

ivory bough
#

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

cold grove
#

playerJoin triggers even if the player is in the loading screen

sick robin
#

anyone in here intrested in being a long term dev that will do things free for minecraft bedrock

drifting ravenBOT
#
Free Work

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.

wary edge
solar dagger
#

how can i clear a loop for an entity if it is no longer rendered?

solar dagger
#

nvm i got it

fallow rivet
#

How do I stop a player from picking up items from the ground?

sterile epoch
#

does anyone know why the scale component returns undefined in players and entities

wary edge
sterile epoch
#

ohh

#

no

winter plaza
#

How do you do a side knockback? Using the entity.applyKnockback()

unique dragon
#
applyKnockback(
    directionX: number,
    directionZ: number,
    horizontalStrength: number,
    verticalStrength: number,
)
dim tusk
sharp elbow
#

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⟩

dim tusk
#

damn you math...
-# I know it's simple math but I hate it.

sharp elbow
#

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
shut citrus
#

Why does the game freeze when more than 1 entity activates addRider() at the same time?

distant tulip
#

use run job

junior hill
#
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?

dim tusk
#

use equippable or inventory

#
const equippable = damagingEntity.getComponent('equippable');
const mainhand = equippable.getEquipment('Mainhand');```
junior hill
#

ah ok

dim tusk
#

also it's damagingEntity and hitEntity are the valid properties

junior hill
#

alright

shut citrus
#

how to use BlockLocation class?

dim tusk
ivory bough
#

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?

digital trout
#

Is it possible to have entity json component events call the script API?

There's no custom componnets for entities it seems

knotty plaza
shut citrus
#
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
distant gulch
#

Can Minecraft Handle this if it's well optimized code?

honest spear
distant gulch
dim tusk
#

also in the sendMessage maybe you meant task not count?

distant tulip
#

tnx
-# edited

fast lark
#

How can i detect if a player is in the overworld

nova wyvern
#

it will return one of the dimension ids

overworld: minecraft:overworld
nether: minecraft:nether
end: minecraft:the_end
fast lark
#

finally it works

#

i was doing it with getComponent

nova wyvern
#

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

fallow rivet
#

How can I make players immortal?

#

The player must take damage but not die

#

And without effect

distant tulip
# fallow rivet 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);
});

fallow rivet
#

What happens if the main player takes 20 damage?

distant tulip
#

he die 🤷‍♂️

fallow rivet
#

Isn't it possible to increase the player's health bar with a script?

#

Make 1000 hp

distant tulip
#

setCurrentValue

fallow rivet
#

I see this in some codes

distant tulip
#

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

cold grove
fallow rivet
#

The text on the heart logo is player hp

sudden epoch
#

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

fallow rivet
#

Then put it in the script file

hazy cosmos
#

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?

dim tusk
hazy cosmos
#

what is the difference between runInterval and running in the main execution function

dim tusk
#

Tho I'm not quite sure what's your question...

hazy cosmos
#

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

serene lava
#

i'm learning how to make scripts for a custom summon directions ¿this is written correctly?

dim tusk
#

the const one is wrong

#
const { id, sourceEntity } = data;
if (id === '' && sourceEntity) {
  // ...
}```
gaunt flare
#

Are you even sleeping coddy? You are everywhere lol

dim tusk
prisma shard
prisma shard
#

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

distant tulip
#

you mean arrow functions or function expression
ah none of that

distant tulip
#

can be useful in situation where the function take time to finish

prisma shard
#

What does async,? and what is difference comparing to functions

distant tulip
#

look into asynchronous functions and promise

prisma shard
#

hm

ivory bough
#
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

prisma shard
distant tulip
#

nope, that is not valid

prisma shard
#

heh

#

idk man

prisma shard
#

thanks\

wheat condor
simple zodiac
#

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

distant tulip
wary edge
prisma shard
#

everyone just casually roasted @wheat condor 77Carchi💀

distant tulip
#

corrected*
big different

#

-# waiting for dingsel to send his correction so i don't have to

simple zodiac
#

its quite hard to explain it in easy ways tbh but I will try my best

distant tulip
simple zodiac
#

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

distant tulip
#

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))

wheat condor
chilly moth
#

how do I open a entity click form when player is sneaking

#

like clicking a entity while sneaking to open a form?

dim tusk
chilly moth
#

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;
  }
})
sterile epoch
#

is dips below 20TPS normal

umbral dune
#

How do I cast a ray to check if a block was hit with the desired origin and direction?

prime zenith
#

Why is MinecraftEffectTypes not working

dim tusk
#

player or not you could use getBlockFromRay()

wary edge
umbral dune
dim tusk
#

btw it's under dimension.

prime zenith
#

Foxed it

prime zenith
#

I needed to use Effects with a get method

#

Wait nvm

#

Its not setting the effect

dim tusk
#

Entity.addEffect('speed', duration * 20, { amplifier: 0, showParticles: false })

prime zenith
#

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

dim tusk
prime zenith
#

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

dim tusk
prime zenith
dim tusk
#
for (const effect of Player.getEffects()) Player.removeEffect(effect.typeId)```
prime zenith
#

Give me a reason just 1 reason why anyone would ever do an unsubscribe world event

dim tusk
deep quiver
prime zenith
#

Ohhh so unsubscribe will still show the event just not all the time

deep quiver
#

unsubscribe unsubscribes from the event or stops the event listener

prime zenith
#

Is there an event for player moves player hits key or player is in a radius of certain coords

#

Ohhh i see

valid ice
#

There is an input event, but it's only for crouch/sneak and jump

prime zenith
#

Thats useful still what about if a plater is in radius of certain coords

valid ice
#

No direct event for that- you can use an interval and test their coords for that.

prime zenith
#

Ok so how do i do that then set there value to x y or z

deep quiver
#

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

dim tusk
#
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');
    }
});```
valid ice
#

Have to factor in view direction if you wanna get accurate direction buttons :(

prime zenith
#

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

prime zenith
#

@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

dim tusk
#

As of now there's now way to detect buttons pressed btw.

prime zenith
#

It doesnt matter sneak works jump works

#

Any 1 imput i just need a way to cancel scripts by player input

hazy cosmos
#

what's your goto solution for connecting a database to a server via the ts api

prime zenith
#

@dim tusk

dim tusk
#

I'm asking, what type of input.

prime zenith
#

Whats possible

dim tusk
#

like be specific.

dim tusk
prime zenith
#

Sneak ets do sneak

dim tusk
grave nebula
#

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

prime zenith
#

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

grave nebula
#

player.isSneaking

prime zenith
#

Thats a valid input? Ok

grave nebula
#

its true or false

valid ice
#

world.afterEvents.playerButtonInput

prime zenith
#

Thats fine all i need is true or false

sudden epoch
#

Oka

prisma shard
#

anyone has a day counter script

#

like it shows how many days you've played

dim tusk
#

There's a built-in thing already

#

If you mean just getting the current day do use world.getDay()

wheat condor
dim tusk
prisma shard
wheat condor
lofty cape
#

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?

prisma shard
#

just putting the night time value

#

and then should it work

wheat condor
#

Btw the second is the best option

lofty cape
wheat condor
wheat condor
#

If you give me the full code i can optimize it as best as I can

prisma shard
#

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?

prisma shard
#

..

#

what should i do

dim tusk
wheat condor
#

You need something that counts play time as minutes or as ticks?

prisma shard
#

how do i use world.getDay() to make the day counter.. that's the question

dim tusk
prisma shard
#

like a night passes == new day

#

we've to detect when the night passes, so then we can add new day

lofty cape
dim tusk
lofty cape
#

Thanks for the info, both of you!

dim tusk
#
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);
});
prisma shard
#

maybe i remeber someone made day counter bfore

prisma shard
#

wheres the variable

dim tusk
prisma shard
wheat condor
honest spear
wheat condor
honest spear
#

understanding how JS handles execution is the key to success

prisma shard
dim tusk
honest spear
#

ohh

#

for each player?

#

then count ticks the are in world

prisma shard
# honest spear Get current tick and divide it by 24000

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

#

?

honest spear
#

its waste of performance

prisma shard
#

can you improve it

wheat condor
#

If it’s for the world is just useless math, you just need world.getday()

dim tusk
honest spear
dim tusk
#

We set dynamic property per tick which is bad.

#

-# not really but not worth it

honest spear
#

yea, i said that, its definitely not good

#

anyway

#

lets fix it

wheat condor
#

Bro just use world.getDay()

prisma shard
honest spear
wheat condor
honest spear
#

hear me out

honest spear
dim tusk
wheat condor
#

So you need it per player?

honest spear
#

well here is pseudo

wheat condor
dim tusk
prisma shard
# honest spear hear me out

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??

honest spear
#
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

wheat condor
#

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

wheat condor
distant tulip
#
//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
}
honest spear
#

I think he wish to count in MC days

distant tulip
honest spear
#

😭