#Script API General

1 messages ยท Page 62 of 1

turbid delta
#

really cool, how come the form is able to show no buttons?

distant tulip
#

event.sourceEntity.runCommand

ivory bough
warped kelp
distant tulip
#

yes

#

you need to filter the entity type

warped kelp
#

Yes

warped kelp
#

Could I use the components of a mob's minecraft:health to detect if a mob's health is at a certain value using Entity.getProperty?

distant tulip
#

entity.getComponent("minecraft:health").currentValue

warped kelp
#

Thank you

prime zenith
#

@dim tusk i actually got it to work tho i may need to work with it so that the display looks nicer

safe stream
#

are complex topics like generic constraints needed for bedrock development ?

proud saddle
#

can we check if player on dimension switch screen

distant tulip
prime zenith
#

can i get help so my systemrun wont try to spawn entities when unloaded as it throws an error when it does

#

full code #1346125732463771739

prime zenith
#

Got it to work

prisma shard
#

is it possible to get minecraft version using script api?
(i know it is not possible, but just for clarification)

prisma shard
prime zenith
#

Next on the list of vanilla features ill be gutting

Fishing

#

Am i making minecraft better or is this no longer minecraft at this point and should be advertised as a game if its own

night acorn
#

huh?

jade grail
#

Anyone got a quick function to get closest player in a certain range

unique acorn
#

closest is the amount of players to get based on closest to furthest, and it returns an array of players

subtle cove
#
player.dimension.getPlayers({ location: player.location })[1]
prime zenith
#

@dim tusk i wanted to ty for the bank after fixing a few broken logics it works but do you know how i can make the button displays remove the namespace which is either minecraft or tg

subtle cove
#
typeId.split(':').pop()
prime zenith
#

What about removing under scores

valid ice
#

typeId.replace(/.*(?<=:)/, '').replace(/_/g, ' ').replace(/(^\w|\s\w)/g, (m) => m.toUpperCase()); Clueless

prisma shard
#

@valid ice

valid ice
#

._.

#

y rotation is your yaw, x rotation is your pitch

subtle cove
#

console.warn(JSON.stringify(player.getRotation()))

valid ice
#

looking straight down gives an x of 90, straight up is x of -90

subtle cove
#

Them move ur view

prime zenith
#

Next q this may be a json ui question but how do i add a picture in the form tied to the item some items have 1 im not sure how or why but others dont

valid ice
#

wdym

prisma shard
#

is it right then

valid ice
#

yeah

#

I think vanilla blocks use an angle of 60, but that would work too ๐Ÿ‘

prime zenith
#

I have a bank script that lets you deposit or withdraw items and sets as a dynamic some items loke crafting table have a pic but i gtg work calls

prime zenith
#

How do i create particles in script

humble lintel
#

world.getDimension('overworld').spawnParticle()?

unique acorn
humble lintel
#

asking an answering

unique acorn
#

makes sense

prime zenith
#

In the dirrection player is facing

cold grove
prime zenith
#

I need the visual

#

Cause im effectively making spells

cold grove
prime zenith
#

I know but i can run it side by side cant i

prime zenith
#

1 sec ill send you pseudo code

wary edge
#

@prime zenith

What you would need is a particle that has molang variables to essentially rotate. Then, using math, get the angle from the block to the entity, pass that data to the particle and spawn it.

prime zenith
wary edge
#
// Pseudocode
ItemUse->raycast
If(raycast){
// Do math to get rotation
Const m = new MolangVariableMap
m.setFloat()
...
Dimension.spawnParticle(particle, m)
}
prime zenith
#

So pseufo code

Player uses certain item with data magic
It checks a mage spell scoreboard
All of the above i csn do
Then it gets the way your facing runs a detect 1 block ahead applies particle then 2 then 3 until it reaches weapons range variable or detects an entity

#

Idk what raycast is btw

humble lintel
prime zenith
#

Ok might be a bit of a learning curve to use tbh

#

Can anyone help me learn how to use raycast

humble lintel
#

i can

junior hill
#
    const { source: player, block } = event;
    const mainhand = player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand);

    if (player.isSneaking && mainhand?.typeId === "minecraft:wooden_sword") {
        system.run(() => rotateBlock(block));
    } else {
        console.log("Rip.");
    }
});```
Why can only one person use the item with the script at a time?
prime zenith
#

Can we voice chat later

humble lintel
junior hill
#

Wait oops

#

const maxSpin = 15;

function rotateBlock(block) {

    const currentState = block.permutation.getState("JCTbuild:spin");
    let spinValue = currentState || 1;


    let newSpin = (spinValue % maxSpin) + 1;


    const newPermutation = block.permutation.withState("JCTbuild:spin", newSpin);

    block.setPermutation(newPermutation);
}

world.beforeEvents.itemUseOn.subscribe((event) => {
    const { source: player, block } = event;
    const mainhand = player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand);

    if (player.isSneaking && mainhand?.typeId === "minecraft:wooden_sword") {
        system.run(() => rotateBlock(block));
    } else {
        console.log("Rip.");
    }
});
#

Why does the item is not able to use it at the same time as someone else, when using the script?

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

world.beforeEvents.itemUse.subscribe(data => {
    const item = data.itemStack;
    const name = item.nameTag;

    if (name != 'wand' || item.typeId != 'minecraft:stick') return;
    const player = data.source;
    const location = player.getHeadLocation()
    const direction = player.getViewDirection()
    let raycast = player.dimension.getEntitiesFromRay(location, direction);

    if (raycast.length < 1) return;
    for (let hit of raycast) {
        const entity = hit.entity;
        if (entity == player) continue;
        system.run(() => {entity.applyDamage(5)});
    }
})
prime zenith
#

Now that works instantly i assume i do need to slow it down so i can make a partical line from player to entity

humble lintel
#

it does work instantly yes

dim tusk
#

i just remove the debug screen on top...

#

it can have no buttons without throwing errors now...

humble lintel
#

yuou coudl increment the steps

#

from the raycast?

prime zenith
humble lintel
#

every step make a particle

#

no

#

let me writei t rq

dim tusk
# humble lintel ```js import { world, system } from '@minecraft/server'; world.beforeEvents.ite...
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
    if (itemStack.nameTag !== 'wand' || itemStack.typeId !== 'minecraft:stick') return;
    
    const { dimension } = source;
    const head = source.getHeadLocation(), view = source.getViewDirection();

    for (const { entity } of dimension.getEntitiesFromRay({ x: head.x, y: head.y + 0.1, z: head.z }, view)) {
        if (entity !== source) system.run(() => entity.applyDamage(5));
    }
});
humble lintel
#

?

#

same thing

#

variables makes it more understandable

junior hill
prime zenith
#

Ill be moving it to its own function as world event will get all the data so it can make sure the mainhand has the tag then will dettect what spell it is player stats ect to calculate its damage from other files but once i learn how this works and learn particles im sure ill figure it out

dim tusk
prime zenith
#

Tho any idea the best way to add particles so it looks like its a straight line

humble lintel
dim tusk
humble lintel
#

better for peopel who are trying to learn

prime zenith
#

Im opposite i like variables

humble lintel
#

^

dim tusk
#

then go cause I don't like them especially make my code long

sharp elbow
#

Otherwise I agree with Coddy

humble lintel
#

jsut preference

dim tusk
#

I mean, since it's basic yes but for short things I usually do variables but I still do direct since it's somewhat annoying

prime zenith
#

That may be why it took so long to break down coddies codes

dim tusk
#

anyways, that's not the point rn...

dim tusk
humble lintel
#
import { Vector3Builder, Vector3Utils } from '@minecraft/math';
import { world, system } from '@minecraft/server';

world.beforeEvents.itemUse.subscribe(data => {
    const item = data.itemStack;
    const name = item.nameTag;

    if (name != 'wand' || item.typeId != 'minecraft:stick') return;
    const player = data.source;
    const location = player.getHeadLocation()
    const direction = player.getViewDirection()
    const raycast = player.dimension.getEntitiesFromRay(location, direction);

    const range = 10;
    if (raycast.length < 1) return;
    for (let hit of raycast) {
        const entity = hit.entity;
        if (entity == player || hit.distance > 10) continue;

        const difference =  Vector3Utils.subtract(location, entity.location);
        for (let step = 1; step < 10; step ++) {
            const transform = Vector3Utils.subtract(location, Vector3Utils.scale(difference, step / 10));
            system.run(() => {player.dimension.spawnParticle('minecraft:heart_particle', transform);})
        }

        system.run(() => {entity.applyDamage(5)});
    }
})
#

