#Script API General

1 messages · Page 25 of 1

warm drum
#

I have a problem with runCommand using script, like the command execute is stuck in the previous version

honest spear
#

Well in theory you can save these information in string for example reading alll properties of objects and values and storing them

#

or you can use JSON.stringify

wintry bane
warm drum
#

JSON.stringify it to store as string then use JSON.parse to convert it back

warm drum
honest spear
#

but JSON cant serialize all kinds

wintry bane
honest spear
#

well no

warm drum
#

I dont think thats possible

honest spear
#

for example shulker contentbwill be lost

#

BlockType is easy

#

as its just string id

wintry bane
#

I know it's not possible now and I'm not looking solutions for the current version, I just wanna know if it's possible in the future

wintry bane
honest spear
#

?

#

block container?

#

idk permutations are very possible

#

but you can save only components known to API

#

with container there is problem with the ItemStack it sekf like i said before

wintry bane
#

entity.setDynamicProperty("test:block", entity.dimension.getBlock(entity.location))

honest spear
#

nah not like that tho

#

it accepts only string

wintry bane
#

I know

honest spear
#

so serialize your data

wintry bane
#

I just wanna know if it'll be possible in the future

honest spear
#

who knows

#

¯_(ツ)_/¯

#

i am sure its not in close future

acoustic basin
#

hey guys, i have a small question here: is there a way to translate, for exmaple, item lore i set in my script in .lang? like, for example, i write in my script item.v360:smiting_template.name, and translate in .lang file?

acoustic basin
slow walrus
#

if you know something's never gonna be undefined, just type cast it. there's those warnings for a reason, because they're general functions that can sometimes return undefiend or whatever. anyway, types aren't in javascript so it doesn't actually matter what you do with them

obsidian coyote
#

iirc you can disable that by setting strict to false?

remote oyster
#

I would leave strict set to true. If the type is saying it might be undefined I would review the code and types to be sure it's not user error.

shy leaf
acoustic basin
half socket
#

Hey guys I have question, Is it possible to get a player's xuid and device using script?

slow walrus
#

no

#

unless you're using server-net

#

but that only works on BDS

#

and you'll have to make http requests to the XBOX live api

#

an sum other shi

half socket
slow walrus
#

here's something you can look at for that https://den.dev/blog/convert-gamertag-to-xuid/

As part of the work on OpenSpartan Workshop I needed the capability to convert a Xbox gamertag into its immutable identifier - the Xbox user ID, also commonly known as the XUID. My plan was to add the option for someone to find all the matches where they played with a specific player.

cold grove
distant tulip
#

when shooting a ray down
can it skip a block?
i am multiplying the view direction with 4 and adding it to the player location and that is the ray start point

#

wait i am spawning it inside the block aren't i 🤦‍♂️

#

yeah nvm i solved that.
that explain the weird offset i am having

nocturne berry
#
block.dimension.runCommandAsync(`execute positioned ${block.location.x} ${block.location.y} ${block.location.z} run function mana_generator`);```

How to put more commands without having to put another block.dimension.runCommandAsync?
knotty plaza
sharp elbow
#

Well, that is what you are already doing, in essence.

rigid surge
#

Just run it directly with api

sharp elbow
#

Depends on what mana_generator does. There are valid use cases for calling commands if, say, it interacts with a legacy command system

rigid surge
sharp elbow
#

All API calls aren't too efficient, that's the nature of them

#

But if there are native methods for what a command could do, then by all means yes. It's simply clearer too

rigid surge
#

Yeah thats a valid point can’t argue with that

nocturne berry
nocturne berry
honest spear
scarlet hemlock
#

Guys, is there a way to check when the moment before the player quits the world to execute a script just right before leaving?

copper lake
scarlet hemlock
#

To remove a block and trigger an entity event

copper lake
#

Might be worth opening a post for this question, I know there are world before events for things but I think when you do before events, they are read only.

scarlet hemlock
#
////////////////////////////////////////////////////
world.afterEvents.projectileHitBlock.subscribe((eventData) => {
  const projectile = eventData.projectile;
  const hitBlockLocation = eventData.location;
  const eventDimension = eventData.dimension;
  const source = eventData.source;

  if (projectile.typeId === "let:light_projectile") {
    const block = eventDimension.getBlock(hitBlockLocation);

    // Check if the block exists and if the source entity has the "light" tag
    if (block && source?.hasTag("light")) {
      const fillCommand = `fill ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} light_block ["block_light_level"=12] replace air`;
      const summonCommand = `summon let:light_marker ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z}`;
      source.runCommand(fillCommand);
      source.runCommand(summonCommand);

      // Set a timer to remove the light block after 100 ticks (5 seconds)
      system.runTimeout(() => {
        const currentBlock = eventDimension.getBlock(hitBlockLocation);
        if (currentBlock.typeId === "minecraft:light_block") {
          currentBlock.setType(BlockTypes.get("minecraft:air"));
        }

        // Despawn the 'let:light_marker' entity at the same location
        eventDimension.runCommandAsync(
          `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
        );

      }, 100); // 100 ticks = 5 seconds
    }
  }
});```

I have this script that sets a light block and summons an entity in a specific coordinate. After 5 seconds, it'll remove the block and despawns the entity. But if the player leaves the world before that, they'll never dissapear
prisma shard
scarlet hemlock
prisma shard
#

yes

scarlet hemlock
#

I have this but I know I'm missing something...

  const playerDimension = player.dimension;

  // First, remove the light block if it's still present at the hitBlockLocation
  const currentBlock = playerDimension.getBlock(hitBlockLocation);
  if (currentBlock && currentBlock.typeId === "minecraft:light_block") {
    currentBlock.setType(BlockTypes.get("minecraft:air"));
  }

  // Then, despawn the 'let:light_marker' entity using the event command
  playerDimension.runCommandAsync(
    `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
  );
});```
prisma shard
prisma shard
scarlet hemlock
prisma shard
#

Instead of:

 currentBlock.setType(BlockTypes.get("minecraft:air"));
  }

You could do:

 currentBlock.setType("minecraft:air");
  }
#

@scarlet hemlock

scarlet hemlock
#

OK, I've changed that. But when I leave the world and open it again, the block and entity are there 😔

prisma shard
unreal cove
scarlet hemlock
scarlet hemlock
prisma shard
#

using console.warn()

unreal cove
scarlet hemlock
prisma shard
unreal cove
scarlet hemlock
prisma shard
#

just put
console.warn('the script is working')

#

In top of your script

#

If this shows in the console, the script is running

scarlet hemlock
#

Like this?

  console.warn('the script is working')
  const playerDimension = player.dimension;

  // First, remove the light block if it's still present at the hitBlockLocation
  const currentBlock = playerDimension.getBlock(hitBlockLocation);
  if (currentBlock && currentBlock.typeId === "minecraft:light_block") {
    currentBlock.setType("minecraft:air");
  }

  // Then, despawn the 'let:light_marker' entity using the event command
  playerDimension.runCommandAsync(
    `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
  );
});```
prisma shard
#

yes

#

Oh wait no

scarlet hemlock
#

Is not showing, so I assume is not working

prisma shard
#

On top of the whole script

scarlet hemlock
#

Oh sry

#

Then yes, the script is working because I have other functions that are working

prisma shard
#

oh

#

k

scarlet hemlock
#

Maybe I'll just go with @unreal cove 's way, I think that should work

prisma shard
#
world.beforeEvents.playerLeave.subscribe(({ player }) => {
 system.run(() => {
 
  const currentBlock = player.dimension.getBlock(hitBlockLocation);
  if (currentBlock.typeId === "minecraft:light_block") {
    currentBlock.setType("minecraft:air");
  };

player.dimension.runCommandAsync(
    `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
  );
})
});```
#

Can you try this @scarlet hemlock

scarlet hemlock
#

Sure

prisma shard
#

OHHHHH

scarlet hemlock
#

Also, do you know how can I summon the entity in the exact center of the light block?

prisma shard
#

wait a seccccccc

scarlet hemlock
#

I'll wait

prisma shard
#

where is your hitBlockLocation variable????

#

@scarlet hemlock

scarlet hemlock
#

@prisma shard

  const projectile = eventData.projectile;
  const hitBlockLocation = eventData.location;
  const eventDimension = eventData.dimension;
  const source = eventData.source;

  if (projectile.typeId === "let:light_projectile") {
    const block = eventDimension.getBlock(hitBlockLocation);

    // Check if the block exists and if the source entity has the "light" tag
    if (block && source?.hasTag("light")) {
      const fillCommand = `fill ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} light_block ["block_light_level"=12] replace air`;
      const summonCommand = `summon let:light_marker ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z}`;
      source.runCommand(fillCommand);
      source.runCommand(summonCommand);

      // Set a timer to remove the light block after 100 ticks (5 seconds)
      system.runTimeout(() => {
        const currentBlock = eventDimension.getBlock(hitBlockLocation);
        if (currentBlock.typeId === "minecraft:light_block") {
          currentBlock.setType("minecraft:air");
        }

        // Despawn the 'let:light_marker' entity at the same location
        eventDimension.runCommandAsync(
          `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
        );

      }, 100); // 100 ticks = 5 seconds
    }
  }
});```
scarlet hemlock
scarlet hemlock
prisma shard
scarlet hemlock
#

No sorry, I removed that

prisma shard
#

You dont need?

#

ok

scarlet hemlock
#

Yes! But since you've told me to wait

#

I removed it 😛

#

Let me add it again

prisma shard
#

bruh

#

i said to wait bcause i realized somthing bruhh

scarlet hemlock
#

Here:

  const projectile = eventData.projectile;
  const hitBlockLocation = eventData.location;
  const eventDimension = eventData.dimension;
  const source = eventData.source;

  if (projectile.typeId === "let:light_projectile") {
    const block = eventDimension.getBlock(hitBlockLocation);

    // Check if the block exists and if the source entity has the "light" tag
    if (block && source?.hasTag("light")) {
      const fillCommand = `fill ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} light_block ["block_light_level"=12] replace air`;
      const summonCommand = `summon let:light_marker ${hitBlockLocation.x + 0.5} ${hitBlockLocation.y + 0.5} ${hitBlockLocation.z + 0.5}`;
      source.runCommand(fillCommand);
      source.runCommand(summonCommand);

      // Set a timer to remove the light block after 100 ticks (5 seconds)
      system.runTimeout(() => {
        const currentBlock = eventDimension.getBlock(hitBlockLocation);
        if (currentBlock.typeId === "minecraft:light_block") {
          currentBlock.setType("minecraft:air");
        }

        // Despawn the 'let:light_marker' entity at the same location
        eventDimension.runCommandAsync(
          `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
        );

      }, 100); // 100 ticks = 5 seconds
    }
  }
});

