#Script API General
1 messages · Page 37 of 1
😎

tried that does not work
code
i did like try catch do { getblock } while (getblock === undefined)
don't have it anymore
nvm here
let claimWand;
do {
claimWand = world.getDimension("overworld").getBlock({ x: 2919, y: 59, z: 0 });
} while (claimWand === undefined);
claimWand = claimWand.getComponent("inventory").container;
You need to check this every tick via runInterval
nevermind the error is different now
okay i'll try that instead
let claimWand;
let _claimid = system.runInterval(()=>{
if (claimWand === undefined) {
claimWand = world.getDimension("overworld").getBlock({ x: 2919, y: 59, z: 0 });
} else {
system.clearRun(_claimid)
}
})
claimWand = claimWand.getComponent("inventory").container;
like so?
how is this possible
oh wait
let _claimid = system.runInterval(()=>{
if (claimWand === undefined) {
claimWand = world.getDimension("overworld").getBlock({ x: 2919, y: 59, z: 0 });
}
if (claimWand !== undefined) {
system.clearRun(_claimid)
}
})
maybe this i'll try
cos i realized the task will immediately be cleared
still does not work tho
function waitForBlockLoading(dimension, location, func) {
let interval = system.runInterval(() => {
if (dimension.getBlock(location) != undefined) {
system.clearRun(interval)
func(dimension.getBlock(location))
}
})
}
waitForBlockLoading(world.getDimension("overworld"), { x: 2919, y: 59, z: 0 }, (block => {
block.setType("stone")
}))
oh that's nicer
function waitForBlockLoading(dimension, location, func) {
let interval = system.runInterval(() => {
if (dimension.getBlock(location) != undefined) {
system.clearRun(interval)
return func(dimension.getBlock(location))
}
})
}
let claimWand = waitForBlockLoading(world.getDimension("overworld"), { x: 2919, y: 59, z: 0 }, (block => {
block.getComponent("inventory").container;
}))
why does it return void
yeah and it is, i tried to add a return to the functio nitself
currently i have this
function waitForBlockLoading(dimension, location, func, callback) {
let interval = system.runInterval(() => {
const block = dimension.getBlock(location);
if (block !== undefined) {
system.clearRun(interval);
const result = func(block);
callback(result);
}
});
}
let claimWand;
waitForBlockLoading(world.getDimension("overworld"), { x: 2919, y: 59, z: 0 }, (block) => {
block.getComponent("inventory").container
}, (result) => { claimWand = result; }
);
nvm that fixed it
For what?!?
what
the reason i need this is to preload an item stack i have saved in a chest so i can use it later
without having to get the block every time i want to do something with it
i've fixed it now, this works perfectly
thank you for the help!
ok..
You can't return a value directly from the code inside runInterval. Using function callbacks can get really hard to manage. You can create an async function that waits for the block if you want to return it directly. Something like:
export function waitForBlock(dimension, location) {
const block = dimension.getBlock(location);
if (block) return Promise.resolve(block);
let ev = {
promise: new Promise((resolve) => {
const runId = system.runInterval(() => {
const block = dimension.getBlock(location);
if (block) {
system.clearRun(runId);
resolve(block);
}
}, 1);
}),
};
return ev;
}
Where do I put this?
how long does it take to load a string from a dynamic property that is 18k characters long
I think somewhere around 0.5 ms
That's concerning.
what is
loading a string 18k chars in length or it taking 0.5ms
It will take much longer to turn this string into an object if you use JSON to store data
i'm implementing a rank system, and i need to reset the world's data and player data every time i wanna begin a new season
i only need to split it by each comma
every 9th character is a comma
my idea was that i have a list of rank redemption codes saved in a file
5 ranks, 400 codes each
the way you receive a rank ever is you're given a rank code
and the used codes would be stored in a dynamic property in the world
In any case, the receiving time is not so long that this would be a problem.
okay that's good to hear
i will have to prevent players from attempting to redeem in quick succession anyway
dont want people brute forcing the codes since the pattern is pretty simple
seems secure enough worst-case scenario it would take 1361 years to find a valid code
nvm i forgot there's more than one they can match for
with 2000 it would be 5.5h
💀
Why don't you just randomly generate the codes?
that wouldn't be a fixed list
did you see my original idea that i am implementing this for
I need a list of codes which can be used to redeem a rank, because I can't save it as a property of a player or of a world
seasons reset
players would lose their ranks
it would become hard for staff to manage requests to get a rank back
my idea is, if you're granted a rank, you get a rank code you can redeem instead of just straightforwardly being given a tag or a property in-game for it
So the idea is that staff don't have to log into the game to grant a rank? How are they keeping track of codes that are already given out?
dynamic property within the world
this is why it's good, the dynamic property will be reset if a new season starts
making each code redemptible again
no need for staff to interfere for the process of re-claiming your ranks on new seasons
If players can re-claim their rank in a new season then why are you clearing the rank at all? Wouldn't it be more convenient for everyone just to leave it?
can't leave it if i need to reset all progress
well i mean there are a few ways indeed but
those will be more tedious to set up
what if you want to quit, and wanna share your rank with somebody else later
this also makes it more convenient
world.afterEvents.playerSpawn.subscribe(() => {
if (!player.hasTag("join")) {
start(player)
player.runCommand('function kingdom_choose')
player.addTag("join")
} else {
return;
}
})```
"player" is not defined (at line 2)
world.afterEvents.playerSpawn.subscribe(({ player }) => {
if (!player.hasTag("join")) {
start(player)
player.runCommand('function kingdom_choose')
player.addTag("join")
} else {
return;
}
})```
ty
function doesnt wanna work
world.afterEvents.playerSpawn.subscribe(({ player }) => {
if (!player.hasTag("join")) {
start(source)
player.addTag("join")
} else {
return;
}
})
function start(player) {
const form = new ActionFormData();
form.button("human");
form.button("witch");
form.button("elf");
form.button("dwarf");
form.show(player).then((response) => {
if (response.selection === 0) {
player.runCommand('tag @s add human')
}
if (response.selection === 1) {
player.runCommand('tag @s add witch')
}
if (response.selection === 2) {
player.runCommand('tag @s add elf')
}
if (response.selection === 2) {
player.runCommand('tag @s add dwarf')
}
});
}```
full code
the menu isnt opening
In fact, the writing there is not very clear
So I'll go write my "guide"
ty I havent undersood anything from that
world.afterEvents.playerSpawn.subscribe(({ player }) => {
if (!player.hasTag("join")) {
start(player);
player.addTag("join");
}
});
async function start(player) {
const form = new ActionFormData()
.title("Choose Your Race")
.button("Human")
.button("Witch")
.button("Elf")
.button("Dwarf");
try {
const response = await forceShow(player, form);
if (response.canceled) return;
switch (response.selection) {
case 0:
player.addTag("human");
break;
case 1:
player.addTag("witch");
break;
case 2:
player.addTag("elf");
break;
case 3:
player.addTag("dwarf");
break;
default:
break;
}
} catch (error) {}
}
async function forceShow(player, form, timeout = Infinity) {
const startTick = system.currentTick;
while ((system.currentTick - startTick) < timeout) {
const response = await form.show(player);
if (response.cancelationReason !== "UserBusy") {
return response;
}
}
throw new Error(`Timed out after ${timeout} ticks`);
}
Sorry for late response, my internet sucks
dw
could you explain whats happening here?
So if player spawn and doesn't have the tag join it calls the functions, you said the form is not opening it is because when player is spawning it's not somewhat "ready" yet so the form didn't open, we make another function where if the form doesn't open because user is busy, it will try over and over again till it opens the form.
-# I hope my grammar isn't shit
cant we make the function run a bit too late instead of doing all that?
nah its perfect
We can but it's not perfect always since it depends the speed of the server.
It can be you want to open the form after 2 seconds syes it opens on local world but how about the server they can be slow and delay the readiness of the player
We made a function force show so that we could use it anytime we want
when playerSpawn fire the player is still joining the game and the joining ui is still showing
forms can't show up in top of other Uis that why we spam show formm until it show up (force show)
can you show me how cuz I need that for other stuff
Why did I even write this?
Idk 😭
future reference lol
You mean how to use the force show function?
no the delay
system.runTimeout(() => {
//code
}, 1 * 20); // 20 ticks = 1 second
And why the hell use this? It's not reliable
We already gave you a better solution and you want the hard way
I need it for smth else
admins should clean up that channel from duplicated posts an keep the best of them
If you say so 🤷
Nothing is clear about what was from Carchi77
and do u know how to make it so you cant leave the menu unless you press a button?
Just some piece of code and how to install it
yeah
there is another one
where?
Just detect the cancelation reason or check if the response is undefined call the form again
https://discord.com/channels/523663022053392405/1240067722281488485
-# i didn't say it is better
You have a mistake. Reasons for cancellation with a capital letter are necessary
Kinda like
if (response.selection === undefined) start(player);
if (response.canceled) start(player);```
Oww shii
It's just code, no explanation of what it is. What I have is that you can throw it at someone as an answer and not explain anything
The way you said it's a mistake I feel like you're angry at me
lol
no, I'm just correcting
Idk but I have this bad side that I always puts the await forceShow(player) inside of try and catch
huh
those are tow different things
I mean the try {} catch {}
ik
how dose try and catch relate to that
How to completely get rid of errors:
index.js
try {
// Importing all modules
} catch {}
yeah i am lost lol
Yeah I know just that, my brain automatically makes me do it.
Let's change the topic..
What do you guys think is a better way to activate an airplane?
Why are there no comments about the ingenious system?
Using WASD JUMP AND SNEAK button
Is it possible for a script to select a specific function file that I type the name of in chat?
wait for the input api i guess
sure
Yeah but I mean what do you think about the system... The player should hold the forward button to charge the airplane and so on and so forth
Wym by function?
Like a .mcfunction file
The main question: WHY?!
just get the name from chat and pass it to runCommand
that is kinda of a lot to ask for
do you have any script api knowledge?
no not much
If you want an add-on made for you for free, you're most likely out of luck. The best thing you can do is watch tutorials and read guides so you can learn how to develop it yourself.
People won't work for free, but you can always offer to pay them to make something for you.
when I leave it opens another menu and when I click on the buttons the menu before show up
Umm, make a post and wait for someone's help. I can't help you always cause I'm kinda busy too
Just put the code I made to that post
when its undefined or cancelled it opens a new menu and doesnt leave the one before so they stack
You can't have a stacked server form ui
you should start learning
we can only guide you in simple stuff that don't take much time
actually...
not stack at onece
and u can actually
What!
-# You don’t understand, you just need to create a separate post and then the script will definitely appear out of thin air (no)
w json ui I opened 3 menus at once and every button worked
I mean if you want to stack it's not ideal
spamming show form dose stack them
I mean yeah it stacks
that work some times tho
Why stack it if you can open a form based on what you only need 😭
I remember wonderful (no) times when I struggled with 20 forms opening at the same time. So yes, this could happen
system.runInterval moments be like:
That happened to me, since I'm kinda lazy to find a way to trigger it so I trigger it when the player sneaks 🤣
yeah
i only seen it when interact with block is used without any control or cool-down
HA, no. This happened because the player on the computer was holding down the block and his click was counted not only when he clicked, but also when he simply held down the mouse
sooo any idea how to fix that?
Could you show me how I would go about this?
Ayy lmfao
you know how to get the message from chat?
Wtf three mentioned in one chat
Wym fix it? It's already working well
Yea I use it fairly often for custom commands
.
Well you can use this -> https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server-ui/uimanager?view=minecraft-bedrock-experimental#closeallforms
world.beforeEvents.chatSend.subscribe(event => {
const message = event.message;
event.sender.dimension.runCommandAsync(`function ${message}`);
})
before calling the form
Much appreciated
Try making a post so it's faster.
ok
But what about canceling a message and an analogue of a custom command. I don’t think it’s cool to receive an error message almost always when you write in chat, and there’s no access rights check either
Lmao I once tried doing this.
world.beforeEvents.chatSend.subscribe(ev => {
const { message, sender, cancel } = ev;
if (message === 'bruh') cancel = true;
});```
Thx
Welcome, I guess?
im making a simple cooldown what should the catergory be?
"you get what you asked for"
whatever your item have
cooldown catergory
you can add it to your item
Is it possible to add property/dynamicProperty to any item?
only to unstackable at this moment
if you need stackable, maybs use lore or smth like it
This is what I need, my item only stacks 1 at a time
max amount on one slot is 1?
then you can use dynamic properties on this item
Yes
How can I make a custom command that only works with my nametag?
if (hasName:'name')
?????
Is it possible to set the entity like align it in the center of the block before spawning?
That's only if you're using Minecraft Preview.
What is Minecraft Preview?
Can I use 1.18.0-beta in a regular server?
1.16.0-beta
Minecraft Beta it's not released, it's just for testing...
afaik you can't.
Ah
No. It's a different version of Minecraft that isn't compatible with the regular game.
https://help.minecraft.net/hc/en-us/articles/4423653831821-How-to-Install-Minecraft-Preview
You want 1.16.0-beta.1.21.43-stable if you're using the beta API in the regular game
Dang, that sucks
1.17.0-beta
I was really looking forward to it
You need to wait next update
I guess I'll track player movement the old fashioned way
Just download / join the beta on the phone... Cause if you're using the old fashion way it would become useless next update
I'm sure it will still work the next update the way I'm prob gonna do it
if (sender.name === 'test')
Ok if you say so 🤷
I was kinda bored...
let jumpTime = {};
world.afterEvents.playerButtonInput.subscribe(({ button, newButtonState, player }) => {
if (button === 'Jump') {
if (newButtonState === 'Pressed') {
jumpTime[player.id] = Date.now();
} else if (newButtonState === 'Released') {
if (jumpTime[player.id]) {
const duration = Date.now() - jumpTime[player.id];
delete jumpTime[player.id];
const milliseconds = duration % 1000;
const seconds = Math.floor((duration / 1000) % 60);
const minutes = Math.floor((duration / (1000 * 60)) % 60);
const hours = Math.floor(duration / (1000 * 60 * 60));
player.sendMessage(`${player.name} held jump for ${hours}h:${minutes}m:${seconds}s:${milliseconds}ms`);
}
}
}
});```
Hello,
It’s been an hour now I’m on a problem that I can’t solve, someone could help me I’m currently.
let targetPlayer = args[1]
let newTargetPlayer = targetPlayer.replace("@", "")
if (!world.getPlayers(newTargetPlayer).hasTag(opTag)) {
///code
}
Is there any way to detect isWalking?
The only thing I see is player.isSprinting, and I'd like to check for walking as well
If not, how can I check movement direction with getVelocity
can I just do .getVelocity().x
and if it's over 1, it's going forward in x direction
over 0*
and if its under 0, it's going backward in x direction'
Wait should be
for (const player of world.getPlayers()) {
if (!player.hasTag(opTag)) {
// code
}
}```
What's the diff here between getPlayers and getAllPlayers?
yes but here you test if the player who has executed the command has the tag out I want to test a player aim```js
case 'cohost':
let args = message.slice(commandPrefix.length).split(/\s+/g);
let targetPlayer = args[1]
break;
and would this be a constant run?
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
let { forward, right, backward, left } = direction(player);
let text = ''
if (forward > 0) {
text = 'forward';
} else if (left > 0) {
text = 'left';
} else if (right > 0) {
text = 'right';
} else if (backward > 0) {
text = 'backward';
} else return;
player.sendMessage(text);
}
})
function direction(player) {
let velocity = player.getVelocity();
let viewDirection = player.getViewDirection();
let viewDirMagnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
let normalizedViewDir = { x: viewDirection.x / viewDirMagnitude, z: viewDirection.z / viewDirMagnitude };
let forwardVelocity = (velocity.x * normalizedViewDir.x + velocity.z * normalizedViewDir.z);
let rightVelocity = (velocity.z * normalizedViewDir.x - velocity.x * normalizedViewDir.z);
let backwardVelocity = -forwardVelocity;
let leftVelocity = -rightVelocity;
forwardVelocity = Math.round(forwardVelocity * 100) / 100;
rightVelocity = Math.round(rightVelocity * 100) / 100;
backwardVelocity = Math.round(backwardVelocity * 100) / 100;
leftVelocity = Math.round(leftVelocity * 100) / 100;
return {
forward: forwardVelocity,
right: rightVelocity,
backward: backwardVelocity,
left: leftVelocity
};
}```
This is not accurate if the player is in the wall the velocity freaks out
I just gave you a simple one because your old code isn't valid
Alright, thanks! That's all I need!
Not unless you put it on runInterval
That's not how you use query option
yes I knew but in fact ca 1hour ago that I am on top I can’t find a solution
Wait, explain it to me first what you are trying to do.
Je veux créer une commande personnalisée pour ajouter et supprimer cohost dans UHC, je fais cela avec opTag
here is a more complete version of my code
if (args[1] != undefined) {
let targetPlayer = args[1]
if (args[2] != undefined) {targetPlayer += " " + args[2]}
let newTargetPlayer = targetPlayer.replace("@", "")
log(newTargetPlayer)
if (validPlayer(newTargetPlayer)) {
if (!world.getPlayers(newTargetPlayer).hasTag(opTag)) {
runCommandAsync(`tag ${newTargetPlayer} add ${opTag}`)
world.sendMessage(`${glyph} ${sender.name} est maintenant co-Host de la partie !`)
sender.runCommandAsync("playsound mob.chicken.plop @a")
}else {
runCommandAsync(`tag ${newTargetPlayer} remove ${opTag}`)
sender.sendMessage(`${glyph} ${newTargetPlayer} n'est plus co-Host de la partie ! `)
sender.runCommandAsync("playsound mob.chicken.plop @a")
}
}else {
sender.sendMessage(`${glyph} !co-host @"Nom du joueur"`)
error(sender)
}
}
I want to create a custom command to add and remove cohost in UHC, I do this with opTag
oh Sorry, I didn’t see that I had sent my message in French
Ok first of all world.getPlayers() is an array so you can't just directly do it that's why I gave you a better one because we get every player inside of that array
Invalid:
if (world.getPlayers().hasTag('') {}```
Valid:
```js
for (const player of world.getPlayers()) {
if (player.hasTag('')) {
}
}```
cert it is not possible to find the player for mttre in a variable with . filter
This is not a full script and my eyes hurt reading this... Is this inside of chatSend?
yes
Send the whole chatSend
@dim tusk
That setup you gave me
I changed the
console.error
to world.sendMessage
What and do not tag me randomly
and I'm not getting any info back
I'm not tagging you randomly, It would be the same as repplying to a message of yours
But yeah, I'm confused as to why I'm not getting a message in world
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
let { forward, right, backward, left } = direction(player);
let text = ''
if (forward > 0) {
text = 'forward';
} else if (left > 0) {
text = 'left';
} else if (right > 0) {
text = 'right';
} else if (backward > 0) {
text = 'backward';
}
world.sendMessage(text);
}
})
function direction(player) {
let velocity = player.getVelocity();
let viewDirection = player.getViewDirection();
let viewDirMagnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
let normalizedViewDir = { x: viewDirection.x / viewDirMagnitude, z: viewDirection.z / viewDirMagnitude };
let forwardVelocity = (velocity.x * normalizedViewDir.x + velocity.z * normalizedViewDir.z);
let rightVelocity = (velocity.z * normalizedViewDir.x - velocity.x * normalizedViewDir.z);
let backwardVelocity = -forwardVelocity;
let leftVelocity = -rightVelocity;
forwardVelocity = Math.round(forwardVelocity * 100) / 100;
rightVelocity = Math.round(rightVelocity * 100) / 100;
backwardVelocity = Math.round(backwardVelocity * 100) / 100;
leftVelocity = Math.round(leftVelocity * 100) / 100;
return {
forward: forwardVelocity,
right: rightVelocity,
backward: backwardVelocity,
left: leftVelocity
};
}
Copy paste this again @distant gulch
I did, the only thing I changed was
Still not an excuse to tag me
Just copy paste it no shenanigans
the console.error
to world.sendMessage
There are no shenanigans, I can't check console on my server
export const opTag = 'operator'
export const commandPrefix = "!"
world.beforeEvents.chatSend.subscribe((event) => {
let sender = event.sender
let message = event.message
let args = message.slice(commandPrefix.length).split(/\s+/g);
if (message.startsWith(commandPrefix)) {
event.cancel = true
system.run(() => {
switch (args[0]) {
case 'cohost':
if (args[1] != undefined) {
let targetPlayer = args[1]
if (args[2] != undefined) {targetPlayer += " " + args[2]}
let newTargetPlayer = targetPlayer.replace("@", "")
log(newTargetPlayer)
if (validPlayer(newTargetPlayer)) {
if (!world.getPlayers(newTargetPlayer).hasTag(opTag)) {
runCommandAsync(`tag ${newTargetPlayer} add ${opTag}`)
world.sendMessage(`${glyph} ${sender.name} est maintenant co-Host de la partie !`)
sender.runCommandAsync("playsound mob.chicken.plop @a")
}else {
runCommandAsync(`tag ${newTargetPlayer} remove ${opTag}`)
sender.sendMessage(`${glyph} ${newTargetPlayer} n'est plus co-Host de la partie ! `)
sender.runCommandAsync("playsound mob.chicken.plop @a")
}
}else {
sender.sendMessage(`${glyph} !co-host @"Nom du joueur"`)
error(sender)
}
}
break;
}
}
})
}
I tested my script and it works idk your part.
I tested it to, and no information is being sent to me
The only thing I need to import
is world and system
from "@minecraft/server"
Hmm, how does the command format look when you type in chat?
right?
like this !cohost @LunaireI
export const opTag = 'operator';
export const commandPrefix = "!";
world.beforeEvents.chatSend.subscribe((event) => {
const sender = event.sender;
const message = event.message;
if (message.startsWith(commandPrefix)) {
event.cancel = true;
const args = message.slice(commandPrefix.length).split(/\s+/g);
switch (args[0]) {
case 'cohost':
if (args[1]) {
let targetPlayer = args.slice(1).join(" ").replace("@", "");
const targetPlayerObject = Array.from(world.getPlayers()).find(player => player.name === targetPlayer);
if (targetPlayerObject) {
if (!targetPlayerObject.hasTag(opTag)) {
targetPlayerObject.addTag(opTag);
world.sendMessage(`${glyph} ${sender.name} est maintenant co-Host de la partie !`);
sender.runCommandAsync("playsound mob.chicken.plop @a");
} else {
targetPlayerObject.removeTag(opTag);
world.sendMessage(`${glyph} ${targetPlayer} n'est plus co-Host de la partie !`);
sender.runCommandAsync("playsound mob.chicken.plop @a");
}
} else {
sender.sendMessage(`${glyph} !cohost @"Nom du joueur"`);
error(sender);
}
} else {
sender.sendMessage(`${glyph} Utilisation: !cohost @"Nom du joueur"`);
error(sender);
}
break;
}
}
});
thanks you guy's
world.sendMessage(`${text}`);```
Not needed.
Since it's a string it should automatically convert.
Weird it did work on mine 🤷
Yeah but what if
I just did
world.sendMessage(`${text}`);
to be extra careful
but I tried thee other way too
Then I thought that maybe my script isn't working
so I did a simple itemUse
but my script isn't running at all
weirdly
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
let { forward, right, backward, left } = direction(player);
let text = ''
if (forward > 0) {
text = 'forward';
} else if (left > 0) {
text = 'left';
} else if (right > 0) {
text = 'right';
} else if (backward > 0) {
text = 'backward';
} else return;
player.sendMessage(text);
}
})
function direction(player) {
let velocity = player.getVelocity();
let viewDirection = player.getViewDirection();
let viewDirMagnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
let normalizedViewDir = { x: viewDirection.x / viewDirMagnitude, z: viewDirection.z / viewDirMagnitude };
let forwardVelocity = (velocity.x * normalizedViewDir.x + velocity.z * normalizedViewDir.z);
let rightVelocity = (velocity.z * normalizedViewDir.x - velocity.x * normalizedViewDir.z);
let backwardVelocity = -forwardVelocity;
let leftVelocity = -rightVelocity;
forwardVelocity = Math.round(forwardVelocity * 100) / 100;
rightVelocity = Math.round(rightVelocity * 100) / 100;
backwardVelocity = Math.round(backwardVelocity * 100) / 100;
leftVelocity = Math.round(leftVelocity * 100) / 100;
return {
forward: forwardVelocity,
right: rightVelocity,
backward: backwardVelocity,
left: leftVelocity
};
}```
This works very fine to me.
Maybe, but unfortunately, nothing in my script is working
I added this to make sure
world.afterEvents.itemUse.subscribe((e) => {
if (e.itemStack.typeId == "minecraft:stick") {
world.sendMessage("Working");
}
})
but that didn't do anything either
My script is bein all messed up
See, I said my scripts work fine.
They may or may not, unfortunately, my script is broken so I can't find out lol
Probably you disabled it on settings or json ui
But as I said it works. That's why I'm confused
Nah, I'm using a server, and I keep my server running the same all the time
I'll try copy and pasting this into a new addon
and see if it works
Did it work
Idk bout him, but I just made a new addon to test, and mine works, thanks!
Is there any way to make it test diagonals?
I'm terrible with javascipt Math
You mean strafe?
Like forward-left?
Oh, makes sense
just a
else if (left > 0 && forward > 0)
But to make it detect backward easier, can I just up the value from > 0 to > 0.5 or something?
wait, that would make it less detecting
I'll make backwards above left and right
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
let { forward, right, backward, left } = direction(player);
let text = '';
if (forward > 0 && left > 0) {
text = 'forward-left';
} else if (forward > 0 && right > 0) {
text = 'forward-right';
} else if (backward > 0 && left > 0) {
text = 'backward-left';
} else if (backward > 0 && right > 0) {
text = 'backward-right';
} else if (forward > 0) {
text = 'forward';
} else if (left > 0) {
text = 'left';
} else if (right > 0) {
text = 'right';
} else if (backward > 0) {
text = 'backward';
} else return;
player.sendMessage(text);
}
});```
You'll make it more not reliable, it's already not reliable you make it even more lol
Yeah, that's why I corrected myself
How can I make it so that it only interacts with the entity if it has a tag?
I'm using playerInteractWithEntity
The one who interacts or the target
interacts
if (player.hasTag('test')) {
// code
}```
Simple as that.
The /loot command always seems to spawn items on the edge of blocks. Is there a way to teleport each dropped item from the command to the center of a block?
block.center().location or block.center()
Yes, but regardless of the position input into the command, the loot will always spawn on the edge
- 0.5 on x and z
Still doesn't place it in the center. The command's probably bugged
Mmhm
you can run the command, then getEntites at the location, filter for items, and tp them to the center i guess
Alright, thanks
chuck the tp stuff in a system.run though, cause the items might not spawn in the same tick
Bonjour
Salut
Ça va?
Ohh, another bug?
That shouldn't happen in the first place.
Yeah, that's what I was thinking
Divine General Maharago
I managed to solve it by running some tests with the entitySpawn afterEvent though
Hi, how are you? Can someone help me recreate some scripts with the same functions?
only unstackable items
AHH
playerSpawn after events triggers after player join the world?
no, when the player spawns
yes it triggers after a player joins the world
you can use event.initialSpawn to see if it's their first time spawning (aka. they joined)
On a function flie can I create variables there? Or create variables in script and import it to my function file
es, by using the import and export sytaxs
playerSpawn triggers when the entity of a player has been loaded into the world
initialSpawn is a bool determining whether or not it is the first time the player’s entity has spawned in since they have joined
@ruby haven
// scripts/config.js
export const myVariable = 12;
// scripts/function.js
import { myVariable } from "./config"
they probably meant mcfunction files
Not a script file but a function file
ohhh, no you cant (i think)
i doubt that it’d be possible
by using scoreboard
I think this one has a bug
like
scoreboard players set "response:1" manager 1
// other .mcfunction
execute if score "response:1" matches 1 run ...
Oh okay well my only goal was to create a skill cause I have this fake block entity that is summonable and I want to create a circle ripple so I need a lot of summon commands with some delays between them
world.afterEvents.playerSpawn.subscribe((event) => {})
do it with script
No the intialspawn cause when I tried using it doesn't actually check if it is your firstime spawning
it does
I have this functions that run and the condition was if it was initiall spawn but when I tried leaving the game and joining back the function still runs so I have to make a tag system
So yeah it think it is definitely a bug
well, initialSpawn is true when its your first time spawning
not if you really jiined for the first first time
Well then it means that if it is not your first time it will be false
If that's the case then nah it's definitely a bug
No
initialSpawn is true, everytime you enter a world and the player spawns, if you die and the player spawns again, it will be false
Oh I misunderstood I thought it only checks the first time you spawned to that world
Well now you know
Just do
if he joins add a tag if he doesnt already haves it.so you can check if its his first join
Yeah that's what I did
world.afterEvents.playerSpawn.subscribe(({initialSpawn})=>{
if (initialSpawn) {
// Code
}
}
)
so then there is no issue
That is what I did but the function still runs if I rejoin the game
obviously?
initial spawn, meaning the first time their ENTITY SPAWNS as they join
doesn't matter if they're a new, fresh player
what matters is if their entity has been spawned for the first time since they initialize their connection
if (player.hasTag("isRegistered") {
// is already registered
else {
player.addTag("isRegistered")
// ..code
}
smth like that
without initialSpawn it will run if you warp dimensions, die, respawn etc
I thought you're telling that if intialspawn works like I thought cause @distant gulch already cleared out the misunderstanding for me
world.afterEvents.playerSpawn.subscribe(({initialSpawn, player})=>{
if (initialSpawn && (!player.hasTag("isRegistered"))) {
// Code to run when they join for the first time ever
player.addTag("isregistered")
}
}
)
Yeah that's what i did
i was giving out an example snippet and he answered after i had begun to write my answer already
Well we just repeated the same conversation we had with @distant gulch
I'm not trying to be disrespectful or something I'm just trying to clarify things
i got that dw
Guys
Quick question
Is the formValues can be changed to other names?
new ModalFormData()
.title('§lTpa')
.dropdown('select player!', playerNames, 0)
.show(player).then((Tpa) => {
if (!Tpa) return;
const selected = playerNames[Tpa[0]];
Like this
What is the command that centers an entity in a block?
entity.teleport(entity.dimension.getBlock(entity.location)?.center())
Can I use this in before events or after events?
Cause I want the entity to be centered upon spawned without delay if possible?
Guys
function tpa(player) {
const players = world.getAllPlayers().filter(p => p.name !== player.name);
const playerNames = players.map(p => p.name);
if (players.length === 0) {
player.sendMessage('§cno others player online!');
player.playSound('random.hurt');
return;
}
new ModalFormData()
.title('§ltpa')
.dropdown('select player', playerNames, 0)
.show(player).then((Tpa) => {
if (!Tpa) return;
const selected = playerNames[Tpa.formValues[0]];
const targetPlayer = players.find(p => p.name === selected);
if (!targetPlayer) {
player.sendMessage('§cplayer is offline!');
player.playSound('random.hurt');
} else {
requestTpa(player, targetPlayer)
targetPlayer.playSound('random.toast');
player.sendMessage(`§c§asent request to §b${targetPlayer.name}`);
player.playSound('random.pop', {
volume: 5
});
}
});
}
Why when I try to send a request to another player it will keep saying the player is offline?
I really can't find the reason
Who can help me solve this?
Try using world.getPlayers() instead of world.getAllPlayers and if it doesn't work just make it direct
It doesn't change anything
Like playerNames accesses the players directly and same with target player, they both have their own world.getPlayers() instead of relying on "players"
I said "try"
guys, how to make entity get a block in 10 block radius every 1 second?
ik that i gotta use system.runInterval, but im stuck at looking for a block in 10 block radius, i dont quite know how to do it
is there a way to pre-calculate the path that an ender pearl would pass through if thrown
do we have a limit of world dynamic properties to world?
pre-calculate the trajectory using math
I heard that too, but it's a disinfo.
just found out you can technically cancel ender pearls from tping when landing
not the dmg tho
world.beforeEvents.entityRemove.subscribe(({removedEntity})=>{
if (removedEntity.typeId == "minecraft:ender_pearl") {
let owner = removedEntity.getComponent("projectile").owner
let ownerLoc = owner.location
system.run(()=>{
owner.teleport(ownerLoc)
})
}
})
keys can only be 32k bit
so there is a limit, you probably will never reach it tho
i meant number of properties
yes but there's no property limit
according to them
there is
it's affects their number?
🤷
nothing is unlimited
the game is running in 32bit
oh
you mean int limit?
what if you removed the owner? (if we can)
char
let me try that
i feel like it might not have privileges
tho
I meant is there some artificial limit of several thousand properties per world
apparently not
as i said echa key can be 32k bit
if you used all string in that range you can't save anymore
okay
i.e. the number of properties is limited only by this?
Tutorial on how to eat up storage space
let pearlMap = new Map();
system.runInterval(() => {
world.getDimension("overworld").getEntities({type: "minecraft:ender_pearl"}).forEach(pearl => {
/** @type {Array} */
let path = pearlMap.get(pearl.id);
if (path) {
pearlMap.set(pearl.id, path + world.getDimension("overworld").getBlock(pearl.location).typeId);
} else {
pearlMap.set(pearl.id, world.getDimension("overworld").getBlock(pearl.location).typeId);
}
});
});
world.beforeEvents.entityRemove.subscribe(({removedEntity})=>{
if (removedEntity.typeId == "minecraft:ender_pearl") {
/** @type {Array} */
let path = pearlMap.get(removedEntity.id);
if (path) {
Frozen.Info(path)
if (!path.includes("minecraft:air")) {
let owner = removedEntity.getComponent("projectile").owner
let ownerLoc = owner.location
system.run(()=>{
owner.teleport(ownerLoc)
})
}
}
}
})
why does the owner not get teleported back
🤨
print the owner.location and compare it to his original location
it is my original loc
for whatever reason if (!path.includes("minecraft:air")) is returning false?
world.beforeEvents.entityRemove.subscribe(({removedEntity})=>{
if (removedEntity.typeId == "minecraft:ender_pearl") {
let owner = removedEntity.getComponent("projectile").owner
let ownerLoc = owner.location
Frozen.Info(JSON.stringify(ownerLoc))
/** @type {Array} */
let path = pearlMap.get(removedEntity.id);
if (path) {
Frozen.Info(path)
if (!path.includes("minecraft:air")) {
system.run(()=>{
owner.teleport(ownerLoc)
})
} else {
Frozen.Info("was false")
}
}
}
})
fixed it
world.beforeEvents.entityRemove.subscribe(({removedEntity})=>{
if (removedEntity.typeId == "minecraft:ender_pearl") {
let owner = removedEntity.getComponent("projectile").owner
const ownerLoc = JSON.parse(JSON.stringify(owner.location))
Frozen.Info(JSON.stringify(ownerLoc))
/** @type {Array} */
let path = pearlMap.get(removedEntity.id);
if (path) {
Frozen.Info(path)
if (path.replace(/minecraft:air/g,'') !== "") {
system.run(()=>{
owner.teleport(ownerLoc)
})
} else {
Frozen.Info("was false")
}
}
}
})
yeah
I recorded 9999 dynamic properties without any problems
?!
yeah it can hold 2^32768 unique key
how does random math work?
Math.floor(Math.random() * 100) + 1``` to return a random integer from 1 to 100.
If you don't add the + 1 it will generate numbers from 0 to 99
Yo if I use yield; early on in the loop would it return immediately or complete loop unless told to return?
(For example)
system.runJob(function* someName(){
for (let I = 0; I > 1000; I++) {
yield;
let someThing = false;
if (someThing) return;
console.warn('Bay Harbor Butcher? NAH more like Bay Harbor Baddie');
}
});
Math.random generates a random number from 0 to 1.
It's up to you to decide how to apply that math.
Would the code run or not? Would it affect how mc calculates the time required for the loop not to lag?
can i set the name tag of an entity to show up differently for a client receiving some form of packet using server-net
Is it possible to make the player's name not appear?
That is, the name does not appear above the character.
From how I understand it, the Job loop will evaluate if it has time left at each yield statement. So in theory that should pause at the start of each loop
If I set a property on an item, will all other items that are the same have the same property value?
No, only the item you set will have that
does anyone know why ```js
function getNearbyEntities(player, maxDistance) {
const nearbyEntities = player.dimension.nearbyEntities({
maxDistance: maxDistance,
families: ["mob", "player"],
location: player.location
});
return nearbyEntities;
}
isn't working?
its not working
you guys should make posts
@uncut summit Please don't make a post and then repost it here.
when I remove families, it works and returns all nearby entities. When I add families back, it stops
i looked on the wiki, it says "mob" accounts for all mobs, including passive and hostile
so not sure what's causing it
oh ok
nearbyEntities is not a method.
my fault, meant to put getEntities
it wasn't a copy paste of my function, it was a retype, but original function is correct
and dont make this a function, just put this in a variable
to get the entities within this array, just use a for loop.
im using it for multiple weapons tho
rn I have the same getEntities in each so i thought making it a function would be cleaner
but do u know what's wrong with the families parameter?
looks right to me.
hm
const stone = Object.values(Protection_Stones).find(stone =>
item.typeId === stone.id && item.name === stone.nombre
);
anyone willing to help me with setEquipment issue? I don't get the problem. (even though nobody responded) although the chat function works but the setEquipment is an issue I don't understand.
The error is straightforward, item is not defined
equippable component only works in player rn...
@dim tusk I think it has to be the item.name
well it might be but I managed to do it on simulated players. You just have to go far away until the simulated player is a (classic not very classic but the one without the steve smile) and the equippable (e.g, offhand) will appear but with other ones it'll just put on automatically.
plus I get it. It doesn't work, but I also don't think mojang is going to work on simulated players anyway :/
I can't help you if you only give me that short code.
Hmm, I never touched simulated players so I cant really say anything but I'm sure the equippable component is not working with entities rn
I'm trying to grab a custom entity I made. I can even spawn it, but I can't get it from world.getEntity()
world.afterEvents.itemUse.subscribe((e) => {
if (e.itemStack.typeId == "minecraft:gold_nugget") {
e.source.sendMessage("Working");
const playerLoc = e.source.location;
const playerView = e.source.getViewDirection();
const playerHyp = Math.sqrt(playerView.x * playerView.x + playerView.y * playerView.y);
e.source.dimension.spawnEntity("mm:empty_entity", e.source.location);
e.source.sendMessage("Working2");
const fireballTp = system.runInterval(() => {
world.getEntity("mm:empty_entity").applyKnockback(playerView.x, playerView.y, playerHyp, playerHyp);
})
system.runTimeout(() => {
system.clearRun(fireballTp)
}, 60);
}
})
The only thing showing an error is the world.getEntity("mm:empty_entity")
ah nvm
maybe
idk
There is no getEntity
well bridge told me there is
but either way, I have a solution
maybe
If you have another way, I'd be glad to know
nvm, my solution is screwe
screwed
spawnEntity returns the entity object.
...
const entity = e.source.dimension.spawnEntity("mm:empty_entity", e.source.location);
e.source.sendMessage("Working2");
const fireballTp = system.runInterval(() => {
entity.applyKnockback(playerView.x, playerView.y, playerHyp, playerHyp);
})
system.runTimeout(() => {
system.clearRun(fireballTp)
}, 60);
}
I can give it to you sl privd the rest of the code if it wouldn't be a hassle
Ah, the entity is from that command
thanks
script*
now I just need to fix some stuff up
Can anyone tell me the math needed to use applyKnockback in the exact direction I'm looking?
why'd you delete your message @ruby haven it's correct tho
I don't really know the math
entityComponentRegistry.registerCustomComponent('example:test')
Does this exist?
Where'd you get that in the first place?
Custom components do not exist for entities; there is no need for them
Is there an alternative to register a component group?
What do you need it for?
I want to make an item that when you right click it gives you life and another that subtracts life.
So you want it to increase your max hearts?
Would that not be an item custom component?
That's possible
Yes
Ah, or are you talking about specifically the health part
You can change your max hearts in player.json based on a tag
For that, component groups are your friend
and you can change your tag with the item
Unfortunately, you'd reach a limit
but that limit is based on how many times you are willing to copy and paste
You got no choice 🤷
"minecraft:health": {
"value": 20,
"max": 20
}
},
"custom:health1": {
"minecraft:health": {
"value": 25,
"max": 25
}
},
"custom:health2": {
"minecraft:health": {
"value": 30,
"max": 30
}
}
Anyone here have the time and passion to volunteer for an on-going Create port for completion ?
"component_groups": {
"custom:health1": {
"minecraft:health": {
"value": 25,
"max": 25
}
},
"custom:health2": {
"minecraft:health": {
"value": 30,
"max": 30
}
}
},
"components": {
//...
}
Is there an easy way in scripts to change an entities targeted enemy. Like let's say I want a skeletons aggro to be changed from its current target to like a specific frog nearby for some reason
used to be able to, it was removed awhile back.
Gotcha darn
guys, how can i detect a block in a ten-block-radius for entity?
you have to use blockVolume
i dont know how to use it, that's y im asking
mind if I dm you?
oki
Do you know about it ? Can i ask you for somre help ?
Just a note. It’s better to write your problem right away than to wait until they answer your “may I ask?”
Is it possible to detect if an entity has a runtime identifier of a boat?
I dont think theres a way to check for runtime ids
Hmm, in you're in phone and use touch and use the WASD pad, when you're in boat in the getMovementVector() cannot be triggered no matter what..
Looks like I'll just make the player stop riding any entity
It seems like the size of all dynamic properties in the world should not exceed one mb?
wdym
i mean
I heard that the byte size of all world dynamic properties cannot exceed one megabyte
that is not true
one megabyte sounds too small
i think there is a limit on how much you can save in a tick
i remember getting a warning related to this
Oh, okay
How do I make it so that when an item spawns it gains a dynamicProperty?
is it possible to accurately get a player's ping
Is it possible to detect if a players model is slim or not cause I made this custom animation and model for the characters player but when my character switches to slim the skin breaks
in world/realm no server
how do you check if a player has an item?
In rp there's a variable called variable.short_arm_offset_left and variable.short_arm_offset_right that will detect if you have slim skin but player needs to go in first person first before this triggers
Wym by spawn, as an entity?
You can't do that since scripts are server side the close one is TPS, tick per second of the world.
In which slot?
is there a way to disable players from stopping sprinting when attacking other players/entities?
so you can't do it for all at once? You have to check each slot category?
Yeah, you need to check each slot... Also for armor and offhand you use a different way too
for inventory you use player.getComponent('inventory').container and player.getComponent('equippable') for armor and offhand
well that sucks. I guess I'll have to make that into a function for convenience.
Do you know how to check each slot using the inventory component?
const inventory = players.getComponent('inventory').container;
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
}```
I was looking to check if a player had an item in any possible slot: inventory, hotbar, hands, and armor
how do i check if a location is inside loaded chunks?
The inventory checks the hotbar too soo
someone?
No I think? The closest thing you can do is make the entity keep moving using applyKnockback()
What I mean is, the system assumes we are not running (isSprinting) when we do running and hitting at the same time. I want when we hit while running, the system still detects that we are running.
How to I applyKnockback in the exact direction I'm looking? I'm using a runInterval to apply knockback to an entity in a straight line, but I can't get the angle right
let view = player.getViewDirection()
player.applyKnockback(view.x, view.z, 1, view.y)
Can I make the entity float? Like just float doesn't levitate or go down just float?
I've tried that
Can I make the entity float? Like just float doesn't levitate or go down just float?
but it's unprecise
applyKnockback is never accurate
Is there a more accurate way?
no
To make a bullet/fireball
or anythinfg that goes straight in the direction I'm looking
anything*
alr
that sucks
Alright, then one more question for you
how can I set the rotation of a mob to face a player
or would I have to use commands?
I mean like the alternative of has_gravity in json.. and I don't want to modify json that's why I'm asking here lol, idk math
- Invisible entity with Boat/Shulker hitbox as a platform.
- Spam
.teleport() - Spam
.clearVelocity() - Spam
.applyKnockback()or.applyImpulse() - invisible blocks
- rides a custom invisible entity.
- Fake it using custom animation while the entity is actually standing on the ground.
Your choices.
Can you detect player.isInWater, and if there is an air block at their head location? If there isn't make a very small applyKnockback with only y strength?
What.
You asked how to make an entity float
I'm assuming you are referring to water, as that's where buoyancy takes place
No, I literally said has_gravity, so I mean in the air
yes
Hmm, yeah saw that.
What's the value do I put in impulse?
why cannot you just use teleport()
I'm riding it
Shouldn't the player also get teleported?
It does dismount the player
ok, I'm calling shenanigans... The Dimension class on MS's stable API's page clearly shows that it has a containsBlock method, yet visual studio has no reference to it for @minecraft/server v1.15.0
That's not a very obvious thing. It would have been easier if you had said "in the air". Gravity takes place everywhere
Probably the visual studio isn't updated that why 🤷
Common sense, gega even understand it
It's in RC.
RC?
^
Release candidate.
Well your common sense is flawed. I would appreciate it if you were a bit more respectful in your speaking to me, as up until now, I've stayed very respectful to you
So they jumped the gun on updating the Stable API documentation?
Let's stop here. Gega understand it immediately and it's not my fault you thought it's like that 🤷
Idk. I dont use ms docs for scripting.
alright, fair enough
I'll gladly stop here
must be script thing then
-# Doesn't dismount me ^
Idk, but yeah I just used clearVelocity()
Ngl, I kinda forget that existed lmao
Looks what I did just trying to experiment things.
It looks like the teleportation doesn't reset the falling momentum, idk, maybe just weird unintended bug
Y'know what's funny? I didn't use teleport to move the armor stand in the block I was looking at... I used applyImpulse
Good job 👍
dimension.getEntities({ location: { x: 0, y: 0, z: 0 }, maxDistance: 10, type: 'minecraft:creeper' });
ty bro
Hmm, I stringified the location, and face location in getBlockFromViewDirection and the stringified values are flipped instead of { x: 0, y: 0, z: 0 } it's { z: 0, y: 0, x: 0 } I remembered someone pointed this out last year...
This works differently on Windows and Android
That's cool...
Just do it manually, its the only way
It's not really that important, I just wanna fetch the the locations... Not too crazy about it. I'm just curious why it's flipped
When using spawnItem is the item like an entity?
howdo i get tps? runinterval and check how many ms it took for 20 attempts?
import { ItemStack } from '@minecraft/server';
const itemStack = new ItemStack('minecraft:stick', 1);
itemStack.nameTag = 'Bruh';
itemStack.setLore(['Bruh','Yes']);
const entity = dimension.spawnItem(itemStack, location);```
how do arrows store their piercing level?
const item = new mc.ItemStack(itemId, 1);
mc.world.getDimension("overworld").spawnItem(item, entityLoc);
I did it like this, is it possible for me to use dynamicProperty, like:
item.setDynamicProperty("seal", true)
some kinda of data (not accessible)
unfortunate
before spawnItem
np
Na there is a command called inputpermission you can achieve that with it
@ruby haven this is what he meant.
I see I think he wants to make combos thingy
you cannot disable sprint with inputpermission
you can "disable" it other ways
what other ways besides slowness
Yeah I just saw it
set speed value on sprint
Is there any way to this?
yeah that
ive disabled sprinting with it before, but it was weird
how so?
its been a bit, i'll have to do it again to explain.
no need
i guess it well be
sense it take a moment to change
that wasnt the problem I think
ill mess around with it again at some point and let you know.
alr
What does struct Scripting::FutureType entail in scriptstats?
Is that await/run jobs?
has there ever been a update from this?
whats the max size limit for script event messages?
2500 chars

Nope, that was it. I haven't touched scripting for almost 2-3 months
2048 bytes
another 
what do you need it for?
someone suggested me to use script event so that i could implement cross compatibility for other addons
communication?
yep
shameless plug time, you could use this: https://discord.com/channels/523663022053392405/1277940040688996512
Is it possible to create a boomerang type projectile using scripts there is an angle offset parameter in the projectile component but I think it only works vertically so I want to make a curving projectile horizontally
I guess so? Just make a function that converts points into curves.
I just realized there is a shulker bullet and also a homing component
Iirc the shulker bullet has hardcoded speed, so the speed the shulker have will be same if you sue it on your own.
const head = player.getHeadLocation();
const view = player.getViewDirection();
player.dimension.spawnEntity('minecraft:pig', { x: head.x + view.x * 2, y: head.y + view.y * 2, z: head.z + view.z * 2 });```
Tysm
can i kill a player with a specific death reason?
player.applyDamage(999, { cause: "anvil" });
has to be an acceptable damage cause
ah
like "freezing", etc
so anything in EntityDamageCause class?
yes
will .getEntities() with EntityQueryOptions also include entities in unloaded chunks?
don't think so. doing /testfor @e[type=type] with that entity doesn't return it if it's in an unloaded chunk
fr
imo bedrock should still return entities in unloaded chunks. Think it does on Java
how do i check what block a player would be interacting with if they clicked on the screen (like getting block from view direction, but w support for mobiles)
Wym by clicked on the screen?
Is the breaking or interacting one
Coddy
Coddy
Coddy
How the heck do I identify the interacting entity with InteractWithEntity?
world.beforeEvents.playerInteractWithEntity.subscribe(event => {
const { player, entityTarget } = event
if (entityTarget.typeId != "ssak:condition_changer") return
})
it's target not entityTarget
-# sorry for late response.
OMAAAAGAA
Is it not possible to transform target into a variable of type entityTarget?
world.beforeEvents.playerInteractWithEntity.subscribe(event => {
const { player, target: entityTarget } = event
if (entityTarget.typeId != "ssak:condition_changer") return
})
That??
That's kinda creepy ngl

I forgot the reference Amanai ohh my god, my brain is slow as fuc in references
Both basically
i need like the view direction but based on the position they’d be clicking on if they touched the screen/left clicked
to make it movile compatible
cos viewdirection is not
Do you need to get directions from the player to some point (block)?
No i need to find out if they were to interact with an ender pearl, what block would be in front of the path first
need to check if they are trying to use it directly on a block
i dont want ppl to pearl glitch easily
Can I access an entities anchor through scripts?
There is still no way to get the item translation code, right?
This addon is fully translated https://t.co/xOcqcv6kZK
I think I know why
how do i check what block a player would be interacting with if they clicked on the screen (like getting block from view direction, but w support for mobiles)
You can only do it inside world events that can provide the block that's been interacted with.
playerInteractWithBlock or itemUseOn
okay i'll check that out ty
how do i create a new Block object
i need to return default values on .getBlock() but i cant figure out how
Dimension.getBlock({ x, y, z })
Entity.dimension.getBlock({ x, y, z })
Entity.dimension.getBlock(Entity.location})
const block = overworld.getBlock(location) ?? dimension.getBlock(location)
is cancelling these supposed to prevent projectiles from being fired
No, that's itemUse
Is there a way to make the spawned arrow through scripting unclaimable?
unclaimable?
Like it can't be picked up.
you can do
player.nameTag = "name"
this will change a player's display name
Ok
Would it be possible to detect items despawning and have it say something like “[item] despawned” in chat
Documentation for @minecraft/server
yeah that work
Can lore be translated?
I don't think so
Can you at least access the global variables before the world was /reload or closed? I know dp exists but I'm kinda curious if you could access it before the data is erased
no
not in reload
maybe in world close (preview)
I'm in preview what is it?
You mean the worldInitialize?
k, lemme try that.
Minato idk if this is intended behavior because I'm using a local world but when you /reload it can access the variables but when leaving the world no. Lol
You could try I'm in 1.21.60
can't right now, sorry
Nah it's okay.. just weird because it's the opposite of the descriptions
try PlayerLeaveBeforeEvent?
Why? Leave before events can access the variables
I did tested it.
the game clear the variables before shutdown event fire?
No, it literally can grab the variable before it clears them
This is the script, sorry kinda messy. I was testing some things
Want to send me a vid?
isn't that what you want?
me?
Yeah, but the description of the class is the opposite of it lol
No, me... Nvm maybe I used it wrongly or because I'm on local world
there is not mention on how vars are handled there
Hmmm, either way that's what I want so I ain't complaining 🤷
🤷
Guys is there a way to add extra in unnamed item? Like it would be <name> - <other>
Since the nameTag returns undefined if the item is unnamed...
Grab item typeId & format it, it's the best you'll get
Expected but sad.. thanks tho
How much characters is limit on lore again?
Or what's is the limit
-# sorry for grammar
Nvm found it.
List of lore lines. Each element in the list represents a new line. The maximum lore line count is 20. The maximum lore line length is 50 characters.
keep in mind you can use line break
Yeah I know but still doesn't fix that I can't access it's original name 😞
we well get client side scripting one day.... i hope
Funny cuz you can access it with commands
I think you can do that through json by using tag system
name=
anyone happen to know if there's a way to find an entity's component groups from script api? I'm trying to figure out if a bee has the "angry_bee" component group applied, but I haven't been able to find it as a component or property or tag. I'm not sure if there's any other way to interrogate an entity for the information
You can't detect groups via scripting.
well, that's unfortunate. I really didn't want to have to change the bee's entity code
Angry bee? Maybe Entity.target (beta)
why this happen?
import * as jjba from "@minecraft/server";
jjba.system.runInterval(() => {
for (const player of jjba.world.getPlayers()) {
player.runCommandAsync(`execute at @s run say gay`)
}
}, 1);
What format version is your manifest?
Try using a newer format version like 1.20 since the execute command you used is new format
And just do player.sendMessage("im gay")
this is an example
for the execute
Hmm, but don't keep using the run command it can be slow sometimes so use the API version as much as possible...
alr ty
🫂
I'm not entirely sure what to do with that.
Since we can't check the components groups itself, M9 I think is trying to suggest to use this to detect if that entity triggered that specific event e.g. minecraft:entity_born or minecraft:become_pregnant
Anyone know why the BlockPermutation.getState had a restrictive type constraint added to it? This breaks basically all custom block examples if you're using 1.18 beta
What's a type constraint?
they still work, the typings just yell at you
iirc there's a workaround for it
somewhere
Oh, the typing.... make sense
Bit odd this change got put in when it breaks stuff
is it working well?
uhhh i just kinda didnt use it cuz
i dont wanna force other addons to use it
Thx, but I was abt to point eventData.getModifiers()
hmm it doesn't force other addons to use it. Unless you're meaning if they want to communicate, otherwise it's completely compatible with other addons
is there an easy way to make a delay system? I want to make a countdown system with a bunch of camera commands, but having a bunch of system.runTimeout() inside of eachother is very unreadable
Ohh, sorry I did say another misinformation... Lol
async function, and then use await system.waitTicks(10) in between your cmds
thank you
I'm sooo stuuupid.
The .show().. I was so confused why its throwing error Cannot read canceled of undefined, I literally destructured it... Ughh
.show(player).then(({ selection }) => {
if (selection.canceled) return;
});```
I literally did that
Whatt
Selection alr is a property💀
yes I know that I was so air headed because I was so focused on one thing I forgot how the other thing works ..
Oh
Can you show an example for this?
async function test() {
console.warn("test1")
await system.waitTicks(10)
console.warn("test2")
}
I see. Thanks!
world.beforeEvents.playerBreakBlock.subscribe((event) =>{
const player = event.player;
const block = event.block;
if (block.type.id.includes("log")) {
player.applyDamage(5);
}
});
First time getting this error
So I add system.run
yes
Question, how can I apply damage to the player when he starts punchin a block
world.afterEvents.entityHitBlock.subscribe((event)=>{
const {damagingEntity} = event
damagingEntity.applyDamage(1)
})
Oh k
Can I position a projectiles offset from an entity using scripts cause I tried it in json but I have no idea where my entities anchor is located at cause that is where the offset parameter bases it's values
Is it possible to set it so a block can store data when a chat command is run?
Essentially I want to try make a block execute a function file (selected by trying a chat command with the file name) and say for example the block is powered it runs that function is something like this possible?
guys, i need some help. i have a scriptevent for entity, the entity runs scriptevent command with timer, basically, i need to remove the item in entities hand. entity picks up the item, everything works just fine, but when i try to check if the entity has item in hand, i get this error
i dont understand y, since in jayly's script documentation it's stated the equippable component exists for every mob entities
code
always show code
import { world, system, ItemStack, TicksPerSecond } from '@minecraft/server'
system.afterEvents.scriptEventReceive.subscribe(({ id, sourceEntity: magmaGolem }) => {
if (id === 'v360:magma_golem') {
const mainhand = magmaGolem.getComponent('equippable').getEquipment('Mainhand')
if (mainhand?.amount >= 1) {
system.runTimeout(() => {
magmaGolem.getComponent('minecraft:equippable').setEquipment('Mainhand', new ItemStack('air', 1))
}, TicksPerSecond * 1)
}
}
})```
i tried and with minecraft namespace, and without, doesn't work...
I don't really trust the information that equippable is now available for all mobs, although it seems to be written in the documentation (but I need to check). But here the error is different... how is the /scriptevent command called?
entity has a timer, and when time comes, entity runs event with queue_command
"events": {
"v360:eat_item": {
"queue_command": {
"command": [
"scriptevent v360:magma_golem"
]
}
}
}```
Apparently it doesn't work that way, for some reason...
Try just using system.runInterval in the script
oki, one sec
still getting the error O_O
.
import { world, system, ItemStack, TicksPerSecond } from '@minecraft/server'
system.runInterval(() => {
world.getDimension('overworld').getEntities({ type: 'v360:magma_golem' }).forEach((entity) => {
const mainhand = entity.getComponent('equippable').getEquipment('Mainhand')
if (mainhand?.amount >= 1) {
system.runTimeout(() => {
entity.getComponent('equippable').setEquipment('Mainhand', new ItemStack('air', 1))
}, TicksPerSecond * 1)
}
})
}, 100)```
Have you removed the scriptevent in the entity code?
yes, and timer, and event

By the way, you don't need to do that. You can write undefined or just don't write anything there
oki
But how can it be that getEntities returns an array that may contain undefined?...
Are you sure the code has been updated?
yes
equippable only exists for players
then how can i make the entity still pick up the item to its hand, and then via script, remove the item from hand?
And I knew that I couldn’t trust the documentation))
i thought equippable works for non player entities...
/replaceitem command
Apparently this is information from beta and it is possible that this will come into force in the future
right, i forgot about it
it used to, but they removed it because some entities equip things weirdly (e.g. foxes using their mouth as a hand)
For the fox, it makes sense
i actually was kinda making this entities code from fox code btw, so it picked up the items and ate them, but i found out that entity eats only food items
i'll try to achive my goal with /replaceitem, thank u Serty
unless they plan to add a "mouth" slot, i think they should add equippable back because it makes a lot of thing impossible now
agree
Simply placing the rightItem group in the fox's mouth is not an option, yes... We must remove the component for all entities. Brilliant
hmm, maybe a new component would be better, like "minecraft:mouth_equipable"
is it possible to add owns? i dont think so but maybe it is
You don't understand. Removing the component for all entities is much cooler
hmm, right
Only tthe fox should be able to use it
because its more useful
Maybe make that the Fox is the only entity you can "interact" with!!
i got it! and fully in json =D
Hello, I’d like to ask a question. Is it possible to change player characteristics, such as speed or strength, without using /effect?
Speed probably, I think for strength we can make that the damage of the entity deals to other and multiply it... movement entityHurt applyDamage
const move = player.getComponent('movement');
move.setCurrentValue(2);
world.afterEvents.entityHurt.subscribe(({ damageSource, hurtEntity, damage }) => {
});```
How can I see a list of events
What events?
Script api events
https://jaylydev.github.io/scriptapi-docs/latest/index.html
Just search to find your needs
I just want a list of usable after/before events
Ohh my bad, serty gave it tho.
@dim tusk this still happens, whyyyyy? 😭
import * as jjba from "@minecraft/server";
jjba.system.runInterval(() => {
for (const player of jjba.world.getPlayers()) {
player.runCommandAsync(`execute at @s[tag=has_stand] run tp @e[type=dekuh:star_platinum,tag=stand_of_${player.nameTag}] ^-0.7^0.1^ facing ^^^4`);
}
});
my manifest is right
player.runCommandAsync(`execute at @s[tag=has_stand] run tp @e[type=dekuh:star_platinum,tag=stand_of_${player.name}] ^-0.7^0.1^ facing ^^^4`);```
but the error is in >@s<
(i know i forgot the run)
Leave it, I'll solve it
Try using old execute command format to see if it still throws error
btw guys is this valid on ActionFormData's body... Idk how to use rawtext in scripts lmao...
.body({ rawtext: [ { text: '' }, { translate: '' }, { text: '' } ] })
-# edit: yes it does infact work
Like <text> <translated> <text>
Valid?
execute as?
How do you hide the "Has custom components" on items?
/gamerule showTags false
Thanks
Is there a place to submit feature requests for bedrock scripting APIs? It'd be awesome if there were a BlockCustomComponent callback for whenever redstone power level changes
Use the onTick component to check if redstone power changes
Sure, that's a lot more heavyweight than it being something handled for you though
how do you spawn a smal mob?
I've installed NPM typings but my intellisense still isnt working. Any ideas?
Intellisense is installed and updated correctly?
Can an Add-On A read a dynamic property from Add-On B?
no
Yea if U save in world
Why
they're saved and read per pack header uuid
Dynamic Property is a value(data to save in the world bro