here

prime zenith
#

Knowing isnt the factor its prefferences

humble lintel
dim tusk
humble lintel
#

oh yeh awhoops

#

uh its hard'

dim tusk
humble lintel
#

so uh might have to do math

#

yeah one sec

#

lol

prime zenith
#

I can store variables externally once and reuse

humble lintel
#
import { world, system, Vector3 } from '@minecraft/server';

function vectorSubtract(vector1 : Vector3, vector2 : Vector3) {
    return {x: vector1.x - vector2.x, y: vector1.y - vector2.y, z: vector1.z - vector2.z};
}

function vectorScale(vector : Vector3, scale : number) {
    return {x: vector.x * scale, y: vector.y * scale, z: vector.z * scale}
}

world.beforeEvents.itemUse.subscribe(data => {
    const item = data.itemStack;
    const name = item.nameTag;

    if (name != 'wand' || item.typeId != 'minecraft:stick') return;
    const player = data.source;
    const location = player.getHeadLocation()
    const direction = player.getViewDirection()
    const raycast = player.dimension.getEntitiesFromRay(location, direction);

    const range = 10;
    if (raycast.length < 1) return;
    for (let hit of raycast) {
        const entity = hit.entity;
        if (entity == player || hit.distance > 10) continue;

        const difference =  vectorSubtract(location, entity.location);
        for (let step = 1; step < 10; step ++) {
            const transform = vectorSubtract(location, vectorScale(difference, step / 10));
            system.run(() => {player.dimension.spawnParticle('minecraft:heart_particle', transform);})
        }

        system.run(() => {entity.applyDamage(5)});
    }
})
#

i kinda have it written in ts so just ignore the : Vector if u dont use typings

dim tusk
#

my muscle memory is insane wadahell...

prime zenith
#

Wait so ignore vector?

humble lintel
#

ignor teh : vector in the functions

#

if yo udont write in typscreiopt

#

my keyboard has low actuation so i mistype a lot

#

mb

dim tusk
#
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
    if (itemStack.nameTag !== 'wand' || itemStack.typeId !== 'minecraft:stick') return;

    const { dimension } = source;
    const head = source.getHeadLocation(), view = source.getViewDirection();

    for (const { entity, distance } of dimension.getEntitiesFromRay({ x: head.x, y: hesd.y + 0.1, z: head.z }, view)) {
        if (entity.id === source.id || distance > 10) continue;

        const diff = { 
            x: head.x - entity.location.x, 
            y: head.y - entity.location.y, 
            z: head.z - entity.location.z 
        };

        for (let step = 1; step < 10; step++) {
            const scale = step / 10;
            system.run(() => dimension.spawnParticle('minecraft:heart_particle', { 
                    x: head.x - diff.x * scale, 
                    y: head.y - diff.y * scale, 
                    z: head.z - diff.z * scale 
                }));
        }

        system.run(() => entity.applyDamage(5));
    }
});
humble lintel
#

this is if u dotn wantvariables or extra functions ^

dim tusk
#

my phone is lagging wtf

humble lintel
#

lol

dim tusk
#

the length difference is insane...

humble lintel
#

lol'

#

it is good practice tho to use varibles, mroe readable for others if that's what ur going for

prime zenith
#

To be honest i could get all the player info set to a var in a reusable function

dim tusk
#

and... Longer

prime zenith
#

There for its the best of both worlds

#

Reusable and readable

dim tusk
dim tusk
#

soo, the getEntitiesFromRay isn't entirely accurate btw...

prime zenith
#

I split it up for 1 set it based if bankmode is 1 it runs deposit if 2 it runs withdraw then turns bankmode to 0 when selection is made it reopens form

It runs withdraw 1 at a time so stacks wont break

dim tusk
#

unlike getBlockFromRay()

turbid delta
#

Ima have fun with that

prime zenith
#

Im not at a computer so im hoping when i get home me and bar can voice chat

dim tusk
#
world.beforeEvents.itemUseOn.subscribe(({ source: player, itemStack, block }) => {
  if (player.isSneaking && itemStack.typeId === 'minecraft:wooden_sword') {
    system.run(() => rotateBlock(block));
  } else console.error('Rip');
});```
untold magnet
#

hmm, is it possible to detect the player while mining a block, not by detecting the block using getBlockFromViewDistance thing.

dim tusk
untold magnet
#

i can use entityHitBlock component, but u can hit around the block and then mine it normally

untold magnet
#

( breaking the block, like how u try to mine bedrock when u was a kid )

dim tusk
#

I assume you know it's permutation so you use type.id

untold magnet
untold magnet
#

a bad example,

untold magnet
#

^ just an example ^

untold magnet
dim tusk
untold magnet
dim tusk
#

variable.attack_time

untold magnet
#

like i have to edit the player json or something idk

dim tusk
untold magnet
dim tusk
#

it's from 0.0 to 1.0, it's a float

untold magnet
#

ah,

dim tusk
untold magnet
dim tusk
#

after mining only...

untold magnet
junior hill
#

The script wont work with 2 players at the same time?

dim tusk
junior hill
#

I want it too

dim tusk
untold magnet
junior hill
#

I never had this problem with my other scripts

#

I dont understand this bug at all

dim tusk
untold magnet
#

like query.getTags() in the player.json

#

hmm,

dim tusk
#

and no you can't check tags using molang since they didn't add it...

#

Tags on items and blocks yes but not entities...

untold magnet
#

when the player hit a block, he will get a tag, and via molang, i can detect the arm swing if it is swinging or not,
if it is the tag will not removed, else the tag will be removed,
and via scripts, i can make a system that can detect blocks from the view distance by 3ร—3ร—3 area, and if the player is facing into that box and he have the tag, he will keep taking damage overtime

#

@dim tusk ^
what d u think?

#

( i just need to make the molang that will detect if the player is swinging his hand / has a specific tag )

dim tusk
prime zenith
#

Im not looking forward to needing to texture hundreds if not thousands of items

#

Can i make a item render so it looks like your holding it with 2 hands

untold magnet
#

yes u can do that, but u need a custom geo items in order to make that happen

untold magnet
dim tusk
#

yes.

prime zenith
#

I have a wep cooldown system i just hate how it will still create a damage indicater even if on cooldown i wish i could remove damage indicaters entirely

fallen hearth
#

${player.name} undefined?

world.afterEvents.entityDie.subscribe(({ damageSource: player, deadEntity: entity }) => {
  world.sendMessage(
      `${entity.typeId} died from ${player.name}!`
  );
});
distant tulip
#

damageSource.damagingEntity

prime zenith
#

How do i give a vanilla mob a custum loot table that overwrites its vanilla

fallen hearth
dim tusk
fallen hearth
#

thankys

prime zenith
#

@fallen hearth if you want the code to only run if its a player use an if for if damaging soyrce is not a player then return

prime zenith
#

How much would it cost to just pay someone to make me a dragon entity

fallen hearth
#
world.afterEvents.entityDie.subscribe(({ damageSource: { damagingEntity: player }, deadEntity: entity }) => {
  if(player.typeId != "minecraft:player") return
  world.sendMessage(
      `${entity.typeId} died from ${player.name}!`
  );
});
prime zenith
#

Im horrible at blockbench

fallen hearth
#

when I use /kill it causes an error in the log

untold magnet
# dim tusk yes.

well, i am trying to rework the RL craft tree chopping system from java to bedrock, but using my own unique way ( just testing )

prime zenith
#

You want to set just damaging entity and check if damaging entity is player

untold magnet
#

( bec i am thinking about making an addon after my big boy 'exe' )

dim tusk
#

that's why it throws a error

#

it can't find the damage or killer

untold magnet
dim tusk
#

do js if (player?.typeId !== 'minecraft:player') {}

#

the damagingEntity can be undefined that's why ? is there.

prime zenith
#

If i ran kill @e in real life would you all be mad at me or just not care cause youd be dead

untold magnet
prime zenith
#

Are you questioning my godliness

fast lark
#

Hi yall

prime zenith
#

You can call me princess not yall

dim tusk
#

The fuck is happening go in #off-topic

untold magnet
prime zenith
#

๐Ÿ˜›

jade grail
#

is this not right?

prime zenith
#

/tp coddy ~ -65 ~

jade grail
#

heres the full line

#

Oml dw i found the probably

#

the f in feet need be cap

prime zenith
#

My feet arent capped my feet are shoed

dim tusk
dim tusk
prime zenith
#

-65 is not up

#

I did relative x relative z and -65 absolute y

#

Thats the void my friend

misty pivot
#

how do i get the name of the button the user clicked in ActionFormData

dim tusk
fast lark
#

Btw that command does not work

#

Someone know if there is an event to detect a server starting up or crashing/close?

#

And one to detect when a player us whispering

#

Is*

dim tusk
dim tusk
#

That's the closest one

dim tusk
fast lark
dim tusk
#

tilde number tilde

#

how it's not valid?

fast lark
#

Yeah im blind

fast lark
valid ice
fast lark
#

How can i take the XUID of a player with script

misty pivot
dim tusk
fast lark
#

Sad

valid ice
#

Unless BDS echsplode

fast lark
dim tusk
dim tusk
valid ice
#

Bedrock
Dedicated
Server

#

A server software for bedrock developed by mojang

fast lark
#

Oh yeah i need that for my bds

valid ice
#

Thereโ€™s probably a way to query XUID with http requests or multiplayer Xbox stuff- I know realm bots can grab player XUID, and realms are just BDS, so

prime zenith
dim tusk
#

im dyslexic

dim tusk
#

I never had a problem in my script at all...

#

plus, it's a sample....

prime zenith
#

If you let an event set and open a form you cant reuse it to allow multiple ways to open it if you need to

If you put form in a function have event run function you can

dim tusk
#

also, if it's there why not use it ๐Ÿคท

dim tusk
prime zenith
#

I know im making a suggestion

dim tusk
#

Anyways

midnight ridge
#

can someone help with this i want to turn the items from entities to itemStacks :

system.runInterval(() => {
  const dimensions = [
      world.getDimension("overworld"),
      world.getDimension("nether"),
      world.getDimension("the_end")
  ];
  for (const dimension of dimensions) {
      const hoppers = dimension.getEntities({
          typeId: "wr:wireless_hopper",
          excludeTypes: ["minecraft:player"]
      });
      for (const hopper of hoppers) {
          const hopperLoc = hopper.location;
          const hopperBlock = dimension.getBlock({
              x: hopperLoc.x,
              y: hopperLoc.y - 1,
              z: hopperLoc.z
          });  
          const container = hopperBlock.getComponent("inventory");
          const items = dimension.getEntities({
              typeId: "minecraft:item",
              location: hopperLoc,
              maxDistance: 1.5
          });
          for (const item of items) {
             
          }
      }
  }
}, 20);```
prime zenith
#