world.beforeEvents.playerLeave.subscribe(({ player }) => {
  system.run(() => {

    const currentBlock = player.dimension.getBlock(hitBlockLocation);
    if (currentBlock.typeId === "minecraft:light_block") {
      currentBlock.setType("minecraft:air");
    };

    player.dimension.runCommandAsync(
      `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
    );
  })
});```
prisma shard
#

you wanna remove the block and despawn entity 2 times?

#

and that won't work because the hitBlockLocation variable is declared outside of the event

scarlet hemlock
#

Right

scarlet hemlock
prisma shard
#

you set the variable hitBlockLocation in projectileHitBlock event, so you can't use the variable in the another event

scarlet hemlock
#

I see that now

copper lake
#

probably need an if

#

else

prisma shard
#

Hmmm i am thinking how could you use the same variable in both events

#

is that even possible idk

scarlet hemlock
#

I can define a new one for this event

#
  const blockLocation = player.location;
  system.run(() => {

    const currentBlock = player.dimension.getBlock(blockLocation);
    if (currentBlock.typeId === "minecraft:light_block") {
      currentBlock.setType("minecraft:air");
    };

    player.dimension.runCommandAsync(
      `event entity @e[family=light_marker,x=${blockLocation.x},y=${blockLocation.y},z=${blockLocation.z},r=1] let:despawn`
    );
  })
});```
#

Hmmm but it won't work

#

Because I need to know where the block was placed

#

(it's starting to make sense for me 😅 )

prisma shard
#

bruh

scarlet hemlock
#

Sorry! I'm actually learning by doing! 😜

scarlet hemlock
#

No... that can't be right, can it?

lyric kestrel
scarlet hemlock
lyric kestrel
#

ah

lyric kestrel
scarlet hemlock
#
  const projectile = eventData.projectile;
  const hitBlockLocation = eventData.location;
  const eventDimension = eventData.dimension;
  const source = eventData.source;

  if (projectile.typeId === "let:light_projectile") {
    const block = eventDimension.getBlock(hitBlockLocation);

    // Check if the block exists and if the source entity has the "light" tag
    if (block && source?.hasTag("light")) {
      const fillCommand = `fill ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} ${hitBlockLocation.x} ${hitBlockLocation.y} ${hitBlockLocation.z} light_block ["block_light_level"=12] replace air`;
      const summonCommand = `summon let:light_marker ${hitBlockLocation.x + 0.5} ${hitBlockLocation.y + 0.5} ${hitBlockLocation.z + 0.5}`;
      source.runCommand(fillCommand);
      source.runCommand(summonCommand);

      // Set a timer to remove the light block after 100 ticks (5 seconds)
      system.runTimeout(() => {
        const currentBlock = eventDimension.getBlock(hitBlockLocation);
        if (currentBlock.typeId === "minecraft:light_block") {
          currentBlock.setType("minecraft:air");
        }

        // Despawn the 'let:light_marker' entity at the same location
        eventDimension.runCommandAsync(
          `event entity @e[family=light_marker,x=${hitBlockLocation.x},y=${hitBlockLocation.y},z=${hitBlockLocation.z},r=1] let:despawn`
        );

      }, 100); // 100 ticks = 5 seconds
    }
  }
});```
lyric kestrel
#

ah

scarlet hemlock
#

Cute dog btw

lyric kestrel
#

thank you

#

She's a dorgi

#

Daschund Corgi mix

scarlet hemlock
#

Now I need to see a full body picture 🤣

lyric kestrel
lyric kestrel
#

then try it

scarlet hemlock
lyric kestrel
#

6 years old

#

she can live to ~12 years

#

but yes

scarlet hemlock
#

My dog has 11 y/o. I adopted him when he was 6 months old. Time flies

lyric kestrel
#

wow

scarlet hemlock
lyric kestrel
#

oh, ye, you don't have block defined

scarlet hemlock
scarlet hemlock
lyric kestrel
#

const block = eventData.getBlockHit().block

scarlet hemlock
#

Now it says Object did not have a native handle. interface property [x] expected type: number (failed parsing interface to Function argument [0])

lyric kestrel
#

1sec

#

sorry @scarlet hemlock I can't help. I have to go downstairs

#

My new dog, Freddie, can't be alone by himself

scarlet hemlock
#

Np thanks!

untold magnet
#

guys

#

const item10 = inv.setItem(10, new ItemStack('minecraft:stick').lockMode == "inventory") will set a locked item?

#

hmm,

#

for (let i = 0; i > 8; i++) const slot0To9 = inv.getItem(i) will check all 9 slots?

#

i want to check if those 9 slots have a specific amount of an item, like if 3 of those 9 slots have dirt a function will execute

distant gulch
#

What

untold magnet
untold magnet
#

look, theres 9 slots in my entity, if 3 slots of those 9 has an item, it will run a function

untold magnet
distant gulch
#

Hold on lemme make it rq see if it works

untold magnet
#

i mean

#

if one slot has 3 items in total, it will not work, it should work only when 3 slots have the same item.

distant gulch
#

So you mean
[ dirt ] [ dirt ] [ dirt ] run function?

untold magnet
#

kinda,

#

and shapeless

distant gulch
#

And [ dirt x3 ] no function

untold magnet
distant gulch
#

So we'll see what we can use

#

Initially I would use LocalStorage or var

#

To count the numbers in each slot and make them readable to the whole client

#

Then assign a number in a list using the item name with the amount

untold magnet
#

lemme show u an example:

O O O
P P O
O P O
= function

O P O
P O O
O O P
= function

P³ O O
O O O
O O O
= no function```
distant gulch
#

And if the list contains 3 pieces of dirt then check each value

#

Yea seems simple enough

#

If youd like to wait like 30 mins

#

I mean I spend hours coding

oblique heath
untold magnet
untold magnet
#

for a new block

#

for the forge

oblique heath
#

so the forge has 3 slots?

lyric kestrel
#

The for loop that you did, only works if i is more than 8

untold magnet
#

those 9 slots in the middle counted from 0 to 8

distant gulch
#

I spent days on my project that converts Minecraft animations into the /camera command or script API system.runTimeOut

oblique heath
#

is it using the custom crafting table component or something?

untold magnet
#

smelt grinded items

#

put the grinded inside those 9 slots

#

with a empty pocket

#
  • some coals
#

to start melting them

oblique heath
#

does the block use this?

untold magnet
#

after a while it will turned into a liquid

untold magnet
oblique heath
#

ok so how is it storing the items?

distant gulch
untold magnet
wanton ocean
#

UI schmui

oblique heath
#

yeah but what is the simple inventory?

#

is it an entity?

untold magnet
#

entity

oblique heath
#

ok

#

do you know the indexes of all the visible slots?

untold magnet
#

maximum inventory size is 256

lyric kestrel
#

Yes, but are they in the correct order? Because the one on the far left could be 0, so have you checked their actual slots?

oblique heath
#

yeah thats what im asking

oblique heath
#

he said the ones in the middle are 0 to 8

lyric kestrel
#

Ah ok. Good

oblique heath
#

but what are these?

untold magnet
#

i changed the slots locations of the last 5 slots

lyric kestrel
#

Oki

untold magnet
#

those 9 slots in the middle is from 0 to 8

#

the rest is from 9 to 14

#

the script will work only on those slots from 0 to 8

untold magnet
#

so,

#

for (let i = 0; i <= 8; i++) { const slots = inv.getItem(i) should get the item from all 9 slots?

distant gulch
#

Show half script

#

So I can help with better interpretation

untold magnet
# distant gulch Show half script
system.runInterval(() => {
  const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
    for (const entity of world.getDimension(dim).getEntities()) {
      const block = entity.dimension.getBlock(entity.location);
      if (entity.typeId === 'my:entity') {
        entity.nameTag = 'NameTag';
        if (block?.typeId !== 'my:block' && entity?.isValid() && block?.isValid()) {
          entity.triggerEvent('exe:dropInv');
          system.runTimeout(() => { if (block?.typeId !== 'my:entity' && entity?.isValid() && block?.isValid()) { entity.triggerEvent('exe:despawn') } }, TicksPerSecond * 0.1);
        }
        const inv = entity.getComponent('inventory').container;
        for (let i = 0; i <= 8; i++) {
          const middleSlots = inv.getItem(i)
        }
      }
    }
  })
})```
#

thats the whole script actually

distant gulch
#

K I'll try and debug it

#

See what I can do and Ill check for any errors

#

What version of script API does it use?

untold magnet
#

the last beta

distant gulch
#

Alr

untold magnet
#

I'll be watching some one-piecebao_icon_entities

distant gulch
#

Oki

remote oyster
distant gulch
#

I was wondering why it wasn't working

#

I always use the latest non betas

remote oyster
#

Current one.

#

The stable non beta is 1.14.0

distant gulch
#

Ik

remote oyster
#

Just making sure so there was no confusion.

distant gulch
#

Kkkkk

#

Btw where'd all the auto completions go

#

Wasn't there an on hold item one?

remote oyster
#

Auto completion is there, if your environment is set up correctly.

distant gulch
#

And what happened to ChatSend

#

On bridge

remote oyster
distant gulch
#

But it worked on non beta before

#

In my SCP mod

remote oyster
#

Not possible. It's never existed for stable.

distant gulch
#

Then how'd it work

remote oyster
#

You must have used beta unknowingly.

distant gulch
#

I never used beta versions

remote oyster
#

Then it didn't work. So the only conclusion on how it could have worked is that you used beta.

distant gulch
#

But I js checked it says 1.11.0

untold magnet
remote oyster
distant gulch
#

I used it for !gms !gms and !gmsp

remote oyster
#

chatSend is beta only.

distant gulch
#

Then also a sphere generator

remote oyster
#

It does not work on stable.

untold magnet
#

u have to use 1.15.0-beta

distant gulch
#

Ok ok

#

I never used beta because the first time I did I lost my Minecraft mod on my Xbox world and there's no way to modify and the -beta was out of beta and the script didn't function

#

I mostly code on Xbox

#

So

remote oyster
#

1.11.0 Stable (AfterEvents)

#

chatSend does not exist.

distant gulch
#

Ik

remote oyster
#

But you don't. Lol.

distant gulch
#

Don't have to keep correcting

remote oyster
distant gulch
#

I'm js saying that's what I remember

untold magnet
distant gulch
#

I don't learn from others I learn from myself sorry not to be ignorant but I never liked learning for others

remote oyster
distant gulch
untold magnet
distant gulch
#

Ive been teaching myself for over like 5 years

#

Only way I'm good at the things I do

#

And still I'm not that good

untold magnet
distant gulch
#

First ever mod I made was an scp096 mod from Funtime Lefty or as of now he calls himself Ayden P.

#

Me and him collabed

#

Then after the only person who has taught me abt mc addon's was Abdul rahixmm the creator of Ace Entities (practically one of the first ever 3D guns mod) he taught me how to make 3D guns and render them ingame when I was 10

#

Then I started working for BlockOps and basically became the owner and the boss

untold magnet
#

jeez

distant gulch
#

And I'm still kinda new to JavaScript

untold magnet
#

my first ever project was EpicPaladins bedrock port, i did removed it bec of the original creator decisionbao_foxxo_blank

distant gulch
#

The first ever thing I made in JavaScript fully by myself after a month of learning took me 2 days to make was the thing I posted

#

A couple days ago

untold magnet
#

don't look at the script

distant gulch
untold magnet
distant gulch
#

Look I send video of the code for the website it's very simple stuff

oblique heath
untold magnet
oblique heath
#

i feel like javascript isn't the most friendly language for beginners

untold magnet
#

nah its too simple for me

#

i like it actually

oblique heath
#

the whole not having types explicitly defined or what ever can be an eyesore when working on large projects imo

untold magnet
#

unlike json-UI, its really hard and hurts

oblique heath
#

json ui is like a black box to me

#

but thats due to lack of documentation honestly

#

its all just json at the end of the day

distant gulch
#

I only do the simplest things on JavaScript

untold magnet
deep quiver
#

Very cool thats mostly html and css tho and also very big jumpscare at the end

oblique heath
#

is there a way to load a chunk without using commands?

sharp elbow
#

Could try an entity with the "minecraft:tick_world" component

oblique heath
#

is there no scripting alternative?

copper lake
# oblique heath is there a way to load a chunk without using commands?

They pretty much all involve using commands to do things like add a ticking area. Then again, I didn't really get that to work with script so I wound up just teleporting myself with script to get the chunk loaded so that I could do other things then move on to the next step. Of course that was me using a script to setup a world with no other players in it.

neat hazel
#

How to get the cooldown component of an item in 'itemUse'??
Only call the function if the cooldown is = 0

bright torrent
#

I’m new to bedrock add on development. Is it possible to set the texture of a black or entity dynamically at runtime. I mean actually generating a new texture, pixel by pixel, not referencing an image in the texture folder.

valid ice
#

It is not possible, no.

bright torrent
#

Is there a way to create a custom map item where you set the pixels?

bright torrent
valid ice
#

Plugins? Sure. Addons? Nope

#

Best you might be able to do is a bunch of particles mimicking a texture

meager zenith
#

how can i an entity's location from player.getEntitiesFromViewDirection

rigid surge
meager zenith
#

tysm

rigid surge
#

Sorry for bad spacing i wrote that out on my phone

meager zenith
meager zenith
#

i only need the first entity

rigid surge
#

No i did individual location

#

U could do an array tho

meager zenith
rigid surge
#

then just break the script after the first entity

meager zenith
#

alr thanks

rigid surge
#

const entities = player.getEntitiesFromViewDirection();
const firstEntity = entities.length > 0 ? entities[0] : null;

if (firstEntity) {
const location = firstEntity.location;
// Do something with the location
}
@meager zenith

meager zenith
#

thanks

rigid surge
#

Np

deep plank
#

You can also just do player.getEntitiesFromViewDirection()[0];

#
const entity = player.getEntitiesFromViewDirection()[0];

if(entity) {
    const loc = entity.location;
    // do something
}
halcyon phoenix
#

What would be better on this situation? I'm using BlockCustomComponent and im creating growing plants should I do

onTick: (event) => {
            const { block, dimension } = event;
            const blockState = block.permutation.getState('si:growth');
            const tickRage = 3200 * (1 +  Math.random())
            
            let timer = 0
            timer = timer + 1

            if (timer = tickRage && !block.permutation.withState("si:growth", 4)) {
                block.setPermutation(block.permutation.withState("si:growth", blockState + 1))
            }
            else null;

        },

or should I

onPlace: (event) => {
            const { block, dimension, previousBlock } = event;
            let blockLoc = block.center()

            let blockState = block.permutation.getState('si:growth');
            if ( blockState == 0 ) {
                const timeoutId = system.runTimeout(() => {
                    
                    block.setPermutation(block.permutation.withState('si:growth', blockState + 1))
                    dimension.spawnParticle("minecraft:crop_growth_emitter", blockLoc)
                },4200 * (1 +  Math.random()))
                vineTimeouts[getBlockLocationAsKeyString(block)] = timeoutId;
            }
        },
 onPlayerDestroy: (event) => {
            const { block } = event;

            const blockLocationKey = getBlockLocationAsKeyString(block);
            if (blockLocationKey in vineTimeouts){
                system.clearRun(vineTimeouts[blockLocationKey]);
                delete vineTimeouts[blockLocationKey];
            }
        }
#

which one is better?

#

also weird interaction with onPlace. When block state is changed onPlace is also triggered.

#

should I stick with the first one?

untold magnet
#

const hmmm = me.afterEvents.wondering

#

how can i make slots accept only a specific item?

#

like slot 0 can have only sticks, when the slot gets a different item it will be cancelled

runic crypt
#

is this how i import multiple scripts ??

import './gwim/gwim-form';
import './gwim/gwim-rank';
untold magnet
#

#1289226687204163799 bao_act_upvote

untold magnet
#

anyone?

glacial widget
#

btw can you use /ability ?

untold magnet
#

gosh the forge system is so complicated

lyric kestrel
#

lol

untold magnet
#

hmmm

#

itemStack?.nameTag = 'Hi' will change the item name right?

untold magnet
#

its not renaming the item for some reason, i think i had to make it has a display name first right?

unreal cove
#

make sure ur re-setting ur itemstack in slot after naming it

untold magnet
#

oh wait a moment,

untold magnet
#

i fixed it by adding an invisible display name for it

near siren
#

Is there any way to change a mob’s target via scripting?

distant tulip
#

not directly but if the mob prioritize who hit hem
you can by applying damage

static nebula
#

Can someone help me? Is there any way I can make an entity release particles? Like if I shoot a bow and the arrow comes out with particles?

distant tulip
shrewd wedge
#

How am give enchanted item

bright torrent
#

Does the script API support Particles at all? Couldn’t see anything? Surely it would make sense to spawn a JSON-defined emitter given something happened

simple zodiac
slim spear
#

wish this error didn't exist

#

it was working fine earlier 😭

shrewd wedge
#

How to give enchanted armour

unique dragon
#

first set the enchantment to the itemstack

#

then set the item on the slot

#

@shrewd wedge

shrewd wedge
#

Ok

#
if (msg == "-item test") {
const inventory = player.getComponent("minecraft:inventory").container;
let itemHeld = inventory.getItem(player.selectedSlotIndex);
player.sendMessage(`${JSON.stringify(itemHeld)}`);

const equippable = player.getComponent("equippable");
const test1 = equippable.getEquipment("feet");
if (test1 !== undefined) {
player.sendMessage(`${test1.typeId}`);
}
}
})
#

