#Script API General

1 messages · Page 31 of 1

subtle cove
#

just say them name ;-;

cold grove
#

I think you make your script only asking here isnt?

buoyant canopy
#

yeah, this one is better

untold magnet
#

i think rItems?.itemStack?.typeId should fix it

amber granite
#

My brain

quick shoal
#

Ok

#

Anyway, I will try rItems?.itemStack?.typeId

buoyant canopy
subtle cove
#

that works a swell

cold grove
quick shoal
#

Which is better

#

Ok I use this
getEntities({type:'item'})

#

Thanks for yall

untold magnet
#

lemme see

subtle cove
#

come again after another bug
we'll torture thy bugs

amber granite
untold magnet
#
import { system } from '@minecraft/server';

const eItems = ['minecraft:diamond'] // add the items ID's here
system.runInterval(() => {
  const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
    for (const item of world.getDimension(dim).getEntities({ type: 'item' })) {
      if (eItems?.includes(item?.typeId)) item.remove();
    };
  });;
});;```
#

like so?

quick shoal
#

I think this is real problem

gaunt salmonBOT
# untold magnet ```js import { system } from '@minecraft/server'; const eItems = ['minecraft:di...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 1 errors:

<REPL0>.js:6:24 - error TS2304: Cannot find name 'world'.

6     for (const item of world.getDimension(dim).getEntities({ type: 'item' })) {
                         ~~~~~

Lint Result

ESLint results:

<REPL0>.js

5:9 error 'dimension' is assigned a value but never used @typescript-eslint/no-unused-vars

quick shoal
subtle cove
gaunt salmonBOT
# quick shoal

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 2 errors:

main.js:99:1 - error TS1128: Declaration or statement expected.

99 });
   ~

``````ansi
main.js:99:2 - error TS1128: Declaration or statement expected.

99 });
    ~

Lint Result

ESLint results:

main.js

99:0 error Parsing error: Declaration or statement expected

quick shoal
buoyant canopy
quick shoal
untold magnet
#

it should remove the item entity from all dimensions not only overworld or nether

subtle cove
untold magnet
#

I'll go eat something

#

im so hungry

buoyant canopy
untold magnet
buoyant canopy
quick shoal
#