I saud its goid practice thats advice

dim tusk
prime zenith
#

No i didnt say that i can still give advice

dim tusk
#

yes, I know it's a good practice but SAMPLE.. sigh I never said you won't use it tho and I never disagree with your point.

dim tusk
midnight ridge
# dim tusk `Entity.getComponent('item').itemStack`
const Container = hopperBlock.getComponent("inventory");
          const items = dimension.getEntities({
              typeId: "minecraft:item",
              location: hopperLoc,
              maxDistance: 1.5
          });
          for (const item of items) {
            const RlItems = item.getComponent('item').itemStack
            const added = Container.container.addItem(RlItems);
                if (added) {
                    item.remove();
                }
          }````
dim tusk
#

What are you doing in the first place.

prime zenith
#

@humble lintel are you around

humble lintel
midnight ridge
# dim tusk What are you doing in the first place.
system.runInterval(() => {
  const dimensions = [
      world.getDimension("overworld"),
      world.getDimension("nether"),
      world.getDimension("the_end")
  ];
  for (const dimension of dimensions) {
      const hoppers = dimension.getEntities({
          typeId: "wr:wireless_hopper",
          excludeTypes: ["minecraft:player"]
      });
      for (const hopper of hoppers) {
          const hopperLoc = hopper.location;
          const hopperBlock = dimension.getBlock({
              x: hopperLoc.x,
              y: hopperLoc.y - 1,
              z: hopperLoc.z
          });  
          const ContainerBelow = dimension.getBlock({
            x: hopperBlock .x,
            y: hopperBlock .y - 1,
            z: hopperBlock .z
        });
          const Container = ContainerBelow.getComponent("inventory");
          const items = dimension.getEntities({
              typeId: "minecraft:item",
              location: hopperLoc,
              maxDistance: 1.5
          });
          for (const item of items) {
            const RlItems = item.getComponent('item').itemStack
            const added = Container.container.addItem(RlItems);
                if (added) {
                    item.remove();
                }
          }
      }
  }
}, 20);```
its gets the entities with typeID wr:wireless_hopper then it gets the wirlessHoppers below it then gets nearby items and i want to add them to the container
solar dagger
#

Isn't there a transfer from container to another method?

dim tusk
dim tusk
midnight ridge
#

i think it called

#

swap

#

swapItems

dim tusk
#

how'd you gonna swap items if the item is an entity?

solar dagger
#

Don't entities have containers?

#

Inventory

midnight ridge
dim tusk
solar dagger
#

I meant from the hopper to the chest

midnight ridge
#

@dim tusk

#
   const items = dimension.getEntities({
              typeId: "minecraft:item",
              location: hopperLoc,
              maxDistance: 1.5
          });
          for (const item of items) {
            const RlItems = item.getComponent('item').itemStack
            const added = Container.container.addItem(new ItemStack(item.typeId, item.amount));
            
                if (added) {
                    item.remove();
                }
          }```
#

same error

dim tusk
midnight ridge
#

itemStack of undefined

dim tusk
humble lintel
#

im lowk tryna get into machiens

#

they kidna coo

#

cool*

#

is there a way to chec kif an entity is in a loaded chun kthrough script?

midnight ridge
dim tusk
midnight ridge
#

something wrong with this line :

  const RlItems = item.getComponent('item').itemStack```
dim tusk
#

Ahh it can't detect the item entity in the area

humble lintel
midnight ridge
#

same error

dim tusk
#

wait lemme try make my own.

midnight ridge
#

waiit

#

i found it

#
const items = dimension.getEntities({
              typeId: "minecraft:item",
              location: hopperLoc.location,
              maxDistance: 10
          });```
#

i forget to add .location

dim tusk
#

Ahh. Lmfao

midnight ridge
dim tusk
#

I didn't notice that lmfao

#

me blind now ..

midnight ridge
#

buuuuuut

#

it doesnt work

#

error is gone but the colector not working

humble lintel
#

coddy I stil get the unloaded chunk error

midnight ridge
humble lintel
#

i used the isvalid check

dim tusk
#

you have a variable with that name imyou did it with . location

#

and you call that with .location again.

humble lintel
#
import { ItemStack, system, world } from '@minecraft/server';

const item = new ItemStack('minecraft:diamond', 1);
system.runInterval(() => {
    const entities = world.getDimension('overworld').getEntities();
    entities.forEach(entity => {
        if (entity.isValid() == true) entity.dimension.spawnItem(item, entity.location);
    })
}, 20)
#

wil lgive u error when i leave my pigs

midnight ridge
#

i removed it

#

aaaaaaaaaaaaaaaaaaaaand

midnight ridge
dim tusk
midnight ridge
humble lintel
#

weird it says entities are still valid even though they not

dim tusk
# midnight ridge <:bao_ext_toldyouso:1016392386433257553> ?
const dimensions = ['overworld', 'nether', 'the_end'];