Do you know why this not working?

slim spear
unique dragon
#

that looks fine

shrewd wedge
#

I put boot on and is not saying I have boot in chat

#

What am I doing wrongly?

unique dragon
#

Feet the first chat

#

char*

#

it's capital letter

shrewd wedge
#

Ohh

unique dragon
#

you can also use enum

shrewd wedge
#

What that?

unique dragon
#

this will show u

shrewd wedge
#

Okay

unique dragon
#

it's optional

#

you can just do "Feet" or EquipmentSlot.Feet

#

same thing

shrewd wedge
#

Oh

#

Okay, thank you

bright torrent
bright torrent
#

Is there a way to set the data for a map item?

unique dragon
#

well, amount and nameTag tho

distant tulip
#

idk if this is off topic or not but most of you here are using github so i think it is the best place to ask
is there a better way to handle pushing addons to a repo the copying both folders to the same folder?
i can use mklink command but there has to be a better alt

shy leaf
#

i mean as in method, the way you do it

distant tulip
#

i can automate that with mklink but is there a better way?

shy leaf
#

hmmm im not sure if theres a better way, mostly cuz i havent touched github that far

#

i just let my IDE to make changes in the fork(branch) and pull request into main repo(branch)

distant tulip
#

i was uploading files manually before but i hit the limit of 100 file so i had to clone the repo and use git

