#Script API General
1 messages · Page 31 of 1
I think you make your script only asking here isnt?
yeah, this one is better
i think rItems?.itemStack?.typeId should fix it
My brain
yeah, but it's less optimized
that works a swell
The @subtle cove fix also is more efficent
lemme see
come again after another bug
we'll torture thy bugs
Are u sure ?
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?
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36m<REPL0>.js[0m:[33m6[0m:[33m24[0m - [31merror[0m[30m TS2304: [0mCannot find name 'world'.
[7m6[0m for (const item of world.getDimension(dim).getEntities({ type: 'item' })) {
[7m [0m [31m ~~~~~[0m
ESLint results:
<REPL0>.js
5:9 error 'dimension' is assigned a value but never used @typescript-eslint/no-unused-vars
Debug result for [code](#1067535608660107284 message)
Compiler found 2 errors:
[36mmain.js[0m:[33m99[0m:[33m1[0m - [31merror[0m[30m TS1128: [0mDeclaration or statement expected.
[7m99[0m });
[7m [0m [31m~[0m
``````ansi
[36mmain.js[0m:[33m99[0m:[33m2[0m - [31merror[0m[30m TS1128: [0mDeclaration or statement expected.
[7m99[0m });
[7m [0m [31m ~[0m
ESLint results:
main.js
99:0 error Parsing error: Declaration or statement expected
Oh now just remaining syntax erro
@quick shoal try this ig
you don't need the const dimension = part
I know so I removed it
it should remove the item entity from all dimensions not only overworld or nether
tOpIc PoRtAllll: https://discord.com/channels/523663022053392405/1301464443162460221
are you trying to remove all the items with the types in the array from all dimensions?
that's what is supposed to happen
Wdym
what are you trying to do?
I'm just remove the
const dimension = [...
removing the item from one dimension only or all 3 dimensions?
I'm just want to avoid player drop the item in ui
so u need the dimensions
removing the item entity from all dimensions is what u need
avoid more issues
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()
}
})
})
No need my map doesn't allow player go to nether or end
And the code is finally working without any error now!!!
nice
now roam far around then use the stick
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()
})
})
Wrong code. item is an entity, not an itemStack
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()
})
})```
@subtle cove
sup
The code u gave me
Works in an odd way
How to fix that
So lemme clear something
make a post 1st
Ok
this seems like a long conv
Done
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.
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.
No I want to avoid another player who not is owner to open the ui
So I need to add a lock at each UI entity
Can I use this??
playerInteractWithEntity
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
}
}
});
I always thought that playerInteractWithEntity was not used for this purpose.
No way the debugger is offline..
Every time debugger go offline just when I want to test the code
You might wanna start using vscode and typescript to help you scripting
why not just test in-game?
Sry im using phone to coding
const player = eventData.player;
const entity = eventData.target;
Oh thanks
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36mmain.js[0m:[33m31[0m:[33m32[0m - [31merror[0m[30m TS2551: [0mProperty 'setActionbar' does not exist on type 'ScreenDisplay'. Did you mean 'setActionBar'?
[7m31[0m player.onScreenDisplay.setActionbar(`§c- 此箱子UI 擁有者為${ownerId}\n請遠離此處再嘗試開啟你的箱子UI!`);
[7m [0m [31m ~~~~~~~~~~~~[0m
[36m@minecraft/server.d.ts[0m:[33m14174[0m:[33m5[0m
[7m14174[0m setActionBar(text: (RawMessage | string)[] | RawMessage | string): void;
[7m [0m [36m ~~~~~~~~~~~~[0m
'setActionBar' is declared here.
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
#debug-playground ;-;
Oh just B and b
*Sry I sent incorrect
Does anyone know how getEntities volume works ?
What dx means ._.
who has all the file of the last version of mc bedrock?
why?
Do you mean the vanilla pack (behavior/resource) or the full game? cus I don't see a point to downgrade
The bedrock vanilla packs does.
Downloadable from: https://github.com/Mojang/bedrock-samples/releases
bedrock.dev archive: https://bedrock.dev/packs
GitHub (RP & BP) : https://github.com/bedrock-dot-dev/packs
Example particles: https://aka.ms/MCParticlesPack
Java Edition's Vanilla Packs: https://mcasset.cloud/
you know in what file is the new pop up animation of the minecraft tip
For people that uses my Script API Docs: Thoughts on current state of ads?
11
19
3
I use an ad blocker
Either its JSON UI (Resource Pack) or hardcoded OreUI
I don't think this is a good idea
Vanilla blocks aren't the only ones with block states. This is too restrictive
does herobrine chest ui also displays shulker boxes' items on lores?
i agreed
Yeah I saw that change and surprised it wasnt mentioned in changelogs.
so who's gonna give feedback to them
@spring axle? (Is it ok if I ping you for this)
Probably will never be supported natively by the chest UI, as that stuff is the item lore (which you can just add to the item yourself)
I think this previews types are messed up. Compostable on itemstack being one of them.
block states types have been released for a while now, i adapted some of the changes to jaylybot a while ago
Custom block state names will work AFAIK, but the types restrict against it at the moment. You'll have to TS ignore it. Let me ask internally
Some types support custom states and some don’t at the moment. Kinda annoyed at the inconsistency
You can get around it like this for now: const age = perm.getState('design:crop_age' as keyof BlockStateSuperset);
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
Why me
because of the [@}
I don't know the answer
Hilarious.
broadcastClientMessage sends a message to the Minecraft client and messageRecieve listens for messages from the client, which can't be sent through scripts.
They aren't really documented, does this even work on BDS?
It's for internal use only
hmmm okay thanks
Can someone help with that please
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).
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
Is there a purpose to doing this though?
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
🐛
I have no mojira account
then make one
Maybe tomorrow
Until they fix it , u have that note , so no one struggles with it , like i did for 8 hours 
Subtract 14?
Can you share a snippet of how you used the method?
._.
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
}
}
Can you share where you originally calculated the volume? In getEntities?
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
It's a figure of speech. What exactly did you write in getEntities()?
lol
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
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?
The volume property using
Dx , dy , dz
Not the subtraction of the vectors in location and volume property
The volume is constant thing
It Is not the area of subtractions
Sorry, I meant to say it selects entities in the volume
Volume it still a cube 80x80x80
It won't change
Even if u put the location -8288 , -82838 - ,82828
U understand?
the volume is relative to the location
so?
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
Have you sent the location of loca to the log to verify the selection is too big?
So the method is bugged
Bro... ,_,
The location is not a factor that changes the volume
The volume will still be as u put it
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
Ok lemme draw u something
I'm well aware of how it works, I don't need an illustration. I appreciate the notion though
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
"first entity volume," is this an entity's collision box? or something else
No the volume i selected
This volume?
Yes
I used that code to check
if ( entitiesArray(arguments).length === 0 ) {
// A code that spawns the entity
}
getEntities is definitely not broken, I'm trying to understand what the issue is
What version of Minecraft and the script API are you using?
It wasn't broken in either of those versions
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
Yes i tried 50 i got 63
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
I created a function for that
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
Although I see my code's not quite right, hehe. It's subtracting Corner2 from 5.
it is working fine for me too
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
What version did u test on it
1.15.0, preview 1.21.50.25
Same results
How._.
mine is 1.13.0 stable
Can you share your nebulous ChunkCenter function?
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
it should be only
Math.floor(x/16)*16+8
why there is +1
Same
Ah let s say
no?
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
your math is wrong man
especially in chunk border
Are u sure ._.
i am
But i test it with particles
And it spawns a particle in the middle of that chunk
How s that possible?
where did that 1 come from?
Wait, that calculation doesn't look right
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
Why did i add the one ._.
Anyways
How does that affect the volume
@distant tulip
That makes no sense
wdym
you are using it as a center
that shift the center 16 block than what you are intending
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
is this the code for that?
Yep
no idea what are you doing wrong
how to enter data in a database?
fac.ore[0].stone += 1
Faction_DB.set("LunaireI", fac)
thank you for the correction
const ore0 = (fac.ore ??= [{}])[0];
ore0.stone = ore0.stone + 1 || 1;
fuck no that aint real
thank you ca walk but now I have 2 valuable stones in my db
world.getPlayer().health ;-;
•-•
const type = item.typeId.split(":")[1];
fac.ore[type] = fac.ore[type] + 1 || 1;
uhhh
I alraydy have db
Faction_DB.set(name, {
name: name,
description: description,
nbJoueur: 1,
chef: leader,
maxPlayers: 5,
power: 0,
bank: 0,
playerList: [leader],
invit: [],
level: 1,
ore: [
{
stone: 0,
coal: 0,
iron: 0,
gold: 0,
redstone: 0,
lapis: 0,
diamond: 0,
emerald: 0
}
]
})
I don’t understand why you use item.
export const Faction_DB = new JsonDatabase("faction")
did u use
let fac = Faction_DB.get(name);
if (!fac) {
fac = somthing()
}
or any check that an object is predefined in the db
Is it somehow possible to use Buffer ?
no
this is all the supported stuff https://wiki.bedrock.dev/scripting/api-environment.html#support
Hmm okay..
Anyways Thank you
its outdated now eh
console.warn(JSON.stringify(Object.keys(Object.getOwnPropertyDescriptors(globalThis)),null,3))
__date_clock got removed
perhaps someone should update it
Feel free to contribute.
Is the isGliding thing only something to be read, or can we actually disable players from gliding?
readonly
What a shame
Thanks though
Does anyone know how to create a script to create custom death messages?
Too good to be true 😞
of course not
is it me or can i not set a scoreboard through before events
Its you
let me explain it to you
😐
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
Look
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
gotcha
alright
ty
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
system.runJob(timer());
function* timer() {
const start = Date.now();
while (Date.now() - start < 1000) {
yield;
}
console.warn("1 sec");
}
thanks
system.runJob(function* timer() {
const start = Date.now();
while (Date.now() - start < 1000) {
yield;
}
console.warn("1 sec");
}());
you gotta call the gen function
is it possible to detect queries in scripts?
I want to detect when an an entity is q.is_delayed_attacking
@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
BPAC?
yes
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.
What u wanna do ?
you wanna apply an effect to each player depending on some type of item they have in their inventory?
Right ?
Close
What about
Detecting when the player receive that item
Instead
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
you're only checking the mainhand or offhand?
yeah I mean you're only checking those two
But it's not very optimized
Ye ye, not whole inventory.
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
Offhand isn't much of a problem ig...
but that's only if you're going above the limit, which hopefully you shouldn't be
What is worrying is the mainhand
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?
why do you need to "cooldown" the message?
I wanna know
hmm
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'
I have an idea
Also I just realized my brain is erroring I wanna check if the player double sneaked
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)
jsut replace those if checks with your code stuff
My bad
You last hope is making ur item in fixed place
Like the last slot of the player inventory
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.
My bad yall
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
not needed
My problem is just tiny, it's how to detect double sneak
he's only checking the mainhand and offhand
My mind is just not very focused
ig the only way rn is to just poll the isSneaking variable on each player
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
but that won't be great for performance
Poll?
I don't remember how it was done
you keep track of the previous sneaking value, then compare it with the current
then you can check for chains
I think it done using an animation controller + script api part
anim controller is probably a much better way
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
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?
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
I haven't worked with anim controller ever in my life
sneak_stop checks if sneak is true, and player is currently not sneaking, in some timeframe
and sneak checks if the player is sneaking
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)
you essentially want a triple toggle state
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
first sneak toggles on, unsneak remains toggled on, then the next sneak toggles final, and then final will toggle itself back to off
10 seconds is 200 ticks
I know
Thanks for the help yall! Really appreciate it!
My controller recommendation will also involve animation-based timers, which you can read about here: https://wiki.bedrock.dev/entities/timers.html#animation-based-timers
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?
@chilly fractal
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
Oh sorry I was reading the docs
I'll give it a try
ah the life_time is in seconds
Only thing I'd change is the transition 'double_sneak'→'default,' since it will immediately transition back to 'sneak'
Ah, I was thinking of q.time_stamp. My mistake
hmm I mean it should
It should? That would mean tapping sneak once successively will trigger the ability
@chilly fractal replace the 30 with like 1 or something, it should be however many seconds you want to allow between inputs before it gets reset
it should yeah
ah true
it should transition once they unsneak again
ngl I kinda wanna try make something with that now
seems cool
Isn't there a res part of this??? Or am I tripping
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
yeah you needa add the controller to your player.json somewhere
Oh, no, nothing in the resource pack needs changed for this implementation. Controllers can exist in both the behavior and resource pack.
Alright then
They do similar things, but have different responsibilities. Server controllers cannot animate any bones, and client controllers cannot execute commands
client is resource and server is behaviour
in your player.json add this
"animations": {
"double_sneak_controller": "controller.animation.player.double_sneak"
},
"scripts": {
"animate": [
"double_sneak_controller"
]
}
I think
(Within the "description" object)
{
"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?
Alright
I'm not sure, but I think the scriptevemt might get sent with the player as the source. Just try get it working and then console log the scriptevent's sourceType variable
Does the item use event work for air?
unfortunately not
Can't wait 'til we can directly detect use and attack input
Guys why is debug not working
Can you elaborate?
#debug-playground The bot works for me for some reason
How do you add an elytra onto a player's chest slot?
I keep getting errors whenever I try it myself.
show your code.
const elytraGet = damagingEntity.getComponent('equippable')
elytraGet.setEquipment("Chest", new ItemStack("minecraft:elytra"))
thats correct
show the error
how do i use block.getComponent(BlockComponentTypes.Inventory) to read a chests inventory?
well to read, you could use the getItem method
and to read every slot, use getItem and a for loop
also, you can simply do block?.getComponent("inventory")
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
sorry for the late response, an emergency happened right after that comment
you didnt import itemStack
After events of the player interact entity only works with entities that does have the component minecraft:interact that also happens with the player interact block, it only triggers when you successfully opens a UI example a crafting table if you use after events on blocks that doesn't swing your arms it won't trigger it no matter what...
Gets?
And before events is only beta
That makes sense, thanks.
they both went stable in 1.21.40
Really? Are you sure? Fuck yeah... I rarely use that anymore lmfao
Thanks
Documentation for @minecraft/server
But, it does that too in other versions
It has no beta and beta version but it doesn't work on non beta... Oh well I'll just test it
playerInteractWithEntity in beforeEvents isn't stable prior to 1.15.0.
Here is 1.14.0:
https://stirante.com/script/server/1.14.0/classes/WorldBeforeEvents.html
Documentation for @minecraft/server
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
What?
I want to add a unique string to it
like an Id so that I can identify it uniquely
nonono
basically I summon multiple entities and they are the same type so I need to add a identifier to them when I summon them
Yeah...entiy.id or dynamic properties?
oh wait
I thought typeId but
yeah entity.id is unique form other id
Thanksss
Documentation for @minecraft/server
in type you need to put new EnchantmentType('<id>') and import EnchantmentType in the server
import { EnchantmentType } from '@minecraft/server';
enchants.addEnchantment({type: new EnchantmentType("fire_aspect") , level:1});```
uhuh
guys, is it possible to know if player get hurt in front? like fron, back or sides
You can compare the position of the player with the position of the damage source, along with the player's viewing direction
oh yeah, that's what I'm thinking.. thanks bro
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
don't worry I'm stupid but i know how to do thing i just needed someone to tell me how
Heya
Can you enchant a item that has been spawned
Not in a inverntory or anything
can you store an array in dynamicProperties?
Yes im pretty sure
entity.setDynamicProperties({state1: this1, state2: this2, state3: this3})
would that work?
or
const states = [];
entity.setDynamicProperties("States", states);
JSON.stringify() & JSON.parse()
Do we know what the max string length is? I know it’s definitely not the 32k limit that some people have mentioned
If it ain't 32k, I dunno what it is
I've had it cap out at 32k a few times for me before
It seems to cap a lot sooner for me
Hmm
[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?
vector doesn't exist in the server modules anymore....
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
...why is projectile not a valid damage cause?
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
nope you can't, you need to use dynamicProperties unfortunately
it will delete the things you stored once the world is closed
it should??
i dunno its throwing an error?????
you did this? damageSource.damagingProjectile
dynamic properties, how does that work
dynamic properties or the const
no i was trying to use it on applyDamage
the dynamic properties will not be removed unless the uuid of the addon is changed or the addon is removed while const or let will be removed once you closed it
lemme see your code
does it accept values or just text
string, numbers, float
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);
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
does it require a player, entity, or item to work, can it work independently on its own
nah.... as longas the thing you setting is there it's good
??, wdym....
so it can work as a standalone variable, or not?
why "unfortunately"?
Hmm? Did I do wrong?
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
nah I was wondering why you said unfortunately
it's not really an unfortunate thing lol
Lol, I don't really know what word is the right one mybad
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
Dis
Now I don't wanna ping you Omniac
But like it isn't working
k
Never use / when running comman inside of events in entity.json
I mean he gave me the anim controller, I have no idea how to use anim controllers lol
Ima take your advise tho
Gimme 1 sec to test
It's okay to use / inside of BP anim controller cause it's required
While if inside of entity.json you can't.
Yeah it told me unknown token lol
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
thanks so much
👍
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
yes
Betttt
it dose
you can also use
Number("x")
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
is there a way i can make it so it only gets set once on world creation
test if it's undefined, and then set it
Idk I like sticking to what I make the first time, unless there are performance differences or like overall the new thing is better than the old thing
otherwise don't set it
what would be better for this, system.runInterval or playerSpawn after events
world.afterEvents.worldInitialize
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
it didn't work my friend
You store them as strings using JSON.strigify
how do you unstring them?
JSON.parse
Thanks
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.
You were probably on an older version of Minecraft or Script engine. DynamicProperty is capable of storing Vector3 {x,y,z} without stringifying it.
An Array looks like this: [ 8, 9, 2], it is considered as an Object. And Vector3 looks like this: {x:0,y:-3,z:9}, it's not an Array but also considered as an Object
const array = [1, 3, 4, 5];
world.setDynamicProperty("myproperty", JSON.stringify(array))
and the oppposite
const propertyarray = world.getDynamicProperty("myproperty");
JSON.parse(propertyarray)
Hi
Someone know how can i change a const but in game
Like with a chat command or idk
Is it possible?
you can't change a const, but you can change a let
How
A constant - no way, that’s why it’s a constant. Use "let"
Describe in more detail what you need
i need to make a prefix for my chat command but i want to make it castomizable
Do you want a custom prefix or command?
prefix
just do dynamic properties
You can use the getDynamicProperty and setDynamicProperty methods on the player to set a prefix for himself. Wait, I'll write an example
send me your chat event snippet
thx
Yo any math nerds online?
world.beforeEvents.chatSend.subscribe(data => {
let player = data.sender
let message = data.message
let prefix = player.getDynamicProperty("prefix") || "!"
if (message.startsWith(prefix)) {
// command
} else {
// message
}
})
@crude bridge
thxx
What do you need?
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 🙃)
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!
Wut
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)
}
?
This
@chilly fractal
Also I don't this anymore
I made a mistake in the code. Copy new
Thanks bro I really appreciate it!
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?
the other vector must use the vector properties from the block location aswell.
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)
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;
}
})
player is not the issue, it's event.source
put eventData.message
I get that from bedrock.wiki
Is there a way to clear the mainhand of a player in stable?
player.getComponent("minecraft:equippable").setEquipment("Mainhand", undefined)
Thank you
how i can add health to a player with this
player.getComponent("health");
you could also just leave it blank
hp.setCurrentValue(hp.currentValue + 1)
thx
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
So the second vector3 is deffo the second location to scan to? I ask only because there is a maxDistance option in the raycast options
When playing a music disc, what part of the hud is that? Its lower than actionbar
wrong channel
Does anyone know how to get the item_id_aux of the armor currently being used with a script?
Can't get the aux ID dynamically. Your best bet is to Map each typeId and their respective Aux Id
Can you get the world's seed in ScriptAPI?
but what if minecraft updates, won't the id change?
I don't know, I don't understand scripting 😅
yes.
That's why it isn't "dynamic"
indo kan?🗿
Indo itu apa
hmm in your opinion what is the best way to display the id from scripting in the HUD?
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.
in the hud?
don't know tbh. I barely touch jsonUI.
🗿
#1135533278061920367 message
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
Isnt easier to make it using json?
what?
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
it definitely is, it'd just have to spawn near the player cause of sim distance
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
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 () => {}
I got many errors but I gonna get one
One sec
There is
[Scripting][error]-ReferenceError: 'player' is not defined at <anonymous> (main.js:15)
I've tried with "eventData.player" but don't work
You tried it with filiationForm.show(eventData.player).then(r => { specifically? No array indexing?
you are referencing unknown array here player[0] out of the scope so be careful with that as you don't even know how much players are there, you better use that player form event
eventData.playerName...
I tried it too
it is
eventData.player
playerName is string you shouldn't really rely on that
you need force show there anyway
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)
})
maybe increase the runTimeout delay a bit
What is that?
A
I see
10 ticks is a half second?
Now it's ready
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
[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]
No errors in [code](#1067535608660107284 message)
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?
No
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)
Can't seem to find in #1067535712372654091 , script to detect player's facing direction using viewdirection?
is there a way to give an entity an item in his right hand?
/replaceitem
I'll check that out thank you!
Is there a scripting equivalent to the loot command?
function getFacingDirection(vector3: Vector3) {
let x = vector3.x;
let y = vector3.y;
let z = vector3.z;
if (Math.abs(y) > Math.abs(z) && Math.abs(y) > Math.abs(x)) {
return y > 0 ? 'Up' : 'Down';
} else if (Math.abs(z) > Math.abs(x)) {
return z < 0 ? 'North' : 'South';
} else {
return x > 0 ? 'East' : 'West';
}
}
The damage function in entityHurt is based on how many hearts entity loses right?
i think it's the number of half hearts
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?
Probably I guess?
You gave me an idea. I want to make my entity doesn't receive any effects I'll just clear entities effects
there is probably a component or something for it
I don't remember it... The only entities that receive any effects are arrows and boats
yes
it wont keep running
there is the initial run and what ever you did there will be applied
events runinterval and so on
I'll just check documentations
warden? ender dragon?
So I use export on other files and import on my entry file?
yeah
I can't find any components the things like this are hardcoded to the entities I guess?
export const x = 5
export function run() {
...
}
a
yes
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);
function getDirectionFromYaw(yaw) {
const directions = ["North", "NorthEast", "East", "SouthEast", "South", "SouthWest", "West", "NorthWest"];
return directions[Math.floor((yaw + 202.5) / 45) % 8];
}
This is a faster method
The block Always same location
Guys who can fix this
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)
}
});
r u trying yo rotate it?
This is the code
How
if u want randomized blocks u gotta do set each block
randomize the integrity for each structure
How
show em bro, imma gone for the next 30 minutes
I don't strong at Math.random()
Math.random gives you a number from 0 to 1 so it's perfect for this, no extra stuff needed
Math.random never returns exactly 1, but it can returns 0
if you wanna do it completely random, just do this:
const stoneChance = Math.random();
const copperChance = Math.random();
const coalChance = Math.random();
yeah ik
0 inclusive -> 1 exclusive
0 <= Math.random() < 1
As I understand it, the problem is that the structure is always the same?
Yea
The ore always spawn on same location
But I not any time now so I can't fix😭
try this
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)
How can I fix this?
Specify main.js in manifest
What do you mean by "specify" in the manifest?
I already made this
and the dependency...
Woopsie
Installation for @minecraft/server
Latest API module install:
npm i @minecraft/[email protected]
Beta API module install:
npm i @minecraft/[email protected]
Preview API module install:
npm i @minecraft/[email protected]
Preview Beta API module install:
npm i @minecraft/[email protected]
It works, thanks!
How can I fix this?
spelling
Thanks
Now I will try this
@warm mason thank u very much
It working as perfectly
What a peculiar button layout
why world.beforeEvents.chatSend.subscribe(data => { not work on 1.14.0-beta?
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
maybe send any errors you have
I don't think there is anything wrong with my code!
yes it enabled
do a console.warn in the root of your script and reload
There is no more 1.14 beta?
Which minecraft version are you on? Latest uses 1.16 beta https://jaylydev.github.io/scriptapi-docs/latest/modules/_minecraft_server_1_16_0_beta.html
and if i remove the chatSend section the sections below still work
Each version of Minecraft has its own beta versions
Since there's no dependency error, I assume he got older minecraft version
Unless otherwise stated I will always assume someone is using the latest verdion.
my ver í 1.21.30
If he does not have an error that he specified the wrong API version, then he can only use 1.14.0-beta
use 1.15.0-beta
it still gives error at that part
Clear minecraft cache
world cache
Or so
you should do this to make sure the script is loading or not
restart minecraft 🗿
when I delete the chatSend and reload the itemUse code below still works
hmm
This can only mean that he actually has a stable version or he did not enable beta APIs in the settings
no
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;
}
}
});```
Debug result for [code](#1067535608660107284 message)
Compiler found 1 errors:
[36m<REPL0>.js[0m:[33m1[0m:[33m20[0m - [31merror[0m[30m TS2339: [0mProperty 'chatSend' does not exist on type 'WorldBeforeEvents'.
[7m1[0m world.beforeEvents.chatSend.subscribe(data => {
[7m [0m [31m ~~~~~~~~[0m
There are no errors from ESLint.
?!
chatSend does not exist in stable release
chatSend
hmmm
Why don't I have this command?...
No errors in [code](#1067535608660107284 message)
No errors in [code](#1067535608660107284 message)
🤷♂️
#debug-playground
sorry
it is follow up to the conversation
Not a huge deal, just excessive bot stuff should be used in the debug channel 🙂
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
hmmm
This is the first time I know the hex can be corresponds for rgba
Thank you stack overflow
Wait the slider doesn't accept float right?
i think no
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
Not sure if it would handle that. Might crash.
Make sense tbh lol... Looks like I need to do it with textField
Probably wouldn't recommend having to scroll through 30,000 possibilities either lol. Ain't nobody trying to do that.
Fr tho 😂
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.
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
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
I see what you did there.
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
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
Set the name to the items lore
item.setLore([entity.nameTag]);
Forgot about lore tbh. Isn't possible to edit the name of the item. Say I bottle an endermite called Bob, could I rename the new item to Bottled Bob or something like that?
Sure yea
You can also just set the item nameTag directly
item.nameTag = `Bottled ${entity.nameTag}`;
dynamic property
Wouldn't work for stacked items
lore
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
How can I fix this?
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
Switch Line 5 with Line 4
source is player.
Can't run source.playSound only source.dimension.playSound which all players can hear
I need it so only the target player can hear it
how are you getting the players?
you can.
source returns the player class.
source isn't classed as Player, it's classed as Entity
if (source instanceof Player)``` maybe?
weird.
the method should work regardless though
Did you try atleast cause I mean player is the one can only use an item 🤷
I dont believe that is required.
That's odd... Maybe just try typing the whole playsound and try it in game
That's what I'm saying.
I find it strange that it returns the entity class though
the world event doesnt but the custom component one does, weird
It does work. I assumed it wouldn't work because of autocomplete and the fact it returns as Entity
I understand your logic, it's alright
oop
very odd that it returns entity
the server banner changed
its now nothing
no banner
nvm the event thing was in the way
rawtext: [
{
translate: "death.attack.indirectMagic",
with: [entity.name, "entity.evocation_fang.name"]
}
]
How do I translate the evocation fang?
Read what is written in the errors
damn the chatSend is now -beta?
Is there not a method for spawning a loot table? Is the only way through runCommand?
i guess i didn't notice cause i love to use chatsend before with -beta scripts
yeah still commands
ah, hopefully a method is added at some point. guess ill stick with commands