system.runInterval(() => {
  for (const dimension of dimensions) {
    for (const entity of world.getDimension(dimension).getEntities()) {
      if (entity.typeId === 'minecraft:armor_stand') {
        const blockBelow = entity.dimension.getBlock(entity.location).below();
        if (!blockBelow?.getComponent('inventory')) continue;

        const inventory = blockBelow.getComponent('inventory').container;
        const nearbyItems = entity.dimension.getEntities({
          type: 'minecraft:item',
          location: entity.location,
          maxDistance: 10
        });

        for (const itemEntity of nearbyItems) {
          if (!entity.hasComponent('item')) continue;
          const itemStack = itemEntity.getComponent('item').itemStack;
          if (itemStack) {
            const added = inventory.addItem(itemStack);
            if (added) itemEntity.kill();
          }
        }
      }
    }
  }
});```
dim tusk
#

Iirc it's fixed in preview ..

humble lintel
#

ah rip lol

midnight ridge
#

also no errors

dim tusk
midnight ridge
dim tusk
midnight ridge
#

wait

dim tusk
#

To check if there's block under there in the first place.

midnight ridge
#

no warns

dim tusk
#

God damnit I'm stupid wait.

midnight ridge
turbid delta
#

The code looks fine to me

#

The code is kind of inefficient though

#

Loops through all entities unnecessarily

dim tusk
# midnight ridge okeeeeeeeeeeeeeeeeeeeeeeey
system.runInterval(() => {
  for (const dimension of ['overworld', 'nether', 'the_end']) {
    for (const entity of world.getDimension(dimension).getEntities({ type: 'minecraft:armor_stand' })) {
      const block = entity.dimension.getBlock(entity.location);
      if (!block?.below()?.getComponent('inventory')) continue;

      const inventory = block?.below()?.getComponent('inventory').container;

      for (const itemEntity of entity.dimension.getEntities({ type: 'minecraft:item', location: entity.location, maxDistance: 10 })) {
        const itemStack = itemEntity.getComponent('item').itemStack;
        let remainingCount = itemStack.amount;
        
        for (let i = 0; i < inventory.size; i++) {
          const slotItem = inventory.getItem(i);
          if (!slotItem || slotItem.typeId !== itemStack.typeId) continue;

          const spaceLeft = slotItem.maxAmount - slotItem.amount;
          
          if (spaceLeft > 0) {
            const toAdd = Math.min(spaceLeft, remainingCount);
            slotItem.amount += toAdd;
            inventory.setItem(i, slotItem);
            remainingCount -= toAdd;
            if (remainingCount === 0) break;
          }
        }

        if (remainingCount > 0) for (let i = 0; i < inventory.size; i++) {
          if (!inventory.getItem(i)) {
            const newStack = itemStack.clone();
            newStack.amount = remainingCount;
            inventory.setItem(i, newStack);
            remainingCount = 0;
            break;
          }
        }

        if (remainingCount === 0) itemEntity.remove();
        else itemStack.amount = remainingCount;
      }
    }
  }
});```
fallen hearth
#

I'm using this but my life doesn't change?

player.getComponent("health").setCurrentValue(10000)
dim tusk
#

yeah it doesn't change it but the health is there.

#

try damaging yourself with /damage @s 20 you don't die...

fallen hearth
#

@dim tusk Does this also serve to increase the player's health above the maximum health value?

dim tusk
#

I guess so...

#

Tho you can't track it visually...

prime zenith
#

@humble lintel are you available

humble lintel
#

boutta watch a movie tho

prime zenith
humble lintel
#

im just chilling rn

prime zenith
#

Ok can we vc add me

humble lintel
#

shoot I dont think i can vc but wanna just dm me

prime zenith
#

Ill try sure

#

But i was hoping to screen share

#

Add ne first

humble lintel
#

i just cant talk and i might not be able to hear u

#

or wait can u send vid?

prime zenith
#

I made a cool reusable funt that gets all items there anount equip slots facing direction x y and z coords

#

Can we try if we cant hear eachother we can text while screensharing

prime zenith
#

im sharing this for ppl who want it as it gets all they stuffand is reusable just put it in a file export where you want it and save it as a variable where your getting players and need it then you do variableYouSetItAs.anythingItReturns it gets all slots and amount all equipment your x y z facing cardinal yaw and pitchslots are obtained by invSlots.slotNumber its useful i think not the cleanest but it works

warm drum
#

Not like that

dim tusk
warm drum
#

like if a zombie kill u, it will spawn another zombie entity but it has ur skin

#

by ur skin i mean any players

#

sound impossible...

distant tulip
#

Not possible

warm drum
#

yeah

#

kinda guess it

prime zenith
#

It was throwing errors if it couldnt find an item so i created a safety net

#

What event is for when a player eats a food item

prisma shard
#

do i do
```js
const pitch = player.getRotation().x;

if (pitch > 85 && (pitch >= -90 && pitch <= -75)) return 'Looking down (Towards negative Y)'
if (pitch < -85 && (pitch <= 90 && pitch >= 75)) return 'Looking up (Towards positive Y)'```

Or is that right

