#Script API General
1 messages · Page 43 of 1
No
Btw can you specify wym by replaces button like put he button back?
Okay so the smile entity kills the player it doesn't actually die cause it has the minimum health component so it will be present in the death scene the problem is after the death scene I expect the player to actually die you know where the respawn UI appears but I can't override the minimum health component so there is no way for it to work
It works now
I just had to replace ‘north’ with like 5 or something
Any way to prevent the player from disappearing without the minimum health component when an entity kills it?
Lmao, see you did something wrong again
I STILL don’t understand why you used north
Because the numbers work and not the words.
Even in /setblock
it's just snippet okay?
-# and I forgot state name again
I still don’t know what you want from me
I thought I explained it very well
Yeah, but I was just making sure, if replace the button with another button or just place it back 🤷
Yeah… i place it back. obviously. once the player is tp’ed back to spawn.
I just destroy it so the player can’t push it again during the animation (the logic is all put into REACHING the button, not PUSHING it)
And for dramatic effect
Anyway im gonna get some dinner
Okay instead of using entitydie how about entity hurt detect if the health of the entity is 2 it will recreate the death scene but how do I make sure that even if the damage of the smile is 100 it will still leave 2 hearts for the player?
Script API isn't capable of doing that on its own at the moment. Assuming you are trying to prevent death.
Nooooooooo
Hello, I have question if there is possibility to trigger events on entity by using in entity behavior properties and control that by script?
Example: Entity has 0-1 properties if it has tag - "test0" it will change in script property to 0 and then event will be triggered and if it has "test1" tag it will trigger another event and it will be done in scripts too.
I don't want use only commands, because it must be set up for many entities on the map
That is possible.
Can you tell me/point me how I can achieve that? I've tried entity.setProperty("test:test, state);
And then in system.runInterval if entity has tag it will check player in radius like that in full script:
import { world, system } from "@minecraft/server";
const CHECKPOINTS = [7, 10];
const SIGN_TYPE = "test:entity";
// Function to set the entity's parkour display state
function setDisplayState(entity, state) {
entity.setProperty("parkour:display_state", state);
}
system.runInterval(() => {
const players = world.getPlayers();
players.forEach((player) => {
const scoreboard = player.getScoreboard();
let checkpoint = scoreboard.getObjective("checkpoint")?.getScore(player) || 0;
const queryOptions = { type: SIGN_TYPE, tags: ["tag1"] };
const nSigns = player.dimension.getEntities(queryOptions);
nSigns .forEach((sign) => {
const distance = player.location.distanceTo(sign.location);
switch (checkpoint) {
case 0:
if (distance <= CHECKPOINTS[0]) {
setDisplayState(sign, 0); // novisible
player.runCommand("scoreboard players set @s checkpoint 1");
}
break;
case 1:
setDisplayState(sign, 1); // appear
player.runCommand("scoreboard players set @s checkpoint 2");
break;
case 2:
if (distance > CHECKPOINTS[0] && distance <= CHECKPOINTS[1]) {
setDisplayState(sign, 2); // visible
player.runCommand("scoreboard players set @s checkpoint 3");
}
break;
case 3:
setDisplayState(sign, 3); // disappear
player.runCommand("scoreboard players set @s checkpoint 0");
break;
default:
break;
}
});
});
}, 20); // Run every tick (20 ms)
how can i make a entity MOVE, not teleport, in a given direction?
how do you make a custom component that ticks randomly ?
world.beforeEvents.worldInitialize.subscribe(event => {
event.blockComponentRegistry.registerCustomComponent("wiki:tick_component", {
onRandomTick: (data => {
let block = data.block
//Code
})
})
})
You life saver human being.
Thanks.
I want to make the random tick a certain range
like, from 5-6 ticks, execute the code
Script:
world.beforeEvents.worldInitialize.subscribe(event => {
event.blockComponentRegistry.registerCustomComponent("wiki:tick_component", {
onTick: (data => {
let block = data.block
//Code
})
})
})```
Block:
```json
"minecraft:custom_components": [
"wiki:tick_component"
],
"minecraft:tick": {
"interval_range": [5, 6],
"looping": true
}
Wait, so how can I set the time taken to move the given value?
it is applying velocity
not "move to" function
Oh :O
right...
now i get it.
function move(entity, vector, time = 1) {
let id = system.runInterval(() => {
if (!entity.isValid() || time < 0) return system.clearRun(id)
entity.applyImpulse(vector)
time--
})
}
Hi. I cant seem to get past and issue in having with privlages in a code i have:
import { HttpRequest,HttpRequestMethod, HttpHeader, http} from '@minecraft/server-net';
import { world } from '@minecraft/server';console.log("før senddata");
export function sendDataToWebsite(data) {
const url ="https//eozghbch9kyk3aa.m.pipedream.net";
const req = new HttpRequest(url);
req.body = JSON.stringify(data);
req.method = HttpRequestMethod.Post;
req.headers = [
new HttpHeader("Content-Type", "application/json")
];
http.request(req);
}
Is there something i am missing? I have server-net in my manifest and permission file in the config folder. On my server i also went inn and changed permissions on all folders and files for my addon to read/write. I am using crafty as a server client that runs in a Docker on my server that is using unraid (so Linux).
this is from nox7 with a proper A* algo and everything
Aw man that's genius lol. Would have taken me a while to figure out.
I thought it is a move to function.
it will look better if you set the rotation too
worst thing you can do with scripting is use AI. dont do it.
Yeah, I get that 🥺 , but I'm not programmer, I'm self-learner, so still using some chatgpt to some base of code is still better than doing all by myself for now. After month of trying I can do simple mechanics like changing blocks, dtecting entities, etc. But for complex scripts or something new is hard for me
The fact that you are a self-learner, on the contrary, should give you a bonus in development
And even if you don’t understand something, it’s better to come here than to an AI that writes absolutely meaningless code
|| By the way, how does a self-learner ask for help if he is a self-learner. It turns out that he is no longer a self-learner
||
So I don't know what am I 😵💫
So what do you need
I managed since my first message above about detecting property of entity to make script which is running events on entity by detecting player in radius.
I wanted do it by properties from 0 to 4 in entity behavior. Script should detect if player is near then change property from 0 to 1, if it's near and stay in radius then change from 1 to 2, if player leave radius it will change to 3 property and then after it will go back to 0.
I made that on in scripts and triggering event with animations
But it's on events not on properties
system.runInterval(() => {
for (let id of ["overworld","nether","the_end"]) {
for (let entity of world.getDimension(id).getEntities({type: "test:entity"})) {
let property = entity.getProperty("parkour:display_state") || 0
if (entity.dimension.getPlayers({location: entity.location, maxDistance: 5})) {
if (property < 2) entity.setProperty("parkour:display_state", property+1)
} else if (property == 3) {
entity.setProperty("parkour:display_state", 0)
} else if (property > 0) {
entity.setProperty("parkour:display_state", 3)
}
}
}
}, 80)
Thank you very much for help!
Do dynamic properties have a creation limit?
no
Thank you, I'm trying to learn, I have another question. Would it be better to save the properties on the player, or to create a system that saves every player in the game, setting properties for each one? Additionally, if I save the players in a map, will the player be removed when they leave, or will they remain in the map? Only if owner leave the world will all the variables reset, correct?
If a player leaves, his variable will not be available. You can check if it is available via the player.isValid() method. When a variable is not available (the entity is not in the world) then you cannot use its methods and properties
I am trying to create a tool to simplify some functionalities during script creation. I'm not sure if it's correct to save this data on the player, or if I should save everything internally in the code.
There is no need to save to the world as it does not change during the game so just save in variables
That doesn't answer my question.
Then I didn’t understand what you needed
It may be obsolete since they have a dedicated event, but I feel like that event is a waste of resources and would be better suited the other way. Personal opinion and thoughts.
Could you provide further clarification? Are you referring to EntityLoad being a waste of resources and should be merged into EntitySpawn?
Correct
Inclined to agree when EntityInitializationCause contains a loaded member.
I suppose raising a ticket may bring resolve.
I already brought it up in the OSS and bumped my message there already. Just gotta wait to see if Navi notices.
Hey, with @server-net I am getting
TypeError: Native property setter [HttpRequest::method] cannot be assigned null or undefined
the doc's example says this req.method = HttpRequestMethod.Post
but mine says Post doesn't exsist its POST request.method = HttpRequestMethod.POST
I've debugged this on it's own and the enum returns undefined.
Imports:import { HttpRequest, HttpHeader, HttpRequestMethod, http } from '@minecraft/server-net';
#1067535608660107284 message I can see someone had the same and setting it to 1.0.0-beta fixed it for them but I am already using it
try using the string directly "Post"
ah new errors, that's progression 😆 thanks
ayee, db insert working, that was the fix thank you 
ur wlc
You might have been using an older version of the types, but nice to see it works
isnt it possible to mute errors?
What do you mean?
like i made a systemfor block breaking keeps throwing a error that dynamic property not found bla bla error in hand, cuz its meant to only be in a pickaxe
if i break with hand ^ i get error, if with pickaxe i dont
if (!itemStack.typeId.includes('pickaxe')) return;
thanks!!
Does anyone know what can cause this error?
The text over the error is the test to see if its a valid string
Omg. And i was just reading about that today. Gises. A new error. But at least im one stepp forward. Thanks for the hint!
Can someone help me with script for detecting if player is on ground?
I have this:
function isPlayerOnGround(player) {
const pos = player.location;
const yPosInt = Math.floor(pos.y);
if (pos.y - yPosInt > 0.1) {
return false;
}
const blockBelow = player.dimension.getBlock({ x: pos.x, y: yPosInt - 1.5, z: pos.z });
return blockBelow && blockBelow.typeId !== "minecraft:air";
}
do I need to take any extra measures to be able to use typescript for my script files? will it work without anything extra
player.isOnGround -_-
\
wow, xd then, thanks a lot!
lol
Yeah yeah, I will remember that after my stupid question 😛
stupidity vs ignorance
Question from another topic, do you guys use any of obfuscating tools? Or do you have any idea of creating good one for js and json files? Is this common to use them?
you might need to pay for a good one
I have one for js, it's not bad and not best. But for json files I've tried looking for, many times but without succeed.
yeah JSON just uses unicode and stuff and is easily decoded with just console.log
obfuscating is trash and since javascript is a garbage language it does not compile
whatever that's supposed to mean
is there any other way to hide the "Has Customised Properties" text on items with dynamic properties other than lang files?
/gamerule showtags false i think
yep that works, thx
does it do anything else than specifically hide this text?
it hides the itemlock triangle and text
oohh
doesnt it hide lore aswell?
that's amazing how have I never heard about this before
good
what db are u using
using get block from a ray that aimed at the edge of a block make the ray go through it, is there any work around for this problem?
If ever someone needs it but I'm now sure if it's really a "solution" but just use getBlockFromRay() instead of getBlockFromViewDirection()
system.runInterval(() => {
for (const player of world.getPlayers()) {
const head = player.getHeadLocation();
const block = player.dimension.getBlockFromRay({ x: head.x, y: head.y + 0.1, z: head.z }, player.getViewDirection(), { maxDistance: 10, includePassableBlocks: true });
console.error(block?.block.typeId, JSON.stringify(block?.block.location))
}
});```
For those who would ask why add 0.1, the y-axis in head location doesn't align in the players view that's why I added it
-# and I feel like I'm kinda late to this problem LMAO
Why is it that when the conditions are filled for me to get weakness, it toggles very quickly between “0” and “event timer index invalid” in the effect duration in-game?
import { world, system, Player } from "@minecraft/server"
system.runInterval(() => {
for (const player of world.getPlayers()) {
if (world.scoreboard.getObjective("killStales").getScore(player.scoreboardIdentity) > 0) world.scoreboard.getObjective("killStales").addScore(player.scoreboardIdentity, -1)
}
}, 200)
system.runInterval(() => {
for (const player of world.getPlayers()) {
if (world.scoreboard.getObjective("killStales").getScore(player.scoreboardIdentity) > 5) player.addEffect("weakness", 3, { showParticles: false, amplifier: (world.scoreboard.getObjective("killStales").getScore(player.scoreboardIdentity) - 6) })
}
})
world.afterEvents.entityDie.subscribe((eventData) => {
if (eventData.deadEntity instanceof Player && eventData.damageSource.damagingEntity instanceof Player) { world.scoreboard.getObjective("killStales").addScore(eventData.damageSource.damagingEntity.scoreboardIdentity, 1) }
})```
how can i set the camera to face the player from above?
can dynamicProperties store an array list?
With JSON.stringify
thanks
use player location in the camera facingLocation
Seriously why doesn’t player.addEffect() work
I have to use player.runCommand() instead
And that’s really slow apparently
Problem is that it works but has the weird index thingy, yeah?
Make it run once a second instead of every tick
Can also check the status of the applied effect, and only add it when the duration is getting low (or does not match the scoreboard value) instead of applying it every single tick
I saw you coddy
Ok but even if I increase the duration it still says invalid index and 0 seconds
Is changing how often it happens really going to change anything?
it’s worth a shot- see if increasing it to once per second does anything ¯_(ツ)_/¯
Note that duration is in ticks and not seconds
Right now there’s also another file that has a similar idea
system.runInterval(() => {
for (const player of world.getPlayers()) {
const hasteLevel = world.scoreboard.getObjective("hasteLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("hasteLevel").getScore(player.scoreboardIdentity) : 0
const strengthLevel = world.scoreboard.getObjective("strengthLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("strengthLevel").getScore(player.scoreboardIdentity) : 0
const speedLevel = world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) : 0
const saturationLevel = world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("saturationLevel").getScore(player.scoreboardIdentity) : 0
const fireResLevel = world.scoreboard.getObjective("speedLevel").getScore(player.scoreboardIdentity) != undefined ? world.scoreboard.getObjective("fireResLevel").getScore(player.scoreboardIdentity) : 0
if (hasteLevel > 0 && player.getEffects().includes("haste") == false) {
player.runCommand(`effect @s haste infinite ${hasteLevel - 1} true`)
}
if (strengthLevel > 0 && player.getEffects().includes("strength") == false) {
player.runCommand(`effect @s strength infinite ${strengthLevel - 1} true`)
}
if (speedLevel > 0 && player.getEffects().includes("speed") == false) {
player.runCommand(`effect @s speed infinite ${speedLevel - 1} true`)
}
if (saturationLevel > 0 && player.getEffects().includes("saturation") == false) {
player.runCommand(`effect @s saturation infinite ${saturationLevel - 1} true`)
}
if (fireResLevel > 0 && player.getEffects().includes("fire_resistance") == false) {
player.runCommand(`effect @s fire_resistance infinite ${fireResLevel - 1} true`)
}
}
})```
I know that very well, thank you very much
Just making sure 👍
This file is much more important than the pvpStaling file, I already turned that one off because it was apparently causing a lot of the lag (found out from the profiling script)
But the ascendantEffects file is also causing a lot of lag
And I’m not entirely sure how to use all the api player.addEffects function correctly
y'know you can just !player.getEffect('haste') right?
It run strictly on the SCOREBOARD EFFECT LEVEL you have, because you BUY those effects
I'm talking about the player.getEffects().includes()
Did you look at the code…?
Of course I did that.
Oh.
umm you're the one who didn't understand my point
Now I realize what you want me to do.
What I'm saying is instead of player.getEffects().includes('haste') === false you can just !player.getEffect('haste')
Yeah yeh
😭🤦
My issue is the player.runCommand
Not the if/else
If I do player.addEffect() well, it doesn’t like the duration for some reason
If you want to set infinite effect using scripts nope you can't
I know that
But I set the duration to like 1 or something and it also doesn’t like it
It gives the effect and immediately cancels it and in the effect time it goes from 0 > “event timer index invalid” in less than 1/5 of a second
It's in ticks, not seconds.
Simple mistake I've made numerous times.
But you literally said you know that
I didn’t realize .addEffect() used ticks
I thought they were talking about system.runInterval().
quick question, what dose duration return if we used getEffect in infinite effect?
Just divide the value to 20
Idk how to do that. I’ll just set [the duration] to 20.
player.addEffect('speed', (value * 20), { showParticles: false, amplifier: 1 })
I read TO 20, not BY 20 dude
I thought they were two different syntaxes by the way you said it
And it's not my fault you read it that way
Well sure I guess you could make an argument that I didn’t know that dividing TO something wasn’t a syntax.
the value you want to set in duration is seconds right? Just divide the value by 20 since 20 ticks is 1 second in real life
That would be times though.
Not divide.
Mehh you can just change it
I’ll just do 20 for one second, thank you
I’ve worked with command blocks for a lot longer before starting to do addons
I know how to work with ticks
Obvious.
Aw, what made that so easy to tell? 🗿
Uh-huh
bump... 👀
not valid value I guess? Afaik the values accepted are from 0 to 2 million?
Or 200k I forgor
How do you even get the data of a certain effect/???????///??///???/
Using Supabase just for a proof of concept. I've never touched server-net so wanted to plat around with it
Duration and amplifier?
Yea
const effect = player.getEffect('haste');
effect.duration;
effect.amplifier;```
Huh
Wym "huh"? It's obvious already
const effect = player.getEffect('haste');
console.error(effect.amplifier, effect.duration); // returns the amplifier and duration of effect, returns 'undefined' if effect doesn't exist on entity```
is there any methods for reloading the world using scripts
I guess I just turned a bind eye to the .getEffect() function, I only ever used the .getEffects() function
purely just script API? No afaik
iirc someone said you can do it with vscode
getEffects() returns an array
Use find()
Or whatever
Would source.removeEffect() remove ALL effects if not specified?
No I think?
Just use getEffects(), get all effects and you said y'know how to use it so it would be easy for you
Ok then would this work? js for (const effect of source.getEffects) { source.removeEffect(effect) }
Hmm...
Yep.
I could also do source.runCommand(“effect @s clear”)
But if Smoky says that’ll work i guess that’ll work
Damn, I felt kinda nvm...
Apparently not
[Scripting][error]-TypeError: value is not iterable at <anonymous> (betterButtonTp.js:323)
*.getEffects()
Not .getEffects
Oh I’m dumb
Minor oversight.
I've made that mistake before.
how do i define that a variable is instance of for example Player class so i could get the autocompletions? Without using TS?
You could either use JSDoc or use type guards.
import {Player} from '@minecraft/server';
/**
* @param {Player} player
*/
function affectPlayer(player) {
// parameter 'player' should give autocompletions for Player
}
import {Player} from '@minecraft/server';
function affectPlayer(player) {
if(!(player instanceof Player)) return;
// parameter 'player' should give autocompletions for Player
}
why without TS
💀
TS is life
because having to compile everytime is ass
Such a minor inconvenience.
tsc --watch go brrr
am i the only one whose game starts doing a long flashback of everything that happened whilst i was gone if i go afk for a long time in my worlds with scripts at like 3-5fps
Am I doing this right? I’m giving anybody who kills the ender dragon ONE dragon egg js killer.getComponent("inventory").container.addItem({ amount: 1, typeId: "minecraft:dragon_egg" })
Or do I have to do something like js killer.getComponent("inventory").container.addItem(new ItemStack = { typeId: "minecraft:dragon_egg", amount: 1 })
.addItem(new ItemStack("dragon_egg", 1))
that would work?
thanks then
how do i send a message to all players in an array
how do I send a message to all players in an array
is my question
what are you questioning
what do you mean in an array
players that are in an array?
filtered result of world.getPlayers()
yes
Player[]
without loop
it will be too inefficient that way
uh, so do you want to send message to only one player?
no
an array..
do you know what an array is..
["apple","banana","mango"]
yes but in order to run methods on multiple players, you need loops
each player in the array should be sent a specific message
is there really no other way than that
for sending messages
ok
can i check if a spawned mob was spawned from a spawner?
How do I track the speed in which a player is moving?
I want to runan applyKnockback horizontal strength based on their speed
Player.prototype.getVelocity()
Whats the diff between prototype and just getVelocity?
nothing
prototype is used to display the methods available for a class
idk what the actual technical definition of it is but like
outside of an actual Player object you cant do Player.getVelocity() it has to be Player.prototype.getVelocity()
In programming, inheritance refers to passing down characteristics from a parent to a child so that a new piece of code can reuse and build upon the features of an existing one. JavaScript implements inheritance by using objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype and acts as the final link in this prototype chain. It is possible to mutate any member of the prototype chain or even swap out the prototype at runtime, so concepts like static dispatching do not exist in JavaScript.
something lik ethis
Ah
just dont care about it it means the same thing as calling method getVelocity() on an actual target that you have
I wasn't sure that getVelocity got speed too, I assumed it was direction of movement
thanks!
alr
well no you have to calculate it based on each direction of movement
idk how but theres def a formula just look it up
it returns Vector3 meaning it gives you the speed they are moving at in each direction
if you move 45 degrees away from south you will move like at speed |x| = 0.5 and |z| = 0.5 i think
I'll go look for a formula lol
not strange it's helpful in many scenarios
better than just 'straightforwardly' returning theactual speed bc that speed can't be really reversed back to a 3-dimensional format
maybe with viewdirection you could but idk im not good at math
alright, thanks so much!
lets say this code is being executed from a block using custom components and on player interact and i wanted to detect every block, then if any of those match X block, i can change them to something else for each block in a 10x10x10 radius, would i have to make a line of code detecting every block all 1000, or can it be done easier like in one swoop.
so pretty much can i interact with my custom block and it changes all cobblestone around it in a 10x10x10 radius to netherrack in less than 1000 lines of code
wait im so dumb i can use a replace command no one look at me
Quick question can you add enchaments in items in the constructor? Like the new ItemStack()
Yes
Yes
You are gonna require lots of logic tho.
I can send you my code (if you want)
You are gonna need to have some kind of filtering and checking position and spawn cause, but using a spawn egg near a spawner will also work like the mob spawner spawning mobs, (the cause you should be detecting is "Spawned" and you should probably make a weakMap and in the beforeEvent of itemUseOn if it's within the Radius of a spawner then y'know? Some logic to stop the entitySpawn event from falsely detecting..)
You got to do a playerInteractWithBlock afterEvent and do a system.runJob() generator function to set as many blocks as you need without causing lag
Nice thanks for confirmation... And you look scary with that pfp
Haha, thanks, I have been designing it for like 2 months, trying to perfect it to the maximum...
Damn it looks nice frfr... Next time if I have time I'll design mine but I don't have something in my mind rn lmao...
-# just an excuse cause I don't know how to design at ALL lol
Lol
speed is just the vector's length
or magnitude
which would be sqrt(x*x + y*y + z*z)
This does what I need pretty well
system.runInterval(() => {
for (const player of world.getAllPlayers()) {
const currentLoc = player.location;
system.runTimeout(() => {
const newLoc = player.location;
const deltaX = newLoc.x - currentLoc.x;
const deltaY = newLoc.y - currentLoc.y;
const deltaZ = newLoc.z - currentLoc.z;
var speed = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2) + Math.pow(deltaZ, 2));
player.onScreenDisplay.setActionBar(Speed - X: ${Math.floor((newLoc.x - currentLoc.x) * 100)}, Z: ${Math.floor((newLoc.z - currentLoc.z) * 100)}\n${Math.floor(speed * 100)})
}, 2)
}
})
Its not abt delta
well yes
it is
but I got speed from finding where u were a couple ticks ago
what would be the equation to do the exact same thing with velocity?
but all in the same tick
instead of running multiple ticks
does pythagorean work with that too?
you velocity is delta-pos over delta-time
Rlly all I want is to be able to track the players speed
yes lol
velocity is just a vector
So it would just be
and your "speed" is just the magnitude of your velocity
speed is velocity without a direction
so you just replace deltaX etc with velocity.x etc
I see
yep
I switched to const
even better
var hoists the variable into the global scope so it's generally not great to use
np 👍
does not have required privileges
👍
finally got my tool based silk touch figured out
avoiding using /setblock command but now theres a slight delay between breaking and particles/sound
yeah this was my 2nd resort for it
i was wondering if there was a native way for it but i guess not
hi there, do someone know if it is possible to use spawnParticles in a way the particle understand it is attached to the player?
for instance, I have a custom particle that have this:json "minecraft:emitter_local_space": { "position": true, "rotation": true, "velocity": false },So when this particle is executed from a animation it takes in consideration the head and looking direction of the mob.
but when executed from API, there is no way to tell the particle what entity/player this particle belongs to?
can I set the lore of an itemstack without tick privileges somehow
Nope
You can however save the data to a map and the next tick set the item's lore and delete the item. (Using some kind of indexing like the slot it's in, the container it's in, the Player's Inventory container it's in, date it has been saved, idk anything to index it.).
no i don't need to add it to a container i just needed to make a function that creates item stacks with lore
its ok tho ill just make sure i only call it w privileges
I said "index" it with any of these suggestions, if you need to set it's lore even if you don't have the required privileges currently.
(Basically make a key to store the new lore value & add that lore later)
yea but the point was i dont want to move to a new tick yet i still needed the lore properties to display for that item in my event so i cant really do that
thx for the suggestion tho
You could just store it in a variable and do whatever you wanna do and then set lore on the next tick from that variable but idk if that works
i know that but I don't want to store it in a separate variable
Why exactly?
looks ugly
💀
it's not that big of a deal anymore, later in my function I will have to add this stack to a player's container anyway so i'll just move some parts around
Bruh
I got a suggestion for you
Group the variables in one line
no i don't need it anymore, the privilege stuff isn't a concern anymore
For example:
const baller1 = "baller1";
const baller2 = "baller2";
Is now:
const baller1 = "baller1", baller2 = "baller2";
ik
Well then..... WHY not use it?
because I don't need to
i've said that twice now sry
it's not of any concern to have tick privileges anymore, I moved some stuff around and everything is perfectly fine now
Alright then ig...
is it possible to open the crafting menu for a player
can it be done with server-net
no
what's the difference between world.getPlayers() & world.getAllPlayers()
none
why do we have two then
except that getAllPlayers doesnt have entityqueryoptions
or playerquery idk what its called
no idea
the other don't?
i thought you said "except that getAllPlayers have entityqueryoptions"
oh
Their functions no differ from each other... Both of them return an array of players
Unless I'm wrong
i use getEntities some times, sense entityqueryoptions in getPlayers don't support some stuff
They might have added getAllPlayers first and then added getPlayers since it wouldn't make sense to have a filter on a function that should return all players
is there a way to accurately get the loot dropped by the block?
What I'm thinking of is before events of playerBreakBlock -> entitySpawn
The only unreliable part is when the item is tp with command blocks or another shit that changes location, it might not work
what I've done is checked for entities around the center location of the block at a 1.5 block radius, for me it works well, but there's obviously edge cases in which it will fail to provide accurate results
like if somebody dropped an item close to it
on afterEvent i think items don't spawn until a tick after the block has been broken
I know that but I already said the problem if we use it.
^
if you listen to beforeEvent of the entitySpawn then I don't think the item could've been teleported yet
only on afterEvent
but i'm not sure
That's still the same case since we need to use the system run to call the entityspawn, so it does it on the next tick... In short it can't detect the original location or the dropped item
you can, the location can be read for before you use system.run() i think
there is no beforeEvent of entityspawn
nvm
but you need to call the entityspawn with system run
show an example idk what ur implying
world.beforeEvents.playerBreakBlock.subscribe(({ block, player }) => {
system.run(() => {
const spawn = world.afterEvents.entitySpawb.subscribe(({ entity }) => {
if (entity.hasComponent('item')) {}
});
});
});```
i never knew you could do this waow
And by the way, a bad way, because the function inside entitySpawn will be duplicated every time a player breaks a block
@dim tusk another way is, if you have the time for it, re-write the item dropping functionality of mc and disable vanilla tile drops
I know that... C'mon
not the best practice probably though
you can just use loot spawn ~~~ mine ~~~ mainhand 🤷
that is a weird way of using events
oh wtf
i never knew that was a thing
Its new.
Want More weirder?
but no it doesn't account for items in containers, for example
idk if disabling tile drops disables container stuff though
So simple to counter
But anyways back to the problem... Yes it will work but if the item is tp'd, not anymore
i definitely have some weird lines in my scripts too
the amount of time gone in re-coding some of my scripts ↗↗
i guess that what happen when you start learning a new api and using it in the same time
My weakness on scripts is the auto formatting of the software
They make my script long 😭
make your own
lol
What I said is straightforward 😑
What is "auto formatting of the software"?
just make it not auto format?
Hmmm...
I don't understand what you're talking about :( what does auto-formatting do?
Thanks I'm boomer on vscode
Turn this```js
import { ActionFormData, ModalFormData } from '@minecraft/server-ui';
into```js
import {
ActionFormData,
ModalFormData
} from '@minecraft/server-ui';```
basically some code editors have a way to format code (organize it) so the code look the same, can be useful when working on a team
imagine work with coddy and he sent you his script
wait... you switched from notpad++? @dim tusk
probably 🤔🤷
lol, good for u
y'know what's funny? When handling json my hand will automatically select notepad++ but if scripts it's vscode now
me using windows notepad
Same 🤣🤣
I did too for a while when coding LISP for AutoCAD
Aww hell nah... Get out of here
They make it readable is all.
Formatters? More like deformatters for me.
Formatted code looks weird to me and deformatted single lined code is very easy for me to understand tbh..
Preferences.
Formatter? I one line my code
I have begun this new semi bad habit of separating different 'groups' of variables from each other with empty lines
actually before I judge whether it is bad or not I need somebody else's opinion
i do it a lot
and it maybe doubles my line count or so
example
the capitalisation is what's confusing me
capitalized Level and Name because
class Enchantment {
constructor(Name, Level) {
this.Name = Name;
this.Level = Level;
}
}
did you guys know that you can save ItemStack with dynamicproperty?
Omg!!!!
amazing
thats how I made my trading system. I saved the itemstack from the items that have been selected
I think mostly everyone knows it
it was not a feature back then
thats why I was impressed
Does anyone have a guideline or known working example of using a ticking area for world.getDimension().getBlock(), I have it "working" but it is a little unreliable. Just want to see if anyone has a better implementation
It's been out since 1.20.50 iirc
But I get what you mean
noway thats so old I tried before 1.21 but didn't work
What version is available 6 months ago
That's how my permanence addon works as well
It's been out since 1.20.60
Later than that setting dp only works on entities and player
Also world if I understand what you're talking about
Ohh yeah I forgor
no you can't
but it did
how?
Stop playing with him mannn
let trades = JSON.parse(world.getDynamicProperty("trading"));
let item = inv.getItem(selection);
trades[player.name].items.push(item);
world.setDynamicProperty("trading", JSON.stringify(trades))
Don't worry he's just trolling...
thats not an ItemStack I mean everything every data of an item
But what you'll get back is nothing at all.
That part is not possible...
I just realized it lmao
did you test that out? try getting the dp back
bruh
Ok sorry I just realized what you meant lmao
I made a trading system with that thats how I save the itmes
Anything is better than your method, which doesn’t work. And ItemDataBase can save all the information
coddy turned into a bad trained ai model fr
it is not functional
In dp you can't save it's data's other than the name, amount, tags, name, lore and components
If you use an object yes it can be possible but using dp? No sorry
Speaking of ai is it possible to make an entity that can set its own components using ai
I cannot provide instructions guidance about illegal and harmful content. Can I assist you with another topic instead?
Just out of morbid curiosity
no
lol, we can't dynamically change the entity components
Component groups exist though…
"dynamically"
But the Mojang believe that they are not needed in scripts
So you could probably, theoretically, set each component to a single component group and hook it up to an AI API
The only thing you can do is send entity events. Your entity JSON needs to define the component groups already.
But that would be REALLY hard to do
And it's unlikely to be optimized
maybe if you turned every component to its own component group
That’s literally what I just said
You have two options when saving items with their data... Either use an entity container or use an object but the drawback is when you reload the world the data saved in the object is also lost
-# and Yes I'm annoying asf
i legit saw his trading system and it does work
with the way he has it set up rn
i’m unsure how i never knew you could use itemstack but it does seem to work for him
components do have parameters, some of them are not in the api yet
that really look impossible, unless you are limiting them
Anyway nice new pfp coddy
bruh Ik
That shouldn't happen
oh wait nvm i realized he stringifies it
See? Ohh my god 😭
If you wanted to write hundreds of thousands of lines of code for every possible component parameter combination
:/
Also the addon would be MASSIVE at that point
try and see, i guess
Right? But it doesn't really describe me... If I have time I will do my own profile
i thought stringifying an itemstack returns nonsense.. because it’s not in the traditional format of an ovject
^ and then hook up entity events to every single component group and make an AI script
Or a simple environment detector
Nah bro. I already can’t code js for sht I also don’t have the patience to do that
Yes.
It doesn't return nonsense but the thing is when stringifying the ItemStack, it only returns things that are accessible in short excluding the container items, or items that have data like potion items, while names, lore, durability, enchantments, amount etc. accessible
well
in theory, it is possible
Well then, off-topic to what I was just talking about, is there a way to easily return a very large array in string form?
You will definitely think I’m stupid, but hear me out, when you print an array it returns the objects as “item1”,“item2”,“item3”, I would at least like to space the results apart and remove the string quotes (there might not actually be string quotes and I’m misremembering but you get the idea)
Yah..
Is there a way to fill a container with an item if you specified the coords of that container? I was thinking about running the in game replaceitem command 27 times but that seemed stupid
get block -> get inventory component -> add item
yeah I tried it before in like 1.19 tho and i swear it just returned an empty array for me
array.join(" ")
Wow it’s really that simple?
yeah
just use runtInterval 🤷
it is alr, we learn over time
Ohh, my god my head hurts rn... I'm like ai but 50% worse
I want to give an example but I'm lazy asf rn :)
Also it's normal... Can you give me the snippet of the code? I wanna read it
Pls don't do that 😭... You're calling it multiple times when you can put it in the variable
That’s not possible for what I’m doing
import { system, world} from "@minecraft/server";
function fillContainer (location, itemType, dimension){
const block = dimension.getBlock(location);
if (!block) return
const container = block.getComponent("minecraft:inventory");
const inventory = container.container;
for (let i = 0; i < inventory.size; i++) {
const item = new ItemStack(MinecraftItemTypes[itemType]);
inventory.setItem(i, item);
}
};
//for testing
system.afterEvents.scriptEventReceive.subscribe((event)=>{
if(event.id !== "test:fill") return
fillContainer ({x:0,y:-60,z:0}, "minecraft:stick", event.sourceEntity.dimension)
})
No as i said i did it many versions ago
In late 2022
never after that have I attempted to stringify an itemstack
You're not that dumb...
don't worry about it
How can I call you this..... I forgot it nvm then
it’s just bad practice to call for the exact same thing multiple times
Doesn’t make a difference, the variable will be a reference to the container
Stringifying an ItemStack and attor in object and see the values using console.error will return empty array but if you use it on addItem or spawnItem things that accept ItemStack it spawns the item with 1:1 copy of the item
It wastes performance to get it multiple times
yes but you can save the container in a variable
He's right, when calling multiple function just store it on variable it helps readability and performance
const container = world.getDimension("overworld").getBlock({ x: 0, y: 0, z: 0 }).getComponent("inventory").container;
for (const slots of container.size) {
container.addItem(new ItemStack())
}```
this is what I meant
there’s probably a syntax error i made it inside of dc
but u get the idea
@patent tapir
you aren't even using slots variable there btw
slots is a number
const block = world.getDimension().getBlock();
const inventory = block?.getComponent('inventory')?.container;
for (let i = 0; i < inventory.size; i++) {
const item = inventory.getItem(i);
}```
-# ok
yes
DONT BE FUCKIN MADDD AND DONT YELL
getItem?
What does this mean
Forget that i just it 😑
That’s my question
You’re probably getting the error because ur attempting to re-define the value of slots
Probably the block is air or the block isn't a container
That's why I added the ?
yes because you can’t loop by a number
use for (let i = 0; i < x; i++) to loop x amount of times
for of gets list of objects inside of array and for loop generate number from value a to value b depends adding or subtracting or whatever
welcome to JavaScript basics
You assume we bullied you?
WELCOME TO THE INTERNET BUDDY
And WELCOME TO THE BASICS OF JS
-# as what Minato said
Just calm down... Three of us are just helping you as much as we can... No one is bullying you, we're just correcting you.. simple mistakes okay?
Yeah he deleted it
Nvm, he left I think?
Oh wow
You deleted it or the mods did?
we are pointing out your mistakes so you learn from them, otherwise what is the point
I don't want to say it....but you're kinda overreacting sometimes
alr, have a great day
You can also stop responding if you feel that you got the response that you needed
My day isn't great... I only slept 3 hours today and my cat died
i’m sorry that your cat died.
I mean it's not really rude but you're just trying to imply that you're done or everything is set or fixed already
sorry to hear about your cat, i hope you feel better soon
and get some sleep dude
Yeah.. I can't now, because I'm already in front of my computer
I will probably feel asleep while I'm working with my things lol
Nah you good...
Everything's good, I mean it's not good my cat died but it's good that I'm still alive...
Yeah, as long as you didn't do anything controversial that might trigger people or communities? You're fine
🤨
when i place a custom block that has an item version the onBeforePlayerPlace custom comp event doesnt fire and the beforeEvents.playerPlayerBlock either???
is this normal
how can be fixed?
damn
but itemUseOn doesnt work either
which is weird
i need to modify the permutation to place depending on certain conditions
what event should i use in that case?
before
actually it works but theres still a problem and it's this event does give me the block where this custom block should be placed
so
it's worse than doing beforeOnPlayerPlace
damn
this is the only problem i see
code?
You have to offset jt. I presume youre immediately replacing the block impacted.
use.cancel = true
system.runInterval(() => block.setPermutation(BlockPermutation.resolve('c:beacon', { 'c:level': level })))
Yeah im doing that
im very bad with Vector related stuff tbh
how do i calculate where to offset this block?
what event you are using for the placing
let {face,block} = event
switch(face){
case"Down" : block = block.below(); break;
case"Up" : block = block.above(); break;
case"East" : block = block.west(); break;
case"North": block = block.south(); break;
case"South": block = block.north(); break;
case"West" : block = block.east(); break;
}
thanks:))!
is face .blockFace right?
yeah
don't forget to check for air block
wdym?
you don't want it to replace blocks it is not supposed to replace
let say player interacted with this face
the block returned is the fence above
hmm?
wait
huh
maybe i sent the wrong order
can you try all the block sides?
also log the blockface to console @steady canopy
switch(face){
case"Down" : block = block.below(); break;
case"Up" : block = block.above(); break;
case"East" : block = block.east(); break;
case"North": block = block.north(); break;
case"South": block = block.south(); break;
case"West" : block = block.west(); break;
}
this should work
idk why i was using them reversed
oh that was it! thank you again 🙂
Wadahell is tyring??
Sounds like a cool Castlevania weapon name
how do you get a player armor using scripts
player.getComponent('equippable').getEquipment('Head');
player.getComponent('equippable').getEquipment('Chest');
player.getComponent('equippable').getEquipment('Legs');
player.getComponent('equippable').getEquipment('Feet'); (nothing diddy related)
player.getComponent('equippable').getEquipment('Offhand');
player.getComponent('equippable').getEquipment('Mainhand');
Is there a way to prevent a player from joining a world?
BDS way is to edit allowlist.json
but without net module, no other way than kick
how do you check typeid
I want to add to tag to the player that way I can check if it has the tag then I will prevent it from joining
What is the allowlist json?
A Bedrock Server file...
It returns an item so just get the typeid normally.
Where can I access it is it a script file?
how ?
like this ?
function applyOnNetherite(player, vector) {
const head = player.getComponent('equippable').getEquipment('Head')?.typeId;
const chest = player.getComponent('equippable').getEquipment('Chest')?.typeId;
const legs = player.getComponent('equippable').getEquipment('Legs')?.typeId;
const feet = player.getComponent('equippable').getEquipment('Feet')?.typeId;
const isNetheriteHead = head === 'minecraft:netherite_helmet';
const isNetheriteChest = chest === 'minecraft:netherite_chestplate';
const isNetheriteLegs = legs === 'minecraft:netherite_leggings';
const isNetheriteFeet = feet === 'minecraft:netherite_boots';
const allNetherite = isNetheriteHead && isNetheriteChest && isNetheriteLegs && isNetheriteFeet;```
Yeah.
so this is valid yeah ?
you there to help me ?
cough cough
function hasNetheriteArmor(player) {
const eq = player.getComponent("equippable");
return !["Head", "Chest", "Legs", "Feet"].find(slot => !eq.getEquipment(slot)?.typeId.includes("netherite"))
} ```
Is this valid
Oh
i was gonna do it... lmao
Thanks
yeah but
anyways, quick question is there's a way to get the id of the owner of the projectile?
function applyOnNetherite(player, vector) {
const head = player.getComponent('equippable').getEquipment('Head')?.typeId;
const chest = player.getComponent('equippable').getEquipment('Chest')?.typeId;
const legs = player.getComponent('equippable').getEquipment('Legs')?.typeId;
const feet = player.getComponent('equippable').getEquipment('Feet')?.typeId;
const isNetheriteHead = head === 'minecraft:netherite_helmet';
const isNetheriteChest = chest === 'minecraft:netherite_chestplate';
const isNetheriteLegs = legs === 'minecraft:netherite_leggings';
const isNetheriteFeet = feet === 'minecraft:netherite_boots';
const allNetherite = isNetheriteHead && isNetheriteChest && isNetheriteLegs && isNetheriteFeet;
// Calculate knockback power
let knockbackPower = 1;
if (allNetherite) {
knockbackPower *= 1.4;
} else {
knockbackPower *= 1.1;
}
// Apply knockback with adjusted power
const adjustedVector = {
x: vector.x * knockbackPower,
y: vector.y * knockbackPower,
z: vector.z * knockbackPower
};
applyImpulseAsKnockback(player, adjustedVector);
}
export class Velocity```
thats, long 
Yeah, for a reason
notice the "export class Velocity"
I am doing something something
...
so will you help me with it ?
that's what i did but it returns undefined for some reason
fuckin hell
im stupid
it works i just turned off my console log
OHHH MY GODDDD
applyKnockback
function hasNetheriteArmor(player) {
const eq = player.getComponent("equippable");
return !["Head", "Chest", "Legs", "Feet"].find(slot => !eq.getEquipment(slot)?.typeId.includes("netherite"))
}
function applyOnNetherite(player, vector) {
const kbPow = hasNetheriteArmor(player) ? 1.4 : 1.1;
setVelocity(player, vector, kbPow)
}
function setVelocity(entity, vector, str = { x: 1, y: 1, z: 1 }) {
const x = vector.x *= str.x ?? str;
const y = vector.y *= str.y ?? str;
const z = vector.z *= str.z ?? str;
const horizontal = Math.sqrt(x * x + z * z) * 2.0;
const vertical = y < 0.0 ? 0.5 * y : y;
entity.applyKnockback(x, z, horizontal, vertical);
}
no choice then....
How do i add an enchantment to an item using scripts
already have it
export function applyImpulseAsKnockback(entity, vector) {
const { x, y, z } = vector;
const horizontalStrength = Math.sqrt(x * x + z * z);
const verticalStrength = y; // Vertical strength directly corresponds to the y-component
// Normalize horizontal direction if there is any horizontal movement
const directionX = horizontalStrength !== 0 ? x / horizontalStrength : 0;
const directionZ = horizontalStrength !== 0 ? z / horizontalStrength : 0;
entity.applyKnockback(
directionX,
directionZ,
horizontalStrength,
verticalStrength
);
}```
i was using this to convert applyKnockback to applyImpulse
why do the enchantments not get sorted by color?
/**
* @param {ItemStack} itemStack
*/
static updateLore(itemStack) {
const properties = {
enchantmentSlots: itemStack.getDynamicProperty("enchantmentSlots"),
usedEnchantmentSlots: itemStack.getDynamicProperty("usedEnchantmentSlots"),
enchantments: JSON.parse(itemStack.getDynamicProperty("enchantments")),
whitescrolled: itemStack.getDynamicProperty("whitescrolled"),
nameTag: itemStack.getDynamicProperty("nameTag")
}
if (!Object.values(properties).includes(undefined)) {
itemStack.nameTag = properties.nameTag
if (properties.enchantments.length > 0) {
properties.enchantments.sort((a, b) => {
const rarityA = Rarities[EnchantmentUtils.getRarity(a.name)].color;
const rarityB = Rarities[EnchantmentUtils.getRarity(b.name)].color;
return RarityOrder.indexOf(rarityA) - RarityOrder.indexOf(rarityB);
});
let nameString = `${properties.nameTag}`
if (properties.usedEnchantmentSlots >= 5) {
nameString += ` §l§d[§r§b${properties.usedEnchantmentSlots}§l§d]§r`
}
const enchantmentString = properties.enchantments.map(enchantment => `\n${Rarities[EnchantmentUtils.getRarity(enchantment.name)].Color}${enchantment.name} ${convertToRoman(enchantment.level)}`).join("")
const finalNameTag = nameString + enchantmentString
itemStack.nameTag = finalNameTag
}
const availableSlots = properties.enchantmentSlots - properties.usedEnchantmentSlots
let lore = [
` `,
`§r§6${properties.enchantmentSlots - properties.usedEnchantmentSlots} slot${("s".repeat(Math.abs(availableSlots - 1))).charAt(0)}`
];
if (properties.whitescrolled) lore.push(`§r§f§lPROTECTED`)
itemStack.setLore(lore)
return itemStack;
}
}
const RarityOrder = ["§5","§4","§d","§e","§b","§7"]
export const Rarities = {
"Basic": {
Tier: 1,
Color: "§7"
},
"Uncommon": {
Tier: 2,
Color: "§a"
},
"Elite": {
Tier: 3,
Color: "§b"
},
"Legendary": {
Tier: 4,
Color: "§d"
},
"Spiritual": {
Tier: 5,
Color: "§4"
},
"Ancient": {
Tier: 6,
Color: "§5"
}
}
fixed it it was all because of a capitalization error
wow
it is ok to reveal/show entity id in public? like there is an item when used it will teleport entity to player, so to remember which entity it is i am using entity id in lore
Totally fine, players cannot get any valuable information from it.
You could hide it on lore using something like:
'§' + id.split('').join('§') and then parse it by removing all section symbols later on
Thnx
Does item frames and painting triggers the playerPlaceBlock?
I'm making some custom explosions. I need to summon an entity that later explodes with some power calculated in script. What is the easiest way to do it?
Lazy :)
Tbh, why would I ask here even if I could just do it? 🤷
I mean I don't think they don't trigger as they are treated as entities
But anyways I don't need it anymore.
But the item frame is treated as a block in bedrock I believe
Idk but I feel like I'm late to this but getting the ItemStack of before and after in itemUse don't make sense to me
I was trying to check if the item decreased it's amount
Bruh lol
But when I do a log their amount is the fuckin same
Yeah cuz it's still beforeEvent
It ain't happened yet
Events
Entity events
Do some molang magic with whatever property the entity has and set that property in script api & trigger event
That shouldn't be... Yes it didn't happen but after it already happens, and the item is used... I'm using ender pearl for example so the amount of before should be higher than the after but it's not ..
I had no choice but to use equippable components and get the amount there :(
Basically set up an event & property and set them from script api
Well you never know where the error is, it may be in the api you're using, for example I was wondering why my server side code isn't working and I kept isolating parts of my code and until I realized the emailing api I'm using just does the error...
send the code
world.beforeEvents.itemUse.subscribe(({ source, itemStack }) => {
console.error('Before:', itemStack.amount);
});
world.afterEvents.itemUse.subscribe(({ source, itemStack }) => {
console.error('After:', itemStack.amount);
});```
That's it
Try this:
world.beforeEvents.itemUse.subscribe(({ source, itemStack }) => {
console.error('Before:', itemStack.amount);
system.run(() => console.error('After:', itemStack?.amount ?? 0));
});
that might actually be a bug. @spring axle you think so?
oh wait
actually
maybe not
try using a different use event like ReleaseUse
since its and enderpearl
though
hmm
that still doesn't make sense
Didn't work... Their output I still the same
Wait I'm trying that
-# didn't work obviously since ender pearl isn't a drawable projectile unlike bows or crossbows
Is it because of the version I'm using? I'm in 1.21.60.21
the item decreasing is probably delayed
use timeout to test how much it is delayed
Probably but still doesn't make sense since the getEquipment() can access it on the same tick but the built-in ItemStack function of it can't?
I'm trying this again but using timeout
well, the callback is getting the ItemStack before the decrease or something
What.
-# next update there's gon be usedItem
hopefully
Does the crafter not have an inventory component?
if so what does it have since I cannot find anything about that I want to fill a crafter using script
I think that it is not yet possible to control crafters via the API
alright thats unfortunate ty
it should work
it is a container and replaceitem dose work with it
Hmm, I haven't played Minecraft for too long to know how the new things work.
let me test it with the api
inventory component don't work but replaceitem command dose @warm mason @sage hamlet
keep in mind it dose work even if the slot is disabled
This is on par with "the equippable component exists for all entities"
crafter is a block
Hello, is it possible to make "moving" structure by scripts? Which will run on x line to left or right and also remove blocks behind?
If you don’t particularly care about the information in the blocks (like inventory of chests or items in a frame), then this is quite easy
New input info is goated
Can you make it move diagonally?
Can you help me with that then? I've tried with setting class "Mover" with all informations like start point, end point, name of structure, direction etc. And then run function with the const and then with structure load in the coords
no i made it to work only in n w s o becouse it wasnt easy to move it when you werent 90 degrees centered
yes
Why? Simply get the vector of the direction in which the player is moving and move along z and x depending on the vector
mine follows your camera as you can see right and left are taken by the player's view
like if you press D to move left it moves on your left not in a costant axis of the world
Yes, I took that into account.
I think I'll do it when I have nothing else to do
is there any way to get entities that are out of simulation distance?
for example i wanna check how many entities are in a chunk starting from y -59 to 320
but when i get like 40-50 blocks far it stops getting these entities
or maybe that isnt it. it could be because the entities are despawning after im far enough
does this have any way to fix?
When it’s out of ticking distance the entity isn’t even loaded, you can’t detect it,
You can do a ticking area (not recommended)
Or just when you re about to stop ticking the chunk you count the entities and save it as the chunk index
I'm trying to make a custom event system, but the cancelling part doesn't work properly:
import { world, Player } from '@minecraft/server';
import { Frozen } from './addons';
export class CustomHitEvent {
/**
*
* @param {Player} hitPlayer
* @param {Player} damagingPlayer
* @param {Number} damage
* @param {ItemStack} itemStack
*/
constructor(hitPlayer, damagingPlayer, damage, itemStack) {
this.hitPlayer = hitPlayer;
this.damagingPlayer = damagingPlayer;
this.damage = damage;
this.itemStack = itemStack;
}
}
export class CustomHitEventSignal {
constructor() {
this.listeners = [];
}
/**
*
* @param {Function} listener - The callback function to subscribe to the event
*/
subscribe(listener) {
this.listeners.push(listener);
}
/**
* Emit the event to all subscribers
* @param {CustomHitEvent} event - The event to emit
* @returns {boolean} - Returns true if the event was not canceled
*/
emit(event) {
for (const listener of this.listeners) {
listener(event);
Frozen.Info("event.cancel:", event.cancel)
if (event.cancel === true) {
return true;
}
}
return false;
}
}
export class CustomEvents {
static CustomHitEvent = new CustomHitEventSignal();
/**
* Emit the custom hit event
* @param {CustomHitEventSignal} signal - The signal to emit the event
* @param {CustomHitEvent} event - The event to emit
*/
static emit(signal, event) {
return signal.emit(event);
}
}
I can cancel the event like shown below, but not inside of a callback like I want to. how can i achieve that?
CustomEvents.CustomHitEvent.subscribe((event) => {
event.cancel = true; // This works
Object.entries(Enchantments).forEach(([key, value]) => {
if (value.onEvent?.name === event.constructor.name) {
if (!(event.itemStack && ItemUtils.getItemType(event.itemStack).length > 0)) return;
const Enchant = EnchantmentUtils.getEnchantments(event.itemStack).find(enchantment => enchantment.name === key);
if (Enchant) {
value.Callback(event, Enchant);
}
}
})
});
/**
* @param {CustomHitEvent} event
* @param {Enchantment} enchantmentInfo
*/
Callback: (event, enchantmentInfo) => {
const { damagingPlayer, hitPlayer, damage, itemStack } = event;
event.cancel = true; // Does not work
if (itemStack) {
const P = (0.06 / 3)*enchantmentInfo.level
const duration = 60
if (Math.random() < P) {
hitPlayer.addEffect("minecraft:slowness",duration,{ amplifier: 0, showParticles: true})
}
}
}
You gotta open a post for this dude.
what is the difference between world.getAllPlayers and world.getPlayers?
getPlayers supports an entity filter as an argument
no difference || If used without parameters ||
ok thx
Can someone help me with moving structure? In post are all details
not all of them
not location and distance iirc
I'm so confused...does playerInteractWithEntity not trigger with an empty hand?
did you try the before event?
might be something weird with before/after
Will try that.
it might be a case of the after event only firing if there's a valid interaction, like breeding or something
An FYI, it will work with empty hand if the entity has:
"minecraft:interact": {
"interactions": [
{
"on_interact": {}
}
]
},
so then yeah, it needs a valid interaction
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]
Guys, wich npm module do i need to download (or vscode extension) so it will show me the diff. things i can add to the manifest
wdym by different things?
npm i @minecraft/[email protected]
alr ty
Why isn’t this working? It’s expecting a number but I don’t know how to turn command[2] into a number if it can be one.
if (command[0] === "pay") {
const sendTo = world.getAllPlayers().find(nm => nm.name.toString().toLowerCase() === command[1].toString().toLowerCase())
if (sendTo) {
if (command[2](typeof Number)) {
system.run(() => {
world.scoreboard.getObjective("coins").addScore(sender.scoreboardIdentity, command[2])
world.scoreboard.getObjective("coins").addScore(sendTo.scoreboardIdentity, command[2])
sender.sendMessage(`§iSent ${command[2]} coins to ${sendTo.name}.`)
})
} else {
system.run(() => {
sender.sendMessage(`§cInvalid integer.`)
})
}
} else {
system.run(() => {
sender.sendMessage(`§cNo player found by the name of '${command[1]}'.`)
})
}
}```
const command = data.message.trim().substring(1).toLowerCase().split(" ")```
Idk why my code spaghettified itself when i sent it but ok
if(command[2](typeof Number))
this is wrong
it should be typeof command[2] === "number"
also command[2] is never a number, it is always a string
use isNaN to check
Thanks but if it’s always a string how do I do the scoreboard thing??
Number('1')
I also forgot I left the typeOf Number thing in there
yeah
Ok :/
so js if (Number(command[2]) > 0) {}
But if it’s not a number it’ll throw an error
Oh
Wait
check if it returns a valid number 1st I think
before comparing it with 0
also command[2] is never a number, it is always a string
use isNaN to check
I can just do ?.valueOf() > 0
Right?
if (Number(command[2])?.valueOf() > 0) {}```
**isNaN **
You can do it in the same one i think
As long as you check if it’s not a number 1st
No, I’ve tried with other similar situations, it’ll throw an error
If the 1st condition doesn’t pass it shouldn’t attempt the 2nd I think …
if(Number(command[0]).isNaN()) {
if(Number(command[0]) > 0) {}
}```
Riiight?
I guess that gives me more opportunity to tell players what they did wrong with the command
I just tried this with (if false && world.sendMessage("Hello")) & the message never gets sent though so I kind of presume it skips the rest of the conditions once it runs into a falsy one ?
use && dude
But yeah for this case it might be better to have two for more proper error handling
It throws an error if i do that!!
It does not as long as you cjeck if it’s NaN first
not always the case
if statement ignore the rest of condition if the first failed in &&
or shouldn’t
Try it first
how did you write it
Fine
only the first??
i thought if any condition fails then the rest will not be checked for
Oh come on, idk! I deleted the code already because it doesn’t work! Do you expect me to just stash away any bad code I’ve written?? (I can’t remember things well at all.)
mahbe I misunderstood what you meant
yeah
if(x && y)
no point in checking y if x is false
rewrite it real quick?
but i meant like
Fine, let me see if I can recreate from basically gone memory give me a minute
if (true && false && Entity.prototype.applyDamage(10)) for example, applyDamage will never run right
doesnt need to be from memory, just try to implement && again.
yeah
if (world.scoreboard.getObjective(“strength”).getScore(player.scoreboardIdentity) != undefined && world.scoreboard.getObjective(“strength”).getScore(player.scoreboardIdentity) > 0) {}
Certainly didn’t work the first time.
So I deleted it and never used it again.
you said there was an error.
Yes, can’t read value of undefined.
Or something along those lines.
that has nothing to do with &&
then .getScore(”strength”) is undefined
i think
Nope.
i don’t work with scoreboard
The score exists.
The player just doesn’t have a score for it.
Whoops, I meant to write .getObjective not .getScore
@jolly citrus
Fixed
yes
nice to know this
i always assumed it worked this way but wasn’t sure
okay.
Well it certainly doesn’t work that way for scoreboards, so i just assumed it didnt work that way for every other thing you can logic
Because WHY would logic work differently for different terms.
also the case for || if the first one is true
is it possible to remove an effect specifically with infinite duration from a player? I want to create some custom enchantments that grant the player permanent effects, but do not want these to override their possible past potion effects
e.g. player first drinks speed 1 for 3 min, then equips boots with speed 2 enchantment and removes them, usign removeEffect("speed") they’d no longer have their 3 minutes of speed 1 yes?
store past effects and re-add them later
You could probably store their current effects before giving them the infinite one then apply it again after the infinite one is removed
so much work 😔
nah
I thoughr about that as I was writing the question but i was skeptical about how reliable it could be
But players can have multiple effects with different amplifiers at once yes?
Multiple of the same one?
ya with different amplifiers
if you have speed 2 and get a burst of speed 3 your speed 2 will come back after speed 3 ends I’m pretty sure
the amplifiers override eachother, no?
just store all infos amplifiers and duration
I was under the impression you could not have the same effect with different amplifiers
you cant
I thought of the opposite but am now doubting my memory
wait dose it override or is there some kinda of priority
man idk
Based on what i remember when i’ve last played, it always prioritizes based on the amplifier
If it does override you have to decide if you want to implement logic to tick down the stored effect while the infinite one is applied or if you want it to keep the same duration the player had prior to getting the infinite duration version
maybe the minecraft wiki answers this question.
i think the duration of all the effects also progress as you have a higher amplifier
if i have speed for 5 min then speed 3 for 1 min i would end up with speed for 4 min after speed 3 ends
i think
When applying an effect already active on the player, higher levels overwrite lower levels, and higher durations overwrite lower durations of the same level.
yes
oh
wait
but will the lower effects come back after one with a higher amplifier ends or not thouguh
It appears not
oh ..
/effect @p speed 30 1 true
/effect @p speed 20 2 true
Player receives speed III for 20 seconds, after 20 seconds they have no speed
Why???
what is line 166
Oh wait I’m dumb
all good
you do delete your messages a lot tho
that make the conversations pointless for future readers
Is there a script method to check how many tickingareas are active in a world?
Don't want to use loader entities cause I only want one chunk loaded
no
there isn't even a method to create a ticking area yet with the api.
