#Script API General

1 messages · Page 11 of 1

turbid oriole
#

The 2023 boom is curious, plus Ore UI is growing since it is more general purpose.

#

It seems like too many people use this library at the same time.:

https://www.npmjs.com/package/minecraft-extra

keen nymph
#

is onStepOn / onStepOff only in preview currently?

wary edge
#

I'd wait 1-2 more weeks if it isn't urgent as it will be stable stable in 1.21.20

keen nymph
umbral dune
#

setDynamicProperty still not working for me

#

the game simply forgets about the property after the second interaction

fallow minnow
neat hound
# umbral dune what's happening?

what is the item stack referring to? the block or the item in your hand... I think you are not setting it on the item in your hand

fallow minnow
#

only the key

fallow minnow
#

this js e.itemStack.setDynamicProperty("source"); is whats wrong

#

the 2nd set

neat hound
umbral dune
#

You can be sure, what I'm reading is "ready"

fallow minnow
#

well i suppose its not

#

forgot that resets it

thorn flicker
#

oh yeah, you dont need to do undefined, you can just leave it blank

umbral dune
#

the code is "small"

import { system, world, ItemStack, Block } from "@minecraft/server";

world.beforeEvents.playerInteractWithBlock.subscribe(e => {
  if(e.itemStack?.typeId === "ewds:resource_counter") {
    e.cancel = true;
    const ready = e.itemStack.getDynamicProperty("isready");
    world.sendMessage(`before setting to "true": ${e.itemStack.getDynamicProperty("isready")}`);
    
    if(ready) {
      e.itemStack.setDynamicProperty("isready", false);
      
      const target = e.block.location;
      const source = e.itemStack.getDynamicProperty("source");
      
      e.itemStack.setDynamicProperty("source");
      
      const minX = Math.min(target.x, source.x), minY = Math.min(target.y, source.y), minZ = Math.min(target.z, source.z);
      const maxX = Math.max(target.x, source.x), maxY = Math.max(target.y, source.y), maxZ = Math.max(target.z, source.z);
      
      const storage = new Map();
      for(let i = minX; i <= maxX; i++) {
        for(let j = minY; j <= maxY; j++) {
          for(let k = minZ; k <= maxZ; k++) {
            const block = e.block.dimension.getBlock({ x: i, y: j, z: k });
            if(block && !block.isAir) {
              storage.set(block.typeId, (storage.get(block.typeId) ?? 0) + 1);
            }
          }
        }
      }
      
      const list = [];
      for(const [block, quantity] of storage) {
        list.push(`${block} (${quantity}x)`);
      }
      
      system.run(() => e.player.onScreenDisplay.setActionBar(list.join(" §7-§r ")));
    } else {
      e.itemStack.setDynamicProperty("isready", true);
      world.sendMessage(`after setting to "true": ${e.itemStack.getDynamicProperty("isready")}`);
      
      const target = e.block.location;
      e.itemStack.setDynamicProperty("source", target);
      
      system.run(() => e.player.onScreenDisplay.setActionBar(`§7source position set to §s${target.x} ${target.y} ${target.z}§r`));
    }
  }
});
fallow minnow
#

what exactly is the issue?

neat hound
#

I t may return the itemStack of what is in your hand, not not what is in your hand... I think you need to do it on the slot.

#

it you can....

wary edge
#

You need to set the item back into the hand

neat hound
#

try puttingit on yourself

umbral dune
valid ice
#

ItemStack is but an abstract reference to an item, it does not have to actually exist in the world.

#

ContainerSlot exists, and is a tangible thing the player can interact with in the world.

#

When you getItem, it's like you're pulling a copy of the item out of the inventory and into the code

neat hound
#

and.... what is this ```js
const source = e.itemStack.getDynamicProperty("source");

  e.itemStack.setDynamicProperty("source");```
umbral dune
#

I'm deleting the property

neat hound
#

Did what Hero said make sense to you Elias?

umbral dune
neat hound
#

Guys.. how do you get what is in the hand... is it this... js const inventory = player.getComponent("inventory"); const selectedItem = inventory.container.getItem(player.selectedSlotIndex);copied from the API example

granite badger
#

that works

neat hound
#

new territory for me... but you are probably on your way to your solution now

remote oyster
valid ice
#

can also ```js
const equipment = player.getComponent("equippable");
const selectedItem = equipment.getEquipment(EquipmentSlot.Mainhand);

neat hound
#

and then he can put his dynamic property on it?

fallow minnow
#

yes

#
player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand)``` returns an itemstack
valid ice
#

don't forget to set it back! echsplode

fallow minnow
#

like this

remote oyster
#

LOL

fallow minnow
#

not directed at anyone btw

#

just joking around

granite badger
#

then add like player.getComponent("equippable").setEquipment(mainhand)

chrome flint
#

i just realized
AND gates are just multiplication operators and OR gates are just addition operators

#

1x1 = 1 , true and true returns true
1x0 = 0, true and false returns false

1+1 = 2 (positive), true or true, return true
1+0 = 1 (positive), true or false, return true
0+0 = 0, false or false, return false

#

🤓

shy leaf
#

i shouldve specified that it only works when the event fires and the player sprints at the same time
but not when the event fires during the sprint

umbral dune
#

How do I get the name string of a block?

chrome flint
#

you can only get the typeID at least, but not the itemStack properties before it was placed

serene radish
#

how do i detect if a command wasn't successful in scripting?

#

successcount seems to do nothing with what im trying to do

shy leaf
#

how do i pass the damage value from entityHurt to entityHitEntity using async
i kinda never tried using async so i wanted to know if async works for those or not

serene radish
glass gull
#

random question but does player.sendMessage just send to the player or to everyone

shy leaf
#

it sends message to specified entity

#

so in that case it would be player only

glass gull
#

ok thanks

#

so does that mean world.sendMessage sends to everyone

shy leaf
#

ye every entity

glass gull
#

ok ok

#

that means my pet dog can read it

chrome flint
#

yeah i thought so xd

shy leaf
#

technically lol

#

idk if Entity has sendMessage though

serene radish
#

nvm my command just wasnt running no matter what, given that the successcount was always 0

glass gull
#

thanks

solar dagger
#

Is dynamic properties better than Map?

granite badger
#

It depends if you want to store data to world permanently or temperatorily

wary edge
chrome flint
solar dagger
wary edge
valid ice
#

what are you doing?

solar dagger
shy leaf
wary edge
shy leaf
#

trying to bypass iframes

valid ice
#

oh

#

set HP directly

#

or use override in applyDamage

shy leaf
#

override, nah

solar dagger
wary edge
shy leaf
#

im trying to get the damage from entityHurt but would health changed event work here?

wary edge
#

Again, what are you trying to do

solar dagger
#

Somewhat

wary edge
#

What are you trying to store?

valid ice
#

Both are very different things and should be used in appropriate places

solar dagger
shy leaf
#

im really not sure cuz entityHitEntity fires before entityHurt so entityHitEntity can only get the damage that was done before the event

solar dagger
#

What's best for dynamic properties/map

shy leaf
#

and idk if health changed event is any different

valid ice
#

To put it bluntly, maps are reset when world closes, dynamic properties are not.

solar dagger
#

