#Script API General
1 messages ยท Page 62 of 1
event.sourceEntity.runCommand
Oh
Would this run if an entity calls the event? ||dumb question I know ๐ญ||
Yes
Could I use the components of a mob's minecraft:health to detect if a mob's health is at a certain value using Entity.getProperty?
entity.getComponent("minecraft:health").currentValue
Thank you
@dim tusk i actually got it to work tho i may need to work with it so that the display looks nicer
are complex topics like generic constraints needed for bedrock development ?
can we check if player on dimension switch screen
no, but you can still use them
no
can i get help so my systemrun wont try to spawn entities when unloaded as it throws an error when it does
full code #1346125732463771739
Got it to work
is it possible to get minecraft version using script api?
(i know it is not possible, but just for clarification)
Only for editor module.
is it importable just like @ minecraft/server
Next on the list of vanilla features ill be gutting
Fishing
Am i making minecraft better or is this no longer minecraft at this point and should be advertised as a game if its own
huh?
Anyone got a quick function to get closest player in a certain range
world.getDimension("dimension_name").getPlayers({ location: Vector3, maxDistance: Number, closest: Number})
closest is the amount of players to get based on closest to furthest, and it returns an array of players
dam ty
that gonna help alot
player.dimension.getPlayers({ location: player.location })[1]
@dim tusk i wanted to ty for the bank after fixing a few broken logics it works but do you know how i can make the button displays remove the namespace which is either minecraft or tg
typeId.split(':').pop()
What about removing under scores
typeId.replace(/.*(?<=:)/, '').replace(/_/g, ' ').replace(/(^\w|\s\w)/g, (m) => m.toUpperCase()); 
a question
with script api
How do i get if player is looking at "down" or "up" ?
i know i have to use player.getRotation() but what do i have to do with it
@valid ice
console.warn(JSON.stringify(player.getRotation()))
oh do i use pitch
looking straight down gives an x of 90, straight up is x of -90
Them move ur view
Next q this may be a json ui question but how do i add a picture in the form tied to the item some items have 1 im not sure how or why but others dont
wdym
if (player.getRotation().x > 85) {
// player is looking down
}
if (player.getRotation().x < -85) {
// player is looking up
}
is it right then
I have a bank script that lets you deposit or withdraw items and sets as a dynamic some items loke crafting table have a pic but i gtg work calls
How do i create particles in script
how to spawn particles?
world.getDimension('overworld').spawnParticle()?
are you asking a question or answering a question
asking an answering
makes sense
What i need is when a certain item is used it sends particles for x amount of blocks or until it hits an entity and if it hits an entity it runs a function
In the dirrection player is facing
Particles will just be a visual thing, you dont need particles for that
particles doenst detect entities, thats my point
I know but i can run it side by side cant i
Not enough data
Btw
An area?
1 sec ill send you pseudo code
@prime zenith
What you would need is a particle that has molang variables to essentially rotate. Then, using math, get the angle from the block to the entity, pass that data to the particle and spawn it.
Which i have no idea how to do at all
// Pseudocode
ItemUse->raycast
If(raycast){
// Do math to get rotation
Const m = new MolangVariableMap
m.setFloat()
...
Dimension.spawnParticle(particle, m)
}
So pseufo code
Player uses certain item with data magic
It checks a mage spell scoreboard
All of the above i csn do
Then it gets the way your facing runs a detect 1 block ahead applies particle then 2 then 3 until it reaches weapons range variable or detects an entity
Idk what raycast is btw
Raycast is when you draw a line from one position to another and it sends the data of whatever it hits back to you
Ok might be a bit of a learning curve to use tbh
Can anyone help me learn how to use raycast
i can
const { source: player, block } = event;
const mainhand = player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand);
if (player.isSneaking && mainhand?.typeId === "minecraft:wooden_sword") {
system.run(() => rotateBlock(block));
} else {
console.log("Rip.");
}
});```
Why can only one person use the item with the script at a time?
Can we voice chat later
sure i can try
Wait oops
const maxSpin = 15;
function rotateBlock(block) {
const currentState = block.permutation.getState("JCTbuild:spin");
let spinValue = currentState || 1;
let newSpin = (spinValue % maxSpin) + 1;
const newPermutation = block.permutation.withState("JCTbuild:spin", newSpin);
block.setPermutation(newPermutation);
}
world.beforeEvents.itemUseOn.subscribe((event) => {
const { source: player, block } = event;
const mainhand = player.getComponent("equippable").getEquipment(EquipmentSlot.Mainhand);
if (player.isSneaking && mainhand?.typeId === "minecraft:wooden_sword") {
system.run(() => rotateBlock(block));
} else {
console.log("Rip.");
}
});
Why does the item is not able to use it at the same time as someone else, when using the script?
here
import { world, system } from '@minecraft/server';
world.beforeEvents.itemUse.subscribe(data => {
const item = data.itemStack;
const name = item.nameTag;
if (name != 'wand' || item.typeId != 'minecraft:stick') return;
const player = data.source;
const location = player.getHeadLocation()
const direction = player.getViewDirection()
let raycast = player.dimension.getEntitiesFromRay(location, direction);
if (raycast.length < 1) return;
for (let hit of raycast) {
const entity = hit.entity;
if (entity == player) continue;
system.run(() => {entity.applyDamage(5)});
}
})
Now that works instantly i assume i do need to slow it down so i can make a partical line from player to entity
it does work instantly yes
I'm in preview...
i just remove the debug screen on top...
it can have no buttons without throwing errors now...
Like add a timeout
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
if (itemStack.nameTag !== 'wand' || itemStack.typeId !== 'minecraft:stick') return;
const { dimension } = source;
const head = source.getHeadLocation(), view = source.getViewDirection();
for (const { entity } of dimension.getEntitiesFromRay({ x: head.x, y: head.y + 0.1, z: head.z }, view)) {
if (entity !== source) system.run(() => entity.applyDamage(5));
}
});
If anyone can help me, https://discord.com/channels/523663022053392405/1346205642859217011
Ill be moving it to its own function as world event will get all the data so it can make sure the mainhand has the tag then will dettect what spell it is player stats ect to calculate its damage from other files but once i learn how this works and learn particles im sure ill figure it out
i didn't say anything about your original code thoo
Tho any idea the best way to add particles so it looks like its a straight line
What are you doing again btw??
just ocnfused why u rewrote lol
oen sec writing it rn
I hate too many variables when you can do it directly
better for peopel who are trying to learn
Im opposite i like variables
^
then go cause I don't like them especially make my code long
Otherwise I agree with Coddy
jsut preference
I mean, since it's basic yes but for short things I usually do variables but I still do direct since it's somewhat annoying
That may be why it took so long to break down coddies codes
anyways, that's not the point rn...
mb, I usually do codes with some knowledge persons lol
import { Vector3Builder, Vector3Utils } from '@minecraft/math';
import { world, system } from '@minecraft/server';
world.beforeEvents.itemUse.subscribe(data => {
const item = data.itemStack;
const name = item.nameTag;
if (name != 'wand' || item.typeId != 'minecraft:stick') return;
const player = data.source;
const location = player.getHeadLocation()
const direction = player.getViewDirection()
const raycast = player.dimension.getEntitiesFromRay(location, direction);
const range = 10;
if (raycast.length < 1) return;
for (let hit of raycast) {
const entity = hit.entity;
if (entity == player || hit.distance > 10) continue;
const difference = Vector3Utils.subtract(location, entity.location);
for (let step = 1; step < 10; step ++) {
const transform = Vector3Utils.subtract(location, Vector3Utils.scale(difference, step / 10));
system.run(() => {player.dimension.spawnParticle('minecraft:heart_particle', transform);})
}
system.run(() => {entity.applyDamage(5)});
}
})
here
Knowing isnt the factor its prefferences
teach him how to install the bundle...
In that case just directly make math...
I can store variables externally once and reuse
import { world, system, Vector3 } from '@minecraft/server';
function vectorSubtract(vector1 : Vector3, vector2 : Vector3) {
return {x: vector1.x - vector2.x, y: vector1.y - vector2.y, z: vector1.z - vector2.z};
}
function vectorScale(vector : Vector3, scale : number) {
return {x: vector.x * scale, y: vector.y * scale, z: vector.z * scale}
}
world.beforeEvents.itemUse.subscribe(data => {
const item = data.itemStack;
const name = item.nameTag;
if (name != 'wand' || item.typeId != 'minecraft:stick') return;
const player = data.source;
const location = player.getHeadLocation()
const direction = player.getViewDirection()
const raycast = player.dimension.getEntitiesFromRay(location, direction);
const range = 10;
if (raycast.length < 1) return;
for (let hit of raycast) {
const entity = hit.entity;
if (entity == player || hit.distance > 10) continue;
const difference = vectorSubtract(location, entity.location);
for (let step = 1; step < 10; step ++) {
const transform = vectorSubtract(location, vectorScale(difference, step / 10));
system.run(() => {player.dimension.spawnParticle('minecraft:heart_particle', transform);})
}
system.run(() => {entity.applyDamage(5)});
}
})
i kinda have it written in ts so just ignore the : Vector if u dont use typings
my muscle memory is insane wadahell...
Wait so ignore vector?
ignor teh : vector in the functions
if yo udont write in typscreiopt
my keyboard has low actuation so i mistype a lot
mb
world.beforeEvents.itemUse.subscribe(({ itemStack, source }) => {
if (itemStack.nameTag !== 'wand' || itemStack.typeId !== 'minecraft:stick') return;
const { dimension } = source;
const head = source.getHeadLocation(), view = source.getViewDirection();
for (const { entity, distance } of dimension.getEntitiesFromRay({ x: head.x, y: hesd.y + 0.1, z: head.z }, view)) {
if (entity.id === source.id || distance > 10) continue;
const diff = {
x: head.x - entity.location.x,
y: head.y - entity.location.y,
z: head.z - entity.location.z
};
for (let step = 1; step < 10; step++) {
const scale = step / 10;
system.run(() => dimension.spawnParticle('minecraft:heart_particle', {
x: head.x - diff.x * scale,
y: head.y - diff.y * scale,
z: head.z - diff.z * scale
}));
}
system.run(() => entity.applyDamage(5));
}
});
this is if u dotn wantvariables or extra functions ^
my phone is lagging wtf
lol
the length difference is insane...
lol'
it is good practice tho to use varibles, mroe readable for others if that's what ur going for
To be honest i could get all the player info set to a var in a reusable function
and... Longer
btw, unrelated but what did you do to the banking system I gave?
your opinion then, you'll get maybe in future what I meant...
soo, the getEntitiesFromRay isn't entirely accurate btw...
I split it up for 1 set it based if bankmode is 1 it runs deposit if 2 it runs withdraw then turns bankmode to 0 when selection is made it reopens form
It runs withdraw 1 at a time so stacks wont break
unlike getBlockFromRay()
Im not at a computer so im hoping when i get home me and bar can voice chat
umm, why get equippable if they are built in ItemStack already?
world.beforeEvents.itemUseOn.subscribe(({ source: player, itemStack, block }) => {
if (player.isSneaking && itemStack.typeId === 'minecraft:wooden_sword') {
system.run(() => rotateBlock(block));
} else console.error('Rip');
});```
hmm, is it possible to detect the player while mining a block, not by detecting the block using getBlockFromViewDistance thing.
world.afterEvents.playerBreakBlock.subscribe(({ brokenBlockPermutation, player, itemStackAfterBreak, itemStackBeforeBreak }) => {
if (brokenBlockPermutation.type.id === 'minecraft:tnt') {
// ...
}
});```
i can use entityHitBlock component, but u can hit around the block and then mine it normally
thats unwhat i meant
( breaking the block, like how u try to mine bedrock when u was a kid )
I assume you know it's permutation so you use type.id
like detecting if the player input mode is the attack / break after the player hit the block
lemme show u an example,
a bad example,
trying to make it so when u are mining the block, u will keep getting damaged,,
^ just an example ^
rl craft?
na, its just an example, i have another idea somewhere in my brain
I don't think there's a way...
like its not possible to detect the input key ( attack / breaking ) ?
nah. molang onky
variable.attack_time
like i have to edit the player json or something idk
yeah I guess so. That's the best thing you can do...
variable.attack_time >= 20 ( on ticks ? )
no, that molang is based into the current swing rotation of players arms
it's from 0.0 to 1.0, it's a float
ah,
so in general its not possible to detect if the player is Minging the block or Not
yeah, but not currently mining
after mining only...
and its not possible to use molang on scripts ig, right?
Is that why?
The script wont work with 2 players at the same time?
you wanted it to not work or want it to work?
I want it too
I think it might work, I dunno any reason it won't? Just try it yet tho...
hmm, i can make it keep damaging u after hitting the block instead
Lol I made the script for a client and he bugging me abt this happening so ig so
I never had this problem with my other scripts
I dont understand this bug at all
tbh, your old one should also work, I dunno why it doesn't work? The only problem in your previous one is you're using equippable if there's built-in one...
hmmmmm, my brain is kinda working,
but frist, is it possible to remove tags via molang?
like query.getTags() in the player.json
hmm,
Use server anim controller then run a commands...
and no you can't check tags using molang since they didn't add it...
Tags on items and blocks yes but not entities...
lemme show u my idea TO detect mining the block
when the player hit a block, he will get a tag, and via molang, i can detect the arm swing if it is swinging or not,
if it is the tag will not removed, else the tag will be removed,
and via scripts, i can make a system that can detect blocks from the view distance by 3ร3ร3 area, and if the player is facing into that box and he have the tag, he will keep taking damage overtime
@dim tusk ^
what d u think?
( i just need to make the molang that will detect if the player is swinging his hand / has a specific tag )
As I said there's no molang to check tags in entities.
Im not looking forward to needing to texture hundreds if not thousands of items
Can i make a item render so it looks like your holding it with 2 hands
like the charged crossbow? or like holding a gun?
yes u can do that, but u need a custom geo items in order to make that happen
but it is possible to detect if the player is swinging his hand or not
yes.
My mind was going 2 handed sword
I have a wep cooldown system i just hate how it will still create a damage indicater even if on cooldown i wish i could remove damage indicaters entirely
${player.name} undefined?
world.afterEvents.entityDie.subscribe(({ damageSource: player, deadEntity: entity }) => {
world.sendMessage(
`${entity.typeId} died from ${player.name}!`
);
});
damageSource.damagingEntity
How do i give a vanilla mob a custum loot table that overwrites its vanilla
world.afterEvents.entityDie.subscribe(({ damageSource.damagingEntity: player, deadEntity: entity }) => {}
{ damageSource: { damagingEntity } }```
@fallen hearth if you want the code to only run if its a player use an if for if damaging soyrce is not a player then return
okay
How much would it cost to just pay someone to make me a dragon entity
world.afterEvents.entityDie.subscribe(({ damageSource: { damagingEntity: player }, deadEntity: entity }) => {
if(player.typeId != "minecraft:player") return
world.sendMessage(
`${entity.typeId} died from ${player.name}!`
);
});
Im horrible at blockbench
when I use /kill it causes an error in the log
well, i am trying to rework the RL craft tree chopping system from java to bedrock, but using my own unique way ( just testing )
You want to set just damaging entity and check if damaging entity is player
I damn knew it lnfao
( bec i am thinking about making an addon after my big boy 'exe' )
/kill isn't a damager.
that's why it throws a error
it can't find the damage or killer
i will rework the entire how to play minecraft :v
after 'exe' ig
do js if (player?.typeId !== 'minecraft:player') {}
the damagingEntity can be undefined that's why ? is there.
nice
If i ran kill @e in real life would you all be mad at me or just not care cause youd be dead
how to do /kill @e in the real world:
step 1: be a god
mission failed
Are you questioning my godliness
Hi yall
You can call me princess not yall
The fuck is happening go in #off-topic
na, i'd rather go to #art-and-modeling instead
You cant derail off topic cause its already off topic get with the program there coddy
๐
I'm not actually kidding..
You too...
is this not right?
/tp coddy ~ -65 ~
My feet arent capped my feet are shoed
Feet with capital letter
why you teleport me up in the sky and that's not how you summon me...
-65 is not up
I did relative x relative z and -65 absolute y
Thats the void my friend
how do i get the name of the button the user clicked in ActionFormData
Dud, my blind asf didn't realize it's - not ~
I see al minus
Btw that command does not work
Someone know if there is an event to detect a server starting up or crashing/close?
And one to detect when a player us whispering
Is*
it will work...
const buttons = ['first', 'second'];
new ActionFormData()
.title('test')
.button(buttons[0])
.button(buttons[1])
.show(player)
.then(({ selection }) => {
if (selection === undefined) return;
const button = buttons[selection];
player.sendMessage(`You clicked: ${button}`);
});
That's the closest one
It's a valid command so yeah it will work you can mix to use ~, ^ and a number...
I see all minus idk about you
~ -65 ~??
tilde number tilde
how it's not valid?
Yeah im blind
Coddy one question
You can use world initialize for startup- nothing exists for shutdown, unless youโre using preview, and idk if it triggers for crashes at all.
And whispering is a no-go
How can i take the XUID of a player with script
System before events for preview mc: https://learn.microsoft.com/en-us/minecraft/creator/scriptapi/minecraft/server/systembeforeevents?view=minecraft-bedrock-experimental
Thx a lot
ah, didn't think of that, thanks, i could also put textures inside of the array, thanks again 
Not possible..
Sad
Unless BDS 
Sorry if im stupid but BDS = ???
as Herobrine said if preview the system.beforeEvents.shutdown.subscribe() exists
bedrock dedicated server
Thereโs probably a way to query XUID with http requests or multiplayer Xbox stuff- I know realm bots can grab player XUID, and realms are just BDS, so
It is good practice to set forms to a variable unless its in a function for reusability i prefer function as you can run the function
I didn't get anything in what you said...
im dyslexic
Yours and mine is different... Mine work always so yeah...
I never had a problem in my script at all...
plus, it's a sample....
If you let an event set and open a form you cant reuse it to allow multiple ways to open it if you need to
If you put form in a function have event run function you can
also, if it's there why not use it ๐คท
I'm not stupid and you know that...
I know im making a suggestion
I think the way you said it is not suggesting...
Anyways
can someone help with this i want to turn the items from entities to itemStacks :
system.runInterval(() => {
const dimensions = [
world.getDimension("overworld"),
world.getDimension("nether"),
world.getDimension("the_end")
];
for (const dimension of dimensions) {
const hoppers = dimension.getEntities({
typeId: "wr:wireless_hopper",
excludeTypes: ["minecraft:player"]
});
for (const hopper of hoppers) {
const hopperLoc = hopper.location;
const hopperBlock = dimension.getBlock({
x: hopperLoc.x,
y: hopperLoc.y - 1,
z: hopperLoc.z
});
const container = hopperBlock.getComponent("inventory");
const items = dimension.getEntities({
typeId: "minecraft:item",
location: hopperLoc,
maxDistance: 1.5
});
for (const item of items) {
}
}
}
}, 20);```
I saud its goid practice thats advice
so umm, you think I'm a beginner or nah?
No i didnt say that i can still give advice
yes, I know it's a good practice but SAMPLE.. sigh I never said you won't use it tho and I never disagree with your point.
@dim tusk 
Entity.getComponent('item').itemStack
const Container = hopperBlock.getComponent("inventory");
const items = dimension.getEntities({
typeId: "minecraft:item",
location: hopperLoc,
maxDistance: 1.5
});
for (const item of items) {
const RlItems = item.getComponent('item').itemStack
const added = Container.container.addItem(RlItems);
if (added) {
item.remove();
}
}````
That's wrong
What are you doing in the first place.
@humble lintel are you around
hello
system.runInterval(() => {
const dimensions = [
world.getDimension("overworld"),
world.getDimension("nether"),
world.getDimension("the_end")
];
for (const dimension of dimensions) {
const hoppers = dimension.getEntities({
typeId: "wr:wireless_hopper",
excludeTypes: ["minecraft:player"]
});
for (const hopper of hoppers) {
const hopperLoc = hopper.location;
const hopperBlock = dimension.getBlock({
x: hopperLoc.x,
y: hopperLoc.y - 1,
z: hopperLoc.z
});
const ContainerBelow = dimension.getBlock({
x: hopperBlock .x,
y: hopperBlock .y - 1,
z: hopperBlock .z
});
const Container = ContainerBelow.getComponent("inventory");
const items = dimension.getEntities({
typeId: "minecraft:item",
location: hopperLoc,
maxDistance: 1.5
});
for (const item of items) {
const RlItems = item.getComponent('item').itemStack
const added = Container.container.addItem(RlItems);
if (added) {
item.remove();
}
}
}
}
}, 20);```
its gets the entities with typeID wr:wireless_hopper then it gets the wirlessHoppers below it then gets nearby items and i want to add them to the container
Isn't there a transfer from container to another method?
const item = Entity.getComponent('item').itemStack;
Container.addItem(new ItemStack(item.typeId, item.amount));```
there is
both should be a container...
how'd you gonna swap items if the item is an entity?
ehm i thought he is talking about somthing els
Nearby entities
I meant from the hopper to the chest
@dim tusk
const items = dimension.getEntities({
typeId: "minecraft:item",
location: hopperLoc,
maxDistance: 1.5
});
for (const item of items) {
const RlItems = item.getComponent('item').itemStack
const added = Container.container.addItem(new ItemStack(item.typeId, item.amount));
if (added) {
item.remove();
}
}```
same error
Read the m message @solar dagger
itemStack of undefined
Import ItemStack in the server.
im lowk tryna get into machiens
they kidna coo
cool*
is there a way to chec kif an entity is in a loaded chun kthrough script?
same
There's item in the area? That shouldn't throws an error
something wrong with this line :
const RlItems = item.getComponent('item').itemStack```
Try .isValid
Ahh it can't detect the item entity in the area
shoudl work thankls
kk let me do raduis 10
same error
wait lemme try make my own.
waiit
i found it
const items = dimension.getEntities({
typeId: "minecraft:item",
location: hopperLoc.location,
maxDistance: 10
});```
i forget to add .location
Ahh. Lmfao