const pitch = player.getRotation().x;

    if (pitch > 85 || (pitch >= -90 && pitch <= -75)) return 'Looking down (Towards negative Y)'
    if (pitch < -85 || (pitch <= 90 && pitch >= 75)) return 'Looking up (Towards positive Y)'```
dim tusk
prime zenith
#

I got it i now gutted vanilla eating woohoo how many vanilla features can i overude lol

drifting ravenBOT
#
What Vanilla Things Can We Modify?

Can

  • Entities
  • Certain Items(Any food items or those found in the windowsapp folder)
  • Entity loot tables
  • Features
  • Feature Rules
  • Biomes

Can't

  • Blocks
  • Block loot tables
  • Items not found in the windowsapp folder
  • Dimensions
prisma shard
dim tusk
prime zenith
#

Hey eating may be faster but given eaten is the core way to boost health in combat thats a good thing

dim tusk
#

they look exactly the same

prisma shard
prisma shard
prime zenith
#

You know ill never get why minecraft has steak nsmed steak in gsme but cooked beef as its call tag

dim tusk
prime zenith
#

Coddy stop attacking ppls code like that its extremely rude

prisma shard
dim tusk
prisma shard
dim tusk
prisma shard
#

uh

#

how to get difficulty... i've searched the docs, but couldn't find getDifficulty() anywhere.... what

dim tusk
prisma shard
#

mojang added getDifficulty()

#

he said

#

but couldn't find getDifficulty() anywher in the docs.... weird

distant tulip
#

preview

prisma shard
dim tusk
#

but as of now, just use this ..

prisma shard
#

i want to get x,y,z of the whole 16 x 16 chunk, the player is Standing on

distant tulip
#

divide corrds by 16 and round it

dim tusk
#

get location then divide by 16?

#

ohh nvm-

prisma shard
#

do i divide 16 with player location?

distant tulip
#

any location you want

prisma shard
#

what

distant tulip
#

yeah

prisma shard
distant tulip
#

or that

prisma shard
#

what diff betwen round and floor

#

if i do it

distant tulip
#

depend on what you want
round get you the nearest corner of the chunk
floor get you the smallest (the origin)

prisma shard
#
        const playerChunk = {
            // The chunk the player is in
            x: Math.floor(player.location.x / 16),
            y: Math.floor(player.location.y / 16),
            z: Math.floor(player.location.z / 16)
        }
        const playerChunkString = `${playerChunk.x}, ${playerChunk.y}, ${playerChunk.z}`
#

its okay?

dim tusk
#

round - 4.7 = 4
floor - 4.7 = 5

dim tusk
distant tulip
prisma shard
#

what

distant tulip
warm mason
prisma shard
dim tusk
#

mb

#

I get confused lmfao

#

-# why bully me?

prisma shard
distant tulip
#

bro stop deleting messages

dim tusk
prisma shard
distant tulip
#

chunks are defined by x and z

prisma shard
#

it does instantly remove the entity

#

but the spider does a sssss sound

distant tulip
#

make a custom mob

prisma shard
distant tulip
#

because it is a snippet?
it is just and idea, you do with it what you need to

prisma shard
#

will that work

distant tulip
#

yes, remove unnecessary components

prisma shard
#

not possible with normal spider?

distant tulip
prisma shard
prisma shard
#

instead of divide i do modulus %

dim tusk
#

you just get the reminder of them, for example 30 divide 16 is 1 with a remainder of 14

prisma shard
prime zenith
#

I cant get my partical function to work

prisma shard
#

can you somehow get memory usage in minecraft bedrock

granite badger
prisma shard
#

k

ivory bough
#

How to detect if entity is in player's view(not necessarily the player's eye view but if the entity is visible on player's device)

prisma shard
midnight ridge
#

@dim tusk tysm ๐Ÿซถ๐Ÿป

prisma shard
#

what's getViewDirection() ...

#

i just saw it on docs

#

it returns vector3, but i dont understand what the docs is trying to say

ivory bough
prisma shard
#

there's a script to detect if entity is in player's large view

#

here

#

credit: made by @distant tulip

warped kelp
#

Could I use transitions state using query health?

warped kelp
#

That came with no context, apologies. Like,

#

If I place two events with normal and activated in custom mob json, would this work?

"states": {
        "default": {
          "transitions": [
            {
              "ego_manifest": "query.health < 330 && query.is_alive"
            },

Using things like calling an event upon reaching the custom entity's health value?

unique acorn
#

that question is for #1067869022273667152

cold grove
strong oar
#

is it possible to use python language for scripting instead of javascript?

strong oar
#

thanks

hybrid island
#

how do i fix this so that it sets the villagers name to nothing

system.runInterval(() => {
    const dimensions = ["overworld", "nether", "the_end"];

    for (const dimensionName of dimensions) {
        const dimension = world.getDimension(`minecraft:${dimensionName}`);
        const entities = dimension.getEntities({ excludeTypes: ["minecraft:player", "minecraft:villager"] });

        for (const entity of entities) {
            if (entity.typeId.startsWith("minecraft:villager") || entity.typeId === "minecraft:wandering_trader") {
                // โŒ Remove villager name tag
                entity.nameTag = "";
                continue; // Skip the rest of the loop for villagers
            }
            if (entity.hasComponent(EntityComponentTypes.Health)) {
                updateMobName(entity);
            }
            if (entity.typeId === "sky:crypt_ghoul") {
                entity.runCommand(`tag @s add dmg35`);
            }
        }
    }
}, UPDATE_INTERVAL);
function getMobStats(entity) {
    let level = 1;
    let maxHealth = null;

    for (const tag of entity.getTags()) {
        if (tag.startsWith("moblvl")) {
            level = parseInt(tag.replace("moblvl", ""), 10) || 1;
        }
        if (tag.startsWith("mobheal")) {
            maxHealth = parseInt(tag.replace("mobheal", ""), 10) || null;
        }
    }

    // If no max health tag is found, use real max health
    if (!maxHealth) {
        const healthComponent = entity.getComponent(EntityComponentTypes.Health);
        if (healthComponent) {
            maxHealth = healthComponent.effectiveMax;
            entity.addTag(`mobheal${maxHealth}`); // Store for future use
        }
    }

    // Hardcoded Level Adjustments for Specific Mobs
    if (entity.typeId === "sky:crypt_ghoul") {
        level = 25;
    }

    return { level, maxHealth };
}
//cant do longer msg

Cant do longe msg

prime zenith
#

How do i change item name of a vanilla item

hybrid island
untold magnet
prime zenith
#

How is it formatted i tried that

untold magnet
prime zenith
#

I tried item.iron_ingot.name=Iron Bar failed

#

Nvm

#

I had a space in it

untold magnet
prime zenith
#

No it was a space issue

chilly moth
#
    const { target,player,ItemStack } = ev;
    if (player.hasTag('gr_interact'))
system.run(() => CustomUi(player))
      player.removeTag("gr_interact")
#

can anyone fix this

#

I want it to open when I sneak interact and

remove tag bcz if dont it open ui on every mob

sharp elbow
#

You are attempting to extract "ItemStack" from the parameter given in this callback. This is case-sensitive

#

Should the system.run and player.removeTag both only happen if the player has that tag? You may want to make a scope for that condition.

if (player.hasTag('gr_interact')){
    system.run(() => CustomUi(player))
    player.removeTag("gr_interact")
}
prime zenith
chilly moth
#

like &&

prime zenith
#

You can but player.isSneaking returns true if player is sneaking and false if not

chilly moth
#

ok let me try

#

I was using is_Sneaking

#

let me try

sharp elbow
#

Block scope; surround your statements in curly brackets to group them together. If put after a control flow statement like if, then the entire scope's contents will execute

chilly moth
#

the player tag works but on every entity for reason

I am trying to open the gui from serverform on my entity

sharp elbow
#

I don't see any condition for the type of entity. The API will not implicitly assume what you need

#

You might add an extra condition like target.typeId == "my:entity" to that if statement, joined by &&

chilly moth
#

๐Ÿ‘๐Ÿฝ

frozen vine
#

onScreenDisplay.setActionBar() Does it support texts from the lang file? Like the titleraw command?

chilly moth
#

player.removeTag gives error

dense sun
#

can we obtain the protection strength of an armor?

distant tulip
#

no

ivory bough
#
system.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id !== "space:peek") return;
    world.getDimension("overworld").runCommand(`tag @a remove anomaly`);
    let loopStart = { x: 3, y: 0, z: 15 };
    let loopEnd = { x: 10, y: 3, z: 30 };

    let playerPos = event.sourceEntity.getHeadLocation();

    let found = false;

    for (let x = loopStart.x; x <= loopEnd.x; x++) {
        for (let y = loopStart.y; y <= loopEnd.y; y++) {
            for (let z = loopStart.z; z <= loopEnd.z; z++) {
                let targetPos = { x, y, z };

                let direction = {
                    x: targetPos.x,
                    y: targetPos.y,
                    z: targetPos.z
                };

                let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
                const logs = [
                  "minecraft:oak_log", "minecraft:spruce_log", "minecraft:birch_log", "minecraft:jungle_log", "minecraft:acacia_log", "minecraft:dark_oak_log", "minecraft:mangrove_log", "minecraft:cherry_log", "minecraft:pale_oak_log"
                ];

                let block = blockRaycast?.block;

                 if (block && logs.includes(block.typeId)) {
                    found = true;
                    const blockLoc = block.location;
                    event.sourceEntity.runCommand(
                        `summon space:anomaly ~${blockLoc.x} ~${blockLoc.y} ~${blockLoc.z + 1} facing @s`
                    );
                    world.getDimension("overworld").runCommand("function tree");
                    break;
                }
            }
            if (found) break;
        }
        if (found) break;
    }

});

let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
This line says not a function typeerror

#

Also can anyone help in #1070606638525980753

prime zenith
#

does anyone have an up to date zombie.json the samples is outdated all i want is for it to not burn in daylight samples teaches it to fly and i somehow took away its ai fixing it

wary edge
drifting ravenBOT
wary edge
#

And this isn't really a ScriptAPI question.

fallow rivet
#

How many times per second does the system runinterval run?

prime zenith
#

20 ticks per second

wary edge
fallow rivet
prime zenith
#

But you can set it how many ticks it takes to run

fallow rivet
prime zenith
#

Not faster then 20 tomes per second but you could run it multiple times if yoou put logic into a function run the function a few times

wary edge
fallow rivet
prime zenith
#

Therw are msny ways to make a player immortsl

wheat condor
#

do you guys know why vscode doesnt recognize prototype functions?

prime zenith
#

You dont need to run anything 100 times per second to achieve that

fallow rivet
#

I plan to make it work faster to fix this

fallow rivet
wheat condor
#

just give the player resistance infinite lvl 255

odd path
#

How do I identify fire block around me?

ivory bough
#
system.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id !== "space:peek") return;
    world.getDimension("overworld").runCommand(`tag @a remove anomaly`);
    let loopStart = { x: 3, y: 0, z: 15 };
    let loopEnd = { x: 10, y: 3, z: 30 };

    let playerPos = event.sourceEntity.getHeadLocation();

    let found = false;

    for (let x = loopStart.x; x <= loopEnd.x; x++) {
        for (let y = loopStart.y; y <= loopEnd.y; y++) {
            for (let z = loopStart.z; z <= loopEnd.z; z++) {
                let targetPos = { x, y, z };

                let direction = {
                    x: targetPos.x,
                    y: targetPos.y,
                    z: targetPos.z
                };

                let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
                const logs = [
                  "minecraft:oak_log", "minecraft:spruce_log", "minecraft:birch_log", "minecraft:jungle_log", "minecraft:acacia_log", "minecraft:dark_oak_log", "minecraft:mangrove_log", "minecraft:cherry_log", "minecraft:pale_oak_log"
                ];

                let block = blockRaycast?.block;

                 if (block && logs.includes(block.typeId)) {
                    found = true;
                    const blockLoc = block.location;
                    event.sourceEntity.runCommand(
                        `summon space:anomaly ~${blockLoc.x} ~${blockLoc.y} ~${blockLoc.z + 1} facing @s`
                    );
                    world.getDimension("overworld").runCommand("function tree");
                    break;
                }
            }
            if (found) break;
        }
        if (found) break;
    }

});

let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
This line says not a function typeerror

wary edge
dim tusk
ivory bough
prisma shard
#

what lol

wheat condor
proud saddle
#

is there a way to check if player busy(action form) without creating a form?

marsh pebble
#

im the 100,000 message in here

simple zodiac
#

I am sorry to disapoint you but this constantly happens here

marsh pebble
#

i saw u typing for a good 2 mins

simple zodiac
#

^

simple zodiac
marsh pebble
#

Ah, Willing to help me?

simple zodiac
#

depends on what the issue is really

marsh pebble
#
import { world, system } from "@minecraft/server";

const COOLDOWN_COMMON = 5 * 20;

const cooldowns = new Map();

world.beforeEvents.itemUse.subscribe((event) => {
    const player = event.source;
    const item = event.itemStack;

    if (item.typeId === "rarity:commondice") {
        const lastUse = cooldowns.get(player.id) || 0;
        const currentTime = system.currentTick;

        if (currentTime - lastUse < COOLDOWN_COMMON) {
            const timeLeft = Math.ceil((COOLDOWN_COMMON - (currentTime - lastUse)) / 20);
            player.onScreenDisplay.setActionBar(`Next Roll In ${timeLeft} seconds`);
            return;
        }

        cooldowns.set(player.id, currentTime);

        const min = 1;
        const max = 10000000;
        const randomValue = Math.floor(Math.random() * (max - min + 1)) + min;

        player.runCommand(`/scoreboard players set @s rng ${randomValue}`);

        player.sendMessage("You rolled.");
    }
});```
I dont see any errors
simple zodiac
#