Ahh

valid ice
#

They are not the same, however. A map can be a dynamic property if converted & set, a map is a native javscript object and unrelated to script API, a dynamic property exists solely within the minecraft environment, and a lot more.

#

You would be better off comparing an object to a map.. although I am sure that many threads for that subject exist online, and you can research that on your own time.

wary edge
#

As previously stated

solar dagger
#

Okay so let's say I want to store items from an entity would I use a dynamic property or map?

valid ice
#

You can use whatever you fancy. Array, object, map, global variables- heck, if you want use a string.

wary edge
solar dagger
#

Ok ok 👌 thanks

random flint
#

You can't put ItemStack in DynamicProperty

solar dagger
chrome flint
#

but you can put dynamic property in itemStack

valid ice
#

string, boolean, number, or vec3 types only

random flint
#

Make a custom entity with the sole purpose of being a itemStack database 🤓

valid ice
#

Imagine if itemstacks in dynamic property- recursive properties, yippee!

spring dove
#

Does someone else has the same problem? it appears like 2 minecrafts are open

solar dagger
#

Well I'm currently using map for the video above

spring dove
#

and consumes so much resources

random flint
valid ice
#

I want them to

#

But I get why they didn't

wary edge
solar dagger
random flint
# solar dagger Would that store the quantity?

You can store the itemStack in dynamicProperty by first getting all its Components (Enchantment, Name, TypeId, Quantity, Durability, etc) and then converting them into JSON stringified objects.

But it has its own downside

valid ice
#

no data sobbing

wary edge
solar dagger
#

Sounds like a few extra steps

wary edge
#

Just wait for 1.22

valid ice
#

Why not just use entity inventory shrug

#

Storage, persistent, per-entity, stores data easily

random flint
neat hound
solar dagger
valid ice
#

Map will always be faster, as it's a native JS method, whereas dynamic props are a script API exclusive.

#

However, speed at that level should not really be a huge concern.

solar dagger
#

Well what if the player leaves the world and I need to transfer their items back.

solar dagger
#

What's the best option between the two

wary edge
#

Like we said

#

Dynamic properties store data to the world. Maps dont

valid ice
#

Would work for your needs, it looks like

wary edge
#

I highly suggest you take the time to learn and read the docs

neat hound
#

I believe they answered you. You said you want to keep the data between sessions. Within a dynamic property you can store only, number or string or boolean or vector3 interface. So within the string you can get creative by taking data and converting it to a JSON obect, then stringifying it, then you can store it as a string. You can retrieve it and revert it back to JSON and so stuff with it.

Look in resources for example code to understand more.

solar dagger
#

Thank you for being helpful 🙂

astral quarry
#

If anybody wants to give feedback on the in Interact API share it here!
#1268601041063247955 message

keen nymph
random flint
#

A slab then?

keen nymph
#

slabs are 8

#

my thing was 2 initially

random flint
#

oh, then a trapdoor tall?

acoustic basin
#

guys, how do i use /scriptevent command and what do i need to make in script file itself for it to work?

wary edge
random flint
#

or smt like that

acoustic basin
keen nymph
hushed ravine
#

Any way to make the compass point to a player without using the world spawn point?

true isle
#

What's a good code editor for android?

hushed ravine
umbral dune
#

Is it possible to give the player a book and quill with specific text inside via scripting?

chrome flint
#

can we force enchant an armor? let's say i want to enchant an armor with protection and fire protection at the same time

#

i know its not possible with script api, but is there a way to do this?

true isle
#

I think you can in creative and save it in a structure to spawn but I haven't tested anything like that

fiery solar
nimble radish
#

wow @amber granite

chrome flint
nimble radish
#

If anyone know how to make a durability system that shows the armo durability of the armor that you have on can you let me know 🙂

amber granite
#

Hmm ?

amber granite
#

Unless u don't know how to use it

distant gulch
amber granite
#

I told him

distant tulip
#

infested blocks itemStack type id bao_comm_squaredeyebrows

nimble radish
distant tulip
#

infested deepslate is the only one withe the right id "minecraft:infested_deepslate"

wary edge
#

Its flattenned in .20 or .10

grave thistle
#

No sound is being played using this:
entity.dimension.playSound("fall.amethyst_block", entity.location, { volume: entity.getDynamicProperty("scan_volume") * 0.01, pitch: 3 });

The scan_volume property is set via UI slider:
sProperty("scan_volume", r.formValues[8] * 0.01);

How come this isn't working?

#

The slider goes from 0-100

noble lagoon
#

It was working perfectly and suddenly it started showing these errors

#

i have no idea what happened

solar dagger
ocean escarp
north rapids
#

How do I test by block id and state?

noble lagoon
#

This thing was working perfectly

solar dagger
#

Oh 😳 I don't use notes in my code, should probably start doing that

north rapids
#

Like "minecraft:dirt" ["dirt_type" = "normal"] ?

noble lagoon
north rapids
thorn flicker
noble lagoon
north rapids
noble lagoon
#

O mano aí explicou

north rapids
#

De qualquer forma, valeu 🫡

noble lagoon
#

Can anyone help me with MolangVariableMap? For particles

distant tulip
thorn flicker
distant tulip
#

i will see what i can do

noble lagoon
#

created in snowstorm

thorn flicker
#

show script side

north rapids
distant tulip
noble lagoon
noble lagoon
thorn flicker
noble lagoon
thorn flicker
#

use 3 equal operators " === "

north rapids
#

Tks

thorn flicker
#

im not sure what it is called, but you could use commands and see the auto completions to figure out.

#

oh you are right, it is dirt_type

#

...and normal

#

lol, okay, everything is right sorry

thorn flicker
north rapids
#

Np tysm for the help

#

Time to go back to remaking hoes

distant tulip
#

@noble lagoon
the script side should look like this

let mvm = new MolangVariableMap(); mvm.setSpeedAndDirection(`v.entityDirection`, 20, vector3 ) //vector3 is direction
entity.dimension.spawnParticle("arc:dash", vector3, mvm) // vector3 is position
#

20 is the speed

thorn flicker
noble lagoon
#

Thanks, I'll look into this better

thorn flicker
#

use setVector3 instead

distant tulip
#

let me take a look at the docs
that was an old script i used

thorn flicker
noble lagoon
#

I separated it into vector3 and a float

#

In different variables

thorn flicker
distant tulip
#

-# i think?

thorn flicker
distant tulip
#

test it and see

noble lagoon
#

v.variable is the string you put inside the method

#

This thing worked before

thorn flicker
#

yeah

#

put variable in string aswell, thats what I do

distant tulip
#

that is not what you are doing?
molangVarMap.setVector3("variable.test", vector3)

#

@thorn flicker

noble lagoon
#

It is instructed that the variable.variableName be only in the particle

#

I'm going to test putting this in the name but I don't think it will change anything

distant tulip
#

that what i was using so idk

#

#1155518084078112809 message

thorn flicker
#

and it's working.

noble lagoon
#

It literally just broke out of nowhere

#

Maybe the snowstorm broke something, which is usual.

thorn flicker
#

then I have no clue.

noble lagoon
#

The problem was simply capital letters

#

I write variableName in the particle

#

But Minecraft reads variablename