I'm just remove the
const dimension = [...

untold magnet
quick shoal
#

I'm just want to avoid player drop the item in ui

untold magnet
#

so u need the dimensions

untold magnet
#

avoid more issues

buoyant canopy
#

switch the map with a forEach ```js
import { system } from '@minecraft/server'

const eItems = ['minecraft:diamond']
system.runInterval(() => {
['overworld', 'nether', 'the_end'].forEach(dim => {
const dimension = world.getDimension(dim)
const items = dimension.getEntities({ type: 'item' })
for (const item of items) {
if (eItems?.includes(item?.typeId)) item.remove()
}
})
})

quick shoal
#

And the code is finally working without any error now!!!

buoyant canopy
#

nice

subtle cove
#

now roam far around then use the stick

buoyant canopy
# quick shoal No need my map doesn't allow player go to nether or end

you could use this if you only want to remove the items in the overworld

import { system } from '@minecraft/server'

const eItems = ['minecraft:diamond']
const overworld = world.getDimension('overworld')

system.runInterval(() => {
  const items = overworld.getEntities({type: 'item'})
  items.forEach(item => {
    if (eItems.includes(item.typeId)) item.remove()
  })
})
warm mason
#
import { system } from '@minecraft/server'

const eItems = ['minecraft:diamond']
const overworld = world.getDimension('overworld')

system.runInterval(() => {
  const entities = overworld.getEntities({type: 'item'})
  entities.forEach(entity => {
    let item = entity.getComponent("minecraft:item").itemStack
    if (eItems.includes(item.typeId)) entity.remove()
  })
})```
amber granite
#

@subtle cove

subtle cove
amber granite
#

The code u gave me

#

Works in an odd way

#

How to fix that

#

So lemme clear something

subtle cove
#

make a post 1st

amber granite
#

Ok

subtle cove
#

this seems like a long conv

amber granite
#

Done

olive rapids
#

Hi, can someone help me edit a script? I don't know how the script works, and I'm looking for someone to fix the script of an addon that performs the function of a kits item.

quick shoal
#

Guys who can tell me how to add an owner to an entity with inventory components. And also only the owner can open the entity inventory.

subtle cove
quick shoal
#

So I need to add a lock at each UI entity

#

Can I use this??
playerInteractWithEntity

subtle cove
#

yeah...

quick shoal
# subtle cove yeah...
world.beforeEvents.playerInteractWithEntity.subscribe((eventData) => {
    const player = eventData.source;
    const entity = eventData.entity;
    if (entity.typeId === 'chest:ui') {
    const ownerId = entity.getDynamicProperty('id');
    if (ownerId !== player.id) {
    eventData.cancel = true
    }
  }
});
quick shoal
quick shoal
#

Every time debugger go offline just when I want to test the code

granite badger
#

You might wanna start using vscode and typescript to help you scripting

random flint
#

why not just test in-game?

quick shoal
subtle cove
gaunt salmonBOT
# quick shoal

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 1 errors:

main.js:31:32 - error TS2551: Property 'setActionbar' does not exist on type 'ScreenDisplay'. Did you mean 'setActionBar'?

31         player.onScreenDisplay.setActionbar(`§c- 此箱子UI 擁有者為${ownerId}\n請遠離此處再嘗試開啟你的箱子UI!`);
                                  ~~~~~~~~~~~~

  @minecraft/server.d.ts:14174:5
    14174     setActionBar(text: (RawMessage | string)[] | RawMessage | string): void;
              ~~~~~~~~~~~~
    'setActionBar' is declared here.

Lint Result

ESLint results:

main.js

81:19 warning The /clear command can be fully replaced with the Container.clearAll api in the @minecraft/server module. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/container#clearall for more information. minecraft-linting/avoid-unnecessary-command

91:19 warning The /clear command can be fully replaced with the Container.clearAll api in the @minecraft/server module. See https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/container#clearall for more information. minecraft-linting/avoid-unnecessary-command

subtle cove
#

#debug-playground ;-;

quick shoal
amber granite
#

Does anyone know how getEntities volume works ?

subtle cove
amber granite
#

What dx means ._.

subtle cove
#

from the location to the other side of the cube

#

the distance

amber granite
#

Yeah it dosen't work tho

#

I put it 80 i got 94 ._.

#

Hilp

#

Wtf is that

#

Hilp

crude bridge
#

who has all the file of the last version of mc bedrock?

random flint
#

why?

crude bridge
#

i want to check something

random flint
#

Do you mean the vanilla pack (behavior/resource) or the full game? cus I don't see a point to downgrade

wary edge
drifting ravenBOT
crude bridge
granite badger
#
poll_question_text

For people that uses my Script API Docs: Thoughts on current state of ads?

victor_answer_votes

11

total_votes

19

victor_answer_id

3

victor_answer_text

I use an ad blocker

random flint
past blaze
#

I don't think this is a good idea

#

Vanilla blocks aren't the only ones with block states. This is too restrictive

chrome flint
#

does herobrine chest ui also displays shulker boxes' items on lores?

granite badger
#

i agreed

wary edge
granite badger
#

so who's gonna give feedback to them

past blaze
#

@spring axle? (Is it ok if I ping you for this)

valid ice
wary edge
#

I think this previews types are messed up. Compostable on itemstack being one of them.

granite badger
#

block states types have been released for a while now, i adapted some of the changes to jaylybot a while ago

spring axle
granite badger
#

Some types support custom states and some don’t at the moment. Kinda annoyed at the inconsistency

spring axle
#

You can get around it like this for now: const age = perm.getState('design:crop_age' as keyof BlockStateSuperset);

distant gulch
#

Is this BDS only?

world.broadcastClientMessage('cm:sayMessage_1', 'hello');

world.afterEvents.messageReceive.subscribe(({ id, message, player }) => {
    world.sendMessage(`player: ${player.name}`);
    world.sendMessage(`id: ${id}`);
    world.sendMessage(`message: ${message}`);
});
#

Becuause it isnt working

#

@valid ice

valid ice
#

Why me

distant gulch
valid ice
#

I don't know the answer

wary edge
#

Hilarious.

fiery solar
granite badger
#

It's for internal use only

distant gulch
#

hmmm okay thanks

amber granite
woeful turtle
# past blaze I don't think this is a good idea

We started a bit restrictive, but we're going to likely tweak this to be both permissive to unknown keys, and maybe to allow the ability to specify custom type mappings (if for example you have a set of typescript types for stuff you build).

granite badger
#
BlockStateArg<T>: T extends `${MinecraftBlockTypes}`
    ? T extends keyof BlockStateMapping
        ? BlockStateMapping[T]
        : never
    : Record<string, boolean | number | string>

This type used in BlockPermutation matches and resolve functions supports custom states which is nice

wary edge
amber granite
#

Hey i have notes for everyone

#

Anyone that gonna use
getEntities volume query option in that method, must know { u must subtract 14 from x , y , z of ur volume } to get the intended volume

#

Because it is bugged

thorn flicker
#

🐛

wary edge
#

That doesn't seem right.

#

In any case then make a bug report at Mojira.

amber granite
#

I have no mojira account

thorn flicker
amber granite
#

Maybe tomorrow

amber granite
sharp elbow
#

Can you share a snippet of how you used the method?

amber granite
#

._.

#

Sorry i recaculate the difference it was 13

#

@sharp elbow

#
function getEntitiesMethodCorrectVolume(vector) {
return { x : vector.x-13, y: vector.y - 13 , z : vector.z - 13
}
}
sharp elbow
#

Can you share where you originally calculated the volume? In getEntities?

amber granite
sharp elbow
#

This still doesn't help me. I want to see what exactly you plugged into getEntities(), in your script. You should not need to subtract anything for it to work

amber granite
#

I didn't plug anything lol

#

I just writed as that

sharp elbow
#

It's a figure of speech. What exactly did you write in getEntities()?

thorn flicker
#

lol

amber granite
#
function entitiesArray(dimension, entityType, loc) {
let loca = ChunkCenter(loc);
loca.x -= 40;
loca.z -= 40;
  let entities = dimension.getEntities({
    type: entityType,
    location: loca,
    volume: { x: 80, y: 80, z: 80 },
    
  });
  return entities;
}
#

Lol

#

I literally didn't plug anything in it

#

After i tested it in the game i found there was 13 blocks difference

#

Between the volume i put is an an argument

#

And the tested volume in the game

#

It s a bug

sharp elbow
#

Let's pretend ChunkCenter() returns {x: 16, y: 0, z: 16}, which is then subtracted by 40 on the x- and z-axes. This should then select entities in a volume between (-24, 0, -24) and (-24 + 80, 0 + 80, -24 + 80), which can be written as (56, 80, 56)

#

Is that not the behavior you are seeing?

amber granite
#

The volume property using
Dx , dy , dz

#

Not the subtraction of the vectors in location and volume property

amber granite
#

It Is not the area of subtractions

sharp elbow
#

Sorry, I meant to say it selects entities in the volume

amber granite
#

Volume it still a cube 80x80x80

#

It won't change

#

Even if u put the location -8288 , -82838 - ,82828

#

U understand?

distant tulip
#

the volume is relative to the location

amber granite
#

Yes exactly

#

☠️ my English isn't englishing very well

distant tulip
#

so?

amber granite
#

So i put 80 , 80 ,80 and i got 94 , 94 , 94

#

After i subtract 13 and put 67 as an argument

#

I got 80

#

X80 x80 cube

sharp elbow
#

Have you sent the location of loca to the log to verify the selection is too big?

amber granite
#

So the method is bugged

distant tulip
#

let me try that

#

that shouldn't change anything

amber granite
#

The location is not a factor that changes the volume

#

The volume will still be as u put it

sharp elbow
#

The location does change where the volume is positioned, though. So if the position is not where you expect it, it could appear as if the volume is wrong

amber granite
#

Ok lemme draw u something

sharp elbow
#

I'm well aware of how it works, I don't need an illustration. I appreciate the notion though

amber granite
#

I made a script

#

That make an entity spawn whenever i place a block

#

And that entity won't spawn until it s outsidr the first entity volume

#

So it can't be my fault

sharp elbow
#

"first entity volume," is this an entity's collision box? or something else

amber granite
#

No the volume i selected

amber granite
#

Yes

#

I used that code to check

if ( entitiesArray(arguments).length === 0 ) {
// A code that spawns the entity
}
cinder shadow
#

getEntities is definitely not broken, I'm trying to understand what the issue is

sharp elbow
#

What version of Minecraft and the script API are you using?

amber granite
#

1.15.0

#

Stable

#

And it shows me in my console that it s promoted to 1.16.0

cinder shadow
#

It wasn't broken in either of those versions

amber granite
#

It is

#

I think

#

We can make a function for that with this formula:
ax+b

cinder shadow
#

there is a 0.1% chance that they mistakenly include something that makes you have to subtract 14 from every coordinate to get the correct position

#

Have you tried it with other numbers?

#

Does that discrepancy change?

#

I have several things that I had built out using getEntities in those versions that work perfectly fine

amber granite
#

Yes i tried 50 i got 63

sharp elbow
#

Here is a quick test I threw together for this. There are fou rcases: one inside the volume, and three just outside it, plus five on a given axis. This should be within the "13" measure you ran into issues with.

#

Let's see if I can get Discord to comply

amber granite
#

I created a function for that

sharp elbow
#
function VecSub(vec1, vec2) {
    return {
        x: vec2.x - vec1.y,
        y: vec2.y - vec1.y,
        z: vec2.z - vec1.z
    }
}
function findEntitiesTwoCorners(dimension: Dimension, type, vec1, vec2) {
    const Volume = VecSub(vec1, vec2);
    console.warn(`location: (${vec1.x}, ${vec1.y}, ${vec1.z})\nvolume: (${Volume.x}, ${Volume.y}, ${Volume.z})`)
    return dimension.getEntities({
        type,
        location: vec1,
        volume: VecSub(vec1, vec2)
    });
}
function test() {
    const Overworld = world.getDimension('overworld');
    const EntityType = 'minecraft:pig';
    const Corner1 = {x: -10, y: 0, z: 10};
    const Corner2 = {x: 5, y: 20, z: 30};
    console.warn(`Executing test. Corners: (${Corner1.x}, ${Corner1.y}, ${Corner1.z}) and (${Corner2.x}, ${Corner2.y}, ${Corner2.z})`)

    //Case 1: Inside volume
    const Pig1 = Overworld.spawnEntity(EntityType, {x: -5, y: 10, z: 20});
    Pig1.nameTag = 'Inside'

    //Case 2: Outside volume, +x
    const Pig2 = Overworld.spawnEntity(
        EntityType,
        VecSub({x: -5, y: 0, z: 0}, Corner2)
    );
    Pig2.nameTag = 'Outside, +x'

    //Case 3: Outside volume, +y
    const Pig3 = Overworld.spawnEntity(
        EntityType,
        VecSub({x: 0, y: -5, z: 0}, Corner2)
    );
    Pig3.nameTag = 'Outside, +y'

    //Case 4: Outside volume, +z
    const Pig4 = Overworld.spawnEntity(
        EntityType,
        VecSub({x: 0, y: 0, z: -5}, Corner2)
    );
    Pig4.nameTag = 'Outside, +z'

    console.warn(
        ...findEntitiesTwoCorners(Overworld, EntityType, Corner1, Corner2)
            .map(_ => _.nameTag)
    );

}

test()
#

I reduced the case count to 4 so this server would like it

#

Log:

[Scripting][warning]-Executing test. Corners: (-10, 0, 10) and (5, 20, 30)

[Scripting][warning]-location: (-10, 0, 10)
volume: (5, 20, 20)

[Scripting][warning]-Inside
amber granite
#

y = x + 13

#

That s it

sharp elbow
#

Although I see my code's not quite right, hehe. It's subtracting Corner2 from 5.

distant tulip
#

it is working fine for me too

amber granite
#

Hmmm

#

Maybe the problem is in my version

sharp elbow
#

I think it's how you are using it. That is why I suggested logging the value of loca to make sure it's what you are expecting

amber granite
#

What version did u test on it

sharp elbow
#

1.15.0, preview 1.21.50.25

amber granite
#

Try on 1.16.0

#

Maybe the problem is in it

sharp elbow
#

Same results

amber granite
#

How._.

distant tulip
#

mine is 1.13.0 stable

amber granite
#

But where did i got 13

#

I don't get it

#

The volume is a relative thing

sharp elbow
#

Can you share your nebulous ChunkCenter function?

amber granite
#

Ok

#
function ChunkCenter(Vector) {

  const centerX = Math.floor(Vector.x) - ((Math.floor(Vector.x) + 1) % 16) + 8;
  const centerZ = Math.floor(Vector.z) - ((Math.floor(Vector.z) + 1) % 16) + 8;

  return { x: centerX, y: Vector.y, z: centerZ };
}
#

@distant tulip

#

I ll give u my version of the script and test on it

distant tulip
#

it should be only
Math.floor(x/16)*16+8
why there is +1

amber granite
#

Ah let s say

distant tulip
amber granite
#

We have 16 by 16 block chunk

#

We divide 16 / 2
We got 8

#

The blocks number in one chunk is an even number

#

So the chunk center should be between two blocks

#

Wait lemme organise my ideas

#

So if we want to know the location of that chunk center

#

We must get it weidth and length

#

And both devide them by 2

distant tulip
#

your math is wrong man
especially in chunk border

amber granite
#

Are u sure ._.

distant tulip
#

i am

amber granite
#

But i test it with particles

#

And it spawns a particle in the middle of that chunk

#

How s that possible?

distant tulip
#

where did that 1 come from?

amber granite
#

Idk ._. fr

#

Wait did u try it with 0 0 0 ?

distant tulip
#

15 15

#

0 0 is the same

amber granite
#

Ahm

#

Yeah ._.

#

It is

#

;-;

dim tusk
distant tulip
# amber granite It is

that is the problem you are having
let say x is 15
the 1 you are adding make it 16 and that is another chunk
making it 24 (23 + that 1 you are adding) instead of 8

amber granite
#

Why did i add the one ._.

#

Anyways

#

How does that affect the volume

#

@distant tulip

#

That makes no sense

distant tulip
#

wdym
you are using it as a center
that shift the center 16 block than what you are intending

amber granite
#

Yeah but

#

I put the main block at 0 0 0

#

So with my incorrect function i ll get 7 as centre

#

And that correct

amber granite
#

Yep

distant tulip
#

no idea what are you doing wrong

amber granite
#

._.

#

So where is the problem;-;

somber onyx
#

how to enter data in a database?

#

fac.ore[0].stone += 1
Faction_DB.set("LunaireI", fac)

buoyant canopy
subtle cove
terse tide
#

my cousin sent me this

#

is this real?

slow walrus
#

fuck no that aint real

somber onyx
subtle cove
#

world.getPlayer().health ;-;

terse tide
#

•-•

subtle cove
#

uhhh

somber onyx
somber onyx
subtle cove
#

i thought u were using item

#

anyway, the way fac was defined is prob the issue

somber onyx
subtle cove
#

did u use

let fac = Faction_DB.get(name);
if (!fac) {
  fac = somthing()
}
#

or any check that an object is predefined in the db

distant gulch
#

Is it somehow possible to use Buffer ?

slow walrus
#

no

subtle cove
#

its outdated now eh

#
console.warn(JSON.stringify(Object.keys(Object.getOwnPropertyDescriptors(globalThis)),null,3))
#

__date_clock got removed

slow walrus
#

perhaps someone should update it

wary edge
#

Feel free to contribute.

sage portal
#

Is the isGliding thing only something to be read, or can we actually disable players from gliding?

distant gulch
#

readonly

sage portal
#

What a shame

Thanks though

olive rapids
#

Does anyone know how to create a script to create custom death messages?

dim tusk
shy leaf
abstract cave
#

is it me or can i not set a scoreboard through before events

distant gulch
#

let me explain it to you

abstract cave
distant gulch
#

beforeEvents are read-only, that means you cant change things atm like a scrreboard, player tag e.t.c

#

so you need to run it one tick delayed

#
system.run(() => {
    // here
});
#

system.run will run the callback in the next tick

chilly fractal
# terse tide is this real?

Firstly, many errors in the code for example "world" & "system" are "World" & "System". Secondly Minecraft Text Too Light. Thirdly No Realms Or Marketplace Buttons. and much more errors

distant gulch
#

"This function cant 5e called in read-onlv mode"

abstract cave
#

gotcha

distant gulch
#

alright

abstract cave
#

ty

distant gulch
#

No problem

#

feel free to dm me when youve got problems

wheat condor
#
system.runJob(function* timer() {
    const start = Date.now();
    while (Date.now() - start < 1000) {
        yield;
    }
    console.warn("1 sec");
});

why does console tell me that runjob expects a generator

distant tulip
slow walrus
slow walrus
#

you gotta call the gen function

halcyon phoenix
#

is it possible to detect queries in scripts?

#

I want to detect when an an entity is q.is_delayed_attacking

sage portal
#

@halcyon phoenix best thing you can do is use a behavior animation controller to trigger a scriptevent.

Otherwise, no, we can't detect that yet

sage portal
chilly fractal
#

Aight so what is the best way to do the following:

  • Each Second I Loop Over Every Player, And Loop Through Their Inventory To Find An Item.
  • Then, Depending On Its Variation I Loop Over An Object To Find The Suitable Key, Then add an effect or more to the player.
amber granite
#

What u wanna do ?

chilly fractal
#

Yeah I got some wrong explanation

#

Code will explain better

slow walrus
amber granite
#

Right ?

amber granite
#

Detecting when the player receive that item

#

Instead

chilly fractal
#
import { world, system } from "@minecraft/server";
import { hasGemInEquSlot } from "../functions/index.js";

let players;
system.runInterval(() => {
  players = world.getPlayers();
  for (let player of players) {
    if (hasGemInEquSlot(player)) { // No Value Or True Means It's In Offhand
      let effect = getGemEffect(item);
      if (!effect) return;
      player.addEffect(effect.id);
    } else if (hasGemInEquSlot(player, false)) { // False Means It's In Mainhand
      if (!player.isSneaking()) return;
      // if player is sneaking and move is found do the move and send cooldown message if already used, but I wanna do a cooldown to the cooldown so the player chat isn't spammed....
    }
  }
}, 20);

Code is not complete it has errors I'm just looking for ways to optimize when I actually implement

#

And don't mind my explanation at first

#

It's uhh

#

Weird, cuz I'm not creative with explaining things

slow walrus
#

you're only checking the mainhand or offhand?

chilly fractal
#

Both

#

Offhand for effects

#

Mainhand for moves

#

I got the offhand part

slow walrus
#

yeah I mean you're only checking those two

chilly fractal
#

But it's not very optimized

chilly fractal
slow walrus
#

yeah I mean in that case this is probably the best way

#

there's not really any other way to do it

#

if you're worried about lag, you could put it all in a runJob, though, it might mean some players get effects applied later

chilly fractal
#

Offhand isn't much of a problem ig...

slow walrus
#

but that's only if you're going above the limit, which hopefully you shouldn't be

chilly fractal
#

What is worrying is the mainhand

slow walrus
#

why?

amber granite
#

What s the item's name ?

#

And how to get it ?

chilly fractal
#

No?

#

Are you asking me if that's the problem or in general?

chilly fractal
# slow walrus why?

Cuz I wanna trigger a move if ur sneaking and having a gem, if you already used it I wanna send u a cooldown message, I don't wanna spam ur chat so I need a cooldown to the cooldown message, how would I implement the double cooldowns and isn't it gonna be laggy?

slow walrus
#

why do you need to "cooldown" the message?

chilly fractal
#

So it doesn't spam you?

#

Actually you know what?

amber granite
slow walrus
#

hmm

chilly fractal
#

I came up was an idea

#

Just using actionbar

chilly fractal
# amber granite I wanna know

I created many items with tiers and stages. And all I do in js part is check If the item starts with the item prefix for example 'youritemprefix:gemname_gem_tier1_2'

amber granite
#

I have an idea

chilly fractal
#

Also I just realized my brain is erroring I wanna check if the player double sneaked

slow walrus
#

Try something like this

system.runInterval(() => {
    system.runJob(function*(){
        const players = world.getPlayers()
        for (let i = 0; i < players.length; i++) {
            const player = players[i]

            const equipment = player.getComponent('equippable')
            if (equipment.getEquipment(EquipmentSlot.Offhand).typeId === 'whatever') {
                // run code
            }
            
            if (equipment.getEquipment(EquipmentSlot.Mainhand).typeId === 'other thing') {
                // run code
            }

            yield
        }
    }())
}, 20)
chilly fractal
#

Like sneaked and then stopped then sneaked

#

Not just sneak

slow walrus
#

jsut replace those if checks with your code stuff

chilly fractal
#

My bad

amber granite
#

You last hope is making ur item in fixed place

#

Like the last slot of the player inventory

sharp elbow
#

Cooldown is pretty easy. Store the current timestamp plus your cooldown period as a variable on the player, then check to see if the time stamp is bigger than that variable value.

chilly fractal
#

My bad yall

amber granite
#

Make a script for that, make it put ur item in the last slots of players inventory

#

So u will check only the last slots

chilly fractal
#

My problem is just tiny, it's how to detect double sneak

slow walrus
#

he's only checking the mainhand and offhand

chilly fractal
#

My mind is just not very focused

slow walrus
#

ig the only way rn is to just poll the isSneaking variable on each player

chilly fractal
#

So I talk about problems I faced before not what I need rn, sorry sorry... uh so anyone know avatar addon? Released Maybe a year ago? Well uh double sneaking (sneak+stopSneaking+sneak) = move triggered

slow walrus
#

but that won't be great for performance

slow walrus
#

check

#

pretty much

#

in a interval

#

every tick

#

since we don't have input events

chilly fractal
#

I don't remember how it was done

slow walrus
#

you keep track of the previous sneaking value, then compare it with the current

#

then you can check for chains

chilly fractal
#

I think it done using an animation controller + script api part

slow walrus
#

anim controller is probably a much better way

chilly fractal
#

It wasn't laggy at all tbh

#

So yeah I am gonna do that

sharp elbow
#

It can be done pretty easily with an animation controller and a timer, provided you can edit the player's definition. Some folks don't like doing that

chilly fractal
#

Just that I have no idea how to do that

#

Now since this is gonna be done in an addon I'll use on my server I don't care if I edit player json or other properties

#

The problem here is how?

slow walrus
#

set up a few anim controller states, like sneak, sneak_stop, double_sneak, and then in each check the one's before and the current sneak value and some timer value

#

or something along those lines

#

like double_sneak checks sneak_stop if it's true, and if the player is currently sneaking, and if it's within some timeframe

chilly fractal
#

I haven't worked with anim controller ever in my life

slow walrus
#

sneak_stop checks if sneak is true, and player is currently not sneaking, in some timeframe

#

and sneak checks if the player is sneaking

sharp elbow
#

I would make four states.
"default"

  • →"sneak1" when the player sneaks (q.is_sneaking)

"sneak1"

  • →"sneakc" when the player stops sneaking (!q.is_sneaking)

"sneakc"

  • play a timer
  • →"sneak2" when the player sneaks again (q.is_sneaking)
  • →"default" if a timer elapses before the player sneaks again (q.any_animation_finished)

"sneak2"

  • Call /scriptevent
  • →"default" when the player stops sneaking (!q.is_sneaking)
slow walrus
#

you essentially want a triple toggle state

chilly fractal
#

I do remember the script api part was checking if the sneak ticks currently are more than 360 (= 1.5 seconds, it's not ticks, I just have no idea what it was) and if was true it means u gotta sneak again

slow walrus
#

first sneak toggles on, unsneak remains toggled on, then the next sneak toggles final, and then final will toggle itself back to off

chilly fractal
#

I know

slow walrus
#

oh lol

#

read too quick

chilly fractal
#

Thanks for the help yall! Really appreciate it!

slow walrus
#

hmm I'll try write something

#

idk if it'll work

#

but should be close

sharp elbow
slow walrus
#

this might work? never used them before but it looks like it should lmao

{
    "format_version": "1.10.0",
    "animation_controllers": {
        "controller.animation.player.double_sneak": {
            "states": {
                "default": {
                    "transitions": [
                        {
                            "sneak": "q.is_sneaking"
                        }
                    ]
                },
                "sneak": {
                    "on_entry": ["v.time = q.life_time;"],
                    "transitions": [
                        {
                            "default": "(q.life_time - v.time) >= 30 && q.is_sneaking"
                        },
                        {
                            "unsneak": "!q.is_sneaking"
                        }
                    ]
                },
                "unsneak": {
                    "on_entry": ["v.time = q.life_time;"],
                    "transitions": [
                        {
                            "default": "(q.life_time - v.time) >= 30 && !q.is_sneaking"
                        },
                        {
                            "double_sneak": "q.is_sneaking"
                        }
                    ]
                },
                "double_sneak": {
                    "on_entry": ["/scriptevent namespace:double_sneak true"],
                    "transitions": [
                        {
                            "default": "!q.is_sneaking"
                        }
                    ]
                }
            }
        }
    }
}
#

then just add a scriptevent listener in your scripts

#

replace 30 with whatever amount of time you want

#

and namespace:double_sneak with whatever

#

@sharp elbow you reckon that'll work?

sharp elbow
#

I like that better than my approach. Should feel nicer since it won't trigger the ability after holding sneak for more than 1.5 seconds, then tapping Sneak

chilly fractal
#

I'll give it a try

slow walrus
#

ah the life_time is in seconds

sharp elbow
#

Ah, I was thinking of q.time_stamp. My mistake

sharp elbow
#

It should? That would mean tapping sneak once successively will trigger the ability

slow walrus
chilly fractal
#

0.7

#

Would that work?

slow walrus
#

it should yeah

slow walrus
#

it should transition once they unsneak again

#

ngl I kinda wanna try make something with that now

#

seems cool

chilly fractal
#

Isn't there a res part of this??? Or am I tripping

slow walrus
#

you could do like a "charge" up by doing a scriptevent at the start of the double sneak, and then another one when they release sneak

slow walrus
chilly fractal
#

No I am resource pack

#

Or I am I understanding this wrong

slow walrus
#

hmm no it shouldn't need any resource pack stuff

#

this is behaviour

sharp elbow
#

Oh, no, nothing in the resource pack needs changed for this implementation. Controllers can exist in both the behavior and resource pack.

chilly fractal
#

Alright then

sharp elbow
#

They do similar things, but have different responsibilities. Server controllers cannot animate any bones, and client controllers cannot execute commands

slow walrus
#

client is resource and server is behaviour

slow walrus
# chilly fractal Alright then

in your player.json add this

"animations": {
  "double_sneak_controller": "controller.animation.player.double_sneak"
},
"scripts": {
  "animate": [
    "double_sneak_controller"
  ]
}
#

I think

sharp elbow
#

(Within the "description" object)

chilly fractal
#
{
  "format_version": "1.10.0",
  "animation_controllers": {
    "controller.animation.player.double_sneak": {
      "states": {
        "default": {
          "transitions": [
            {
              "sneak": "q.is_sneaking"
            }
          ]
        },
        "sneak": {
          "on_entry": ["v.time = q.life_time;"],
          "transitions": [
            {
              "default": "(q.life_time - v.time) >= 30 && q.is_sneaking"
            },
            {
              "unsneak": "!q.is_sneaking"
            }
          ]
        },
        "unsneak": {
          "on_entry": ["v.time = q.life_time;"],
          "transitions": [
            {
              "default": "(q.life_time - v.time) >= 30 && !q.is_sneaking"
            },
            {
              "double_sneak": "q.is_sneaking"
            }
          ]
        },
        "double_sneak": {
          "on_entry": ["/scriptevent ds:double_sneak true"],
          "transitions": [
            {
              "default": "!q.is_sneaking"
            }
          ]
        }
      }
    }
  }
}
#

So is this correct?

#

Also how'd I put the player name?

#

In the message?

slow walrus
maiden ivy
#

Does the item use event work for air?

thin steeple
past blaze
#

Can't wait 'til we can directly detect use and attack input

deft nest
#

Guys why is debug not working

sharp elbow
#

Can you elaborate?

deft nest
sage portal
#

How do you add an elytra onto a player's chest slot?

#

I keep getting errors whenever I try it myself.

thorn flicker
sage portal
# thorn flicker show your code.
const elytraGet = damagingEntity.getComponent('equippable')
elytraGet.setEquipment("Chest", new ItemStack("minecraft:elytra"))
thorn flicker
#

show the error

grave thistle
#

how do i use block.getComponent(BlockComponentTypes.Inventory) to read a chests inventory?

thin steeple
#

and to read every slot, use getItem and a for loop

#

also, you can simply do block?.getComponent("inventory")

dire ferry
#
world.afterEvents.playerInteractWithEntity.subscribe((event) => {
  world.sendMessage("after event");
});

world.beforeEvents.playerInteractWithEntity.subscribe((event) => {
  world.sendMessage("before event");
});

beforeEvent works, afterEvent doesn't work... wtf?
on stable 1.15.0

sage portal
thorn flicker
sage portal
#

Ah.
Okay, yeah that makes sense

#

Thanks

thorn flicker
#

lol

#

I knew that was the issue

#

had to make sure

dim tusk
#

Gets?

dire ferry
dim tusk
#

Thanks

remote oyster
dim tusk
#

It has no beta and beta version but it doesn't work on non beta... Oh well I'll just test it

remote oyster
halcyon phoenix
#

How do I add a custom key for a summoned entity?

#

on block I used to get the blockLocation but a summoned entity seems different

halcyon phoenix
#

I want to add a unique string to it

#

like an Id so that I can identify it uniquely

wary edge
halcyon phoenix
halcyon phoenix
wary edge
halcyon phoenix
#

oh wait

#

I thought typeId but

#

Thanksss

halcyon phoenix
#
enchants.addEnchantment({type:"fire_aspect", level:1});

what am I doing wrong?

dim tusk
halcyon phoenix
#

ahh I see

#

new EnchantmentType("fire_aspect")

#

like that ?

dim tusk
#

guys, is it possible to know if player get hurt in front? like fron, back or sides

past blaze
dim tusk
past blaze
#

I'm just glad you understood. I thought I was gonna have to make up some code for you 😅

#

... In retrospect that kinda sounds demeaning. Sorry

dim tusk
scarlet lynx
#

Heya

#

Can you enchant a item that has been spawned

#

Not in a inverntory or anything

halcyon phoenix
#

can you store an array in dynamicProperties?

scarlet lynx
halcyon phoenix
#

entity.setDynamicProperties({state1: this1, state2: this2, state3: this3})
would that work?

scarlet lynx
#

Um

#

yeah I thinmk

halcyon phoenix
#

or

const states = [];
entity.setDynamicProperties("States", states);
valid ice
#

JSON.stringify() & JSON.parse()

wispy iron
valid ice
#

If it ain't 32k, I dunno what it is

#

I've had it cap out at 32k a few times for me before

wispy iron
valid ice
#

Hmm

tawdry wedge
#

[Scripting][error]-Plugin [§aSky§bGen §r§lEssentials - 2.0.0] - [Index.js] ran with error: [SyntaxError: Could not find export 'Vector' in module '@minecraft/server']

#

how to fix this?

dim tusk
tawdry wedge
#

yeah i just removed it and i thousands of lines to fix...

#

and for some reasons my custom gui is not appearing in the game , any guesses why it isn't

#

#1302518343965610009

shy leaf
#

...why is projectile not a valid damage cause?

abstract cave
#

is there a way i can make a variable that remains the same even if you restart the world, i dont mean constants, i want it to be changed if the player runs a custom command with a value, but it keeps getting redeclared every world restart, can anyone help

dim tusk
#

it will delete the things you stored once the world is closed

dim tusk
shy leaf
#

i dunno its throwing an error?????

dim tusk
abstract cave
abstract cave
shy leaf
dim tusk
dim tusk
shy leaf
#

i yeeted it away

#

just try applyDamage with projectile as damageCause

abstract cave
dim tusk
dim tusk
# abstract cave dynamic properties, how does that work

you could use it on world, itemStack, and entities not currently on blocks..

//set
itemStack.setDynamicProperty('<id>', <value>); //values can be string, float, interger

//get
const dynamicProperty = itemStack.getDynamicProperty('<id>');
console.error(dynamicProperty);
dim tusk
# past blaze You can compare the position of the player with the position of the damage sourc...
world.afterEvents.entityHurt.subscribe(ev => {
    const hurtEntity = ev.hurtEntity;
    const damagingEntity = ev.damageSource.damagingEntity;
    const damagingProjectile = ev.damageSource.damagingProjectile;

    if (hurtEntity instanceof Player) {
        let direction = '';

        const hurtLocation = hurtEntity.location;
        const damagingLocation = damagingEntity ? damagingEntity.location : damagingProjectile ? damagingProjectile.location : null;

        if (damagingLocation) {
            const angleDiff = (Math.atan2(hurtEntity.getViewDirection().z, hurtEntity.getViewDirection().x) * (180 / Math.PI) - Math.atan2(damagingLocation.z - hurtLocation.z, damagingLocation.x - hurtLocation.x) * (180 / Math.PI) + 360) % 360;

            if (angleDiff >= 315 || angleDiff < 45) {
                direction = 'front';
            } else if (angleDiff >= 45 && angleDiff < 135) {
                direction = 'left';
            } else if (angleDiff >= 135 && angleDiff < 225) {
                direction = 'back';
            } else if (angleDiff >= 225 && angleDiff < 315) {
                direction = 'right';
            }

            if (damagingLocation.y > hurtLocation.y + 1) {
                direction = 'top';
            } else if (damagingLocation.y < hurtLocation.y - 1) {
                direction = 'bottom';
            }

            hurtEntity.sendMessage(`${direction}`);
        }
    }
});```

I did it lmao, sorry it took too long I'm doing an manifest creator in html....
#

just asking if i could do better

abstract cave
dim tusk
abstract cave
abstract cave
#

okee

#

ty

slow walrus
dim tusk
slow walrus
# abstract cave is there a way i can make a variable that remains the same even if you restart t...

yep, use a dynamicProperty.

as said before, you can use it on these things: world, Player, Entity, ItemStack, depending on your use case

for example, if you wanted to store a global command prefix, you would use the world's dynamic properties, with something like this:

world.setDynamicProperty('command_prefix', '!')

const command_prefix = world.getDynamicProperty('command_prefix') // '!'

If you had settings that changed per player, like lets say a rank, you would use the player's dynamic properties;

const player = // some player

player.setDynamicProperty('rank', 'Member')

const player_rank = player.getDynamicProperty('rank') // 'Member'

dynamic properties can be strings, numbers, booleans, or Vector3s. If you want to store objects, you can do so by JSON.stringify'ing the object, then setting the dynamic property to that string, and later you can JSON.parse the string after getting the dynamic property

slow walrus
#

it's not really an unfortunate thing lol

dim tusk
chilly fractal
#

Wait what the hell

#

Oh nvm

#

I think I might be trippin or something cuz I saw my time was 10:20 and coddy sent the message at 10:31

#

And also double sneak ain't working for some reason

chilly fractal
#

Now I don't wanna ping you Omniac

#

But like it isn't working

slow walrus
#

yo

#

what's up with it

#

feel free to ping btw

chilly fractal
#

I replaced it with /say hi

#

It isn't working lol

slow walrus
#

have you got it in your player.json?

#

send your files

chilly fractal
#

Ima open post gimme sev

#

Sec

slow walrus
#

k

dim tusk
chilly fractal
#

Ima take your advise tho

#

Gimme 1 sec to test

dim tusk
#

While if inside of entity.json you can't.

chilly fractal
remote oyster
#

If anyone has free time, this person could use some help fixing their script. I already posted a list of errors in there. Simple stuff.

#1302518343965610009 message

slow walrus
#

👍

chilly fractal
#

Yo yall is parseInt supported?

#

In mcbe's quickJS

#

I don't think so but here are all the document links, feel free to give them a look:
Official Docs
Jayly Docs

Landing page containing a high-level introduction of Script APIs for Minecraft: Bedrock Edition.

slow walrus
chilly fractal
#

Betttt

distant tulip
chilly fractal
#

I know, just I don't think it's gonna work like this:

(parseInt(parts[3].replace('cracked', '')) - 4)
#

Basically getting points of gem based on typeId, so yeah

#

Actually it would work anyway

abstract cave
slow walrus
#

test if it's undefined, and then set it

chilly fractal
slow walrus
#

otherwise don't set it

abstract cave
slow walrus
#

world.afterEvents.worldInitialize

halcyon phoenix
#

I cant store an array in dynamicProperties

#

that dude scammed me

#

setDynamicProperties("locs", {x: 1,y:2,z:3})

It said conversion failed expected type, Number

halcyon phoenix
cold grove
halcyon phoenix
cold grove
#

JSON.parse

halcyon phoenix
#

Thanks

remote oyster
# halcyon phoenix setDynamicProperties("locs", {x: 1,y:2,z:3}) It said conversion failed expecte...

This doesn't look right either. You showed an example for a Vector3 Type which dynamic properties accept. The error would not be "expected Number". I'm only pointing this out so if anyone else reads your comment it will not confuse them. Your error was more involved, more in-depth, which isn't shown here. Outside a number, string, boolean, or Vector3, you will have to stringify it as Tadase mentioned.

random flint
thin steeple
#

and the oppposite

const propertyarray = world.getDynamicProperty("myproperty");
JSON.parse(propertyarray)
crude bridge
#

Hi

#

Someone know how can i change a const but in game

#

Like with a chat command or idk

#

Is it possible?

chrome flint
warm mason
#

Describe in more detail what you need

crude bridge
warm mason
#

Do you want a custom prefix or command?

crude bridge
#

prefix

warm mason
#

You can use the getDynamicProperty and setDynamicProperty methods on the player to set a prefix for himself. Wait, I'll write an example

chrome flint
#

send me your chat event snippet

chilly fractal
#

Yo any math nerds online?

warm mason
crude bridge
warm mason
chilly fractal
#

Some way to calculate the amount of blocks you pass in a second and multiple it by 3 and then applyKnockback in the direction you are looking

#

Basically dash but calculated

#

Not fixed value, rather on how much speed you are

#

Moving at, so speed effect matters

#

And also any entity that is found in the raycast that starts from your head location (before dashing) is damaged, I can do the api parts my self, just the raycasting and math stuff is too advanced for me

#

Cuz I'm currently running on yesterday's sleep. (I slept 4am, and I didn't drink any coffee or tea or anything today so I'm 🙃)

warm mason
#
let oldPos = {}

system.runInterval(() => {
  for (let player of world.getAllPLayers()) {
    let oldLoc = oldPos[player.name] || player.location
    if (distance(player.location, oldLoc) > 3) { // If block per second > 3
      let view = player.getViewDirection()
      let targets = []
      let loop = 0
      let interval = system.runInterval(() => {
        loop++
        if (loop > 20) {
          system.clearRun(interval)
          for (let target of targets) {
            target.applyDamage(5, {
              damagingEntity: player,
              cause: "ramAttack"
            })
          }
        } else {
          for (let entity of player.dimension.getEntities({ location: player.location, maxDistance: 1.5 }).filter(entity => !targets.some(ent => entity.id == ent.id) && entity.id != player.id)) {
            targets.push(entity)
          }
        }
      })
      player.applyKnockback(view.x, view.z, 3, view.y*3)
      delete oldPos[player.name]
    } else {
      oldPos[player.name] = player.location
    }
  }
})
#

That's not all!

chilly fractal
warm mason
#
function distance(vector1, vector2) {
  return Math.sqrt(Math.abs(vector1.x - vector2.x)**2 + Math.abs(vector1.y - vector2.y)**2 + Math.abs(vector1.z - vector2.z)**2)
}
chilly fractal
#

And what about the raycast?

#

(If you can do it, and if you want to do it)

warm mason
chilly fractal
#

Alright!

#

Thanks!

#

Really appreciate it bro!

warm mason
chilly fractal
grave thistle
#

is the second vector3 in getEntitiesFromRay the distance from the first vector3. so getEntitiesFromRay(block.location, { x: 0, y: 10, z: 0}) would get all entities 10 blocks above the block's location?

thorn flicker
#

otherwise, it'll legit try to do a raycast from the block location to the coords 0, 10, 0 in the world

#
const bl = block.center()
block.dimension.getEntitiesFromRay(bl, { x: bl.x, y: bl.y + 10, z: bl.z})
#

(I recommend center)

terse pulsar
#

How I get the player that send a message correctly?

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

world.beforeEvents.chatSend.subscribe((eventData) => {
  const player = eventData.sender;
  switch (event.source) {
    case '!adm':
      eventData.cancel = true;
      if (player.isOp) {
        player.sendMessage("Command lauched")
      } else {
        player.sendMessage("Only admins!")
      }
      break;
    default: break;
  }
})
thorn flicker
#

put eventData.message

terse pulsar
thorn flicker
#

seems like a mistake

near siren
#

Is there a way to clear the mainhand of a player in stable?

warm mason
near siren
#

Thank you

plush moss
#

how i can add health to a player with this
player.getComponent("health");

thorn flicker
warm mason
plush moss
#

thx

shy leaf
#

after some testing, i found out that a player-owned projectile that deals damage would get wolves to track on the target

#

for some reason, projectiles that dont deal damage somehow doesnt get wolves to track the target when its summoned via scripts

#

but manually throwing the projectile does (tested with snowball)

#

i dont remember if shoot function on projectile component is required though

grave thistle
near siren
#

When playing a music disc, what part of the hud is that? Its lower than actionbar

slow walrus
#

wrong channel

covert beacon
#

Does anyone know how to get the item_id_aux of the armor currently being used with a script?

random flint
#

Can you get the world's seed in ScriptAPI?

covert beacon
covert beacon
random flint
#

That's why it isn't "dynamic"

covert beacon
random flint
#

Indo itu apa

covert beacon
# random flint yes.

hmm in your opinion what is the best way to display the id from scripting in the HUD?

random flint
#

ActionFormData can directly use texture path from your resource pack.

Since it doesn't rely on Aux id, it's always be consistent. Though, blocks texture might need a different handling

"textures/items/diamond" will show diamond.

random flint
#

don't know tbh. I barely touch jsonUI.

covert beacon
#

🗿

covert beacon
untold magnet
#

uh,

#

i think it is possible to make ore generation using scripts, right?

#

but wait, how could i make the script works only inside of some specific biomes

#

welp, i screwd

cold grove
untold magnet
#

i wanna do something to generate my new ores and the marketplace will accept it

#

bec feature / feature rules aren't allowed for some reason

slim spear
terse pulsar
#

Why this code keeps sending me anonymous?

#
let filiationForm = new MessageFormData();
filiationForm.title("Choose Your Filiation");
filiationForm.body("wich side you gonna get in? there are two options, the marine(honor) and the pirate(bounty), you can change it");
filiationForm.button1("marine");
filiationForm.button2("pirate");

world.afterEvents.playerSpawn.subscribe((eventData) => {
  filiationForm.show(player[0]).then(r => {
    if (r.canceled) {
      filiationForm.show(eventData.playerName);
      return
    } else if (r.selection === 0) {
      world.sendMessage("Welcome to §lBlock Fruits server, you selected marine");
      return
    } else if (r.selection === 1) {
      world.sendMessage("Welcome to §lBlock Fruits server, you selected pirate");
      return
    }
  })
})
#

I tried player spawn and join

sharp elbow
#

Can you share the full error? @terse pulsar "anonymous" just means the name of your function is undefined, which happens when you use arrow functions () => {}

terse pulsar
#

One sec

terse pulsar
#
[Scripting][error]-ReferenceError: 'player' is not defined    at <anonymous> (main.js:15)
#

I've tried with "eventData.player" but don't work

sharp elbow
#

You tried it with filiationForm.show(eventData.player).then(r => { specifically? No array indexing?

honest spear
distant tulip
#

eventData.playerName...

terse pulsar
distant tulip
#

it is
eventData.player

honest spear
#

playerName is string you shouldn't really rely on that

distant tulip
#

you need force show there anyway

warm mason
# terse pulsar ```js let filiationForm = new MessageFormData(); filiationForm.title("Choose You...
function showForm(player) {
  let filiationForm = new MessageFormData();
  filiationForm.title("Choose Your Filiation");
  filiationForm.body("wich side you gonna get in? there are two options, the marine(honor) and the pirate(bounty), you can change it");
  filiationForm.button1("marine");
  filiationForm.button2("pirate");

  filiationForm.show(player).then(r => {
    if (r.canceled) {
      system.runTimeout((() => showForm(player)), 10)
    } else {
      world.sendMessage("Welcome to §lBlock Fruits server, you selected " + (["marine", "pirate"][r.selection]));
    }
  })
}

world.afterEvents.playerSpawn.subscribe(data => {
  if (data.initialSpawn) showForm(data.player)
})
terse pulsar
#

Oh

#

Interessing

distant tulip
#

maybe increase the runTimeout delay a bit

terse pulsar
#

A

#

I see

#

10 ticks is a half second?

distant tulip
# terse pulsar What is that?

so basically when the player is joining the world the game can't show forms to hem
so it get canceled
we repeat the showing of the form until it succeed

terse pulsar
# warm mason Now it's ready
[Scripting][error]-InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: Player    at showForm (main.js:15)
    at <anonymous> (main.js:25)
#

New error

#

Oomaga

#

I used the Microsoft docs when I put player[0]

gaunt salmonBOT
distant tulip
#

hmm

#

did you change anything

north depot
#

this is right?

        player.dimension.runCommand(`loot spawn ${block.location.x} ${block.location.y} ${block.location.z} loot "blocks/folder1/folder2/`${block.typeId}`_loot"`);

?

#

or how can i spawn it depend the item?

terse pulsar
#

I tried make it into another file but the same error

#
[Scripting][error]-InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: Player    at showForm (filiation.js:11)
    at <anonymous> (filiation.js:21)


[Scripting][error]-InvalidArgumentError: Unexpected type passed to function argument [0]. Expected type: Player    at showForm (filiation.js:11)
    at <anonymous> (filiation.js:21)
wary edge
#

Can't seem to find in #1067535712372654091 , script to detect player's facing direction using viewdirection?

rich kernel
#

is there a way to give an entity an item in his right hand?

rich kernel
#

I'll check that out thank you!

near siren
#

Is there a scripting equivalent to the loot command?

wary edge
distant tulip
#

there is this too

dim tusk
#

The damage function in entityHurt is based on how many hearts entity loses right?

buoyant canopy
distant tulip
#

depend on a lot of stuff
the entity can have resistance or damage modifier

#

wait dose entityHurt give the damage applied or the final damage received?

dim tusk
terse pulsar
#

How i make two files or more keep running?

#

I use import?

distant tulip
dim tusk
distant tulip
# terse pulsar I use import?

yes
it wont keep running
there is the initial run and what ever you did there will be applied
events runinterval and so on

terse pulsar
distant tulip
#

yeah

terse pulsar
#

Ok

#

How i export 🥲

dim tusk
buoyant canopy
soft rune
#

a

fathom pecan
#

yes

remote oyster
#

Random Code

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

// Interval at which the code runs (20 ticks = 1 second)
const TICK_INTERVAL = 20;

// Cardinal directions based on yaw ranges
const DIRECTIONS = ["North", "NorthEast", "East", "SouthEast", "South", "SouthWest", "West", "NorthWest"];

// Run the function every TICK_INTERVAL ticks (every 1 second)
system.run(() => {
    // Get all players in the world. For simplicity, we process just the first player.
    const player = world.getPlayers()[0];  // No need to check length, if no players this will be undefined

    // If a player is found
    if (player) {
        // Get the player's yaw (horizontal rotation) from getRotation
        const { x: yaw } = player.getRotation();

        // Normalize yaw to be within the range [0, 360)
        const normalizedYaw = (yaw % 360 + 360) % 360;

        // Calculate the index based on yaw and the direction array
        const index = Math.floor((normalizedYaw + 22.5) / 45) % 8;

        // Get the player's facing direction from the directions array
        const direction = DIRECTIONS[index];

        // Log the direction the player is facing
        console.log(`Player is facing: ${direction}`);
    }
}, TICK_INTERVAL);
balmy mason
#

This is a faster method

quick shoal
#

The block Always same location

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

world.afterEvents.itemUse.subscribe((e) => {
    const location = ({
        x: -89,
        y: -60,
        z: -12
    });
    const stoneChance = 1.0;
    const copperChance = 0.3;
    const coalChance = 0.2;
    const dimension = world.getDimension('overworld');
    const player = e.source;

    if (e.itemStack.typeId === 'mine:reset') {
        player.onScreenDisplay.setActionBar('§l§6正在重置礦場!');
        player.playSound('random.orb');
        world.structureManager.place('air', dimension, location, { integrity: 1 });
        system.runTimeout(() => {
            world.structureManager.place('stone', dimension, location, { integrity: stoneChance });
            world.structureManager.place('copper', dimension, location, { integrity: copperChance });
            world.structureManager.place('coal', dimension, location, { integrity: coalChance });
            player.onScreenDisplay.setActionBar('§l§b礦場重置完畢!');
        }, 60)
    }
});
random flint
#

r u trying yo rotate it?

quick shoal
#

This is the code

quick shoal
random flint
#

oh

#

structure is predetermined build

quick shoal
#

The compiler said just can 3-4 argument..

#

Then how

random flint
#

if u want randomized blocks u gotta do set each block

slow walrus
#

randomize the integrity for each structure

quick shoal
#

How

random flint
quick shoal
#

I don't strong at Math.random()

slow walrus
#

Math.random gives you a number from 0 to 1 so it's perfect for this, no extra stuff needed

random flint
slow walrus
#

if you wanna do it completely random, just do this:

const stoneChance = Math.random();
const copperChance = Math.random();
const coalChance = Math.random();
slow walrus
#

0 inclusive -> 1 exclusive

#

0 <= Math.random() < 1

warm mason
#

As I understand it, the problem is that the structure is always the same?

quick shoal
#

The ore always spawn on same location

#

But I not any time now so I can't fix😭

warm mason
#

It says that it is always random, but it seems to me that this is not so

#

for example:

world.structureManager.place('stone', dimension, location, {
  integrity: stoneChance,
  integritySeed: Math.random() + ""
});
#

It would be better to just place blocks using a script (because this way you won’t have empty spaces)

indigo eagle
#

How can I fix this?

cold grove
indigo eagle
#

I already made this

subtle cove
#

and the dependency...

gaunt salmonBOT
cold grove
#

Woopsie

gaunt salmonBOT
indigo eagle
#

It works, thanks!

indigo eagle
#

How can I fix this?

subtle cove
#

spelling

indigo eagle
#

Thanks

quick shoal
#

@warm mason thank u very much

#

It working as perfectly

past blaze
hazy nebula
#

why world.beforeEvents.chatSend.subscribe(data => { not work on 1.14.0-beta?

random flint
#

Good question. It should. Perhaps your script version isn't supposed to be on 1.14.0-beta

#

Or... you got a logic or syntax error!

Turn on the content log bruh

distant tulip
#

maybe send any errors you have

random flint
#

100% ur manifest

#

Check if pack got cached into ur world folder

hazy nebula
hazy nebula
random flint
#

do you have beta api toggled on in ur world?

#

the toggle... in the setting

hazy nebula
distant tulip
#

do a console.warn in the root of your script and reload

wary edge
#

There is no more 1.14 beta?

granite badger
hazy nebula
#

and if i remove the chatSend section the sections below still work

warm mason
random flint
#

Since there's no dependency error, I assume he got older minecraft version

wary edge
hazy nebula
warm mason
distant tulip
hazy nebula
warm mason
#

Clear minecraft cache

distant tulip
#

world cache

warm mason
#

Or so

distant tulip
random flint
#

restart minecraft 🗿

hazy nebula
distant tulip
#

hmm

warm mason
#

This can only mean that he actually has a stable version or he did not enable beta APIs in the settings

hazy nebula
#

wait a m

#
world.beforeEvents.chatSend.subscribe(data => {
  let player = data.sender;
  let msg = data.message.trim();

  if (msg.startsWith('!scepter')) {
      let args = msg.split(' ');
      
      if (args.length >= 2) {
          let scepterName = args.slice(1).join(' ');

          let item = new ItemStack("minecraft:blaze_rod", 1);

          item.setLore([`spirits: ${scepterName}`]);

          player.getComponent("inventory").container.addItem(item);

          data.cancel = true;
      }
  }
});```
gaunt salmonBOT
hazy nebula
warm mason
#

chatSend

distant tulip
#

hmmm

warm mason
distant tulip
gaunt salmonBOT
gaunt salmonBOT
distant tulip
#

🤷‍♂️

valid ice
#

#debug-playground

warm mason
distant tulip
#

it is follow up to the conversation

valid ice
#

Not a huge deal, just excessive bot stuff should be used in the debug channel 🙂

dim tusk
#
system.runInterval(() => {
    for (const player of world.getPlayers()) { 
        if (player.isSneaking) {
            player.isSneaking = false;
            const form = new ModalFormData().title('Hex to RGA Converter').textField('Enter Hex Code (e.g., #FF5733):', '');
            form.show(player).then(response => {
                if (!response.canceled) {
                    const hexCode = response.formValues[0];
                    try {
                        const rgbaColor = hexToRgba(hexCode);
                        player.sendMessage(`RGBA: ${rgbaColor}`);
                    } catch (e) {
                        player.sendMessage('Invalid hex code.');
                    }
                }
            });
        }
    }
});
function hexToRgba(hex) {
    hex = hex.replace(/^#/, '');
    
    if (hex.length === 3) {
        hex = hex.split('').map(char => char + char).join('');
    }
    
    const bigint = parseInt(hex, 16);
    const r = ((bigint >> 16) & 255) / 255;
    const g = ((bigint >> 8) & 255) / 255;
    const b = (bigint & 255) / 255;
    
    return `(${r}, ${g}, ${b}, 1)`;
}```
#

Useless thing I did for awhile

distant tulip
#

hmmm

dim tusk
#

This is the first time I know the hex can be corresponds for rgba

#

Thank you stack overflow

dim tusk
#

Wait the slider doesn't accept float right?

unique dragon
#

i think no

dim tusk
#

I mean this kinda stupid but is it possible to have drop-down that reached 30k+?

#

Yeah ngl it sounds so fuckin stupid

#

Can't test it rn

remote oyster
dim tusk
remote oyster
#

Probably wouldn't recommend having to scroll through 30,000 possibilities either lol. Ain't nobody trying to do that.

remote oyster
# dim tusk Make sense tbh lol... Looks like I need to do it with textField

I think that is a good idea. Since it's possible for them to use uppercase, lowercase, and a mix of the two, I would suggest making the string lowercase in the textField after getting their input, then comparing that lowercase string with your list as lower case as well, to confirm you have a match. Makes it simple at not having to rely on the user to spell with case sensitivity in mind.

dim tusk
#

I'm trying to make hex to rgba but I want it to also work on name a only, but I need to list more than 1k of it

dim tusk
# remote oyster I think that is a good idea. Since it's possible for them to use uppercase, lowe...
const colorData = {
    "blue": "#0000FF",
    "red": "#FF0000",
    "pink": "#FFC0CB"
};

function getColorHexByName(colorName, colorData) {
    return colorData[colorName.toLowerCase()] || null;
}

system.runInterval(() => {
    for (const player of world.getPlayers()) { 
        if (player.isSneaking) {
            player.isSneaking = false;
            const form = new ModalFormData().title('Hex to RGBA Converter').textField('Enter Hex Code or Color Name:', '');
            form.show(player).then(response => {
                if (!response.canceled) {
                    let input = response.formValues[0];
                    let hexCode = input.startsWith("#") ? input : getColorHexByName(input, colorData);
                    
                    if (hexCode) {
                        try {
                            const rgbaColor = hexToRgba(hexCode);
                            player.sendMessage(`RGBA: ${rgbaColor}`);
                        } catch (e) {
                            player.sendMessage('Invalid hex code.');
                        }
                    } else {
                        player.sendMessage('Color name not found.');
                    }
                }
            });
        }
    }
});

function hexToRgba(hex) {
    hex = hex.replace(/^#/, '');
    
    if (hex.length === 3) {
        hex = hex.split('').map(char => char + char).join('');
    }
    
    const bigint = parseInt(hex, 16);
    const r = ((bigint >> 16) & 255) / 255;
    const g = ((bigint >> 8) & 255) / 255;
    const b = (bigint & 255) / 255;
    
    return `(${r}, ${g}, ${b}, 1)`;
}
#

Here lmao 😂...

#

I will make a separate file contains all colors people know...

#

Yoo I discovered something. +1 knowledge

#
function hexToName(hexCode, colorData) {
    for (const [name, hex] of Object.entries(colorData)) {
        if (hex.toLowerCase() === hexCode.toLowerCase()) {
            return name;
        }
    }
    return null;
}```
#

I can get the name of the color by getting the hex

dim tusk
#

Tbh, my first idea is o create a color wheel but it's already impossible since there's a lot of colors

#

Even if I try to use ActionFormData it would be A LOT

grave thistle
#

Is there a way to store an entity's name within an item? I'm trying to make it so endermites can be bottled and need to retain the name if it's been tagged

chilly fractal
#
item.setLore([entity.nameTag]);
grave thistle
chilly fractal
#

Sure yea

#

You can also just set the item nameTag directly

#
item.nameTag = `Bottled ${entity.nameTag}`;
chilly fractal
subtle cove
#

lore

chilly fractal
#

Yeah I suggested lore & nameTag

#

I think lore should be for when you have something like an id for an item, and nameTag should be for fun :) [by fun I mean bottling frogs & ghasts]

#

My personal favorite item is "Bottled JimDavis (Screaming)"

#

Brotha killed me in a hardcore world in Java so I decided to take revenge on him in bedrock

#

He is just stilling on wall of shame in an item frame

indigo eagle
#

How can I fix this?

grave thistle
#

Is there a way to make something classed as a player so I can run .playSound? I'm using a custom item component with onUseOn and the only option is source

weary umbra
grave thistle
#

I need it so only the target player can hear it

shy leaf
thorn flicker
#

source returns the player class.

dim tusk
grave thistle
#

source isn't classed as Player, it's classed as Entity

shy leaf
#
if (source instanceof Player)``` maybe?
thorn flicker
#

the method should work regardless though

dim tusk
thorn flicker
shy leaf
#

yeah its quite odd

grave thistle
dim tusk
# grave thistle

That's odd... Maybe just try typing the whole playsound and try it in game

thorn flicker
#

it should work.

#

please try it

dim tusk
thorn flicker
#

I find it strange that it returns the entity class though

#

the world event doesnt but the custom component one does, weird

grave thistle
#

It does work. I assumed it wouldn't work because of autocomplete and the fact it returns as Entity

thorn flicker
shy leaf
#

oop

thorn flicker
#

very odd that it returns entity

shy leaf
#

the server banner changed

thorn flicker
#

no banner

#

nvm the event thing was in the way

gaunt flare
#
rawtext: [
                {
                    translate: "death.attack.indirectMagic",
                    with: [entity.name, "entity.evocation_fang.name"]
                }
            ]

How do I translate the evocation fang?

warm mason
dim tusk
#

damn the chatSend is now -beta?

grave thistle
#

Is there not a method for spawning a loot table? Is the only way through runCommand?

dim tusk
grave thistle
#

ah, hopefully a method is added at some point. guess ill stick with commands