see if you can make the file print anything at all and continue from there

#

just to see if its even loaded

marsh pebble
#
{
  "format_version": 2,
  "header": {
    "name": "Dice RNG",
    "description": "Adds custom dice with RNG functionality.",
    "uuid": "738e20c3-80ed-4262-b945-73392353fdf8",
    "version": [1, 0, 0],
    "min_engine_version": [1, 19, 0]
  },
  "modules": [
    {
      "type": "script",
      "language": "javascript",
      "uuid": "3c66d2e3-1952-42e8-b293-4baf2e3bb612",
      "entry": "scripts/main.js",
      "version": [1, 0, 0]
    }
  ]
}```
Manifest
valid ice
#

You need script dependencies in there

marsh pebble
dim tusk
# marsh pebble like what
{
    "format_version": 2,
    "header": {},
    "modules": [],
    "dependencies": [
        {
            "description": "server",
            "module_name": "@minecraft/server",
            "version": "1.18.0-beta"
        },
        {
            "description": "server-ui",
            "module_name": "@minecraft/server-ui",
            "version": "1.4.0-beta"
        }
    ]
}```
marsh pebble
#

ohh

#

Okay

#

@dim tusk

dim tusk
marsh pebble
#

?

dim tusk
#
system.run(() => Player.runCommand() );
marsh pebble
#

or am i trippin

dim tusk
marsh pebble
#

um

marsh pebble
#

@dim tusk Im a bit confused

marsh pebble
#

great

#

bc

#

im still learing js

#

slowly

#

bc im slow

marsh pebble
#

wait

dim tusk
marsh pebble
#

wym

#

player.onScreenDisplay.setActionBar(Next Roll In ${timeLeft} seconds);

#

system.run(() => player.runCommand(Next Roll In ${timeLeft} seconds) );

dim tusk
# marsh pebble wym

so yeah lemme explain it to you, since you're dealing beforeEvents means before it happens, you can't modify the world, so the purpose of system.run is to run the thing in the next tick, to escape the read-only mode, tho it's not just system.run only you can use anything as long as it happens next tick not the same tick...

marsh pebble
#

ah okay

#

im learning beforeEvents and after events today

#

do im not the best

fervent topaz
#

@granite badger how would i make ur interpreter block thing into just one script that runs when the world loads

shut citrus
#

Why weakness effect cancels player's attack but doesn't for mobs

prisma plaza
#

Anyone know a good way to check if a shield blocked a hit?

humble lintel
#