#

A rather stupid problem, I noticed it by seeing that the errors only wrote the name of the particle with everything in lowercase

dense skiff
#
        "canopy:customFuse": {
            "minecraft:explode": {
            "fuse_length": 4, // change this from ScriptAPI
            "fuse_lit": true,
            "power": 4,
            "causes_fire": false
            }
        },
    }

Is this possible? Current solution is just to make lots of different component groups with different fuse times and select the appropriate one, but I'd rather just be able to set the value smoothly.

subtle cove
#

Sth like that

dense skiff
#

beta's only got the afterevent I think

#

ill take a look

subtle cove
#

U can control an event what comp_group to add/remove

dense skiff
#

yes you can trigger events, but I want to modify some event settings, and then trigger it

#

since those are writable

subtle cove
#

Hmm, so they removed the beforeevent of it

#

There was setModifiers in beforeevent

amber granite
#

Yeah

north rapids
#

How do I modify the block state?

dense skiff
#

@subtle cove The data driven entity trigger event can modify which components are used, but not the arguments of those components. Is there a way to edit the arguments?

north rapids
#

system.run() maybe?

dense skiff
#

Nah that's different this is already an afterevent. It only gives you the strings of the component id.

north rapids
#

Oh

subtle cove
dense skiff
#

dang

#

did you double check the event? I might be looking at this wrong

shy leaf
#

does anyone have a template for detecting player selecting slot

#

actually nvm i can make one

dense skiff
#

player.selectedSlotIndex?

shy leaf
#

i was looking for smth like detecting the change

#

should be simple to make

dense skiff
#

Yep-- I've done it. A runInterval that updates the lastSelectedSlot, then you can just check if the player has scrolled since the last tick with this:

function hasScrolled(player) {
    return player.selectedSlotIndex !== lastSelectedSlots[player.id];
}```
shy leaf
#

neato, ty

#

(i almost made the code too complex until i saw this)

dense skiff
#

yw

dense skiff
near siren
#

Is there any alternative for isOp() for realms?

remote oyster
gray tinsel
#

how would I add custom classes to a preexisitng class like Player?

near siren
#

Not sure if you can completely, but I dont see why not. I think you'd use 'extends' to extend from the Player class.Doc for extends

MDN Web Docs

The extends keyword is used in class declarations or class expressions to create a class that is a child of another class.

gray tinsel
#

yeah I'm not sure if that would really work unfortunately as I want to kinda create a manager system per player, and the best I have at the moment is a map storing the playerId and manager

#

specifically for the player since you can't create a new instance of a player so I would somehow need to convert the parent to the extended class

valid ice
prisma shard
#

uh

#

so

shy leaf
#

would setting an entity's health value in entityHitEntity event apply the health before the entity gets 'hurt'?

prisma shard
valid ice
#

Have you read the docs

prisma shard
#

i am messing for 1 hour

#

with docs

#

location returns even if i shoot the projectile even at a block

#

but i cant detect if i have hit entity

prisma shard
#

um, i... am ... on.... 1.4.0-beta

#

there is no projectileHitEntity

shy leaf
#

Why

prisma shard
prisma shard
#

oh

valid ice
#

I'm sure you can figure that out

prisma shard
#

i cannt

prisma shard
#

this my full code

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

world.afterEvents.projectileHit.subscribe(( { location: hitLocation, source } ) => {
    // i have to figure out now that the code will run after hitting a entity
    // these code run even if i shoot the arrow on a block

if (source instanceof Player) {
    const hitDistance = Math.trunc(calculateDistance(source.location, hitLocation));
    const interval =
    system.runInterval(() => {
        world.getAllPlayers().forEach(source => {
            source.onScreenDisplay.setActionBar(`Player has hit an entity ${hitDistance} blocks away`)
        });
    });
    interval;
    system.runTimeout(() => {
        system.clearRun(interval);
    }, secondsToTicks(1));
};
});

/**
  * Calculates the distance between a Vec3 and another Vec3
  * @param {Vector3} vecA - First Vec3
  * @param {Vector3} vecB - Second Vec3
  * @returns {number} The distance between the Vec3 and the other Vec3
  */
function calculateDistance(vecA, vecB) {
    const dx = vecA.x - vecB.x;
    const dy = vecA.y - vecB.y;
    const dz = vecA.z - vecB.z;
    const distance = Math.hypot(dx, dy, dz);

    return distance;
}

/**
 * converts seconds to ticks
 * @param {number} second
 * @returns {number} tick
 */
function secondsToTicks(second) {
    const tick = second * 20;
    return tick;
}```
#

help me fix pls

#

i have to figure out now that the code will run after hitting a entity
these code run even if i shoot the arrow on a block

#

thats the problem

gray tinsel
valid ice
#

I have mine in a file which is imported into each file I use. I don't think it really matters as long as your manifest file can access it..?

gray tinsel
#

Ah right ok

granite badger
chrome flint
chrome flint
#
world.afterEvents.projectileHit.subscribe((event) => {
  let {location: hitLocation, source} = event
  let entityHit = event.getEntityHit()
  if (!(source instanceof Player) || !entityHit) return;
  const hitDistance = Math.trunc(calculateDistance(source.location, hitLocation));
  const interval =
    system.runInterval(() => {
      world.getAllPlayers().forEach(source => {
        source.onScreenDisplay.setActionBar(`Player has hit an entity ${hitDistance} blocks away`)
      });
    });
  system.runTimeout(() => {
    system.clearRun(interval);
  }, secondsToTicks(1));
});

@prisma shard

shy leaf
#

wait a damn minute

#

is onBeforeDurabilityDamage technically entityHitEntity but focused on item?

#

i should test smth with this

thorn flicker
shy leaf
#

for some reason

thorn flicker
#

I think that's why

granite badger
#

E.g. swords take durability damage when it hits an entity

shy leaf
#

oh hmmm

granite badger
#

oh there is onHitEntity too as mentioned

thorn flicker
#

ye

#

I would've expected a "cause" property or something for the durability.

#

is the durabilityDamage property able to be edited?

granite badger
#

the other event listeners pretty does that, that durability fires when it’s like "when everything happens", also yes you can edit damage

thorn flicker
#

meaning we can use this instead of getting the durability component, and making methods out of that

granite badger
#

custom item only*

thorn flicker
#

well yeah

#

ik

#

well this doesnt trigger the damage, this just edits the damage obviously

burnt remnant
#

i have a game theory, normal mods that are common on java have it so you can make chairs and sit in them, theoretically for bedrock, could you make a chair block and when you interact with it, it teleports you inside the block and plays the animation for when you are inside a minecart so it looks like you are sitting, and when you move the player, the animation stops?

#

cause using an entity is so boring and unoriginal

glacial widget
#

How do I getComponent a players armor slots?

wary edge
sage sparrow
#

hi there, I noticed that sometime ago mojang/microsoft have changed the way they handle player.name ingame for consoles (at least for PS)
before ingame our player.name was the same as gamertag set on microsoft profile account.
now it uses the PSN name as player.name... which is causing some issues of correlation to my ban system.
is there a way I can get ingame the xbox gamertag instead of the PSN name? I know player.id would be unique, but I need to correlate it with the right gamertag