strong oar
#

Does anyone have template for connectable chairs/sofas

subtle cove
strong oar
#

Just like this one

#

#1283826268839874580 message

untold magnet
#

umm, how can i make something run for only one time inside runInterval?

#

if (something === true) { run something for only one time, no more }

#

system.runTimeout(() => { ,,, }, TicksPerSecond * 100000000) will run the thing after a decade

#

system.runJob(somhow) i fr don't have any idea

#
 Inside a runInterval!
 ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
if (something === ture) {
  const run = system.run(() =>  { myCommand });
  system.clearRun(run)
}```?
slow walrus
#
system.runTimeout(() => {
  console.log('Hello World!'
}, 10) // 10 ticks
#

oh

#

nvm

#
let run_flag = true;
system.runInterval(() => {
  if (run_flag) {
    // do whatever
    run_flag = false
  }
})
#

@untold magnet

untold magnet
#

lemme think about something else

#

nvm..

#

it has to be something like let amount = 1; right?

#

if i put system.runTimeout inside a system.run, is it will run that instantly first, then it will have the runTimeout delay?

#

i dont think so

slow walrus
untold magnet
#

system.run(() => { ,,, }, 1)?

slow walrus
#

it's outside of the interval

untold magnet
untold magnet
#

hmmm

slow walrus
#

misread

#

it will happen only once

#

if your variable is outside of the interval

#

you're only setting it to false inside the interval

distant tulip
#

what ", 1" for

untold magnet
#
let amount = 1;
↓ inside a runInternal
for (let i = 0; i < amount; i++) {
system.run(() => { ,,, }, i)
}```this sounds stupid too
untold magnet
distant tulip
#