coddy I stil get the unloaded chunk error
check if the area loaded or not
i used the isvalid check
This is wrong I just realized.
you have a variable with that name imyou did it with . location
and you call that with .location again.
import { ItemStack, system, world } from '@minecraft/server';
const item = new ItemStack('minecraft:diamond', 1);
system.runInterval(() => {
const entities = world.getDimension('overworld').getEntities();
entities.forEach(entity => {
if (entity.isValid() == true) entity.dimension.spawnItem(item, entity.location);
})
}, 20)
wil lgive u error when i leave my pigs
๐คก
i removed it
aaaaaaaaaaaaaaaaaaaaand
this happens
Read your code
?
weird it says entities are still valid even though they not
const dimensions = ['overworld', 'nether', 'the_end'];
system.runInterval(() => {
for (const dimension of dimensions) {
for (const entity of world.getDimension(dimension).getEntities()) {
if (entity.typeId === 'minecraft:armor_stand') {
const blockBelow = entity.dimension.getBlock(entity.location).below();
if (!blockBelow?.getComponent('inventory')) continue;
const inventory = blockBelow.getComponent('inventory').container;
const nearbyItems = entity.dimension.getEntities({
type: 'minecraft:item',
location: entity.location,
maxDistance: 10
});
for (const itemEntity of nearbyItems) {
if (!entity.hasComponent('item')) continue;
const itemStack = itemEntity.getComponent('item').itemStack;
if (itemStack) {
const added = inventory.addItem(itemStack);
if (added) itemEntity.kill();
}
}
}
}
}
});```
Ohh yeah I forgot it returns true even tho the entity doesn't exist anymore ..
Iirc it's fixed in preview ..
ah rip lol
not working
also no errors
The item is added?
try doing console.error(blockBelow.typeId)
wait
To check if there's block under there in the first place.
God damnit I'm stupid wait.
okeeeeeeeeeeeeeeeeeeeeeeey
The code looks fine to me
The code is kind of inefficient though
Loops through all entities unnecessarily
system.runInterval(() => {
for (const dimension of ['overworld', 'nether', 'the_end']) {
for (const entity of world.getDimension(dimension).getEntities({ type: 'minecraft:armor_stand' })) {
const block = entity.dimension.getBlock(entity.location);
if (!block?.below()?.getComponent('inventory')) continue;
const inventory = block?.below()?.getComponent('inventory').container;
for (const itemEntity of entity.dimension.getEntities({ type: 'minecraft:item', location: entity.location, maxDistance: 10 })) {
const itemStack = itemEntity.getComponent('item').itemStack;
let remainingCount = itemStack.amount;
for (let i = 0; i < inventory.size; i++) {
const slotItem = inventory.getItem(i);
if (!slotItem || slotItem.typeId !== itemStack.typeId) continue;
const spaceLeft = slotItem.maxAmount - slotItem.amount;
if (spaceLeft > 0) {
const toAdd = Math.min(spaceLeft, remainingCount);
slotItem.amount += toAdd;
inventory.setItem(i, slotItem);
remainingCount -= toAdd;
if (remainingCount === 0) break;
}
}
if (remainingCount > 0) for (let i = 0; i < inventory.size; i++) {
if (!inventory.getItem(i)) {
const newStack = itemStack.clone();
newStack.amount = remainingCount;
inventory.setItem(i, newStack);
remainingCount = 0;
break;
}
}
if (remainingCount === 0) itemEntity.remove();
else itemStack.amount = remainingCount;
}
}
}
});```
I'm using this but my life doesn't change?
player.getComponent("health").setCurrentValue(10000)
the heart icons doesn't increase?
yeah it doesn't change it but the health is there.
try damaging yourself with /damage @s 20 you don't die...
@dim tusk Does this also serve to increase the player's health above the maximum health value?
@humble lintel are you available
hello im at my girl's house but i can help for a bit rn
boutta watch a movie tho
I dont want to bother you if your busy
no i can proll help for a bit
im just chilling rn
Ok can we vc add me
shoot I dont think i can vc but wanna just dm me
I made a cool reusable funt that gets all items there anount equip slots facing direction x y and z coords
Can we try if we cant hear eachother we can text while screensharing
im sharing this for ppl who want it as it gets all they stuffand is reusable just put it in a file export where you want it and save it as a variable where your getting players and need it then you do variableYouSetItAs.anythingItReturns it gets all slots and amount all equipment your x y z facing cardinal yaw and pitchslots are obtained by invSlots.slotNumber its useful i think not the cleanest but it works
Not like that
I don't think you should've returned unknown there.
like if a zombie kill u, it will spawn another zombie entity but it has ur skin
by ur skin i mean any players
sound impossible...
Not possible
-# warning: not BEGINNER friendly...
It was throwing errors if it couldnt find an item so i created a safety net
What event is for when a player eats a food item
do i do
```js
const pitch = player.getRotation().x;
if (pitch > 85 && (pitch >= -90 && pitch <= -75)) return 'Looking down (Towards negative Y)'
if (pitch < -85 && (pitch <= 90 && pitch >= 75)) return 'Looking up (Towards positive Y)'```
Or is that right
const pitch = player.getRotation().x;
if (pitch > 85 || (pitch >= -90 && pitch <= -75)) return 'Looking down (Towards negative Y)'
if (pitch < -85 || (pitch <= 90 && pitch >= 75)) return 'Looking up (Towards positive Y)'```
itemCompleteUse
itemStartUse
itemStopUse
itemUse
I got it i now gutted vanilla eating woohoo how many vanilla features can i overude lol
Can
- Entities
- Certain Items(Any food items or those found in the windowsapp folder)
- Entity loot tables
- Features
- Feature Rules
- Biomes
Can't
- Blocks
- Block loot tables
- Items not found in the windowsapp folder
- Dimensions
^
can i get a answer at this
?
calm down...
Hey eating may be faster but given eaten is the core way to boost health in combat thats a good thing
they look exactly the same
i am trying my best not to ping. lmfao
no
You know ill never get why minecraft has steak nsmed steak in gsme but cooked beef as its call tag
I'm blind, I didn't saw the || because of the ugly format.
Coddy stop attacking ppls code like that its extremely rude
then can i get a answer now
what???????
dude.
you're OA
why not try both?
you're weird
hmm ill use ||
I just said bad format but it's not the code itself but the tabing since it's a snippet....
uh
how to get difficulty... i've searched the docs, but couldn't find getDifficulty() anywhere.... what
Minato made one in the #1067535712372654091
mojang added getDifficulty()
he said
but couldn't find getDifficulty() anywher in the docs.... weird
preview
ah i see
btw, another question
how to get the x,y,z location of the "chunk" player is in?
i want to get x,y,z of the whole 16 x 16 chunk, the player is Standing on
divide corrds by 16 and round it
do i divide 16 with player location?
any location you want
what
yeah
why not floor
or that
depend on what you want
round get you the nearest corner of the chunk
floor get you the smallest (the origin)
const playerChunk = {
// The chunk the player is in
x: Math.floor(player.location.x / 16),
y: Math.floor(player.location.y / 16),
z: Math.floor(player.location.z / 16)
}
const playerChunkString = `${playerChunk.x}, ${playerChunk.y}, ${playerChunk.z}`
its okay?
round - 4.7 = 4
floor - 4.7 = 5
I don't think you need the Y there
y is not needed
what
huh, that is wrong
round 4.7 = 5
round 4.3 = 4
ceil 4.3 = 5
floor 4.7 = 4
why?
i want x,y,z of the chunk
then why Y is not needed
bro stop deleting messages
That doesn't make sense...
.. huh
chunks are defined by x and z
ur getDifficulty() summons spider and it does spider sound
it does instantly remove the entity
but the spider does a sssss sound
make a custom mob
then why didnt you in your snippet
because it is a snippet?
it is just and idea, you do with it what you need to
so do i copy vanilla spider mob code
will that work
yes, remove unnecessary components
cave spider is only able to detect difficulty?
not possible with normal spider?
i used these component groups
can u come in #1067869022273667152 general i need some help
const playerChunk = {
// The chunk the player is in
x: Math.floor(player.location.x % 16),
y: Math.floor(player.location.y % 16),
z: Math.floor(player.location.z % 16)
}
const playerChunkString = `${playerChunk.x}, ${playerChunk.y}, ${playerChunk.z}`
what would return if i would do this
instead of divide i do modulus %
remainder...
you just get the reminder of them, for example 30 divide 16 is 1 with a remainder of 14
actually it gets the relative position within that chunk
I cant get my partical function to work
can you somehow get memory usage in minecraft bedrock
script memory usage and more stats - https://marketplace.visualstudio.com/items?itemName=mojang-studios.minecraft-debugger
k
How to detect if entity is in player's view(not necessarily the player's eye view but if the entity is visible on player's device)
player.getEntitiesFromViewDirection()[0]
@dim tusk tysm ๐ซถ๐ป
what's getViewDirection() ...
i just saw it on docs
it returns vector3, but i dont understand what the docs is trying to say
View direction only returns entity from eye
Oh
there's a script to detect if entity is in player's large view
here
credit: made by @distant tulip
Could I use transitions state using query health?
Huh?
That came with no context, apologies. Like,
If I place two events with normal and activated in custom mob json, would this work?
"states": {
"default": {
"transitions": [
{
"ego_manifest": "query.health < 330 && query.is_alive"
},
Using things like calling an event upon reaching the custom entity's health value?
that question is for #1067869022273667152
Not scripting related. #1067869590400544869 #1067869022273667152
is it possible to use python language for scripting instead of javascript?
No
thanks
how do i fix this so that it sets the villagers name to nothing
system.runInterval(() => {
const dimensions = ["overworld", "nether", "the_end"];
for (const dimensionName of dimensions) {
const dimension = world.getDimension(`minecraft:${dimensionName}`);
const entities = dimension.getEntities({ excludeTypes: ["minecraft:player", "minecraft:villager"] });
for (const entity of entities) {
if (entity.typeId.startsWith("minecraft:villager") || entity.typeId === "minecraft:wandering_trader") {
// โ Remove villager name tag
entity.nameTag = "";
continue; // Skip the rest of the loop for villagers
}
if (entity.hasComponent(EntityComponentTypes.Health)) {
updateMobName(entity);
}
if (entity.typeId === "sky:crypt_ghoul") {
entity.runCommand(`tag @s add dmg35`);
}
}
}
}, UPDATE_INTERVAL);
function getMobStats(entity) {
let level = 1;
let maxHealth = null;
for (const tag of entity.getTags()) {
if (tag.startsWith("moblvl")) {
level = parseInt(tag.replace("moblvl", ""), 10) || 1;
}
if (tag.startsWith("mobheal")) {
maxHealth = parseInt(tag.replace("mobheal", ""), 10) || null;
}
}
// If no max health tag is found, use real max health
if (!maxHealth) {
const healthComponent = entity.getComponent(EntityComponentTypes.Health);
if (healthComponent) {
maxHealth = healthComponent.effectiveMax;
entity.addTag(`mobheal${maxHealth}`); // Store for future use
}
}
// Hardcoded Level Adjustments for Specific Mobs
if (entity.typeId === "sky:crypt_ghoul") {
level = 25;
}
return { level, maxHealth };
}
//cant do longer msg
Cant do longe msg
How do i change item name of a vanilla item
if you want to not edit the item json you can just do this as the start of the itemname in itemstack "ยงrยงfNot wooden shovel" it wont be italic
via texts/en_US.lang
How is it formatted i tried that
item.diamond.name=Diamond
item.iron_ingot.name=Iron Bar
probably its bec of an issue with the lang path idk
No it was a space issue
const { target,player,ItemStack } = ev;
if (player.hasTag('gr_interact'))
system.run(() => CustomUi(player))
player.removeTag("gr_interact")
can anyone fix this
I want it to open when I sneak interact and
remove tag bcz if dont it open ui on every mob
You are attempting to extract "ItemStack" from the parameter given in this callback. This is case-sensitive
Should the system.run and player.removeTag both only happen if the player has that tag? You may want to make a scope for that condition.
if (player.hasTag('gr_interact')){
system.run(() => CustomUi(player))
player.removeTag("gr_interact")
}
wdym? by scope
Put in if(player.isSneaking)
like &&
You can but player.isSneaking returns true if player is sneaking and false if not
Block scope; surround your statements in curly brackets to group them together. If put after a control flow statement like if, then the entire scope's contents will execute
the player tag works but on every entity for reason
I am trying to open the gui from serverform on my entity
I don't see any condition for the type of entity. The API will not implicitly assume what you need
You might add an extra condition like target.typeId == "my:entity" to that if statement, joined by &&
๐๐ฝ
onScreenDisplay.setActionBar() Does it support texts from the lang file? Like the titleraw command?
player.removeTag gives error
can we obtain the protection strength of an armor?
no
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id !== "space:peek") return;
world.getDimension("overworld").runCommand(`tag @a remove anomaly`);
let loopStart = { x: 3, y: 0, z: 15 };
let loopEnd = { x: 10, y: 3, z: 30 };
let playerPos = event.sourceEntity.getHeadLocation();
let found = false;
for (let x = loopStart.x; x <= loopEnd.x; x++) {
for (let y = loopStart.y; y <= loopEnd.y; y++) {
for (let z = loopStart.z; z <= loopEnd.z; z++) {
let targetPos = { x, y, z };
let direction = {
x: targetPos.x,
y: targetPos.y,
z: targetPos.z
};
let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
const logs = [
"minecraft:oak_log", "minecraft:spruce_log", "minecraft:birch_log", "minecraft:jungle_log", "minecraft:acacia_log", "minecraft:dark_oak_log", "minecraft:mangrove_log", "minecraft:cherry_log", "minecraft:pale_oak_log"
];
let block = blockRaycast?.block;
if (block && logs.includes(block.typeId)) {
found = true;
const blockLoc = block.location;
event.sourceEntity.runCommand(
`summon space:anomaly ~${blockLoc.x} ~${blockLoc.y} ~${blockLoc.z + 1} facing @s`
);
world.getDimension("overworld").runCommand("function tree");
break;
}
}
if (found) break;
}
if (found) break;
}
});
let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
This line says not a function typeerror
Also can anyone help in #1070606638525980753
does anyone have an up to date zombie.json the samples is outdated all i want is for it to not burn in daylight samples teaches it to fly and i somehow took away its ai fixing it
The samples are up to date though?
Downloadable from: https://github.com/Mojang/bedrock-samples/releases
bedrock.dev archive: https://bedrock.dev/packs
GitHub (RP & BP) : https://github.com/bedrock-dot-dev/packs
Example particles: https://aka.ms/MCParticlesPack
Java Edition's Vanilla Packs: https://mcasset.cloud/
And this isn't really a ScriptAPI question.
How many times per second does the system runinterval run?
20 ticks per second
By default, it runs every 1 tick. You can change this.
Can I make this faster?
But you can set it how many ticks it takes to run
Is it possible to run it 100 times in 1 second?
Not faster then 20 tomes per second but you could run it multiple times if yoou put logic into a function run the function a few times
No. What are you trying to acheive?
Making players immortal
Technicually if they got the logic to run 5 times per tick they might
Therw are msny ways to make a player immortsl
do you guys know why vscode doesnt recognize prototype functions?
You dont need to run anything 100 times per second to achieve that
health.setCurrentValue(50);
How can I fix this?
I plan to make it work faster to fix this
Btw The number on the heart logo represents the player's health
just give the player resistance infinite lvl 255
How do I identify fire block around me?
system.afterEvents.scriptEventReceive.subscribe((event) => {
if (event.id !== "space:peek") return;
world.getDimension("overworld").runCommand(`tag @a remove anomaly`);
let loopStart = { x: 3, y: 0, z: 15 };
let loopEnd = { x: 10, y: 3, z: 30 };
let playerPos = event.sourceEntity.getHeadLocation();
let found = false;
for (let x = loopStart.x; x <= loopEnd.x; x++) {
for (let y = loopStart.y; y <= loopEnd.y; y++) {
for (let z = loopStart.z; z <= loopEnd.z; z++) {
let targetPos = { x, y, z };
let direction = {
x: targetPos.x,
y: targetPos.y,
z: targetPos.z
};
let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
const logs = [
"minecraft:oak_log", "minecraft:spruce_log", "minecraft:birch_log", "minecraft:jungle_log", "minecraft:acacia_log", "minecraft:dark_oak_log", "minecraft:mangrove_log", "minecraft:cherry_log", "minecraft:pale_oak_log"
];
let block = blockRaycast?.block;
if (block && logs.includes(block.typeId)) {
found = true;
const blockLoc = block.location;
event.sourceEntity.runCommand(
`summon space:anomaly ~${blockLoc.x} ~${blockLoc.y} ~${blockLoc.z + 1} facing @s`
);
world.getDimension("overworld").runCommand("function tree");
break;
}
}
if (found) break;
}
if (found) break;
}
});
let blockRaycast = event.sourceEntity.getBlockFromRay(playerPos, direction, {maxDistance: 20 });
This line says not a function typeerror
Because it's a function on the Dimension class.
event.sourceEntity.dimension.getBlockFromRay()
Oh ty
what lol
dimension.getBlock(location).typeId === 'minecraft:fire'
is there a way to check if player busy(action form) without creating a form?
im the 100,000 message in here
I am sorry to disapoint you but this constantly happens here
really took you that long to type that
i saw u typing for a good 2 mins
^
getting side tracked
Ah, Willing to help me?
depends on what the issue is really
import { world, system } from "@minecraft/server";
const COOLDOWN_COMMON = 5 * 20;
const cooldowns = new Map();
world.beforeEvents.itemUse.subscribe((event) => {
const player = event.source;
const item = event.itemStack;
if (item.typeId === "rarity:commondice") {
const lastUse = cooldowns.get(player.id) || 0;
const currentTime = system.currentTick;
if (currentTime - lastUse < COOLDOWN_COMMON) {
const timeLeft = Math.ceil((COOLDOWN_COMMON - (currentTime - lastUse)) / 20);
player.onScreenDisplay.setActionBar(`Next Roll In ${timeLeft} seconds`);
return;
}
cooldowns.set(player.id, currentTime);
const min = 1;
const max = 10000000;
const randomValue = Math.floor(Math.random() * (max - min + 1)) + min;
player.runCommand(`/scoreboard players set @s rng ${randomValue}`);
player.sendMessage("You rolled.");
}
});```
I dont see any errors
see if you can make the file print anything at all and continue from there
just to see if its even loaded
Theres this
{
"format_version": 2,
"header": {
"name": "Dice RNG",
"description": "Adds custom dice with RNG functionality.",
"uuid": "738e20c3-80ed-4262-b945-73392353fdf8",
"version": [1, 0, 0],
"min_engine_version": [1, 19, 0]
},
"modules": [
{
"type": "script",
"language": "javascript",
"uuid": "3c66d2e3-1952-42e8-b293-4baf2e3bb612",
"entry": "scripts/main.js",
"version": [1, 0, 0]
}
]
}```
Manifest
You need script dependencies in there
like what
{
"format_version": 2,
"header": {},
"modules": [],
"dependencies": [
{
"description": "server",
"module_name": "@minecraft/server",
"version": "1.18.0-beta"
},
{
"description": "server-ui",
"module_name": "@minecraft/server-ui",
"version": "1.4.0-beta"
}
]
}```
wrap that part with system.run
?
system.run(() => Player.runCommand() );
this?
system.run(() => Player.runCommand(scoreboard players set @s rng ${randomValue}) );
or am i trippin
yeah, but obviously change Player to the right target.
um
system.run(() => player.runCommand(scoreboard players set @s rng ${randomValue}) );
@dim tusk Im a bit confused
that's correct...
do what you did previously...
wym
player.onScreenDisplay.setActionBar(Next Roll In ${timeLeft} seconds);
system.run(() => player.runCommand(Next Roll In ${timeLeft} seconds) );
so yeah lemme explain it to you, since you're dealing beforeEvents means before it happens, you can't modify the world, so the purpose of system.run is to run the thing in the next tick, to escape the read-only mode, tho it's not just system.run only you can use anything as long as it happens next tick not the same tick...
@granite badger how would i make ur interpreter block thing into just one script that runs when the world loads
Why weakness effect cancels player's attack but doesn't for mobs
Anyone know a good way to check if a shield blocked a hit?
Does anybody know if it's possible to detect what entity your looking at through a spyglass? Would the GetEntityFromRay work??
Really wish we could limit the damage scaling on CreateExplosion, still surprised we can't with it turning into an orbital nuke to any radius past 4
and functions u want to apply to that entity
nuke
It does 85 damage at a radius of just 6
Just wanting to detect if you look at a specific mob for a quest in my pack
I will take a look (lol) and see (lol) what works!! ๐
here i can write a small snippet of it
import { world, system } from '@minecraft/server';
world.beforeEvents.itemUse.subscribe(({itemStack, source}) => {
system.run(() => {
if (itemStack.typeId != 'minecraft:stick') return;
//Cast ray and get all the entities from ray
const start = source.getHeadLocation();
const direction = source.getViewDirection()
const raycast = source.dimension.getEntitiesFromRay(start, direction, {
//Max distance of the raycast
maxDistance: 10
})
//For every entity hit by the raycast run a function
raycast.forEach(hit => {
//Cancel if it hits you
if (hit.entity == source) return;
//Do whatever to the entity or run a function
})
});
});
@covert goblet
should be the basics
hey guys! is there a way i could get an output of a command? e. g. i want to do /locate biome "biome" and get the output that the command will give, and take out the coords of the output
No.
okie, thank you
the only output you can get from a command is a success count
which will not give you enough information
to get a certain biome
it's not really a biome that i need but the coordinates
but it isn't possible, so it doesn't matter anyway
yeah, not possible
is there a way to execute a locate biome command in scripts so the output was shown in the chat? maybe somehow execute it as a player
basically, what i'm trying to achieve, is so that when i feed by dino some seeds, it will give coordinates to a biome, and the command output should be written in the chat
can anyone share a snippet of how to send entity id's via script
for horse renderer
is it possible to detect slime chunks
to?
yes
wdym
send it where
I want to render custom entity in ui
I was told that u need to pass id's through for it to render
how
to where...
action bar? title? inventory?...
serverform
body or title
is it possible to detect if the player is in a slime chunk
yes
credit to obscraft23
isSlimeChunkPos(player.location.x, player.location.z)
omg thanksssss
that's why you're best
thanks to @faint hare
what if i have structures/folder/another_folder/mystruct.mcstructure?
Much appreciated ๐
If i did a before player leaves even and cancled it does that mean player can never leave
Folder:another_folder/mystruct
ah, alright, thank you
title
foreach(livingPersonOnEarth as person) {
if (person.likesPineappleOnPizza) {
reality.deleteEntity(person);
} else {
console.log(person.name + " may live. They have good taste.");
}
}
import { world} from '@minecraft/server';
import { ActionFormData } from '@minecraft/server-ui';
world.beforeEvents.itemUse.subscribe((event) => {
const { source, itemStack } = event;
if (itemStack.typeId !== "minecraft:stick") return;
const entity = source.dimension.getEntities({type: "minecraft:cow", closest:1})[0]
new ActionFormData()
.title("Special Offer!")
.body(`Player id: ${source.id}\nCow Id: ${entity.id}`)
.button("...")
.show(source)
.then(({ selection }) => {
//..
})
});
hello bros
I have a question
is there a way to store data for a item
I know dynamic property's do that
but those only work in no-stackable items
the only solution I have found is storing it in the item lore
If i ran a before eve t for entity removed if its an armor stand cancel or will that just leave a dead armorstand on world
Whats the most effective way to make an armorstand unmovable and unkillable
damage sensors
Like cause i gutted vanilla hp system
well damage sensors are the most effective way
Idk what you mean by damahe sensers
entity component, yes, you can use that on any entity
Ok well should be easier then zombies i tried changing zombies instead broke there ai
if you wanna use damage sensors you would need to copy the armor stand's code from the game files then add the component to it
I know that
okay
maybe?
.show gives error
before event?
system.run(()=>{
//code
})
wrap it up in system run
sorry for the delayed reply
ok
replaceitem entity @s slot.weapon.mainhand 0 ${blockItem.typeId} 1
how can i convert the command to scripts?
world.getDimension('overworld').runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 ${blockItem.typeId} 1\`);
maybe this?
or uh
player.getCompinent('inventory').container.setItem(player.selectedSlotIndex, new ItemStack())
somethign like that let me check
import { ItemStack, world } from '@minecraft/server';
world.beforeEvents.chatSend.subscribe(e => {
const plr = e.sender;
const msg = e.message;
if (!msg.startsWith('!')) return;
plr.getComponent('inventory')?.container?.setItem(plr.selectedSlotIndex, new ItemStack('minecraft:stick', 1))
})
something like this
u can ignore chatsend
thats juist what i used to get the player
player.getComponent("equippable").setEquipment("Mainhand" ,new ItemStack(`${blockItem.typeId}`))
this only works on players, for entities use the code baRD gave you
it doesn't work on armor stand
Which version of the module do I use in 1.21.50
Check the version list https://jaylydev.github.io/scriptapi-docs/latest/
Other than being able to cancel an action, is there any reason why to go with beforeEvent instead of afterEven? I'm looking at the documentation for [email protected] and there are barely any properties for beforeEvent - and also it seems to be readonly so an extra system.run is needed
Can playerId from PlayerJoin be used to /kick the player? I wanted to kick by id
Can i make it so a bow cannot fire if not fully charged
Entirely depends on use case.
PlayerInteract for example, before event can detect an empty hand wherras after does not.
anyone know if I can get a promsie from a runjob
Oh I didn't know that
what do yo mean
thank you for the help
no...
kick requires a target
and why use playerJoin?
just use playerSpawn
I made an item hopper block that has it's own inventory
I was wodnerign if anyone would be able to put their ideas into it
'as to why it creates this issue
just wanna know if anyone can give me their own inputs
function handleInventory(storage : Entity, block : Block) {
const nearbyItems = block.dimension.getEntities({
location: block.location,
maxDistance: 10,
type: 'minecraft:item'
})
const container = storage.getComponent('inventory')?.container;
if (!container) return;
for (let entity of nearbyItems) {
const item = entity.getComponent('item')?.itemStack;
if (!item) return;
if (container.emptySlotsCount < 1) {
//Find slots with similar Items
const similarSlots = findSimilarSlots(container, item);
if (similarSlots.length < 1) continue;
const similarItem = container.getItem(similarSlots[0]);
if (!similarItem) continue;
if (similarItem.amount + item.amount < similarItem.maxAmount) {
const newItem = similarItem;
newItem.amount += item.amount
container.setItem(similarSlots[0], newItem)
entity.remove();
} else {
const difference = similarItem.maxAmount - similarItem.amount;
const newItem = similarItem;
newItem.amount += difference;
container.setItem(similarSlots[0], newItem);
const newDropItem = item;
if (difference < 1) {
entity.remove();
} else {
newDropItem.amount -= difference;
block.dimension.spawnItem(newDropItem, entity.location);
entity.remove();
}
}
} else {
const emptySlots = findEmptySlots(container);
if (emptySlots.length < 1) continue;
container.setItem(emptySlots[0], item);
entity.remove();
}
}
}
container.addItem() already exists? why find similar slots, unless there is something I'm missing on
find similar slots for items that are already in the inventory
explain more?
container.addItem() already does that
yeah
crazy
yeah i mean it works jsut nto when there's multiple items
pronbably bc the count goes over 256
its cool tho
damn i wrote all of that
just for nothijng lmao
yeah it gives the same error
weird
same thing with the item amount
entity?.setDynamicProperty('test', +1) could work?
1
( will it expand it with 1 or only set the DP with 1 ? )
const DP = dynamic property
+1 is like saying 1, if you want to add 1 to it then just do entity?.setDynamicProperty('test', 1 + 1)
set dp to 1
const iTest = entity?. getDynamicProperty('iTest');
entity?.setDynamicProperty('iTest', iTest + 1);
will work but slow asf
what cennac said
that works, you can do this aswell
let iTest = entity?.getDynamicProperty('iTest');
entity?.setDynamicProperty('iTest', iTest++);
the problem is i have tried something similar to that before, and it was extremely slow im not kidding
( i tried this method )
optimize your code then ig
I tried it, doesn't give me an error
its not an optimizing thing, it was just very slow bec the script needs to get the dynamic property each time i want to adjust it
just to make sure, I'll do some work testing out multiple different ways to see which one is the best,
wait really? that's weird
did u create an explosion
of itmes
yeah, I can send a video if you want
yep
hm interesting
i used a chest instead of a custom block tho
didn't feel like coding a custom block
oh im using entity containers
oh, huh
yeah i dont think we're able to make custom container blocks
so i jsut use entities
with custom components
how do you open the container tho
makes sense, I'll try with an entity
maybe minecart chest
Uh yeah I just realized I closed my terminal for regolith
my bad...
so my edits were not applied
lmaooo
oh lol
const container = overworld.getBlock(location).getComponent("inventory").container;
const inventory = player.getComponent("inventory").container;
whats wrong?
@unique acorn add item doesn;t automatically remove item entities right
make sure the block is in a loaded chunk
yes
yeah so if my container is full but one slot has 63 dirt and I drop 64 I won't be abe to remove only 63 from the item entity
addItem() returns the rest of the items when slot is full, so you can use dimension.spawnItem()
it is
i dont think ender chest has inventory component
so maybe try a chest or barrel or another block
// Crate system
world.afterEvents.itemStartUseOn.subscribe((data) => {
const { source: player, block } = data;
const { x, y, z } = block.location;
if (x == 180 && y == 91 && z == -47) { // Cords of enderchest that will open the crate GUI
player.runCommand("playsound random.pop2 @s");
new ModalFormData()
.title("ยงfOpen Crates")
.dropdown("\nยงbSelect a crate key to open!\n\nยง7Crates give better loot the higher rarity it is!\n\n", [...CRATE_DROPDOWN])
.show(player)
.then(res => {
if (res.canceled) return;
const { location, itemStack } = CRATES[res.formValues[0]];
if (!location || !location.x || !location.y || !location.z) {
return failedMessage(player, "Invalid crate location.");
}
const overworld = world.getDimension("overworld");
if (!overworld) {
return failedMessage(player, "World dimension not found.");
}
// Ensure integer coordinates for block location
const blockLocation = {
x: Math.floor(location.x),
y: Math.floor(location.y),
z: Math.floor(location.z)
};
// Debug: Log the location being checked
player.sendMessage(`Debug: Checking crate at X:${blockLocation.x}, Y:${blockLocation.y}, Z:${blockLocation.z}`);
const block = overworld.getBlock(blockLocation);
if (!block) {
return failedMessage(player, "Crate block not found.");
}
// Debug: Confirm the block type
player.sendMessage(`Debug: Found block type: ${block.typeId}`);
const inventoryComponent = block.getComponent("inventory");
if (!inventoryComponent) {
return failedMessage(player, "Crate block has no inventory. Ensure itโs a chest or crate.");
}
const container = inventoryComponent.container;
if (!player.runCommand(`clear @s ${itemStack} -1 1`).successCount) {
return failedMessage(player, `You do not have a ${convertTypeId(itemStack)} Key.`);
}
const crateType = convertTypeId(itemStack);
const inventory = player.getComponent("inventory").container;
for (let i = 0; i < 3; i++) { // Gives 3 random items from the crate rarity chest
const drawnSlot = Math.max(randomInt(0, container.size - container.emptySlotsCount - 1), 0);
const item = container.getItem(drawnSlot);
if (!item) continue;
if (!inventory.emptySlotsCount)
player.dimension.spawnItem(item, player.location);
else inventory.addItem(item);
}
player.runCommand("kill @e[r=5,type=item]");
successfulMessage(player, `Successfully opened a ${crateType} Crate!`);
addScore(player, "cratesOpened", 1);
return;
});
}
});
world.beforeEvents.playerInteractWithBlock.subscribe((block) => {
const Intblock = block.block;
const player = block.player;
const blockX = Math.floor(Intblock.location.x);
const blockY = Math.floor(Intblock.location.y);
const blockZ = Math.floor(Intblock.location.z);
// Enter cords of crate opener chest
if (blockX === 180 && blockY === 91 && blockZ === -47) block.cancel = true;
});
show me all possible ways to increases the dynamic property value
bec these:
setDynamicProperty('smth', 1+1)
or
let i = getDynamicProperty('smth')
setDynamicProperty('smth', i++ / i + 1)
doesn't work properly
Funny I somewhat made the same thing to the other guy before
this one...
i mean it is either slow or bugged or just doesn't work,
check the original property value first then do +1
simple as that...
const val = world.getDynamicProperty('coddy:val') ?? 0;
world.setDynamicProperty('coddy:val', val + 1);```
let i = player?.getDynamicProperty('iO') ?? 0;
player?.setDynamicProperty('iO', i+1);?
unless I misunderstood something omfao
yes, idk why complicate your life
i have tried it before, for my hardcoded forge, it was extremely slow
since setting dynamic property overwrites the old one, you need to get the original val then add...
( i was running alot of dynamic properties at once )
it would never be slow at all
you're doing a lot of things probably
then why the hell was it very slow for me back then?
to make it act like scoreboard...
idk ๐
how a val + 1 would be slow?
no freaking idea
it's not even complicated math... Like what? It just adds ๐ญ
thats my life with my addon bugs
lmaoo
anyways what im trying to do here is making a fully functional energy generator system, generating energy / saving energy / converting energy
and spending energy
Did you saw it?
My goofy really set an ItemStack with another ItemStack
that's kinda easy, tho what type of energy...
how you'll transfer the energy and how to generate the energy
no unfortunately not
is there a better way to stop the item from respawing when I use addItem
Sorty wrong room
This one my mann @humble lintel
function* pickupItems(storage: Entity, block: Block) {
const nearbyItems = block.dimension.getEntities({
location: block.location,
maxDistance: 10,
type: 'minecraft:item',
excludeTags: ['test:item_ignore']
})
const container = storage.getComponent('inventory')?.container;
if (!container) return;
for (let entity of nearbyItems) {
const item = entity.getComponent('item')?.itemStack;
if (!item) continue;
const addItem = container.addItem(item);
const location = entity.location;
entity.remove();
if (addItem) block.dimension.spawnItem(addItem, location).addTag('test:item_ignore');
yield;
}
}
Maybe im just dumb but i cant figure it out
og bruh lmaoo
the one I gave is perfect already...
-# for me lmfao
as for the basic tier, u have only a hand crank block that will generate tiny amount of energy every 2 clicks,
but for the enhanced tier, which u can generate energy via burning coal and u can save the energy inside of a battery blocks, and to transfer the energy u need some wires for the connection.
You can refer to how I did it.
i have the same one nbtu does urs give any errors when u launch a bunch of items at once
like break a chest full of items type of stuffg
no, I tried with everything with lores, names, durability etc.
it works fine... YET
seems easy enough tbh
it is easy, but fixing the upcoming bugs is hard lol
ahh, it's normal
yeah lmao
Since the script only accepts items from 0 - 255
The best thing you can do is split them off unfortunately
i cant left a single bug in things like energy generators
I'm bored, I'm making an rc car.
especially with the forge or things that u need to make important stuff, u dont need to put the ingredients and get a log instead of the needed output
it uses 6 slots
one for the fuel
4 for the input
one for the output
and 2 extra ones for the flame and the arrow icons, and i have to work for each one of these all at the same time.
hmm, should i have all of my systems inside of one runInterval or having each one has its own runInterval?
( like which one is more efficient? )
use only one interval pls
don't have an interval for each one
That ain't a good idea
Especially if it's a lot, tho if you're just doing it in a short time that's okay.
but for a long time... NO just no.
they're both massive, and requires a short interval tick thing, so having both of them inside of one interval is a good thing,
Hi!
I have a question
Is there a way to make a block remember which players interact with it?
Save the coordinate in dynamic properties
Ok, thank you!
Does anyone have hasItem helper function?
like checking the item entity is holding or checking if he's holding a specific id only?
hasItemInInventory
So redundant, lol
here we go again...
Well first, the description given (or lack thereof) is probably not even to spec
Can you be more specific please
"I need to test if the player has a given <item> in their inventory" is not what Coddy's function does
It's not, they were vague
yeah deleted it lmfao
What you sent would certainly work for testing any item in that container, just ... I cannot imagine that ever being useful
There's simpler ways to do even that
Could you iterate over all slots and determine if each one is empty?
I defined one only but you can certainly do it.
And I forgot you can check inventory, my mind stuck in equippable component not available in entieis
And since yorue already here, you can just give it to him... Because you said it's bad ๐คท
Nah
nice response...
Does anyone know if its possible to grab a players coordinate and saving it on a scoreboard? Like, save their X coordinate to a scoreboard every 10 seconds or so?
Yes
Are you confused on how to put this in a pack, or how it works?
My main issue is that I'm not sure what the scoreboard's name has to be.
also is that using a beta/experimental API? (it's my first time using scripts)
Well, looking at the code they sent, can you clarify one thing for me?
the scoreboard name is literally just x y and z
It looks like that snippet grabs all of the player's coordinates, but if I'm understanding correctly, you only want to grab one coordinate every 10 seconds or so (x, y, or z). Is that correct?
I just want it to save coordinates so that I can print them using tellraw. The time isn't important that was just an example.
system.runInterval(() => { // Every 10 seconds, run this code.
for (const player of world.getPlayers()) { // Check each player in the world.
for (const key in player.location) { // Repeat the following code for the X, Y, and Z coordinates.
let obj = world.scoreboard.getObjective(key) ?? world.scoreboard.addObjective(key, key); // Get the scoreboard objective associated with the coordinate.
obj.setScore(player, Math.floor(player.location[key])); // Set the value.
}
}
}, 200); // 20 ticks equals 1 second, so 200 ticks is 10 seconds.
I tried those but it's still not working (I'm like 99.9% sure I'm doing something wrong tho)
const scoreboards = {
x: world.scoreboard.getObjective('playerX') ?? world.scoreboard.addObjective('playerX'),
y: world.scoreboard.getObjective('playerY') ?? world.scoreboard.addObjective('playerY'),
z: world.scoreboard.getObjective('playerZ') ?? world.scoreboard.addObjective('playerZ'),
};
system.runInterval(() => {
for (const player of world.getPlayers()) {
for (const key of ['x', 'y', 'z']) scoreboards[key].setScore(player, Math.floor(player.location[key]));
}
}, 10 * 20);
This is customizable, for example here it's playerX, playerY and playerZ
if works fine to me... Means you did something wrong..
Do the scoreboard objectives x, y, and z exist?
Have you created them?
he doesn't need to, it's in the scripts already
Oh I see, I missed that part
This does not use any beta script API capabilities, but there could be something wrong with your pack.
@viral mirage
Try pls.
Alr, one sec
Is there something I have to do to make a script run every tick? Similar to tick.json for functions?
Have you imported both world and system from "@minecraft/server"?
Otherwise no; assuming that snippet is in the entry of a pack with scripting enabled, it sets itself up. system.runInterval will invoke the callback function after so many ticks, on repeat
no... I was just copy pasting what Coddy wrote ๐ญ
It's my first time lol
mb guys
Imma try that
That's often neglected in most snippets haha, no worries
plus, did you turn in your log gui?
Looks like I'll put those imports in snippets from now on...
I don't even know what that means bro ๐ญ
I also have no clue how to do the imports, imma look at the docs rq
settings -> creator -> content log gui
just scroll down.
What version are you? I might just give you a pack already.
1.21.62, I think I got it now tho, imma try it with the imports
Yeah it still aint working... ๐
I was taking the script imports from the template, but not the manifest ๐
I give up
Ohh
That's an easy fix
Change the version 1.18.0-beta in manifest into 1.17.0 and for 1.4.0-beta change to 1.3.0
how to remove air block when using structureManager.createFromWorld()?
It's working now, thank you so much
i feel smart after seeing this
the version in the manifest can keep it that way (1.18.0-beta & 1.4.0-beta), you just NEED to enable Beta APIs in the Eperimental section ON THE WORLD
The problem is beta changes thru version so you can't just leave it as 1.18.0 beta in the next update that's why people use stable always
how do I give a entity a item to hold like allay and then take it back or replace it with item in hand through scripts
If i run a runJob that doesnโt do anything just yields will it create more lag than a runJob that yields after running a great task?