shy leaf
#

would setting an entity's health to 0 kill them?

cold grove
shy leaf
#

well no

#

i mean

#

im using a calculation that gets damage value to set health

#

so

cold grove
#

Yes then

shy leaf
#

aight ty

distant tulip
remote oyster
# gray tinsel how would I add custom classes to a preexisitng class like Player?

I'm just piggybacking off what Herobrine64 showed you to give more clarity:

import { Player } from '@minecraft/server';

export function initializePlayerPrototype() {
    Object.defineProperties(Player.prototype, {
        isSpecialPlayer: {
            get() {
                return true;
            }
        },
        setTestProperty: {
            set(value) {
                this.setDynamicProperty('test', value);
                return this;
            }
        },
        addTwoNumbers: {
            value(param1, param2) {
                return param1 + param2;
            }
        }
    });
}
import { world } from '@minecraft/server';
import { initializePlayerPrototype } from './playerPrototypeModifications';

// Handle the worldInitialize event
world.afterEvents.worldInitialize.subscribe(() => {
    // Initialize the Player prototype
    initializePlayerPrototype();
    
    // Additional initialization code
});
#

Some may disagree with you using Prototypes. If you know what you are doing then ignore the hate you may get.

grave thistle
#

How do I add text from a language file to a text box in an ActionFormData(); UI?

cold grove
#

.body({ translate: 'my.body' })

neat hazel
#

system.runTimeout, system.runInterval, system.run
What is the difference between them and what are they for?

wary edge
viscid horizon
#

can I import whole js files into my entry file or can it only be constants and functions that can be exported

buoyant canopy
viscid horizon
buoyant canopy
#
import "./file.js"
viscid horizon
buoyant canopy
#

can you show a screenshot of your scripts folder?

#

and the script you have done the import in and the one you imported?

shy leaf
viscid horizon
shy leaf
#

are you sure the js files are in the same directory the main script file is in?

#

you can set the path if you didnt know

#

(though the content log should say something if the file wasnt there)

buoyant canopy
buoyant canopy
#

it should work then

subtle cove
#

What does the other files look like...

prisma shard
#

uh

#
const interval = system.runInterval(() => {
});


// the question is- do i need to put the variable here?
// because the interval is stored in a variable
// then how the code run, if its stored in a variable?
// i tried removing this "interval;", but it still work...
// does clearRun runs the variable, then stops it?
interval;


system.runTimeout(() => {
   // stop the runInterval after 1 second
   system.clearRun(interval);
},20);
```^
#

help me solve this confusion @valid ice

valid ice
#

?

prisma shard
#

i described the question in comments

#

in the code

#

//

distant tulip
#

🗿 learn js

prisma shard
#

why not explain that

#

the problem

distant tulip
#

you keep coming with stuff like this

prisma shard
#

but i am not asking for code

#

this channel is for solving anyone's confusion isnt it

valid ice
#

interval is a number which is the ID of the runInterval loop

distant tulip
#

the code is not stored in the variable the code run and return a number that we store in the variable
that number refer to that interval
look at it like this "hey i am ruining an interval with the id xxxx"
then when we want to clear it we can do that easily sense we have it "address"

valid ice
#

When you clearRun that variable, it stops the runInterval

neat hound
# prisma shard oh

you can also put the clearRun inside of the first interval if you add a timer```JS
let ctr=0
const runId = system.runInterval(() => {
if (ctr++ == 20) system.clearRun(runId);

<go do stuff here>

),1}```

prisma shard
neat hound
prisma shard
neat hound
#

yes

prisma shard
#

i wanna use for loop

neat hound
#

No, for loop goes fast

tiny tartan
#

use system.runTimeOut

prisma shard
neat hound
#

try it... see how many iterations of a for loop you get in a tick

#

It is best to test out your theories, that is how you learn... from experience

distant tulip
prisma shard
#
const interval = system.runInterval(() => { });
        
system.runTimeout(() => {
     system.clearRun(interval);
}, secondsToTicks(1.5));```
prisma shard
neat hound
#

Yes it may, but if you wanted to do something with the counter, then it is there. Either way works, just showing alternatives... there is even a 3rd way with a for loop and and just system.runTimout.

distant tulip
#

yeah
he is looking for something like a for loop, so i can see why is that better

neat hound
#

But for readability and maintainability by others, then the 1st way is best, no one has to guess what you are trying to do and make sure your math is correct.

neat hound
#

even if it is one

chrome flint
distant tulip
#

system.currentTick could also be used

last latch
#

onTestFailed: wasdhc:simulatedplayer - Failed to spawn test structure with path 'structures/wasdhc/simulatedplayer.mcstructure pops up whenever i run a gametest. I want to test something out using simulatedPlayer but for some reason it wants ot place a tst structure, can i avoid it?
code :

import { register } from "@minecraft/server-gametest";
register("wasdhc", "simulatedplayer", ((gameTestData) => { console.warn("ASd"); }));
neat hound
# chrome flint doesnt really need to

I know it does not need it, but best practice is to be clear in your intent. I try to w rite my code like someone else has to maintain it.... like the intern who does not know the details of the method

chrome flint
wary edge
last latch
subtle cove
#

Prob a special .mcstructure

distant tulip
#

there is one here

chrome flint
wary edge
#

Gametest isnt meant for normal addons

distant tulip
chrome flint
chrome flint
valid ice
#

Isn't there only one available version?

prisma shard
#

can anyone give me a delay function

chrome flint
prisma shard
#

that will delay some code to the desired ticks

#

..

prisma shard
chrome flint
warm drum
#

This is not exactly where to ask it but do u guy remember the hidden setting in BDS that allow certain command?

prisma shard
valid ice
#

idk

warm drum
#

Like the privilege level 4 setting

chrome flint
distant tulip
#

@warm drum

last latch
#

sorry for hte ping, forgot to turn off

prisma shard
#

so i gotta make a function myself

#

like waitTicks

#

that returns a promise

wary edge
#

Are you on edu or smthng?

distant tulip
#

-# not this talk again lol

chrome flint
#

i wonder why you can't update your minecraft loll

remote oyster
buoyant canopy
#

can we read the container of a chest in a saved structure without placing it? i assume the answer is no, because we can get the permutation, and not the block itself.

sudden nest
#

Can't you not reassign the movement component value of any entity? Like if i want this entity to not move? Since it's only read-only.

#

If we can't then sadge

prisma shard
grave nebula
#

is it possible to grab the items of a players inventory and see what item they are holding?

valid ice
#

It is possible, yes

grave nebula
#

how would i go about doing it

valid ice
#

const item = player.getComponent('equippable')?.getEquipment('Mainhand') will return an ItemStack

grave nebula
#

ah ok thanks

prisma shard
#

or also you can do it this way

grave nebula
#

how would i go about returning all the items as json and if you have like a list of the possible functions with that

#

like every inventory item

#

and like the amount, enchantments, etc

prisma shard
#

loop though the container

grave nebula
#

its not an array is it?

#

ive tried forEach with no luck

valid ice
#

You need to player.getComponent("inventory").container.getItem() for each slot

grave nebula
#

ah ok