uhmm
why do you need system.run for that

untold magnet
#

no?

slow walrus
#

why

distant tulip
#

why

slow walrus
#

do you need it

untold magnet
#

i just want to run something inside the runInterval only once,

slow walrus
#

yeah so do what I said

untold magnet
#

ugh

untold magnet
distant tulip
#

do it need to be inside the runInterval ?

slow walrus
#
let run_flag = true; // OUTSIDE of interval, will only be true ONCE
system.runInterval(() => {
  if (run_flag) {
    // everything in here only runs ONCE
    run_flag = false // set the flag to false, so it doesn't ever run again
  }
})
untold magnet
slow walrus
untold magnet
#

lemme try and see

#

hopefully it will work as how i want

distant tulip
#

btw system.run is mostly only used for exiting read only mod in before events

distant tulip
#

for your case
no

#

runInterval do the same thing anyway

untold magnet
#

that for testing only tho

#

it should send that message whenever i place the block just like the first time, not only ONCE

untold magnet
# untold magnet i knew it

its just a test to see, placing the block will spawn an entity
that entity is detected using a runInterval, the sendMessage is inside that runInterval

distant tulip
#

place block event be like:
"why i am here"

untold magnet
#

whenever this if (something === true) it will run something only once,

untold magnet
#

this is the code:

if (something === true) {
   // runSomething only once
   system.runTimeout(() => { the same commamd i want to run only once but after 80s }, TicksPerSecond * 80)
}```
#

lemme make it clear to understand

slow walrus
slow walrus
#

show your whole code, not weird abstract snippets of it

#

that doesn't tell us anything

distant tulip
#

dealing with block place without block place event is something new

subtle cove
#

uhh, iirc wave made a blockupdate event

untold magnet
#
        const coal = entity.getDynamicProperty('coal')
        if ( item9?.typeId === 'minecraft:coal') entity.setDynamicProperty('coal', true)
        if (coal === true) {
          //run only once
          system.runTimeout(() => { if (slots9Dyc === true && slot11Dyc === true) { item9.amount -= 1 } else entity.setDynamicProperty('coal', false) }, TicksPerSecond * 80);
        }```item9 = inv.getItem(9)
#

@slow walrus @distant tulip bao_act_upvote

untold magnet
distant tulip
#

so? you can runInterval in the event after block place

untold magnet
#

if slot 9 has coal on it, it will run something once, and it will degrees the amount after 80s

#

to be honest, i want to degrees the coal amount immediately, but only once bec after 80s it will remove one coal from that slot

slow walrus
untold magnet
subtle cove
#

use containerslot if ur using runtimeout/interval

untold magnet
#

is this will explain it?

        const inv = entity.getComponent('inventory').container;
        const coal = entity.getDynamicProperty('coal')
        if (item9.typeId === 'minecraft:coal') entity.setDynamicProperty('coal', true)
        if (coal === true) {
          //run only once
          system.runTimeout(() => { item9.amount -= 1 }, TicksPerSecond * 80);
        }```
#

forgot to put this const item9 = inv.getItem(9);

untold magnet
slow walrus
#

that's still only 6 lines 😭

#

send

#

all of it

subtle cove
#
const inv = event.source.getComponent("inventory").container
const item9 = inv.getSlot(9);
const coal = entity.getDynamicProperty('coal');
if (item9.hasItem() && item9.typeId === 'minecraft:coal') {
    entity.setDynamicProperty('coal', true);
}
if (coal === true) {
    //run only once
    system.runTimeout(() => {
        if (!item9.hasItem() || item9.typeId !== "minecraft:coal") return;
        if (slots9Dyc === true && slot11Dyc === true) {
            if (item9.amount === 1) item9.setItem();
            else item9.amount -= 1;
        } else entity.setDynamicProperty('coal', false);
    }, TicksPerSecond * 80);
}
untold magnet
#

that runTimeout will run one time every 80s
it will run 80s after coal === true

subtle cove
untold magnet
#

yes, looks buddy

subtle cove
#

hmmm, but what event is it in?

#

before such interval gets triggered again

untold magnet
#

when coal === true, it will decrease one item only one time, bec system.runTimeout will decrease the item after 80s infinitely,

#

hmmmm

#

lemme do something

subtle cove
#

make a post if u may

untold magnet
#

nvm, it has the same issue

untold magnet
#

why is it soo complicated bao_foxxo_angry

subtle cove
#

custom furnace?

untold magnet
#

its a forge block, it needs coal as a fuel

#

i thought about something really stupid

subtle cove
#

the slot needs continuos checking, not just every 80s

untold magnet
#

when the player interacts with the block while holding flint and steel, it will light the block and make it start burning the coals,

untold magnet
subtle cove
#

and that spark lasts for how long...

#

man, id create a post for this just sayin

untold magnet
# untold magnet wait a moment

if (something === true) { system.runTimeout * after 80s)
something = false will happen after 10s, is it will run that timout even if that something isn't true?

untold magnet
untold magnet
subtle cove
#

it still tries to timeout unless it's clearRunned

untold magnet
#

if i set that something to false before the runTimeout, it should not run the command inside it bec the section that it's in is turned off right?

#

lemme make the code and send it inside that post, hopefully someone will help

subtle cove
#

run, runTimeout, runInterval are like rogue code that's sent to run at scheduled tick

#

so u might have to save the runId to clearRun if ever the 'something' turns false

#

or just clearRun when u set(something, false)

fallow rivet
#

Is it possible to use Dynamicproperty for an item?

last latch
#

What is the difference between
world.getEntity(identifier)
and
world.getDimension(MinecraftDimensionTypes.overworld).getEntities().find((x) => x.id === identifier)

#

cuz getEntity works on a beforeEvent but getEntities.find() doesnt

tiny tartan
fallen cape
#

Oh wait

#

It should be the same...

#

If you're not using a typeid instead of the numeric id

last latch
#

i dont want a cow

#

i want a specific cow

subtle cove
#

uhh, both works for me tho

supple yoke
#

worker is kind of fun

#

actually optimizing is fun in general

last latch
# subtle cove uhh, both works for me tho
world.beforeEvents.entityRemove.subscribe(({ removedEntity }) => {
    console.warn(world.getEntity(removedEntity.id) + " entity found using getEntity()");

    console.warn(world.getDimension(MinecraftDimensionTypes.overworld).getEntities().find((x) => x.id === removedEntity.id) + " entity found in array");
});
#

when a entity dies this happens

last latch
#

aha

bright torrent
#

Would it be possible to make a custom version of the lead? Like with a different texture, but the same behavior?

untold magnet
#

anyone alive?

thorn flicker
untold magnet
#

does this:
const coal = entity.getDynamicProperty('coal', 0)
coal++
will increase that number?

#

like from 0 to 1 to 2?

thorn flicker
#

no

untold magnet
#

make sense actually

thorn flicker
#

so you need to set the dynamic property, and get the current value of it, and do + 1

untold magnet
untold magnet
thorn flicker
#

what way would be "better"

untold magnet
untold magnet
#

          system.runTimeout(() => {
            if (coalPrc === 0) entity.setDynamicProperty('coalPrc', 1);
            if (coalPrc === 1) entity.setDynamicProperty('coalPrc', 2);
            if (coalPrc === 2) entity.setDynamicProperty('coalPrc', 3);
            if (coalPrc === 3) entity.setDynamicProperty('coalPrc', 4);
            if (coalPrc === 4) entity.setDynamicProperty('coalPrc', 5);
            if (coalPrc === 5) entity.setDynamicProperty('coalPrc', 6);
            if (coalPrc === 6) entity.setDynamicProperty('coalPrc', 7);
            if (coalPrc === 7) entity.setDynamicProperty('coalPrc', 8);
          }, TicksPerSecond * 10);```this will change the number once every 10s