hello p[eople

#

what if i make gambling in mc

#

that's very illegal

covert goblet
#

Does anybody know if it's possible to detect what entity your looking at through a spyglass? Would the GetEntityFromRay work??

humble lintel
#

yes

#

depends on the distance

cinder shadow
#

Really wish we could limit the damage scaling on CreateExplosion, still surprised we can't with it turning into an orbital nuke to any radius past 4

humble lintel
#

and functions u want to apply to that entity

cinder shadow
#

It does 85 damage at a radius of just 6

covert goblet
humble lintel
#

that's possible

#

use the entitfromray thing

covert goblet
humble lintel
#

here i can write a small snippet of it

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

world.beforeEvents.itemUse.subscribe(({itemStack, source}) => {
    system.run(() => {
        if (itemStack.typeId != 'minecraft:stick') return;
        //Cast ray and get all the entities from ray
        const start = source.getHeadLocation();
        const direction = source.getViewDirection()
        const raycast = source.dimension.getEntitiesFromRay(start, direction, {
            //Max distance of the raycast
            maxDistance: 10
        })

        //For every entity hit by the raycast run a function
        raycast.forEach(hit => {
            //Cancel if it hits you
            if (hit.entity == source) return;
            //Do whatever to the entity or run a function
        })
    }); 
});
#

@covert goblet

#

should be the basics

acoustic basin
#

hey guys! is there a way i could get an output of a command? e. g. i want to do /locate biome "biome" and get the output that the command will give, and take out the coords of the output

acoustic basin
round bone
#

which will not give you enough information

#

to get a certain biome

acoustic basin
#

but it isn't possible, so it doesn't matter anyway

round bone
#

yeah, not possible

acoustic basin
#

is there a way to execute a locate biome command in scripts so the output was shown in the chat? maybe somehow execute it as a player

#

basically, what i'm trying to achieve, is so that when i feed by dino some seeds, it will give coordinates to a biome, and the command output should be written in the chat

chilly moth
#

can anyone share a snippet of how to send entity id's via script

for horse renderer

prisma shard
#

is it possible to detect slime chunks

distant tulip
chilly moth
distant tulip
#

send it where

chilly moth
#

I want to render custom entity in ui

#

I was told that u need to pass id's through for it to render

prisma shard
distant tulip
chilly moth
#

serverform

distant tulip
distant tulip
prisma shard
distant tulip
#

yes

prisma shard
#

how can i

distant tulip
#

credit to obscraft23
isSlimeChunkPos(player.location.x, player.location.z)

prisma shard
#

that's why you're best

distant tulip
#

thanks to @faint hare

acoustic basin
#

what if i have structures/folder/another_folder/mystruct.mcstructure?

covert goblet
prime zenith
#

If i did a before player leaves even and cancled it does that mean player can never leave

wary edge
acoustic basin
chilly moth
prime zenith
#

foreach(livingPersonOnEarth as person) {
if (person.likesPineappleOnPizza) {
reality.deleteEntity(person);
} else {
console.log(person.name + " may live. They have good taste.");
}
}

distant tulip
# chilly moth title
import { world} from '@minecraft/server';
import { ActionFormData } from '@minecraft/server-ui';

world.beforeEvents.itemUse.subscribe((event) => {
    const { source, itemStack } = event;
    if (itemStack.typeId !== "minecraft:stick") return;
    const entity  = source.dimension.getEntities({type: "minecraft:cow", closest:1})[0]
    new ActionFormData()
        .title("Special Offer!")
        .body(`Player id: ${source.id}\nCow Id: ${entity.id}`)
        .button("...")
        .show(source)
        .then(({ selection }) => {
            //..
        })
});
worldly pier
#

hello bros

#

I have a question

#

is there a way to store data for a item

#

I know dynamic property's do that

#

but those only work in no-stackable items

#

the only solution I have found is storing it in the item lore

prime zenith
#

If i ran a before eve t for entity removed if its an armor stand cancel or will that just leave a dead armorstand on world

unique acorn
#

you can't cancel it

#

EntityRemove before event isnt cancelable

prime zenith
#

Whats the most effective way to make an armorstand unmovable and unkillable

unique acorn
#

damage sensors

prime zenith
#

Like cause i gutted vanilla hp system

unique acorn
#

well damage sensors are the most effective way

prime zenith
#

Idk what you mean by damahe sensers

unique acorn
prime zenith
#

So thats an armorstand component

#

To add

unique acorn
#

entity component, yes, you can use that on any entity

prime zenith
#

Ok well should be easier then zombies i tried changing zombies instead broke there ai

unique acorn
#

if you wanna use damage sensors you would need to copy the armor stand's code from the game files then add the component to it

prime zenith
#

I know that

unique acorn
#

okay

prime zenith
#

Tho zombies is outdated

#

Is that even resistent from kill command

unique acorn
#

maybe?

distant tulip
chilly moth
#

yeah

#

that line shows error

#

@distant tulip ยฟ

distant tulip
#

sorry for the delayed reply

chilly moth
#

ok

shut citrus
#

replaceitem entity @s slot.weapon.mainhand 0 ${blockItem.typeId} 1

#

how can i convert the command to scripts?

humble lintel
#

world.getDimension('overworld').runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 ${blockItem.typeId} 1\`);

#

maybe this?

#

or uh

shut citrus
#

oh

#

I mean using js method

humble lintel
#

player.getCompinent('inventory').container.setItem(player.selectedSlotIndex, new ItemStack())

#

somethign like that let me check

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

world.beforeEvents.chatSend.subscribe(e => {
    const plr = e.sender;
    const msg = e.message;

    if (!msg.startsWith('!')) return;
    plr.getComponent('inventory')?.container?.setItem(plr.selectedSlotIndex, new ItemStack('minecraft:stick', 1))
})
#

something like this

#

u can ignore chatsend

#

thats juist what i used to get the player

unique acorn
unique acorn
shut citrus
#

it doesn't work on armor stand

pallid stag
#

Which version of the module do I use in 1.21.50

somber cedar
safe stream
#

Other than being able to cancel an action, is there any reason why to go with beforeEvent instead of afterEven? I'm looking at the documentation for [email protected] and there are barely any properties for beforeEvent - and also it seems to be readonly so an extra system.run is needed

fallen hearth
#

Can playerId from PlayerJoin be used to /kick the player? I wanted to kick by id

prime zenith
#

Can i make it so a bow cannot fire if not fully charged

wary edge
#

PlayerInteract for example, before event can detect an empty hand wherras after does not.

humble lintel
#

anyone know if I can get a promsie from a runjob

worldly pier
#

what do yo mean

safe stream
#

thank you for the help

dim tusk
#

kick requires a target

#

and why use playerJoin?

#

just use playerSpawn

humble lintel
#

I made an item hopper block that has it's own inventory

#

I was wodnerign if anyone would be able to put their ideas into it

#

'as to why it creates this issue

#

just wanna know if anyone can give me their own inputs

#
function handleInventory(storage : Entity, block : Block) {
    const nearbyItems = block.dimension.getEntities({
        location: block.location,
        maxDistance: 10,
        type: 'minecraft:item'
    }) 

    const container = storage.getComponent('inventory')?.container;
    if (!container) return;
    for (let entity of nearbyItems) {
        const item = entity.getComponent('item')?.itemStack;
        if (!item) return;
        if (container.emptySlotsCount < 1) {
            //Find slots with similar Items
            const similarSlots = findSimilarSlots(container, item);
            if (similarSlots.length < 1) continue;

            const similarItem = container.getItem(similarSlots[0]);
            if (!similarItem) continue;
            if (similarItem.amount + item.amount < similarItem.maxAmount) {
                const newItem = similarItem;
                newItem.amount += item.amount
                container.setItem(similarSlots[0], newItem)
                entity.remove();
            } else {
                const difference = similarItem.maxAmount - similarItem.amount;
                const newItem = similarItem;
                newItem.amount += difference;
                container.setItem(similarSlots[0], newItem);

                const newDropItem = item;
                if (difference < 1) {
                    entity.remove();
                } else {
                    newDropItem.amount -= difference;
                    block.dimension.spawnItem(newDropItem, entity.location);
                    entity.remove();
                }
            }
        } else {
            const emptySlots = findEmptySlots(container);
            if (emptySlots.length < 1) continue;
            container.setItem(emptySlots[0], item);
            entity.remove();
        }
    }
}
unique acorn
humble lintel
#

find similar slots for items that are already in the inventory

unique acorn
#

explain more?

humble lintel
#

So then if there's an item thjat's already there

#

we can just incrememnt value

unique acorn
#

container.addItem() already does that

humble lintel
#

if the amount is less than its max amount that means there's space

#

oh? really

unique acorn
#

yeah

humble lintel
#

didnt know that lol

#

well i coded the whole thing with setitem

#

lmaoooo

unique acorn
#

crazy

humble lintel
#

yeah i mean it works jsut nto when there's multiple items

#

pronbably bc the count goes over 256

unique acorn
#

its cool tho

humble lintel
#

damn i wrote all of that

#

just for nothijng lmao

#

yeah it gives the same error

#

weird

#

same thing with the item amount

untold magnet
#

entity?.setDynamicProperty('test', +1) could work?

humble lintel
#

1

untold magnet
#

const DP = dynamic property

unique acorn
#

+1 is like saying 1, if you want to add 1 to it then just do entity?.setDynamicProperty('test', 1 + 1)

humble lintel
untold magnet
humble lintel
#

what cennac said

unique acorn
untold magnet
unique acorn
#

optimize your code then ig

unique acorn
untold magnet
#

just to make sure, I'll do some work testing out multiple different ways to see which one is the best,

humble lintel
#

did u create an explosion

#

of itmes

unique acorn
#

yeah, I can send a video if you want

unique acorn
humble lintel
#

hm interesting

unique acorn
#

i used a chest instead of a custom block tho

#

didn't feel like coding a custom block

humble lintel
#

oh im using entity containers

unique acorn
#

oh, huh

humble lintel
#

yeah i dont think we're able to make custom container blocks

#

so i jsut use entities

#

with custom components

unique acorn
#

how do you open the container tho

humble lintel
#

entity interaction

#

with a very small size / collision box

unique acorn
#

makes sense, I'll try with an entity

humble lintel
#

maybe minecart chest

humble lintel
#

Uh yeah I just realized I closed my terminal for regolith

#

my bad...

#

so my edits were not applied

#

lmaooo

unique acorn
#

oh lol

pseudo timber
#

const container = overworld.getBlock(location).getComponent("inventory").container;
const inventory = player.getComponent("inventory").container;

whats wrong?

humble lintel
#

@unique acorn add item doesn;t automatically remove item entities right

unique acorn
humble lintel
#

yeah so if my container is full but one slot has 63 dirt and I drop 64 I won't be abe to remove only 63 from the item entity

unique acorn
#

addItem() returns the rest of the items when slot is full, so you can use dimension.spawnItem()

pseudo timber
humble lintel
#

i keep getting undefined

#

hm okay

pseudo timber
#

block/ender chest goes here

unique acorn
#

so maybe try a chest or barrel or another block

pseudo timber
#
// Crate system
world.afterEvents.itemStartUseOn.subscribe((data) => {
    const { source: player, block } = data;
    const { x, y, z } = block.location;
    if (x == 180 && y == 91 && z == -47) {  // Cords of enderchest that will open the crate GUI
        player.runCommand("playsound random.pop2 @s");
        new ModalFormData()
            .title("ยงfOpen Crates")
            .dropdown("\nยงbSelect a crate key to open!\n\nยง7Crates give better loot the higher rarity it is!\n\n", [...CRATE_DROPDOWN])
            .show(player)
            .then(res => {
                if (res.canceled) return;

                const { location, itemStack } = CRATES[res.formValues[0]];

                if (!location || !location.x || !location.y || !location.z) {
                    return failedMessage(player, "Invalid crate location.");
                }

                const overworld = world.getDimension("overworld");
                if (!overworld) {
                    return failedMessage(player, "World dimension not found.");
                }

                // Ensure integer coordinates for block location
                const blockLocation = {
                    x: Math.floor(location.x),
                    y: Math.floor(location.y),
                    z: Math.floor(location.z)
                };

                // Debug: Log the location being checked
                player.sendMessage(`Debug: Checking crate at X:${blockLocation.x}, Y:${blockLocation.y}, Z:${blockLocation.z}`);

                const block = overworld.getBlock(blockLocation);
                if (!block) {
                    return failedMessage(player, "Crate block not found.");
                }

                // Debug: Confirm the block type
                player.sendMessage(`Debug: Found block type: ${block.typeId}`);

                const inventoryComponent = block.getComponent("inventory");
                if (!inventoryComponent) {
                    return failedMessage(player, "Crate block has no inventory. Ensure itโ€™s a chest or crate.");
                }

                const container = inventoryComponent.container;

                if (!player.runCommand(`clear @s ${itemStack} -1 1`).successCount) {
                    return failedMessage(player, `You do not have a ${convertTypeId(itemStack)} Key.`);
                }
                const crateType = convertTypeId(itemStack);
                const inventory = player.getComponent("inventory").container;
                for (let i = 0; i < 3; i++) {   // Gives 3 random items from the crate rarity chest
                    const drawnSlot = Math.max(randomInt(0, container.size - container.emptySlotsCount - 1), 0);
                    const item = container.getItem(drawnSlot);
                    if (!item) continue;
                    if (!inventory.emptySlotsCount)
                        player.dimension.spawnItem(item, player.location);
                    else inventory.addItem(item);
                }
                player.runCommand("kill @e[r=5,type=item]");
                successfulMessage(player, `Successfully opened a ${crateType} Crate!`);
                addScore(player, "cratesOpened", 1);
                return;
            });
    }
});

world.beforeEvents.playerInteractWithBlock.subscribe((block) => {
    const Intblock = block.block;
    const player = block.player;

    const blockX = Math.floor(Intblock.location.x);
    const blockY = Math.floor(Intblock.location.y);
    const blockZ = Math.floor(Intblock.location.z);
            // Enter cords of crate opener chest
    if (blockX === 180 && blockY === 91 && blockZ === -47) block.cancel = true;
});
untold magnet
#

show me all possible ways to increases the dynamic property value
bec these:
setDynamicProperty('smth', 1+1)
or
let i = getDynamicProperty('smth')
setDynamicProperty('smth', i++ / i + 1)
doesn't work properly

dim tusk
untold magnet
dim tusk
#

simple as that...

#
const val = world.getDynamicProperty('coddy:val') ?? 0;

world.setDynamicProperty('coddy:val', val + 1);```
untold magnet
dim tusk
#

unless I misunderstood something omfao

dim tusk
untold magnet
dim tusk
#

since setting dynamic property overwrites the old one, you need to get the original val then add...

untold magnet
#

( i was running alot of dynamic properties at once )

dim tusk
#

you're doing a lot of things probably

untold magnet
dim tusk
dim tusk
#

how a val + 1 would be slow?

untold magnet
#

no freaking idea

dim tusk
#

it's not even complicated math... Like what? It just adds ๐Ÿ˜ญ

untold magnet
#

thats my life with my addon bugs

untold magnet
#

anyways what im trying to do here is making a fully functional energy generator system, generating energy / saving energy / converting energy

dim tusk
#

My goofy really set an ItemStack with another ItemStack

dim tusk
#

how you'll transfer the energy and how to generate the energy

humble lintel
#

is there a better way to stop the item from respawing when I use addItem

prime zenith
#

Sorty wrong room

dim tusk
humble lintel
#
function* pickupItems(storage: Entity, block: Block) {
    const nearbyItems = block.dimension.getEntities({
        location: block.location,
        maxDistance: 10,
        type: 'minecraft:item',
        excludeTags: ['test:item_ignore']
    })

    const container = storage.getComponent('inventory')?.container;
    if (!container) return;
    for (let entity of nearbyItems) {
        const item = entity.getComponent('item')?.itemStack;
        if (!item) continue;
        const addItem = container.addItem(item);
        const location = entity.location;

        entity.remove();
        if (addItem) block.dimension.spawnItem(addItem, location).addTag('test:item_ignore');
        
        yield;
    }
}

Maybe im just dumb but i cant figure it out

#

og bruh lmaoo

dim tusk
#

the one I gave is perfect already...
-# for me lmfao

untold magnet
# dim tusk how you'll transfer the energy and how to generate the energy

as for the basic tier, u have only a hand crank block that will generate tiny amount of energy every 2 clicks,
but for the enhanced tier, which u can generate energy via burning coal and u can save the energy inside of a battery blocks, and to transfer the energy u need some wires for the connection.

dim tusk
#

You can refer to how I did it.

humble lintel
#

i have the same one nbtu does urs give any errors when u launch a bunch of items at once

#

like break a chest full of items type of stuffg

dim tusk
#

it works fine... YET

humble lintel
#

I get an error with the amount being over 256

#

but it works perfectly fine

untold magnet
dim tusk
humble lintel
#

yeah lmao

dim tusk
#

The best thing you can do is split them off unfortunately

untold magnet
dim tusk
#

I'm bored, I'm making an rc car.

untold magnet
#

it uses 6 slots
one for the fuel
4 for the input
one for the output
and 2 extra ones for the flame and the arrow icons, and i have to work for each one of these all at the same time.

untold magnet
dim tusk
#

don't have an interval for each one

#

That ain't a good idea

#

Especially if it's a lot, tho if you're just doing it in a short time that's okay.

#

but for a long time... NO just no.

untold magnet
sleek gorge
#

Hi!

#

I have a question

#

Is there a way to make a block remember which players interact with it?

cold grove
sleek gorge
#

Ok, thank you!

tight plume
#

Does anyone have hasItem helper function?

dim tusk
sharp elbow
#

So redundant, lol

dim tusk
sharp elbow
#

Well first, the description given (or lack thereof) is probably not even to spec

sharp elbow
#

"I need to test if the player has a given <item> in their inventory" is not what Coddy's function does

dim tusk
#

This is more for entities not for players tho .

#

Ohh,

#

mb then...

sharp elbow
#

It's not, they were vague

dim tusk
#

yeah deleted it lmfao

sharp elbow
#

What you sent would certainly work for testing any item in that container, just ... I cannot imagine that ever being useful

#

There's simpler ways to do even that

#

Could you iterate over all slots and determine if each one is empty?

dim tusk
#

And I forgot you can check inventory, my mind stuck in equippable component not available in entieis

#

And since yorue already here, you can just give it to him... Because you said it's bad ๐Ÿคท

sharp elbow
#

Nah

dim tusk
#

nice response...

viral mirage
#

Does anyone know if its possible to grab a players coordinate and saving it on a scoreboard? Like, save their X coordinate to a scoreboard every 10 seconds or so?

dim tusk
#

Yes

viral mirage
#

Thank you!

#

Can you link the documentation for this? I'm a bit lost

somber fiber
viral mirage
#

also is that using a beta/experimental API? (it's my first time using scripts)

somber fiber
dim tusk
somber fiber
#

It looks like that snippet grabs all of the player's coordinates, but if I'm understanding correctly, you only want to grab one coordinate every 10 seconds or so (x, y, or z). Is that correct?

viral mirage
somber fiber
# viral mirage I just want it to save coordinates so that I can print them using tellraw. The t...
system.runInterval(() => { // Every 10 seconds, run this code.
  for (const player of world.getPlayers()) { // Check each player in the world.
    for (const key in player.location) { // Repeat the following code for the X, Y, and Z coordinates.
      let obj = world.scoreboard.getObjective(key) ?? world.scoreboard.addObjective(key, key); // Get the scoreboard objective associated with the coordinate.
      obj.setScore(player, Math.floor(player.location[key])); // Set the value.
    }
  }
}, 200); // 20 ticks equals 1 second, so 200 ticks is 10 seconds.
viral mirage
# dim tusk ^^

I tried those but it's still not working (I'm like 99.9% sure I'm doing something wrong tho)

dim tusk
#
const scoreboards = {
  x: world.scoreboard.getObjective('playerX') ?? world.scoreboard.addObjective('playerX'),
  y: world.scoreboard.getObjective('playerY') ?? world.scoreboard.addObjective('playerY'),
  z: world.scoreboard.getObjective('playerZ') ?? world.scoreboard.addObjective('playerZ'),
};

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    for (const key of ['x', 'y', 'z']) scoreboards[key].setScore(player, Math.floor(player.location[key]));
  }
}, 10 * 20);