valid ice
#
const container = player.getComponent("inventory").container;
for (let i = 0; i < container.size; i++) {
  container.getItem(i);
  //Other stuff
}```
prisma shard
#

BRO I SWEA-

valid ice
#

size should really be set before the loop as well

#

saves performance

grave nebula
#

alr

prisma shard
grave nebula
#

😭

prisma shard
#

lol\

valid ice
#

sadge

prisma shard
#

herobrine

#

hey

#

can u make a delay function for me @herobrine

valid ice
#

?

prisma shard
#

yeah,

prisma shard
#

so i have to make waitTicks function myslef

grave nebula
#
world.getAllPlayers().forEach(async player => {
  const container = player.getComponent("inventory").container;
  const size = container.size
  for (let i = 0; i < size; i++) {
    const item = container.getItem(i);
    if (!item) return;
    world.sendMessage(JSON.stringify({ typeId: item.typeId, amount: i, enchants: item.enchants }))
  }
})```

when running this it doesnt seem to grab weapons ex: diamond sword or a bow
#

and i wanted to test enchants with it

wary edge
#

You're going to have a hard time being stuck in an old version. Just update it. It's going to annoy a lot of people especially since you never specify the version you're using

wary edge
grave nebula
#

ok it still doesnt work with weapons

valid ice
#

Should work for everything

grave nebula
sharp elbow
#

(and you won't want to print i for amount, that's your iterating variable)

grave nebula
#

i just saw that 😭

#

fixed the amount

#

but still no bow showing up

#
world.getAllPlayers().forEach(async player => {
  const container = player.getComponent("inventory").container;
  const size = container.size;
  for (let i = 0; i < size; i++) {
    const item = container.getItem(i);
    if (!item) return;
    world.sendMessage(JSON.stringify({ typeId: item.typeId, amount: item.amount }))
  }
})```
valid ice
#

aside from the .enchants property, I do not see a problem there

grave nebula
#

damn

valid ice
#

ah wiat

wary edge
#

Is it the .size

valid ice
#

return would return

#

out of the function

wary edge
#

Ah

valid ice
#

You want to use continue

grave nebula
#

ah ok

#

yep works

#

thanks

#

😭 im slow sometimes

valid ice
#

the return is triggering on the first empty slot- essentially saying, "if this slot is empty, then stop this forEach iteration"

grave nebula
#

#1271187723486625833 i plan on making a inventory gatherer like this for easier use

sharp elbow
#

We didn't see it at first either. It's an easy mistake

prisma shard
prisma shard
#

I JUST DIDNT PUT RETURN,

#

thats why the function was not working lol

grave nebula
#

😭

#

what is the enderchest component id?

valid ice
#

welp

#

ShadyMoon stole your return

grave nebula
#

💀

valid ice
grave nebula
valid ice
#

womp womp fr

grave nebula
#

😭

#

was gonna make enderchest see

valid ice
#

Everyone and their grandmother wants it

sharp elbow
#

So the ender chest is outright not accessible?

valid ice
#

Only with commands

sharp elbow
#

Ah, fair. /replaceitem and such

grave nebula
#

it probably is thru replaceitem

valid ice
#

yep.

#

Very slow, many iterations, and can only access certain item data.

grave nebula
#

why has mojang been so closed up abt it

#

weve been asked for awhile 😭

valid ice
#

I am sure they're working on many things that the community wants

grave nebula
#

yea

#

right...

valid ice
#

script devs are pretty generous with features- if it exists, they would release it.

grave nebula
#

fair

#

but i couldnt imagine it not being possible

valid ice
#

it's definitely possible- it's accessible via commands, so it has to exist on some level.

grave nebula
#

mhm

valid ice
#

Priorities for script API at the moment is getting HCF & custom components out

grave nebula
#

hcf?

valid ice
#

DEATH TO HCF RAHHHHHHHHH

valid ice
grave nebula
#

what do those even do 😭

valid ice
#

Item & block components & events

#

Some components were made stable, others were tweaked and made stable, and events were completely removed in favour of custom components in script API

grave nebula
#

they need to make the getComponent a class so i can actually see what im doing instead of guessing if it exists 😭

valid ice
#

it autocompletes for me/

grave nebula
#

i dont get shi from it

umbral dune
#

Does ItemStack.prototype.setLore need system.run?

grave nebula
#

shouldnt

valid ice
#

It does

grave nebula
#

why 😭

umbral dune
#

(The answer is up to me, right?)

valid ice
#

setLore modifies the world, so if it's being used in a before event, it needs to be pushed to the next tick

#

If you are not using a before event, it does not need system run

prisma shard
grave nebula
#

is it possible to get an items enchants

umbral dune
wary edge
valid ice
# grave nebula

I see- it completes for me.
You can also use jsdocs to type cast the container variable.

grave nebula
prisma shard
valid ice
grave nebula
#

i have an old inventory see somewhere but i cant find it

valid ice
#

1.15.0-beta 😱

prisma shard
#

@grave nebula
i have a whole class,
which has methods like getEnchant, addEnchant, removeEnchant

wary edge
#

You dont need a custom class for that

prisma shard
#
import {EnchantmentTypes, ItemEnchantableComponent} from '@minecraft/server';

export class Enchantments {
    //returns an Array of Enchantments the itemStack has
    static getEnchants(itemStack){        
        let enchantmentsArray = [];
        if(!itemStack.hasComponent(ItemEnchantableComponent.componentId)) return []
        const eCompo = itemStack.getComponent(ItemEnchantableComponent.componentId);
        enchantmentsArray = eCompo.getEnchantments();
        return enchantmentsArray;        
    }
}

@grave nebula

grave nebula
#

thx

prisma shard
valid ice
#

Back in my day enchant component sucked to use

prisma shard
#

whats the time in ur area

valid ice
#

?

prisma shard
#

just curous

valid ice
#

1:22 pm

prisma shard
#

i am staring at my pc at midnight as always 🙂

umbral dune
#

What happens if the length of the string I put in setLore() is greater than 50 characters?

valid ice
umbral dune
#

funni

valid ice
#

Would be nice if it auto-truncated it

sharp elbow
sharp elbow
#

I guess I'm asking if we still need to pass an EnchantmentType instance to the type property

wary edge
valid ice
sharp elbow
#

Mm

grave nebula
#
world.getAllPlayers().forEach(async player => {
  const container = player.getComponent("inventory").container;
  const size = container.size;
  let inventory = []
  for (let i = 0; i < size; i++) {
    const item = container.getItem(i);
    if (!item) continue;
    const enchants = Enchantments.getEnchants(item) || [];
    inventory.push({typeId: item.typeId, name: item.name, lore: item.getLore(), amount: item.amount, placement: i, enchants: enchants})
  }
  world.sendMessage(JSON.stringify({ playerId: player.id, inventory: inventory}))
})```
how would i get the items name?
#

neither work

valid ice
#
const enchantment = item.getComponent('enchantments');
    const enchantmentList = enchantment.enchantments;
    for (const enchantType in enchants) {
        enchantmentList.addEnchantment(new Enchantment(enchantType, enchants[enchantType] || undefined));
    }
    enchantment.enchantments = enchantmentList;