#

in total 70s

thorn flicker
#

that's bad

#

lol

untold magnet
#

im wondering if i can make it better

thorn flicker
#

I just told you how.

untold magnet
#

just show me how

untold magnet
#

should i say it? ||how||

thorn flicker
#

this is so simple, I dont think I need to show you how lol

#

I told you how already

untold magnet
#

my brain in a holiday rn

#

just write it

thorn flicker
#

give your best attempt.

#

then come back.

untold magnet
#

just...
write it bec my brain isn't working

thorn flicker
#

no.

#

you already have the variable of getting the dynamic property, use that variable when setting the dynamic property and just do + 1

#

you are getting the current value and adding onto it.

untold magnet
#

setDynamicProperty('coal' +1)
dont mind me im stupid without my brain

thorn flicker
#

you didnt use the variable.

#

just add the variable before the math, and you will be all set.

untold magnet
#

if (coalPrc === 0) entity.setDynamicProperty('coalPrc') + 1?

thorn flicker
#

the setDynamicProperty methods requires 2 parameters.

untold magnet
#
const t17x = stupid({ as: hell })
thorn flicker
untold magnet
#

buddy i just have no idea how to write itbao_doggo_smug

thorn flicker
#

thats a problem.

#

atleast you tried.

untold magnet
#

at least i will learn from those mistakes

#

hopefully

thorn flicker
#
entity.setDynamicProperty('coal', coalPrc + 1)
#

also in your logic this will only go up if it's 0

#

which makes this pointless

#

if this wasnt intentional, remove the if statement, or better yet, check if its defined in the if statement instead.

thorn flicker
terse tide
#

Its possible tô make a wait function

#

Like a set Timeout?

distant tulip
#

system.runTimeout

terse tide
#

But can I make it so that when I have a tag it waits a certain amount of time?

distant tulip
#

if(player.hasTag('hmm')) system.runTimeout

terse tide
#

Thanks

distant tulip
terse tide
#

Ye

#

Comand wait 300 ticks comand

#

Broh? Its possible or not

distant tulip
#

idk wdym but you can use await and runtimeout

oblique eagle
#

anyone know how to get this to face where the player is facing when spawned? player.runCommandAsync(`summon myth:uppercut_spell_effect ~ ~ ~ ${PlayerViewDirection.z} 0`)

unique dragon
#

use player rotation

#

and invert the values

halcyon phoenix
#

Hey I need your opinions people:
I got 3 different plants
Should I make 1 global timer and give each plant a probability to grow
OR
Should I make independent timers for each plant

which one would be better and would not have issues in the future?

subtle cove
subtle cove
untold copper
#
    "format_version": 2,
    "header": {
        "name": "§aGlitch §cPvP §eFunctions §ev1.0.2 BP§r",
        "description": "Made by @untakensoulz",
        "uuid": "c9abbf4e-1cd5-4869-8a1b-486fcf435708",
        "version": [
            1,
            1,
            0
        ],
        "min_engine_version": [
            1,
            18,
            0
        ]
    },
    "modules": [
        {
            "type": "data",
            "uuid": "84d5a89b-8dcc-0308-a7d7-fd5f8123bba7",
            "version": [
                3,
                6,
                   9
            ]
        },
        {
            "type": "script",
            "language": "javascript",
            "entry": "scripts/main.js",
            "uuid": "2fa09013-80e6-c43a-e1c7-73dafb30fdd0",
            "version": "1.6.0"
        }
    ],
    "metadata": {
        "authors": [
            "@untakensoulz",
            "Author here"
        ]
    },
    "dependencies": [
        {
            "description": "@minecraft/server module dependency",
            "module_name": "@minecraft/server",
            "version": "1.4.0-beta"
        },
        {
            "description": "@minecraft/server-ui module dependency",
            "module_name": "@minecraft/server-ui",
            "version": "1.4.0"
        }
    ]
}```
#

does anyone know why my manifest is tweaking this is my first time updating it 😭

shut citrus
#

Why the update is nothing specical

untold copper
#

idk im slow

supple yoke
#

reading wikis for algorithms give me a brain hammorrhage

#

i fucking hate how "scientific" they sound bro.

shy leaf
#

or just, you know, entity.setDynamicProperty('coalPrc', coalPrc)

velvet swallow
#

How can I obtain player kills and deaths?

supple yoke
untold magnet
#

ugh

#

let coal = entity.getDynamicProperty('coal')
coal = true ← should set the value of coal into true, right?

unreal cove
#

no

unreal cove
#

entity.setDynamicProperty('coal', true)

untold magnet
#

i was writing that

#

let coal = entity.getDynamicProperty('coal')
coal = 0 ← should set the value of coal into 0?

unreal cove
#

no

#

you have to use setDynamicProperty

untold magnet
#

so this is useless: coalPrc = 0;

#

bec coalPrc is getDynamic not set

unreal cove
#

yup

#

that will simply just change the value of that variable to 0

untold magnet
#

should i use it or not?

#

i mean should i use it to change the value of that property or not?

subtle cove
#
if (coalPrc < 8) {
  entity.setDynamicProperty("coalPrc", coalPrc + 1)
}```
ruby haven
#

Is it possible to create a custom dimension through scripting API

ruby haven
#

But is it possible in addons

wary edge
round bone
subtle cove
#

#1046947779118895114 ...

round bone
#

thanks

subtle cove
#

Wc

untold magnet
#

um, guys

#

entity.isValid() = inside loaded chunks?
!entity.isValid() = inside unloaded chunks?

#

i want to force the script to work on the entity when it is inside loaded chunks

static nebula
#

Can someone help me? How do I make it so that when I click on a block holding an item in my hand it sends a message in the chat?

static nebula
untold magnet
#

lemme make it for u,

#

wait a moment