This is customizable, for example here it's playerX, playerY and playerZ

dim tusk
somber fiber
#

Have you created them?

dim tusk
somber fiber
somber fiber
viral mirage
#

Alr, one sec

#

Is there something I have to do to make a script run every tick? Similar to tick.json for functions?

sharp elbow
#

Have you imported both world and system from "@minecraft/server"?

#

Otherwise no; assuming that snippet is in the entry of a pack with scripting enabled, it sets itself up. system.runInterval will invoke the callback function after so many ticks, on repeat

viral mirage
#

It's my first time lol

#

mb guys

#

Imma try that

sharp elbow
#

That's often neglected in most snippets haha, no worries

dim tusk
#

plus, did you turn in your log gui?

#

Looks like I'll put those imports in snippets from now on...

viral mirage
#

I also have no clue how to do the imports, imma look at the docs rq

dim tusk
#

just scroll down.

dim tusk
viral mirage
dim tusk
viral mirage
dim tusk
viral mirage
#

I give up

dim tusk
#

That's an easy fix

#

Change the version 1.18.0-beta in manifest into 1.17.0 and for 1.4.0-beta change to 1.3.0

shut citrus
#

how to remove air block when using structureManager.createFromWorld()?

viral mirage
trail marten
#

the version in the manifest can keep it that way (1.18.0-beta & 1.4.0-beta), you just NEED to enable Beta APIs in the Eperimental section ON THE WORLD

dim tusk
chilly moth
#

how do I give a entity a item to hold like allay and then take it back or replace it with item in hand through scripts

wheat condor
#

If i run a runJob that doesnโ€™t do anything just yields will it create more lag than a runJob that yields after running a great task?