``` from an old script of mine
grave nebula
#

its nameTag isnt it

valid ice
#

yes

grave nebula
#

yep

#

hmm

#

it still doesnt work

valid ice
#

You can't get the lang file definition for the name, if that's what you're after

grave nebula
#

oh

valid ice
#

e.g. "Blackstone Bricks"

grave nebula
#

damnit

#

😭

valid ice
#

Gotta format the typeId

grave nebula
valid ice
#

Or manually map all typeIds to their respective names

valid ice
grave nebula
#

oh god

#

i mean it works

#

🤷‍♂️

valid ice
#

Removes the namespace, replaces underscores with spaces, and capitalizes the start of each word

grave nebula
#

W

#

regex >

valid ice
#

real

#

Regex helped me do custom enchants from item lore back in the day

#

fun (& laggy) times

grave nebula
#

ok slight issue

#

when i have items with data ex: red sand what would i grad

#

grab*

#

item.data?

valid ice
#

can't

grave nebula
#

bru

wary edge
#

Wait for the flatenning

valid ice
#

No way to get that, unfortunately

grave nebula
#

😭 wtf mojang

#

how would i add a item/remove one from the player inventory?

valid ice
#

transferItem, moveItem, etc

umbral dune
#

help? the lore doesn't appear on my item, what gamerule do I have to enable to show the lore of my item?

valid ice
#

No gamerule needed

#

Are you setting the item back after updating the lore?

umbral dune
#
system.run(() => {
        const result = `§7source position set to §s${target.x} ${target.y} ${target.z}§r`.replace(/(?![^\n]{1,49}$)([^\n]{1,49})\s/g, "$1\n");
        e.itemStack.setLore(typeof result === "array" ? result : [result]);
        inventory.setItem(e.player.selectedSlotIndex, e.itemStack);
      });
umbral dune
valid ice
#

Maybe try defining the itemstack & the player as a variable outside of the system run

umbral dune
#

do you mean that?

system.run(() => {
        const result = `§7source position set to §s${target.x} ${target.y} ${target.z}§r`.replace(/(?![^\n]{1,49}$)([^\n]{1,49})\s/g, "$1\n");
        e.itemStack.setLore(typeof result === "array" ? result : [result]);
      });
      inventory.setItem(e.player.selectedSlotIndex, e.itemStack);
valid ice
#

player & item

#

and outside the system run

umbral dune
#

I don't understand

valid ice
#

const itemStack = e.itemStack;
const player = e.player;

#

And work with those instead of the event variables

umbral dune
#

hm, I'll do that, if it works I'll let you know

#

@valid ice it didn't work, and I had to change all variables that had the name "block" to avoid conflicts.

valid ice
#

ah lol

umbral dune
#

I guess there's nothing I can do. ⚔️

grave thistle
#

Do translation keys not work for slider labels on modal UI forms? Every other aspect works like toggles and buttons, but slider just display the key and not the key's value

#

Slider key is config_UI_1.slider_1 both in my script and the en_US language file

#

Also noticed the key doesn't work for the textbox on action form UI

untold magnet
#

sup guys

#

well, I'm trying to do something a little bit complicated

#

making the new custom blocks always has the regular statements, but when the player starts looking at the block, the statement will be changed in a specific case, but when the player looks around the block it will automatically change into the regular statement

#

without using "minecraft:ticks" or custom block components

#

i might not be doing that for now, cuz maybe mojang will introduce it later i mean who knows :/

devout dune
#
    at <anonymous> (bundle.min.js)
    at forEach (native)
    at createSystems (bundle.min.js:1)
    at init (bundle.min.js:1)
    at <anonymous> (bundle.min.js:1)

Hey! @wary edge any idea why im getting an undefined error here!
Im sure its the second event im subscribing to, because i get no error when it is commented out

wary edge
devout dune
wary edge
devout dune
devout dune
random flint
#

playerInteract is beta

devout dune
random flint
#

switch to beta in the manifest json

devout dune
random flint
#

wdym

#

entityHitEntity is stable iirc

distant tulip
#

maybe try item use and get entity from view

devout dune
#

so the onInteract

gray tinsel
buoyant canopy
buoyant canopy
#

does it fire on entities?

#

it doesn't fire on blocks for sure.

distant tulip
#

huh
i tested it it blocks

#

are you using itemUseOn?

buoyant canopy
#

how did your test go exactly? i used afterEvents.itemUse to detect when i use an item on a block that isn't normally interactable and it didn't detect it.

#

the item also doesn't have interactions

#

the after event only fires when i am looking away from a block

distant tulip
#

itemUse always fire on use
i used that and getBlockFromViewDirection

buoyant canopy
#

are you sure about that?

neat hazel
#

Why doesn't it work?

mc.world.afterEvents.playerSpawn.subscribe(eventData => {
  const player = eventData.player
  if (eventData.initialSpawn) {
    worldInitialized(player)
  }
})
distant tulip
#

yeah?
let retest that

subtle cove
#

Item right click triggers ItemUse on block or air

distant tulip
subtle cove
#

Getblockview is just 2nd approach

subtle cove
buoyant canopy
#

i would retest as well when i can

buoyant canopy
neat hazel
shy leaf
oak lynx
#
world.beforeEvents.playerPlaceBlock.subscribe(data => {
    const loc = data.block.location
    console.warn(!isLocInPlayerIsland(loc, data.player))
    if (isInMapRegion(loc) && data.player.getGameMode() == GameMode.survival) {
        if (!isLocInPlayerIsland(loc, data.player)) {
            data.cancel = true
        }
    }
})

all the functions work properly as in they return true and false at the right moments

distant tulip
buoyant canopy
shy leaf
#

if it works, then you didnt make the form to check for cancel

shy leaf
#

itll open the form by their own, since the form was already told to do that

neat hazel
shy leaf
#
function dcConfig(player) {
    let form = new ModalFormData()
    .title("Dungeons Combat Settings")
    .toggle("Toggle Mod\n(You can use compass to open this menu.)", player.getDynamicProperty("dc_state"))
    .slider("Camera Distance", 15, 30, 1, player.getDynamicProperty("dc_camdist"))
    .slider("Camera Position", 1, 4, 1, player.getDynamicProperty("dc_campos"))
    .slider("Camera Lerp", 10, 50, 5, player.getDynamicProperty("dc_camlerp"));  
    form.show(player).then((response) => {
        const { canceled, formValues, cancelationReason } = response;
        if (response && canceled && cancelationReason === "UserBusy") {
            dcConfig(player);
            return;
        }
        if (canceled) return;
        player.setDynamicProperty("dc_state",formValues[0])
        player.setDynamicProperty("dc_camdist",formValues[1])
        player.setDynamicProperty("dc_campos",formValues[2])
        player.setDynamicProperty("dc_camlerp",formValues[3])
        if (player.getDynamicProperty("dc_state") == true) {
            setcamera(player)
        } else {
            clearcamera(player)
        }
    })
    }

this is my modal form

neat hazel
shy leaf
#

you can just put it inside a runinterval with a check

#

to test it

#

(if you dont mind)

amber granite
#

No way

buoyant canopy
remote oyster
#

Put the form in a function. Call it in a spawn event. Verify if it's their initial spawn. Then call the function for the form. Verify if the user is busy. If they are, then recall the function. It will loop without creating a memory leak. When they are no longer busy the form will pop up on their screen.

neat hound
# neat hazel Open an ActionForm when the player enters the world

It may be too soon, either push it out a few secs in ticks ... or do a sendMessage to see if stuff can be seen at that time yet. I did something where I let them know where they last died when they re-log back on in case they did not choose to respawn at that time. I had to push the message 40 ticks.

subtle cove
#

I'm not reading essays, am i...

shy leaf
# shy leaf ```js function dcConfig(player) { let form = new ModalFormData() .title(...
form.show(player).then((response) => {
        const { canceled, formValues, cancelationReason } = response;
        if (response && canceled && cancelationReason === "UserBusy") {
            dcConfig(player);
            return;
        }
        if (canceled) return;
        player.setDynamicProperty("dc_state",formValues[0])
        player.setDynamicProperty("dc_camdist",formValues[1])
        player.setDynamicProperty("dc_campos",formValues[2])
        player.setDynamicProperty("dc_camlerp",formValues[3])
        if (player.getDynamicProperty("dc_state") == true) {
            setcamera(player)
        } else {
            clearcamera(player)
        }
    });```
#

just use this as an example

oak lynx
# oak lynx ```ts world.beforeEvents.playerPlaceBlock.subscribe(data => { const loc = da...
world.beforeEvents.playerPlaceBlock.subscribe(data => {
    const loc = data.block.location
    const player = data.player
    if (player.getGameMode() == GameMode.survival) {
        if (!isLocInPlayerIsland(loc, player) || isInMapRegion(loc)) data.cancel = true
    }
})

i doubt anyone will ever search for anything like this ever but i feel like sending the solution anyways (dont do conditions at 2am it doesnt end well)
canceling block placement when outside plot and spawn

neat hound
#

Helps if you add a subject,.,, for the search

#

nice code tho

distant tulip
#

@buoyant canopy

world.afterEvents.itemUse.subscribe(e=>{
  const b = e.source.getBlockFromViewDirection()?.block??e.source.getEntitiesFromViewDirection()[0]?.entity
  console.warn(b?.typeId);
})
buoyant canopy
distant tulip
#

latest stable

oak lynx
buoyant canopy
#

i did my test in a 1.21.10 preview

oak lynx
shy leaf
subtle cove
shy leaf
#

ok suggestion

oak lynx
distant tulip
shy leaf
#

you must stop it before it becomes unstoppable

buoyant canopy
amber granite
buoyant canopy
distant tulip
#

or itemUseOn

buoyant canopy
amber granite
#

But

shy leaf
amber granite
#

Hmm did u try itemUseOn ?

shy leaf
#

iirc you need to use beforeEvents.worldInitialize for item's custom components

subtle cove
#

itemStartUseOn

buoyant canopy
amber granite
#

Hmmm , but

#

The vault interaction it just like bonemeal

#

Bonemeal on grass block

distant tulip
distant tulip
buoyant canopy
#

that clears things, so does the itemUseOn fires when using a trial key on a used Vault?

oak lynx
#

i did it once for a box pvp server

#

never again

sudden nest
#

I literally organized my project structure with guilt in my heart just because I saw a large project that is organized xp

shy leaf
wary edge
sudden nest
#

Decoupling files into another files from other folders = ☠️

oak lynx
wary edge
distant tulip
oak lynx
shy leaf
amber granite
#

switch(x){
case🐫 : console.log("camelCase")
break;
}

strange dagger
sudden nest
# shy leaf Why

I mean I use index.ts/js (for each directory to just easily import it, but still need to exclude some coupled files, so it doesn't blow up) so it's really hard and time consuming for me

buoyant canopy
#

i keep each feature in its dedicated file

shy leaf
buoyant canopy
strange dagger
# shy leaf what did you use to despawn the shark
"minecraft:despawn": {
                "despawn_from_chance": false,
                "despawn_from_distance": {
                    "min_distance": 10000,
                    "max_distance": 999999
                },
                "despawn_from_inactivity": false,
                "despawn_from_simulation_edge": false,
                "min_range_inactivity_timer": 30,
                "min_range_random_chance": 800,
                "remove_child_entities": false
            },
shy leaf
#

oh i thought it was scripts

amber granite
distant tulip
random flint
buoyant canopy
strange dagger
distant tulip
buoyant canopy
#

ye

#

but every other block in the game is 😂

distant tulip
#

kinda wired

shy leaf
#

you could use that

#

and then use scripts to despawn sharks instead

buoyant canopy
sudden nest
strange dagger
shy leaf
distant tulip
strange dagger
shy leaf
#

put that inside entity json

sudden nest
#

Yippee my discord following to dev and script resources post now works

strange dagger
buoyant canopy
#

like : minecraft:behavior.random_swim

strange dagger
random flint
strange dagger
random flint
#

The actual entity was out of the player camera, so Minecraft unloaded the model for performance

strange dagger
shy leaf
#

try increasing the entity's collision box or hitbox

pale terrace
#

Is it possible to make an item unable to be picked up?

random flint
shy leaf
subtle cove
shy leaf
#

nvm then

pale terrace
#

damm it

#

You can't apply animations to an item using playanimation either, right? I tried but I didn't get any results

shy leaf
#

you can filter out items and play animations on player

#

but you cant apply animations on item

pale terrace
pale terrace
shy leaf
#

then no

chrome flint
pale terrace
chrome flint
#

mines compatible with any item lol including custom ones from other addons

pale terrace
chrome flint
#

then display the item in it

pale terrace
#

thank you!

pale terrace
chrome flint
pale terrace
chrome flint
#

each entity can display 1-2 item, mainhand and offhand

#

if that's what you mean

pale terrace
chrome flint
pale terrace
#

nice

#

thank you!

true isle
#

is on random tick before or after event?

shy leaf
#

this lists the afterevents ordering

#

theres also beforeevents orders so you could check that

viscid horizon
#

would this work or is it stupid

subtle cove
subtle cove
#

Practice the native methods, madudes

#

applyDamage

amber granite
#

This is not even runCommands ☠️

viscid horizon
#

I got lazy

subtle cove
#
[{families:["infantry"]}, {type:"ata:vehicle"}, {type:"ata:aircraft"}]
.forEach(q => {
    if (target.matches(q)) target.applyDamage(125, {cause:"override"}) 
}) ```
viscid horizon
subtle cove
#

Those {} are just EntityQueryOptions

viscid horizon
#

where uh would I fit these

subtle cove
#

Just at the target.runCommand

#

Replace it there

#
if (target....) {
    [{}].forEach... 
} ```
viscid horizon
#

okay 👍

viscid horizon
#

what if I want to damage each families with different amounts of damage?

subtle cove
#
[{families: ["infantry"]}, {families: ["mob"]}, ...othrstuff]
``````js
const dmgs = {
    infantry: 100,
    mob: 50
}    
``````js
const dmg = dmgs[q.families?.[0]] ?? 125
target.applyDamage(dmg, {cause: "override"}) 
grave thistle
#

Why isn't this displaying the message? It only displays the translation keys + whatever is within the ${}

entity.sendMessage({ translate: `seeker_wand.scan_message_1`.concat(` `, `seeker_wand.scan_1`, ` `, `${i}`, ` `, `seeker_wand.scan_message_2`, ` `, `${bSide}!`) });

#

Doesn't work removing .concat and adding + between the keys

grave thistle
# shy leaf that?

In game it's displayed as "seeker_wand.scan_message_1 seeker_wand.scan_1 999 seeker_wand.scan_message_2 East"

near siren
#

When someone teleports far away and they're just in 'limbo' for a couple of seconds, is this just a realm thing or a general thing? Made a script for my realm and it takes a while before people can move after teleporting

shy leaf
#

oh

#

thats cuz stuff inside

` `

is stringified

chrome flint
shy leaf
#

whatcha trying though

near siren
shy leaf
grave thistle
shy leaf
#

and on top of that, i dunno what concat is

#

can you tell me about it

grave thistle
#

.concat() is just a simpler was of adding strings without using +

shy leaf
#

i think the game is seeing the strings as whole

#

except for ${} part

grave thistle
#

So msgVar.concat("string1", "string2") would add the string in the msgVar variable, string1 and string2 together

subtle cove
#

translate each seeker wand

chrome flint
grave thistle
#

Oh, so concat each { translate: "example" }

#

Instead of all together

shy leaf
#

sounds like a big fat line is coming right up

chrome flint
#

idk if % templates still works for translate strings

subtle cove
#
{rawtext:[{translate:'wand.e'},{translate:'wand.g'}]}
chrome flint
grave thistle
#

Between each translate key brackets

chrome flint
#
let rawmessage = {
  rawtext:[
    {translate:'seeker_wand.scan_message_1'},
    {text: ' '},
    {translate:'seeker_wand.scan_1'},
    {text: ' ${i} '},
    {translate:'seeker_wand.scan_message_2'},
    {text: ' ${bSide}!'},
  ]
}

entity.sendMessage(rawmessage);
#

@grave thistle

grave thistle
mellow socket
#

Is there a way to give a custom model to the Agent in EE?
or make a custom agent? (as in like a new entity)

near siren
#

Will see it in the morning, but having trouble writing a promise that waits for a player to load in and return them.

wary edge
remote oyster
remote oyster
# near siren Will see it in the morning, but having trouble writing a promise that waits for ...

This code is untested and based on the assumption that teleporting a player triggers the playerSpawn event. If this assumption holds true, you can listen to the playerSpawn event before teleporting the player. After teleportation, you can verify in the event handler whether the spawned player matches the one being teleported. If they are a match, you can resolve the promise and proceed with other actions.

import { world, Player, Dimension, Vector3, PlayerSpawnAfterEvent } from "@minecraft/server";

/**
 * Teleports a player and returns a promise that resolves when the player has fully loaded.
 * @param player - The player to teleport.
 * @param location - The destination coordinates.
 * @param dimension - The dimension to teleport the player to (optional).
 * @returns A promise that resolves when the player has fully loaded.
 */
function teleportPlayer(player: Player, location: Vector3, dimension?: Dimension): Promise<void> {
    return new Promise((resolve, reject) => {
        try {
            // Subscribe to the playerSpawn event before teleporting
            const playerSpawnSubscription = world.afterEvents.playerSpawn.subscribe((event: PlayerSpawnAfterEvent) => {
                if (event.player.name === player.name) {
                    // Unsubscribe from the event after the player has spawned
                    world.afterEvents.playerSpawn.unsubscribe(playerSpawnSubscription);
                    resolve();
                }
            });

            // Teleport the player
            player.teleport(location, dimension);
        } catch (error) {
            reject(error);
        }
    });
}

// Usage
const player = world.getPlayers()[0];
const location = { x: 100, y: 20, z: 100 };

teleportPlayer(player, location)
    .then(() => {
        console.log("Player has fully loaded after teleporting.");
        // Proceed with further actions
    })
    .catch((error) => {
        console.error("Failed to teleport player:", error);
    });
#

This is only a theory to experiment with. If it works then you have a potential solution. If not, then it's back to the drawing board.

#

I may also add, you can check player.isValid(), and if it returns false, call your function to loop back until it returns true. Once true, you know you should be safe to execute code off the player as needed.

alpine ibex
#
import { EntityType } from 'net/minecraft/entity/EntityType';
import { AttributeModifierMap } from 'net/minecraft/entity/ai/attributes/AttributeModifierMap';
import { EntityAttributeCreationEvent } from 'net/minecraftforge/event/entity/EntityAttributeCreationEvent';
import { SubscribeEvent } from 'net/minecraftforge/eventbus/api/SubscribeEvent';
import { Attributes } from 'net/minecraft/entity/ai/attributes/Attributes';

class AkazaEntity {
    static EntityAttributesRegisterHandler = class {
        @SubscribeEvent
        onEntityAttributeCreation(event) {
            const attributes = new AttributeModifierMap.MutableAttribute();
            attributes.createMutableAttribute(Attributes.field_233821_d_, 0); // Example attribute
            // Add more attributes as needed
            event.put(EntityType.AKAZA, attributes);
        }
    }
}
#

Does this work?

shy leaf
#

is that for java?

alpine ibex
#

Bedrock

shy leaf
#

thats for bedrock?

alpine ibex
shy leaf
#

i mean for me i dont know cuz

#

there are class that ive never seen before

cold grove
#

Some features of js are unavailable

alpine ibex
cold grove
#

Any version

alpine ibex
#

Also I'm going to try do scripting since my demons slayer mod will break in 1.21.20 which is very sad

#

I will crash out

prisma shard
shy leaf
#

tell me

cold grove
#

Chatgpt

shy leaf
#

where did you get that

prisma shard
#

please don't use chatGPT for bedrock script api

alpine ibex
shy leaf
#

have you

#

checked the script api docs

prisma shard
shy leaf
#

?

#

i mean

prisma shard
shy leaf
#

minecraftforge? spyBruh

cold grove
#

Those routes looks like java modding

alpine ibex
shy leaf
cold grove
#

Oh bibble

prisma shard
shy leaf
#

like

#

i dunno what youre trying to do either

#

you never mentioned that except "does this work"

prisma shard
prisma shard
neat hound
sudden nest
woven loom
alpine ibex
#
// Define the rotation angles for the swinging animation
const swingAngles = [0, 30, 60, 90, 60, 30, 0];

// Function to perform the swinging animation
function performSwingAnimation(entity) {
    let swingIndex = 0;

    const swingInterval = setInterval(() => {
        // Rotate the entity's arm or any other part based on the swingAngles array
        // In this example, we are rotating the entity's yaw (horizontal rotation)
        entity.yaw = swingAngles[swingIndex];

        // Increase the swing index for the next angle in the array
        swingIndex++;

        // If the end of the swingAngles array is reached, clear the interval to stop the animation
        if (swingIndex >= swingAngles.length) {
            clearInterval(swingInterval);
        }
    }, 100); // Adjust the interval duration to control the speed of the animation
}

// Call the performSwingAnimation function when you want to trigger the swinging animation
// For example, when a player swings a sword or attacks
performSwingAnimation(playerEntity); // Pass the entity object that you want to animate

I made something that makes the player constantly swing 😔🙏

shy leaf
#

used for loop