static nebula
untold magnet
# static nebula Ok, thanks
import { world } from '@minecraft/server';

world.afterEvents.playerInteractWithBlock.subscribe(({ itemStack, block, player }) => {
  if (block?.typeId === 'minecraft:dirt' && itemStack?.typeId === 'minecraft:stick') world.sendMessage(`${player} is interacting with dirt using ${itemStack.typeId}`)
})```
#

idk maybe the sendMessage have issues

#

if it has issues just change it

untold magnet
#

oh wait

untold magnet
fallen cape
static nebula
static nebula
shy leaf
#

what version is your minecraft

static nebula
#

1.21.22

shy leaf
#

i guess you can still try beforeevent

#

just in case

static nebula
#

Let me try

#

Yes, now it works, thank you very much.

untold magnet
#

i think

#

playerInteractWithBlock works only on items that can interact with blocks

#

like shovel can interact with dirt or axe can with wood

fallen cape
untold magnet
#

u have to use itemUseOn component

north rapids
#

How do I get an anchored position for the player? Something similar to the command 'execute as @s anchored eyes positioned ^^^0.8 '

subtle cove
#

maybe player.getHeadLocation()

north rapids
#

The anchor part I believe is that, but what about the offset?

#

Maybe if I get the block in the direction of the player's view and use the vector it will work

untold magnet
#

isValid should make it works inside the loaded chunks only right?

#

!isValid will make it work inside unloaded chunks only, right?

#

entity.isValid() → works only inside loaded chunks
!entity.isValid() → works only inside unloaded chunks
without isValid → works inside loaded and unloaded chunks

north rapids
#

I think I'll just use a runCommand

subtle cove
#
e.isValid()// true loaded
e.isValid()// false unloa(ded)
north rapids
#

I don't want to spend hours making a vec-2 to vec-3 converter

#

I was thinking about using getRotation()

deep plank
#

Removing z properties won't take you an hour, lol.

north rapids
#

Considering I'm completely dumb, yes

subtle cove
#

also ur prob gona use that converter furthermore

halcyon phoenix
#

is there anyway to create entity displays?

#

same as the one in java

supple yoke
#

if I were to choose to keep either promises or for while loops

#

it's async all the way

#

ppl need to learn their async await man

subtle cove
#

Promise.all

supple yoke
#

my beloved

#

more useful than race imo

#

or any of the Promise statics for that matter

subtle cove
#

i used it to collect member's approval to create a group

supple yoke
#

nice

#

promises is nice

#

second best JavaScript feature ngl

#

(the fist would be arrow functions)

subtle cove
#

then aboozed it like diz```js
await new Promise(r=>{ return })

supple yoke
#

what

subtle cove
#

neva to return

#

awaiting for nothing

supple yoke
#

sure ig

subtle cove
#

basically, there's resolve, reject, and abort

supple yoke
#

uh huh and?

subtle cove
#

dunno

supple yoke
#

then what were you going on about

#

fair

#

been using typed array recently

#

they're pretty fun

#

bitwise stuff makes me feel smart af lol

subtle cove
#

hopefully someday I'll have time to experiment lots with such data type

oblique eagle
steep hamlet
#

is it possible to change knockback resistance?

sage portal
#

If you're going to use commands instead of the native method, you don't even have to worry about figuring out rotations.

thorn flicker
#

You should use native methods instead of commands tho

distant tulip
sage portal
thorn flicker
distant tulip
thorn flicker
distant tulip
#

under dimension class

thorn flicker
#

im not talking about the method to spawn an entity

distant tulip
thorn flicker
#

no interface

distant tulip
#

wdym

thorn flicker
oblique eagle
distant tulip
#

use native methods
it is much easier

keen gull
#

How can i create loop? Loop wich will run command in every 2 second

thorn flicker
thorn flicker
#

however, it takes time for the entity to update its rotation after being spawned sometimes.

oblique eagle
#

it says dimension undefined

distant tulip
thorn flicker
#

get the player's dimension.

oblique eagle
keen gull
# thorn flicker system.runInterval

Okey but it does not work

import { system } from "@minecraft/server";

system.runInterval(() => {
system.runCommandAsync("effect @a regeneration 2 3");
}, 1);

I should replace system.runCommandAsync with something(bc it gives error)but i did not know with what.

oblique eagle
#

says vector3 is undefined

thorn flicker
#

because its undefined, obviously, its just a placeholder.

#

use the variable you made thats stores the player's dimension.

oblique eagle
#

it works

#

thx

#

wait

#

it kinda works

#

rotation is messed up a bit

thorn flicker
#

?

#

inverting them would mean it faces you

oblique eagle
#

my brain is tired idk

#

it faces where the player is facing only in some directions

thorn flicker
#

it takes a bit for the rotation to update, like I said

#

maybe that's what you are experiencing

oblique eagle
#

oh

oblique eagle
#

its really lame

#

im spam clicking the same direction and it is not changing direction lol

thorn flicker
#

idk if they are going to "fix" this or not

#

is it even broken? I dont know, but its lame either way

#

lol

thorn flicker
#

it should be

#

by taking time, I meant like a couple seconds

oblique eagle
#

oh

#

my entity exists for only like half a second

#

i can see it turn tho

#

i see it spawn then rotate but face the wrong direction

supple yoke
distant tulip
#

i am using same thing and it is working fine
keep in mind the body rotation need time
you can fix that with animations

steep hamlet
#

how to check if an entity is alive?

round bone
#

how can I communicate with my websocket server on world?

supple yoke
supple yoke
round bone
runic crypt
#

how can i make a refrigerator that actually stores items ?

#

like a chest thing ?

distant tulip
round bone
#

I used /connect and I don't really know what should I do next

supple yoke
# round bone or commands

Minecraft lets you connect to a websocket server when you’re in a game. The server can receive and send any commands. This lets you build a bot that you can … (well, I don’t know what it can do, let’s explore.) Minecraft has commands you can type on a chat window. For example, type / to start a command … Programming Minecraft with Websockets Rea...

runic crypt
#

also @distant tulip can you join my world i wanna test something ??

runic crypt
supple yoke
#

really nice resource

runic crypt
round bone
#

got it, is there any list with listeners?

supple yoke
round bone
#

I would like to add support for Realms for my API that I wrote today

#

so I have to use websockets to send somehow request to Discord

supple yoke
#

uh huh

round bone
#

so um, can I somehow listen to scriptevent command or smth>

rugged tinsel
#

you can send a tellraw to the player that has the websocket connected

#

the tellraw can be read from your websocket

round bone
supple yoke
#

here are all events (that I know of) that can be subscribed to

#

which includes chat messages if that's what you're looking for

rugged tinsel
#

afaik, there's no other way to send strings to websockets

round bone
#

I think this will be pretty easy way

rugged tinsel
#

PlayerMessage is the event you'll want to listen for

round bone
#
import { Server } from "ws";
import { v4 } from "uuid";

const wss = new Server({ port: 8080 });

wss.on('connection', (ws) => {
    ws.send("WebSocket server has been started!");

    ws.on('message', (message) => {
        console.log(`${message}`);
        ws.send(`You sent: ${message}`);
    });

    ws.on('close', () => {
        console.log("Client has been disconnected.");
    });

    ws.send(
        JSON.stringify({
            "header": {
                "version": 1,                    
                "requestId": v4(),         
                "messageType": "commandRequest",
                "messagePurpose": "subscribe"
            },

            "body": {
                "eventName": "PlayerMessage"
            },
        })
    );
});

console.log('WebSocket server is running on ws://localhost:8080');
#

I got some code already xD

supple yoke
#

nice 👍

round bone
#

I thought it was a bit harder

runic crypt
#

@distant tulip
what happened ??

distant tulip
#

i said i gtg
kinda busy
just ask here it is not a hard thing to do

runic crypt
#

oki

#

can anyone tell me how to make something in which if i right click an npc (custom npc) a chest ui opens up in which i can actually put items and take them out later

#

??

carmine yarrow
#

What world event recently got an option to only fire once on use ?

wary edge
carmine yarrow
#

Thanks!

woven loom
# round bone ```ts import { Server } from "ws"; import { v4 } from "uuid"; const wss = new S...

i made a simple wrapper that you might find that this useful
https://github.com/WavePlayz/bedrock-websocket-server-wrapper/


let { Server } = require("./bwssw.js")


let server = new Server()
    
server.onConnect( async client => {
    const { name } = client
    
    let response = await client.runCommand( "say " + name + " joined" )
    
    if ( await client.test( "x=0,y=0,z=0,r=5" ) ) {
        client.sub( "PlayerMessage", event => {
            console.log( event )
        
            client.unsub("PlayerMessage")
        } )
    } else {
        
    }
} )

server.onDisconnect( client => {
    // code
} )

server.start(8089)

setInterval( async () => {
    let bannedPlayers = await server.client( "tag=ban" )

    bannedPlayers.forEach( client => {
        client.disconnect()
    } )
}, 1e3 )



GitHub

Contribute to WavePlayz/bedrock-websocket-server-wrapper development by creating an account on GitHub.

round bone
#

🫡

#

I already bought sample discord.js (Node.js) cheap host and everything is working fine

#

Just need some time to publish it

sage portal
#

does the entityHurt afterEvent detect when the damage is fatal?

unique dragon
#

you can do this getting the health of the entity that was hurt

#

then you can calculate if it's fatal using this:

const hurtEntityHealth = hurtEntity.getComponent('health').currentValue;
const isFatal = (hurtEntityHealth - damage) <= 0 ? true : false;
#

tbh idk if that works

#

or just get the life, should work

oblique heath
shy leaf
#

since its entityHurt event, the currentValue for health would be after the damage anyway

unique dragon
#

cause there's no before event yet

#

bruh i already want to use that event

#

annoying to cancel the fatal damage using json

terse tide
#

Its possible to make a text display in block using json and script api?

terse tide
#

Anyone

unique dragon
#

and u spawn it above the block

terse tide
#

That would be cool, but what I really need is to make a display on the block texture

oblique heath
#

basically like a sign right?

terse tide
#

Ye

oblique heath
#

not possible

drowsy scaffold
#

is there any way to prevent a player from using / commands with scripts or regular bds?

bright torrent
terse tide
#

Thanks

bright torrent
#

No problem. I wanted to do something similar. I though about modifying map items’ data directly but I believe that’s not possible

little sphinx
#

How can I get the player's main hand slot in a script?

shy leaf
little sphinx
#

Ok thanks

little sphinx
#

like this?

shy leaf
little sphinx
#

The item in main hand

shy leaf
little sphinx
#

But then how do I get the main hand item?

shy leaf
#

that gives you the main hand item

little sphinx
#

I want a code where I can know which block the player is holding at the moment but this is the first time I use scripts

round bone
#

I can't listen to /tellraw

#

and any other commands

#

unless I can somehow send message as a player

round bone
#

okay: did some research, I can pull this out 100% for worlds, but I'm not sure about Realms yet

ruby haven
#

Is it possible to create custom buttons because I wanna create a dogdge system where I add a custom dodge button

idle dagger
#

someone help with #1290170284917395496

round bone
#

should I make another post when I'm updating my showcase or just push it into another message inside the thread of post?

#

#1289931246042087567 reference to this btw

shy leaf
#

thats what it says in showcase channel description

round bone
#

it's support for worlds/Realms

#

it's not that much changes, but it's a perfect for Realms/worlds

#

so I'm not really sure xd

shy leaf
#

woah

#

realms?

round bone
#

yeah

#

I'm not really sure

#

but worlds 100%

#

I haven't tested on Realms yet

warm drum
#

When will 1.15.0 @minecraft-server will be released? 1.21.40?

remote oyster
#

Oh, my apologies, you mean for Stable, not Beta.

buoyant canopy
#

other than loops is there a change dimension detector in the script api?

buoyant canopy
#

that's beta

remote oyster
#

You didn't specify 😜

buoyant canopy
#

you're right, i forgot

remote oyster
#

In stable, you only have the option of looping through players.

buoyant canopy
#

i guess that's my only option then

untold magnet
#

let procsC
entity.setDynamicProperty('procsC', procsC + 1); returns a log

remote oyster
#

?

#

Is that a question or a random statement?

untold magnet
#

this is the log

#

at this line
entity.setDynamicProperty('procsC', procsC + 1);

round bone
#

(procsS ?? 0) + 1

remote oyster
untold magnet
remote oyster
warm drum
#

Yeah

#

1.15.0 stable

#

1.21.40 maybe?

remote oyster
#

#random lol

round bone
#

just you probably

#

or I don't know something xD

untold magnet
#

i mean

#

entity.setDynamicProperty('coalPrc', coalPrc + 1); this works just fine

round bone
#

coalPrc might be undefined, this might be the issue

#

or any other type

remote oyster
# round bone or I don't know something xD

Don't worry about it lol.

Partitions on Android are represented by device node names like mmcblk0, mmcblk0p1, etc., which correspond to the physical block devices and their partitions. Your name, for a brief moment, resembled that, but I couldn't recall the actual spelling of such node names until I went back to verify haha.

remote oyster
# untold magnet I'm using that method ('coalPrc' coalPrc + 1) and it works fine, but not for the...
let procsC = entity.getDynamicProperty('procsC');

entity.setDynamicProperty('procsC', procsC + 1);

const test = entity.getDynamicProperty('procsC');

console.log(test);

This will not work, because I am declaring procsC but not defining it. It's not defined because the dynamic property it's trying to retrieve in that variable doesn't exist. Meaning that I have not created it nor defined it before attempting to get its value. When a dynamic property doesn't exist it returns undefined, thus the variable procsC will be undefined. So in the next line of code you attempt to set a value for a dynamic property called procsC by adding a variable and a number. Since procsC is undefined due to the failed attempt in the first line of code, you get an error. You can't add 1 to a variable that is not defined by a number.

Now, let's forget the example above. Let's assume you do in fact declare and define procsC in your code which you have not shown us. Then you must be sure it's a number and nothing else. You cannot mathematically add 1 to a string, vector, or any other type that is not a number without prior intervention.

ruby haven
#

Is it possible to create custom buttons because I wanna create a dogdge system where I add a custom dodge button

remote oyster
ruby haven
#

Nooooo my dreams are crushed😭😭😭

remote oyster
#

Back to the drawing book then 🤪

quasi meteor
#

can I save .txt or any file via script api?

round bone
#

the closest thing you can do is render a textField form with default value that you would like to save

#

and manually save it

#

or use WebSockets/HTTP requests to export some data and handle them by their servers

round bone
#

I thought about smth different

remote oyster
#

Yea lol

untold magnet
#

ugh...
if (item9?.typeId === 'minecraft:stick') item9.nameTag = 'f'

#

should change the item name, right?

#

somehow its not

#

why?

subtle cove
#

if its itemstack u need setitem

untold magnet
#

if (item9?.typeId === 'minecraft:stick') inv.setItem(9).nameTag = 'f'?