#Script API General

1 messages · Page 36 of 1

chilly fractal
#

Yes

#

Only unstackable items tho

#

Like totems and stuff

jade grail
#

I see thanks

chilly fractal
#

You're welcome

terse pulsar
#

How i use the script debugger bots?

dim tusk
#

I'm asking the after events you used not the before event.

#

But what he gave should work

sharp elbow
#

Anyone know what the script Watchdog settings are by default on Realms? The value of the timeout specifically

#

Or perhaps more generally: If anyone knows what the default timeout setting might be on BDS.

sharp elbow
#

Seems to be 10 seconds (10000 ms) as of 1.21.43

fiery solar
dim tusk
#

Do I separately make a dynamic property for every location that I store in item or just one property

fiery solar
dim tusk
fiery solar
junior hill
#

and running said function

fervent topaz
meager cargo
#

Hello!
Does the playerInteractWithEntity event require the minecraft:interact component in the entity's behavior?

meager cargo
#

Thanks!

warm mason
#

if you use afterEvents then yes, but you can do it without components

torn leaf
#

can anyone help me? maybe this is oot, but i want to ask how to connect LoginSecurity / AuthMeReloaded plugin to MYSQL database. i have node for my server and i have website with DirectAdmin panel. I've tried connecting it properly, but the plugin is giving an error, and the log says "plugin cannot connect to database"

slow walrus
#

completely the wrong place to ask lmao

misty pivot
#

it says the knockback is not a function, which i don't understand why

target.applyKnockback(player.location.x, player.location.z, 8, 0.1)```
misty pivot
#

aight, gimme a sec

#
const Runner = system.runInterval(() => {
    const players = world.getPlayers();
    for (let player of players) {
        let target = player.dimension.getEntities({location: player.location, excludeNames: [ player.name ], maxDistance: 8, closest: 1});
        target.applyKnockback(player.location.x, player.location.z, 8, 0.1)
    }
})```
#

well technically this isn't the full code, but i shortened it down to be able to be sent here

jolly citrus
#

use applyImpulse i think or wtv its called

ruby haven
#

I made an entity that stomp attacks and I want to make the players get knocked away if they are within 10 radius from the entity should I use apply knockback or create explosion?

random flint
#

you're basically calling Array.applyKnockback, which of course, doesn't work

misty pivot
#

i tried adding [1] and even with mobs nearby, it said it wasn't a function, which is odd

random flint
#

Array[0]

misty pivot
#

ahhh

#

let me try

#

yep, adding a [0] worked, thanks

ruby haven
#

Is there a function that lets me check the specific family of an entity

ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityHitEntity.subscribe((event) => {
  if (event.damagingEntity.typeId == 'mz:smile') {
    const victim = event.hitEntity;
    const victimFamily = victim.getComponent('minecraft:type_family');
    if (victimFamily != 'demon') {
      victim.applyImpulse()
    }
  }
});

This is my code so far the goal is:
I made an entity that stomp attacks and I want to make the players get knocked away if they are within 10 radius from the entity.

I don't know if I did something wrong

ruby haven
distant gulch
ruby haven
keen laurel
#

Is it possible to import other files into the javascript that minecraft uses? I'm trying to import a json file that I custom made, but it's importing as ___.json.js, lol

keen laurel
spring axle
wary edge
spring axle
idle dagger
#

how to get all entities in world like

overworld.getAllEntities()

#

?

warm mason
#
function getAllEntities(options) {
  let all = []
  for (let id of ["overworld","nether","the_end"]) {
    all = all.concat(world.getDimension(id).getEntities(options))
  }
  return all
}
tight sparrow
#

Ia there a method for world.afterEvents.dataDrivenEntityTrigger.subscribe to make my mob apply impulse to target when my mob specific event is active

tight sparrow
#

Yeah I mean on a target of my mob when event is active

#

I try to do this target=entity.target
But not working?

wary edge
#

Any content log?

tight sparrow
wary edge
#

There you go.

tight sparrow
#

What so that's the problem?

#

The target after event class is beta?

jolly citrus
#

best way to detect the player that threw a projectile (when it has spawned, not when it has hit something)?

tight sparrow
wary edge
jolly citrus
tight sparrow
#

Um what is it?

tight sparrow
keen laurel
# spring axle hmm that would be nice wouldn't it

honestly just imported a json file anyways by just copying the whole thing and assigning it to a var lmao... a little cursed but it works so 🤷‍♂️

export const jsonObject = {
  "a": {
    "z": 1,
  },
  "b": {
    "z": 2,
  },
}
tight sparrow
jolly citrus
#
world.afterEvents.projectileHitEntity.subscribe((data) => {
    let projectile = data.projectile;
    let isAbility = projectile.getDynamicProperty("isAbility")??false

why do i get Failed to call function 'getDynamicProperty'

jolly citrus
#

this isnt the full file so

#

nothing else is relevant

valid ice
#

Is the projectile valid

warm mason
#

Entity is not valid

jolly citrus
#

how do i make it valid then ..

#

is there any other property i can check for it

warm mason
#

No way

jolly citrus
#

id perhaps?

#

ok yes id works

warm mason
#

You need to set the value of "destroyOnHit" (or whatever it is) in the projectile component to false

jolly citrus
#

but its okay

#

i found a new fix

warm mason
#

So that the projectile is not destroyed upon collision and destroy it manually after executing the code

jolly citrus
#

why do i get this humongous stack of slowdowns when i /reload

warm mason
#

Lol 5 milliseconds. I wouldn't call it a "slowdown". This means you are running complex code at the beginning of loading scripts

jolly citrus
#

because i do not run anything complex specifically at the beginning of loading scripts

#

more like i run complex systems all the time

#

my pack is filled with loops at intervals of 1-2 ticks

fiery solar
jolly citrus
fiery solar
jolly citrus
#

this one is probably the most resource intensive one

#

yes this one is every 20 ticks but it's complex

#

i need to check what claim a player is in

#
system.runInterval(() => {
    let dimension = world.getDimension("overworld")
    const enderPearls = dimension?.getEntities({
        location: { x: 0, y: 64, z: 0 },
        maxDistance: 88 * 1.5,
        type: "minecraft:ender_pearl"
    });
    
    const players = dimension?.getEntities({
        location: { x: 0, y: 64, z: 0 },
        maxDistance: 88 * 1.5,
        type: "minecraft:player"
    });
    
    const allEntities = [...(enderPearls || []), ...(players || [])];
    for (const plr of allEntities) {
        const check = BlockVolumeUtil.intersects({ x: plr.location.x, z: plr.location.z },
            {
                from: { x: spawnArea.xMin, z: spawnArea.zMin },
                to: { x: spawnArea.xMax, z: spawnArea.zMax }
            })

            if (check && (plr.typeId == "minecraft:player" ? (plr.getDynamicProperty("spawntag") ?? 0) > 0 : true == true)) {
            let spawnLocation = { x: 0, y: 66, z: -1 }; 
            let playerLocation = plr.location;
            
            let teleportVector = {
                x: spawnLocation.x - playerLocation.x,
                y: 0,
                z: spawnLocation.z - playerLocation.z
            };

            let length = Math.sqrt(teleportVector.x ** 2 + teleportVector.z ** 2);
            let normalizedTeleportVector = {
                x: teleportVector.x / length,
                y: teleportVector.y,
                z: teleportVector.z / length
            };

            let teleportDistance = -1;
            let teleportX = playerLocation.x + teleportDistance * normalizedTeleportVector.x;
            let teleportY = playerLocation.y; 
            let teleportZ = playerLocation.z + teleportDistance * normalizedTeleportVector.z;

            while (
                teleportX > spawnArea.xMin && teleportX < spawnArea.xMax &&
                teleportZ > spawnArea.zMin && teleportZ < spawnArea.zMax
            ) {
                teleportX += teleportDistance * normalizedTeleportVector.x;
                teleportZ += teleportDistance * normalizedTeleportVector.z;
            }

            system.run(() => {
                Frozen.Flag("Spawnglitch", plr);
                plr.teleport({ x: teleportX, y: teleportY, z: teleportZ });
                plr.runCommandAsync(`inputpermission set @s movement disabled`);
                system.runTimeout(() => {
                    plr.runCommandAsync(`inputpermission set @s movement enabled`);
                }, 20);
            });
        }
    }
}, 1);

anti-spawnglitch stuff

#

tp ender pearls to be land outside of spawn

#

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const playerClass = player.getDynamicProperty("class");
        if (playerClass === "bard") {
            const inventory = player.getComponent("inventory");
            const heldItem = inventory.container.getSlot(player.selectedSlotIndex);
            try {
            if (heldItem.typeId === "minecraft:iron_ingot") {
                const team = player.getDynamicProperty("team");

                for (const target of world.getDimension(player.dimension.id).getEntities({type: "minecraft:player",maxDistance: 16, location: player.location})) {
                    if (target.getDynamicProperty("team") === team) {
                        target.addEffect("resistance", 100, {
                            amplifier: 0
                        });
                    }
                }
            }
            } catch {}
        }
}
}, 1);

passive buffs for faction members (there's more to it than this but its all just repeated if statements

dim tusk
fiery solar
# jolly citrus i need to check what claim a player is in

Without being able to run the whole addon I can't tell you what is slowing you down the most, but you have a lot of loops inside loops and loops running in parallel. There are also more efficient ways to check land claims, especially if you have many of them.

simple arch
#

how can I have a simulated player equip a shield using getComponent("equippable"):setEquipment(offhand) i tried it but it didn't work.

wary edge
#

Is there a...onxpgranted perhaps? Theoretically...if I wanted to double the xp someone gets from doing an action(editing vanilla files is not possible due to smelting and other sources). I can't also just double the xp amount after each xp spawned.

jolly citrus
jolly citrus
#

try something like Entity.getComponent("equippable").setEquipment(EquipmentSlot.Offhand, new ItemStack("minecraft:shield", 1))

#

not sure if it’s actually like that im not on pc atm

distant tulip
wary edge
distant tulip
#

an event for it would be nice

jolly citrus
jolly citrus
distant tulip
jolly citrus
#

that’s not going to prevent it from detecting the manual addition as increase

distant tulip
#

manual addition?

jolly citrus
distant tulip
#

no that should prevent it

gusty bramble
#

Just a quick one. How would I go about something like this

./HC items 100 (would multiply the 100 by 8 giving an output of “800 gt”)
And
./HC gt 80 (would divide the 80 by 8 giving an output of “10 items”)

jolly citrus
#

if a player gains a xp, add +a more xp

jolly citrus
#

by detecting the xp change you mean detecting if the amount of experience a player has has been changed since last iteration?

jolly citrus
# distant tulip

exactly, so if u add any amount to xp it will trigger the interval to update oldxp again

#

oldxp -1
xp 0
add 2 to xp -> oldxp becomes 2
because xp changed, add the amount changed, xp becomes 4 -> okdxp becomes 4
because xp changed AGAIN (by 2), add the amount changed, xp becomes 6 -> oldxp becomes 6
and so on….

#

i think it wiuld get stuck in a loop like this

jolly citrus
distant tulip
#

that what i did

jolly citrus
#

so it would detect +10, then give another 10, and giving this 10 would also detect the amount to be changed again and get stuck in loop

jolly citrus
distant tulip
#

i did...

jolly citrus
#

where

#

oh

distant tulip
#

there is no loop

#

the value update
so the condition don't get triggered again

jolly citrus
#

oh wait right

#

i thought about implementing it a bit differently but now i inderstand why with ur logic it would work

distant tulip
#

yeah

jolly citrus
#

i was going to update oldxp before adding the doubled amount

distant tulip
#

you need to keep track of the amount added,, so yeah

keen laurel
#

is there any way to run a custom command using a command block... i thought chatSend would work for some reason lol

keen laurel
simple arch
#

lua getting through my head

simple arch
#

but hold up. What I found weird is that the simulatedplayer not showing the equipment which it is odd

#

oonly armor not shields, fireworks, etc...

ruby haven
#

What does apply impulse do?

ruby haven
quick shoal
#

Yes

ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityHitEntity.subscribe((event) => {
  if (event.damagingEntity.typeId == 'mz:stomp1') {
    const victim = event.hitEntity;
    const attacker = event.damagingEntity;

    if (victim && attacker) {

      const attackerPos = attacker.location;
      const victimPos = victim.location;

      const direction = {
        x: victimPos.x - attackerPos.x,
        y: 0,
        z: victimPos.z - attackerPos.z,
      };


      const magnitude = Math.sqrt(direction.x ** 2 + direction.z ** 2);
      const normalizedDirection = {
        x: direction.x / magnitude,
        y: 2,
        z: direction.z / magnitude,
      };

      const strength = 5;
      const knockback = {
        x: normalizedDirection.x * strength,
        y: normalizedDirection.y * strength,
        z: normalizedDirection.z * strength,
      };

      victim.applyImpulse(knockback);
    }
  }
});

Why is my knockback not working cause I made my boss summon another entity to do the attacking which is called mz:stomp1 and after 0.1 seconds that entity disappear is that the reason why my knockback system is not working?the entity disappears before the script runs

dim tusk
#

Is this valid in runJob? I genuinely don't know how to use this thing.

system.runJob(function* test() {
   yield
});```
quick shoal
slow walrus
#

so it's like

system.runJob(function*(){}())
#

you gotta call it to get the generator which the runJob uses

dim tusk
ruby haven
ruby haven
#

What is better to use apply knockback or apply impulse?

warm mason
ruby haven
#

A boss that stomps and knockbacks players away from it

warm mason
ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityHitEntity.subscribe((event) => {
  if (event.damagingEntity.typeId == 'mz:stomp1') {
    const victim = event.hitEntity;
    if (victim) {
      victim.applyKnockback(0, 0, 0, 10, 0);
    }
  }
});

I tried simplyfiying the code to just make the players upwards but it doesn't work can you see why?

warm mason
proud saddle
ruby haven
#

Oh I see I thought there is a y value hahaha thanks

proud saddle
warm mason
#

directionX, directionZ, horizontalStrength, verticalStrength

ruby haven
#

Ill try it now

proud saddle
proud saddle
ruby haven
ruby haven
proud saddle
ruby haven
#

It still doesn't work I tried it 😭

warm mason
#

code

ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityHitEntity.subscribe((event) => {
  if (event.damagingEntity.typeId == 'mz:stomp1') {
    const victim = event.hitEntity;
    if (victim) {
      victim.applyKnockback(1, 1, 10, 5);
    }
  }
});
ruby haven
thorn flicker
#

yes.

warm mason
ruby haven
warm mason
#

I tested this not long ago, and it doesn’t work very well here either.

thorn flicker
#

use entityHurt instead then.

ruby haven
thorn flicker
#

yes.

ruby haven
ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityHurt.subscribe(({ damageSource, hurtEntity }) => {
  if (damageSource.damagingEntity.typeId == 'mz:stomp1') {
    const victim = hurtEntity;
    if (victim) {
      victim.applyKnockback(1, 1, 10, 5);
    }
  }
});

It is working sometimes and sometimes not but for other entities there are times it gets delayed also for player

jade grail
#

in a entityhurt event how do i get how much damage is getting dealt

ruby haven
jade grail
jade grail
#

thanks

ruby haven
jade grail
#

i needed it so i could make a damage indicator

ruby haven
jade grail
ruby haven
ruby haven
#

I think the reason is it is checking entities that got hurt that was not cause by the damaging.entity?

warm mason
#

Right!

pallid portal
#

(begrudgingly new at scripting)

How does one set up an addon to begin using scripts?
(please do correct me if I am wrong)

  • add a script module in the manifest (of the behaviour pack only)
  • also add a decency for @minecraft server (for some reason...)
  • create a folder for scripts
  • make a main.js file (to 'subscribe' whatever scripts that needs to be subscribed in the game for your addon to work)

then make whatever script files you need... right?

( and unless need be, you do not have to enable Beta API to do scripting in general?)
(and those who may be more of a hobbyist or a dabbler, could they skip the npm setup?)

warm mason
pallid portal
# warm mason https://wiki.bedrock.dev/scripting/starting-scripts.html

that sadly does not answer the question.

That only spoonfeeds how to make a script file that spams "Hello World"

And not how said script file can be applied to anything in a addon.
Namely, subscribe a different script file for a block event (ex. a player interacts with "Block X" while holding an axe, and it is replaced with "Block Y". aka a stripped log event)

warm mason
pallid portal
#

The link provided sadly does not explian how to import js files. Not even contain a link to it.

It just lists a whole bunch of information. None of which is helpful to explaining how to solve the question.

warm mason
pallid portal
#

a russain doc... why?

Imma rather leave this channel.
Seems like it does not help at all with a person looking to learn.
And not be sent on goose chases while at it.

warm mason
warm mason
distant gulch
#

Then open those files and try changing things around

#

That helps with codon

pallid portal
#

codon?

I'll have a look, thank you.

distant tulip
#

that is the slowest way of learning

untold magnet
#

uh, just to make sure
const slot = inv?.getSlot('Mainhand'); is how i can get itemStack slot, right?

distant tulip
#

isn't getSlot argument an index

untold magnet
untold magnet
distant tulip
#

also it uses an index (number)

untold magnet
#

i had to use getSlot

distant tulip
#

why not

untold magnet
# distant tulip why not
world.afterEvents.playerInteractWithEntity.subscribe(({target: entity, itemStack, player}) => {
  const inv = player?.getComponent('minecraft:inventory')?.container;
  const slot = inv?.getSlot('Mainhand');
  if (entity?.typeId === 'my:entity') if (itemStack?.typeId === 'minecraft:raw_iron') slot?.setItem(new ItemStack('minecraft:raw_copper', 1));
})```just replacing the item after interacting with the entity, after interacting with it, it will replace the item that u are holding with another item.
warm mason
#
const slot = inv?.getSlot(player.selectedSlotIndex);
distant tulip
#

i mean why do you even need to get the slot
just set it directly

warm mason
#

?

warm mason
untold magnet
#

ah, i thought theres a better waybao_foxxo_blank

untold magnet
autumn seal
sterile epoch
#

how do I make something in a script run through a command?

#

i want it to when a person is standing in a certain area it runs a script. but in a command block so it doesn't cause lag with system run interval

gusty bramble
#

I’m not the best at this lol

chilly fractal
#

Elaborate, explain what you mean

#

What am I supposed to think of when you say "./HC gt 8"

warm mason
chilly fractal
sterile epoch
#

how do I use script events?

chilly fractal
#

/scriptevent namespace:id message

warm mason
#

A new version 1.18.0-beta has been released for documentation. There's nothing new there...

warm mason
sterile epoch
#

oh, it wasn't working because I misspelt it

chilly fractal
gusty bramble
# chilly fractal What am I supposed to think of when you say "./HC gt 8"

Ok well

My idea is to make a command to calculate the amount of time X amount of items will add up in a hopper counter. Or if you specify the amount of game ticks it will tell you how many items you need to got that time

So the math for that is this

Items > game ticks

[items] x8 = [game ticks]

game ticks > items

[game ticks] ÷8 = [items]

warm mason
#

Well, let's start with the fact that custom commands are impossible

gusty bramble
#

No it’s not? My addon literally uses ./ for everything

chilly fractal
#
//Command
player.sendMessage(`Game ticks: ${itemsCount*8}`);

// Another Command
player.sendMessage(`Items: ${gameTicks/8}`);```
gusty bramble
#

Thx

chilly fractal
#

You're welcome

warm mason
#

You can't trust anyone, not even documentation

wooden zealot
#

Is it possible to spawn a mob tamed to the player

warm mason
warm mason
unique dragon
wooden zealot
#
import { world, system } from '@minecraft/server';
import { tameableMobs } from 'api/utils/lists'; // Corrected import path

function spawnMob(player, entityName, isMountable) {
  const location = player.location;
  const dimension = player.dimension; // Get the player's dimension
  const entity = dimension.spawnEntity(entityName, location); // Spawn the specific mob

  // Tame the entity to the player
  const tameableComponent = entity.getComponent("tameable");
  if (tameableComponent) {
    tameableComponent.tame(player);
  }

  const type = isMountable ? "Mount" : "Pet";
  player.runCommandAsync(`tellraw @a {"rawtext":[{"text":"Your ${entityName.replace("lycanite:", "")} has been bound, you will now find it in your ${type} Manager."}]}`);
  
  return entity; // Return the entity
}

world.afterEvents.itemUse.subscribe(event => {
  const player = event.source;
  const item = event.itemStack;
  const itemId = item.typeId;

  const mobs = tameableMobs[itemId];
  if (!mobs) return;

  const mob = mobs[Math.floor(Math.random() * mobs.length)];
  spawnMob(player, mob.name, mob.is_mountable);

  // Remove the soulstone from the player's inventory
  player.runCommandAsync(`clear @s ${itemId} 1`);
});
 
#

i tried it but the mob dosent spawned tamed

warm mason
#

Well, then most likely it cannot be tamed, because getComponent() gives undefined, because the mob does not have a component

wooden zealot
#

i hit an entity and it didnt start attacking it

#

however when i hit it it dosent attack me

#

2 secs

warm mason
wooden zealot
#

wait nvm its attacking me

#

i tried using entity events aswell but it didnt work

#

wait now its tamed

#

gimme a sec

gaunt salmonBOT
# wooden zealot ```js import { world, system } from '@minecraft/server'; import { tameableMobs }...

Debug result for [code](#1067535608660107284 message)

Compiler Result

Compiler found 1 errors:

<REPL0>.js:2:30 - error TS2792: Cannot find module 'api/utils/lists'. Did you mean to set the 'moduleResolution' option to 'nodenext', or to add aliases to the 'paths' option?

2 import { tameableMobs } from 'api/utils/lists'; // Corrected import path
                               ~~~~~~~~~~~~~~~~~

Lint Result

ESLint results:

<REPL0>.js

1:17 error 'system' is defined but never used @typescript-eslint/no-unused-vars

untold magnet
#

how can i force it to work on the entity only when the chunks are loaded?, using blocks right?

#

const block = entity?.dimension.getBlock(entity?.location)
if (count % 20 === 0 && entity?.isValid() && block?.isValid() === true) { ,,, }?

wooden zealot
#

alr its working ty

untold magnet
alpine nebula
#

How do I detect if block has been destroyed by explosion?

tawny reef
#

how can i create a modded scoreboard

jolly citrus
#
world.beforeEvents.playerLeave.subscribe(({ player }) => {
    let inv = player.getComponent("inventory").container;
    let invMap = []
    let invSize = inv.size
    for (let i = 0; i < invSize; i++) {
        invMap.push(inv.getItem(i))
    }
    let effects = player.getEffects();
    let armor = player.getComponent("equippable").getEquipment;
    let dimension = player.dimension;
    let loc = player.location;
    let name = player.name;

    if ((player.getDynamicProperty("spawntag") ?? 0) > 0) {
        system.run(() => {
            let entity = dimension.spawnEntity("tr:combat", loc);
            let container = entity.getComponent("inventory").container
            invMap.forEach((value,index)=>{
                if (value instanceof ItemStack) {
                    container.addItem(value);
                }
            })
            let HeadArmor = armor(EquipmentSlot.Head);
            let ChestArmor = armor(EquipmentSlot.Chest);
            let LegsArmor = armor(EquipmentSlot.Legs);
            let FeetArmor = armor(EquipmentSlot.Feet);
            if (HeadArmor) container.addItem(armor(EquipmentSlot.Head));
            if (ChestArmor) container.addItem(armor(EquipmentSlot.Chest));
            if (LegsArmor) container.addItem(armor(EquipmentSlot.Legs));
            if (FeetArmor) container.addItem(armor(EquipmentSlot.Feet));

            entity.nameTag = `§c${name} §7[Combat-Logger]`;
        });
    }
});

what does the error mean

chilly fractal
jolly citrus
#

why do i have to run /reload every time i start up my world

#

if i don't the bp doesn't take efffect

meager pulsar
#

can functions run with runJob returns values somehow?

fiery solar
distant gulch
#

Anyone down to work with me on learning to use Script API to the fullest extent?

fiery solar
alpine nebula
#

How can I disable block from dropping loot if it was blown up by explosion?

#

Like TNT do

distant gulch
#

What's the difference between system.run, system.timeout, system.waitTicks, etc?

distant tulip
jolly citrus
#

how do i set a player's view direction

distant tulip
#

tp

fiery solar
jolly citrus
jolly citrus
alpine nebula
distant tulip
#

beforeevent

distant tulip
distant gulch
meager pulsar
jolly citrus
#

do i need to use commands

meager pulsar
#

Their location

#

Like detect id there are logs in a cube around a certain location

#

Return true or false depending on that

jolly citrus
distant gulch
#

Alr, when does that come in useful?

jolly citrus
#

and there's some things that will take a lot of time to process and sometimes you wanna handle those asynchronously

#

to prevent other things from slowing down

#

in other programs api requests are commonly asynchronous, because otherwise the rest of ur code would be blocked from running further until a response is given

meager pulsar
#

How many jobs can I have running at a time?

unique acorn
#

difference between runCommand and runCommandAsync?

jolly citrus
#
hit.setRotation({x: -180, y: hit.getRotation().y})

why does this not do anything

fiery solar
jolly citrus
#

when i apply the rotation through .teleport it works perfectly fine

#

but not this way

distant gulch
#

Thanks @jolly citrus

jolly citrus
distant gulch
#

One last question for everyone for at least 3 minutes

#

What's the diff between applyImpulse and applyKnockback

#

I've never used applyImpulse

#

and am not even sure how to

#

Because I use applyKnockback to create dashing

jolly citrus
distant gulch
#

Ah

jolly citrus
#

idk about the values though

distant gulch
#

Alright

jolly citrus
#

it works a bit differently

distant gulch
#

Works for me

#

Thanks

#

Can I use runInterval(() => {
blah blah blah
}, 0);

For a constant run?

fiery solar
distant gulch
#

alright

#

thanks

slim hamlet
#

anyone has an idea why the getEntitiesFromRay doesnt work properly in this case?

export default function ({block}) {
    const state = block.permutation.getState('minecraft:cardinal_direction')
    let direction = {}
    switch (state) {
        case "north":
            direction = { x: 0, y: 0, z: -1 };
            break;        
        case "south":
            direction = { x: 0, y: 0, z: 1 };
            break;        
        case "west":
            direction = { x: -1, y: 0, z: 0 };
            break;
        case "east":
            direction = { x: 1, y: 0, z: 0 };
            break;
        default:
            break;
    }
    const entities = block.dimension.getEntitiesFromRay(block.location, direction,{maxDistance:10})
    console.warn(entities.length);
    for (const entity of entities) console.warn(entity.distance);
}```
neat hazel
#

Is it possible to detect if the player is walking forward or backward?

remote oyster
neat hazel
dim tusk
# neat hazel How can I do this? I'm a beginner in the subject
system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        let { forward, right, backward, left } = direction(player);
        let text = ''
        if (forward > 0) {
           text = 'forward';
        } else if (left > 0) {
           text = 'left';
        } else if (right > 0) {
           text = 'right';
        } else if (backward > 0) {
           text = 'backward';
        } else return;
        player.sendMessage(text);
    }
})

function direction(player) {
    let velocity = player.getVelocity();
    let viewDirection = player.getViewDirection();

    let viewDirMagnitude = Math.sqrt(viewDirection.x ** 2 + viewDirection.z ** 2);
    let normalizedViewDir = { x: viewDirection.x / viewDirMagnitude, z: viewDirection.z / viewDirMagnitude };

    let forwardVelocity = (velocity.x * normalizedViewDir.x + velocity.z * normalizedViewDir.z);
    let rightVelocity = (velocity.z * normalizedViewDir.x - velocity.x * normalizedViewDir.z);

    let backwardVelocity = -forwardVelocity; 
    let leftVelocity = -rightVelocity; 
    
    forwardVelocity = Math.round(forwardVelocity * 100) / 100;
    rightVelocity = Math.round(rightVelocity * 100) / 100;
    backwardVelocity = Math.round(backwardVelocity * 100) / 100;
    leftVelocity = Math.round(leftVelocity * 100) / 100;
    return {
        forward: forwardVelocity,
        right: rightVelocity,
        backward: backwardVelocity,
        left: leftVelocity
    };
}```

This works very fine to me.
dim tusk
# neat hazel Thnk u

Btw soon this would be useless cause there's a more accurate way but it's currently in preview

#

It can detect wasd up and down button even if we disabled it's movement

neat hazel
distant gulch
#

Can you make double jumps with script api?

#

Well, specifically air-jumps (as many as I want to add)

#

Less about that now

tawny jungle
#

is there any way i can append the contents of an array to the bottom of another array?

distant gulch
#

More about how to detect when an elytra is being used

slow walrus
#

you mean back right?

distant gulch
tawny jungle
#

yes

distant gulch
#

Where it pushes certain contents to the front of an arrow

#

array*

slow walrus
#
const array1 = [1,2,3]
const array2 = [4,5,6]

array1.push(...array2) // [1,2,3,4,5,6]
tawny jungle
#

thats what is so weird

#

this is what i used:

var vanillaEquippableIds = [
...
]
export const mBEquippableIds = [
    vanillaEquippableIds.push(mBTypeIds)
]```
slow walrus
#

tf

#

why do you have a random spread in an empty array?

tawny jungle
#

wdym

slow walrus
#

and you need to spread the mbTypeIds (assuming it's also an array)

#

oh wait what

#

wtf

#

what are you even doing there lmao

tawny jungle
#

the "..." was just so that i didn't have to copy all the contents of the array

slow walrus
#

ah right

#

well

#

first, you're not even correctly pusing mBTypeIds onto vanillaEquibbableIds. right now you're pushin the entire array onto it, instead of it's items

#

second, that will put it int vanillaEquippableIds, not your new array

tawny jungle
#

i see

slow walrus
#

use this

import { mBTypeIds } from "./mBTypeIds.js";
var vanillaEquippableIds = [
// ...
]
export const mBEquippableIds = [
    ...vanillaEquippableIds,
    ...mBTypeIds
]
#

that will spread both arrays into the new one

tawny jungle
#

ah, i didn't realized i needed to spread it

#

thanks

#

that worked great bao_foxxo_smile

distant gulch
#

Guys, why is the server-net module* only for BDS?

quick shoal
distant gulch
#

Ohh, i completely forgot you

#

wait

warm mason
#

If you don't have internet, you won't be able to use it.

quick shoal
#

Mvm

warm mason
distant gulch
#

hmmm okay

misty pivot
#

how would i applyImpulse an entity towards the player?

warm mason
misty pivot
#

how about applyImpulse? that's applyKnockack, which doesn't work for items as i tried

warm mason
#

Do you need an item lying on the ground to be attracted to the player?

misty pivot
#
entity.applyImpulse(-player.getViewDirection())```
warm mason
#

😌

#

Well. You need to make a determination of direction and distance

misty pivot
warm mason
#

Apparently I should still give people this function.....

misty pivot
#

the applyknockback earlier?

warm mason
# misty pivot the applyknockback earlier?
function getDirection(vector1, vector2) {
  let distance = Math.sqrt((vector1.x-vector2.x)**2 + (vector1.y-vector2.y)**2 + (vector1.z-vector2.z)**2) || 0.001
  let direction = {
    x: (vector2.x-vector1.x)/distance,
    y: (vector2.y-vector1.y)/distance,
    z: (vector2.z-vector1.z)/distance
  }
  return direction
}
misty pivot
#

ah i see

#

thanks

dim tusk
quick shoal
dense sun
#

are there any functions i can use to find out the performance ?

dense sun
#

i used this it prints 0

slow walrus
#

currDate - lastDate is in milliseconds so you need to / 1000 to convert to seconds

distant tulip
#

0/1000 is still 0
also no one test performance in seconds
unless you are a python user

slow walrus
slow walrus
dense sun
#

0 i made it 1 so it got fixed

slow walrus
#

:l

last latch
#

is it somehow possible to detect if the player after joining is valid to hear sounds?

#

i want to play a sound after joining but i need to use a timeout

#

because sounds are played after rendering the world. The player is valid after joining

untold magnet
#

uh

#

if (eEntity?.typeId?.startsWith('exe:')) return; shouldn't work on entities that starts with 'exe:' right?

#

it works on them, somehow

last latch
#

or the eEntity itself

dim tusk
last latch
#

i thought of a variable or a method to detect that

dim tusk
untold magnet
# last latch is the typeId defined?
system.runInterval(() => {
  count++;
  let slots = 0;
  const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
    for (const entity of world.getDimension(dim).getEntities()) {
      if (entity?.typeId === 'my:entity' && entity?.isValid()) {
        const dim = entity?.dimension;
        const loc = entity?.location;
        const entities = dim?.getEntities({location: loc, maxDistance: 18});
        entities?.forEach((eEntity => {
          if (eEntity?.typeId.startsWith('exe:')) return;
        }));
      };
    };
  });
});```this is all
last latch
#

i tried catching and tryTeleport

#

but both execute without errors

#

so i guess it isnt possible

dim tusk
#
if (eEntity.typeId.startsWith('exe:')) {
   console.error('bruh');
}```
untold magnet
#

cuz that return thing isn't working, somehow

warm mason
untold magnet
warm mason
#

Do console.warn(eEntity.typeId)

last latch
#

why did you send me a script for checking if the player joined

warm mason
#

Well, you need to play the sound when you join

last latch
#

i asked for a method or variable to check if the player is able to hear sounds

last latch
warm mason
last latch
#

players dont hear anything when they join

#

after some time they start to hear

#

or render the game

warm mason
#

playerSpawn - event when a player spawns. He can do anything

#

Well, you can set the delay for a second just in case

last latch
#

sometime the device can lag and take more than a second

last latch
#
AfterEvents.PlayerSpawned(({ player, playerJoined }) => {
    if (!playerJoined) return;

    player.hud.setTitle(
        titleGreeting,
        {
            subtitle: subtitleGreeting,
            fadeInDuration: 10,
            fadeOutDuration: 10,
            stayDuration: 20 * 10
        }
    );

    player.playSound("random.levelup");
});
#

this is what i use

warm mason
last latch
#

the sound is not being heard

untold magnet
last latch
#

a property

untold magnet
#

but return is not

subtle cove
#

it's initialSpawn

last latch
#

yea

#

i use RockWrap

warm mason
subtle cove
#

Ok

last latch
#

true

subtle cove
#

Might have to extend the durations

last latch
#

do you mean the title?

#

or the delay between playing the sound and jjoining

subtle cove
#

Have u tried extending it?

last latch
#

what do you mean by extending it?

subtle cove
#

Like 30 40

last latch
#

the delay? as in system.runTimeout?

subtle cove
#

Fade delay

last latch
#

the title is not the problem

#

the playSound is the problem

subtle cove
#

Ok, u can try runTimeout on playSound

last latch
#

i did

#

and it works

#

but it is risky

#

depends on how much time it takes the device to render the game

#

i guess will need to stick with timeouts

untold magnet
#
system.runInterval(() => {
  count++;
  const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
    for (const entity of world.getDimension(dim).getEntities()) {
      if (entity?.typeId === 'my:entity' && entity?.isValid()) {
        const dim = entity?.dimension;
        const loc = entity?.location;
        const entities = dim?.getEntities({location: loc, maxDistance: 18});
        entities?.forEach((eEntity => {
          if (eEntity?.typeId.startsWith('exe:')) console.warn('a'); ← is warning
          if (eEntity?.typeId.startsWith('exe:')) return; ← isn't returning
          eEntity?.addEffect('nausea', TicksPerSecond * 10, {amplifier: 0, showParticles: false});
        }));
      };
    };
  });
});```*why?*
last latch
#

how do you know it isnt returning?

untold magnet
#

lemme edit it really quick

untold magnet
dim tusk
#

The warning shows up right?

untold magnet
last latch
#

you first check if the entity is my:entity

untold magnet
last latch
#

is that correct?

untold magnet
distant gulch
#

What's wrong here?

const playerGrab = world.getPlayers()
playerGrab.forEach((e) => {
    if (e.isGliding) {
        if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 8) {
            e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
            world.scoreboard.getObjective("doubleJump").addScore(e.source, 1);
            e.runCommand("clear @s elytra");
            system.runTimeout(() => {
                e.runCommand("replaceitem entity @s slot.armor.chest elytra");
            }, 2)
        }
    }
})
dim tusk
#

It checks the entities, if the entity exists another array of entities but certain distance but it checks if entities have id starts with exe:

#

So I don't think he did something wrong here. He also said that the warning shows up it just doesn't return

untold magnet
distant gulch
#

Thanks!

#

Is that the only thing wrong?

dim tusk
untold magnet
#

I'll try it

dim tusk
#
if (!eEntity.typeId.startsWith('exe')) {
}```
untold magnet
#

startsWith is broken

#

I'll use other method

#

later

subtle cove
#

Remove the code if it's still doing it

#

Ight be a different file

dim tusk
untold magnet
#

I'll try the other method later.

#

it will work, 100%

dim tusk
# untold magnet not working either
system.runInterval(() => {
  count++;
  const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
    for (const entity of world.getDimension(dim).getEntities()) {
      if (entity?.typeId === 'my:entity' && entity?.isValid()) {
        const dim = entity?.dimension;
        const loc = entity?.location;
        const entities = dim?.getEntities({ location: loc, maxDistance: 18 });
        entities?.forEach(eEntity => {
          if (eEntity?.typeId.startsWith('exe:')) {
            console.warn('a');
            return;
          }
          eEntity?.addEffect('nausea', TicksPerSecond * 10, { amplifier: 0, showParticles: false });
        });
      }
    }
  });
});
#

I just realized, the return is almost equivalent to continue in your case

#
entities?.filter(eEntity => !eEntity?.typeId.startsWith('exe:'))
  .forEach(eEntity => {
    eEntity?.addEffect('nausea', TicksPerSecond * 10, { amplifier: 0, showParticles: false });
  });
last latch
#

almost?

#

isnt that the same?

dim tusk
last latch
#

yeah

#

i would say in that case it is 1:1 like ccontinue

dim tusk
#

And certainly they're not the same

last latch
#

true

dim tusk
# last latch true

Continue skips the rest of the code in the current iteration of a loop and moves to the next iteration while return exits it early and immediately

last latch
#

yeah

#

i said that return in that case is like continue

#

i never said that return is continue

dim tusk
last latch
#

i meant

#

that not almost

#

but 1:1

#

like it working 1:1 in his case

#

my bad

#

sorry

dim tusk
#

I gave an explanation to that, before you said it's almost a 1:1

last latch
#

yea

#

my bad

#

i will try explaining/asking more clearly next time

dim tusk
#

Nah it's good, everything's good

untold magnet
distant gulch
#

I'm having trouble here

#

I want something to be active for every player

#

but this isn't doing that

#
const playerGrab = world.getPlayers()
playerGrab.forEach((e) => {
#

The inputs I have in the forEach function aren't being run constantly

#

or maybe just aren't beiing run on the players in the world

fiery solar
alpine nebula
#

What am I doing wrong? I want to read some permutations from block before it explodes but I'm getting this error:

[Scripting][inform]-Detected bomb: {"x":3,"y":69,"z":-422}

[Scripting][inform]-test: undefined

[Scripting][error]-TypeError: Native variant type conversion failed. Function argument [1] expected type: number | boolean | string    at <anonymous> (atomic_bomb/atomic_bomb_explosion.js:110)
#

Here is my code that goes under world.beforeEvents.explosion.subscribe(explodeEvent => {

// Trigger an explosion if the bomb block has been blown up
    const impactedBombBlocks = explodeEvent.getImpactedBlocks().filter(b => b.typeId === blockID);
    system.run(() => {
        if (impactedBombBlocks) {
            for (let i = 0; i <= impactedBombBlocks.length; i++) {
                // const block = explodeEvent.dimension.getBlock(impactedBombBlocks[i]);
                const block = impactedBombBlocks[i];
                // const { x, y, z } = block.location;
                const { x, y, z } = block.bottomCenter();
                console.log(`Detected bomb: ${JSON.stringify(block)}`);

                const blockCardinalDirection = block.permutation.getState('minecraft:cardinal_direction');
                console.log(`test: ${blockCardinalDirection}`);

                const entityRotationPermutation = 'nubs:rotation';
                // create rotation table for entities
                const cardinalToRotationTable = {
                    'north': 0,
                    'south': 2,
                    'west': 3,
                    'east': 1
                };

                // remove block
                block.setPermutation(BlockPermutation.resolve("minecraft:air"));
                // kill dropped loot
                const drop = explodeEvent.dimension.getEntities({ type: 'item', closest: 1 })[0];
                drop.kill();
                // spawn entity
                explodeEvent.dimension.spawnEntity(`${entityID}`, { x: x, y: y, z: z });
                // find summoned entity
                const entity = explodeEvent.dimension.getEntities({ type: entityID, closest: 1 })[0];
                // set entity properties for correct rotation
                entity.setProperty(entityRotationPermutation, cardinalToRotationTable[blockCardinalDirection]);
            }
        }
    })
warm mason
#

block.permutation.getState('cardinal_direction');

subtle cove
alpine nebula
alpine nebula
#

It causes errors because blockCardinalDirection is undefined

wary edge
alpine nebula
wary edge
#

Other blocks might be impacted.

alpine nebula
#

Doesn't const impactedBombBlocks = explodeEvent.getImpactedBlocks().filter(b => b.typeId === blockID) filter it?
(const blockID = 'nubs:atomic_bomb_block';)

wary edge
subtle cove
#

what's its all states look like in script?

alpine nebula
#

¯_(ツ)_/¯

wary edge
subtle cove
#

uhm, that block instance turns air inside the system.run
thats why its typeId is air and has no cardinal_direction

subtle cove
# alpine nebula ¯\_(ツ)_/¯
world.beforeEvents.explosion.subscribe(explodeEvent => {
    // Trigger an explosion if the bomb block has been blown up
    const impactedBombBlocks = explodeEvent.getImpactedBlocks().reduce((array, block) => {
        if (block.typeId !== blockID) return array;
        return array.concat({ block, permutation: block.permutation })
    }, []);
    //if length is !0 
    if (!impactedBombBlocks.length) return;

    const dim = explodeEvent.dimension;

    system.run(() => {
        const entityRotationPermutation = 'nubs:rotation';
        const cardinalToRotationTable = {
            'north': 0,
            'south': 2,
            'west': 3,
            'east': 1
        };
        const query = { type: 'item', closest: 1 };

        for (let i = impactedBombBlocks.length; i--;) {
            // const block = explodeEvent.dimension.getBlock(impactedBombBlocks[i]);
            const { block, permutation } = impactedBombBlocks[i];
            // const { x, y, z } = block.location;
            const { x, y, z } = block.bottomCenter();
            console.log(`Detected bomb: ${JSON.stringify(block)}`);

            console.log(`test: ${JSON.stringify(permutation.getAllStates())}`);

            // create rotation table for entities
            const cardinalToRotation = cardinalToRotationTable[permutation.getState('minecraft:cardinal_direction')];

            // remove block
            block.setType("air");
            query.location = { x, y, z };
            // kill dropped loot
            const drop = dim.getEntities(query)[0];
            drop?.kill();
            // spawn entity
            const entity = dim.spawnEntity(entityID, { x, y, z });
            // set entity properties for correct rotation
            entity.setProperty(entityRotationPermutation, cardinalToRotation);
        }
    })
});
```idk if the `drop.kill()` would work properly tho
sharp elbow
#

If not, I expect that drop.remove would

alpine nebula
jolly citrus
distant gulch
distant gulch
#

And can I put 0 as the interval, or does it need to be 1

distant gulch
fiery solar
distant gulch
#

Thanks

#

I'm making a combat system

#

I've made two moves for a sword, double jumps, dashes, teleports

#

Very fun

untold magnet
#

uh, is the world.getDimension({ matchAll('all 3 dimensions') }) a thing?

#

i mean is it a better way to get all 3 dimensions at once?

#

cuz i wanna get all 3 dimensions without putting it inside of a loop

jolly citrus
#

is playerInteractWithBlock the only event called when a player right clicks a chest

#

or bed etc

distant gulch
#

This isn't working:

system.runInterval(() => {
    playerGrab.forEach((e) => {
        if (e.isGliding) {
            if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
                e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
                world.scoreboard.getObjective("doubleJump").addScore(e, 1);
                e.runCommand("clear @s elytra");
                system.runTimeout(() => {
                    e.runCommand("replaceitem entity @s slot.armor.chest elytra");
                }, 2)
            }
        }
    })
}, 0)
#

Is this something wrong with this code?

#

I'm gliding, and nothing is happening

warm mason
#
system.runInterval(() => {
    world.getAllPlayers().forEach((e) => {
        if (e.isGliding) {
            if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
                e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
                world.scoreboard.getObjective("doubleJump").addScore(e, 1);
                e.runCommand("clear @s elytra");
                system.runTimeout(() => {
                    e.runCommand("replaceitem entity @s slot.armor.chest elytra");
                }, 2)
            }
        }
    })
})```
distant gulch
#

What did you change?

distant gulch
#

Oh you changedfor getAllPlayers

warm mason
distant gulch
#

I had it as getPlayers

#

Oh yes, I never added that to showcase

#

You also removed the 0 in the system.runInterval

#

does that also make it every tick>

#

?*

warm mason
distant gulch
#

Alright

#

Thanks, I'll test it

untold magnet
# warm mason yes

is there any better way to const dimension = ['overworld', 'nether', 'the_end'].map(dim => {
for (const entity of world.getDimension(dim).getEntities()) { get all 3 dimensions without putting it inside of a loop like that?

distant gulch
#

Hmm, this is frustrating, it's still not working

#
const playerGrab = world.getAllPlayers();
system.runInterval(() => {
    playerGrab.forEach((e) => {
        if (e.isGliding) {
            if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
                e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
                world.scoreboard.getObjective("doubleJump").addScore(e, 1);
                e.runCommand("clear @s elytra");
                system.runTimeout(() => {
                    e.runCommand("replaceitem entity @s slot.armor.chest elytra");
                }, 2)
            }
        }
    })
    playerGrab.forEach((e) => {
        if (e.isOnGround) {
            world.scoreboard.getObjective("doubleJump").setScore(e, 8);
        }
    })
    playerGrab.forEach((e) => {
        if (e.isOnGround) {
            if (e.isSneaking) {
                if (e.isJumping) {
                    e.applyKnockback(e.getVelocity().x, e.getVelocity().z, 7, -0.4);
                }
            }
        }
    })
})
distant gulch
#

This is what I currently have @warm mason

distant gulch
#

And all my other code outside of this segment works

#

But this isn't running anything

warm mason
#
system.runInterval(() => {
    world.getAllPlayers().forEach((e) => {
        if (e.isGliding) {
            if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
                e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
                world.scoreboard.getObjective("doubleJump").addScore(e, 1);
                e.runCommand("clear @s elytra");
                system.runTimeout(() => {
                    e.runCommand("replaceitem entity @s slot.armor.chest elytra");
                }, 2)
            }
        }
    })
    playerGrab.forEach((e) => {
        if (e.isOnGround) {
            world.scoreboard.getObjective("doubleJump").setScore(e, 8);
        }
    })
    playerGrab.forEach((e) => {
        if (e.isOnGround) {
            if (e.isSneaking) {
                if (e.isJumping) {
                    e.applyKnockback(e.getVelocity().x, e.getVelocity().z, 7, -0.4);
                }
            }
        }
    })
})```
jolly citrus
#

does container.addItem() return undefined if the item wasn't able to be added for reasons such as the container being full?

warm mason
#

Most likely yes

jolly citrus
#

i feel like it would return it back if it couldn't be added

#

i'm going to try that first

#

weird that the documentation doesn't include which one is returned when

warm mason
#

I think it will increase the itemStack that ended up (for example 3 stones + 3 stones = 6 stones)

fiery solar
distant gulch
#

When you press space in air, it glides

#

I want it to boost you up with knockback

#

remove your elytra

#

and give it back

#

I have the scoreboard so they can only airjump 8 times

fiery solar
# distant gulch remove your elytra

Does applyKnockback not work when gliding? Either way I think the issue here is that you're only doing the knock back if the player is sneaking, jumping and on the ground. Don't you want !e.isOnGround?

distant gulch
#
world.getAllPlayers().forEach((e) => {
        world.sendMessage("loop works");
        if (e.isGliding) {
            if (world.scoreboard.getObjective("doubleJump").getScore(e) <= 7) {
                e.applyKnockback(e.getViewDirection().x, e.getViewDirection().z, 0.3, 3.5);
                world.scoreboard.getObjective("doubleJump").addScore(e, 1);
                e.runCommand("clear @s elytra");
                system.runTimeout(() => {
                    e.runCommand("replaceitem entity @s slot.armor.chest elytra");
                }, 2)
            }
        }
    })
#

This is the double jump

distant gulch
#

Can someone help me with this error: "[SCP-Project Orgon BP - 1.0.0] - [main.js] ran with error: [SyntaxError: Invalid Redefinition of lexical identifier at clicks/lever.js:37]

#

No

autumn seal
#

I see

#

youre redefining a constant though?

distant gulch
#

I thought case was their own pieces of code so I didnt know if they could be accessed outside of each case

autumn seal
#

is it possible switch cases arent block independent unless you wrap them with {}

#

have you tried

        //logic
    }
    case 'south': {
       //logic
    }
}```
distant gulch
#

no

warm mason
#

Why use switch/case if there is if/else

distant gulch
warm mason
#

Moreover, your code is quite monotonous, it is easier for you to substitute variables than to write a separate piece for each case

distant gulch
#

Oh it is because i redeclared it

distant tulip
#

in js inside a switch statement all case blocks share the same scope unless explicitly wrapped in their own block (using {})
so that is invalid redefinition of the variable
keep in mind a scope can access the parent scope variables but not the other way around

distant gulch
autumn seal
#

wrap them individually

#

both cases

distant gulch
#

Ive only just started script API a week ago so I'm very new

distant tulip
#

yeah
i can't speak in general

warm mason
autumn seal
#

I thought that was the case but I don't really use switch cases often

distant gulch
distant tulip
#

you did the same thing
i said they share the same scope

warm mason
#

Use if/else - no no no
suffer with switch/case - yes, that’s our opinion.

distant gulch
#

Idk what coding scope is

autumn seal
#

can you send the code

#

of your example

distant gulch
distant tulip
warm mason
autumn seal
#

dublicate

#

I like how that sounds

distant gulch
#

Ahh

#

I understand it now

warm mason
#

and one field for all cases

#

Very convenient

distant gulch
#

Here script

meager pulsar
#

what des this do?

                    dimension.runCommand(`setblock ${location.x} ${location.y} ${location.z} air destroy`);
                });```
distant tulip
#

my brain just auto type
const h = help=="hi"?"2":help=="hello"?"":undefined

meager pulsar
#

idk what system,run is for

valid ice
distant tulip
#

it is kinda "useless" outside before events

valid ice
#

It's main use is in before events, yes

kind tendon
#

100,000 messages!

valid ice
autumn seal
#

who was the message to get the channel over 100k

kind tendon
#

mine :)

distant gulch
autumn seal
#

unless someone deletes a message >:)

kind tendon
#

can you not say stuff like that please @distant gulch

distant gulch
#

Why

warm mason
kind tendon
kind tendon
distant gulch
valid ice
#

If I had a nickel for every time someone said 100k messages, I'd be able to buy a house

distant tulip
#

we will get 100000 message that claim the 100000 message someday

autumn seal
#

fellas we just hit 100k messages

valid ice
warm mason
#

By the way, this is the most popular development channel

autumn seal
#

I think it'd be different if the name was something common like "john"

distant tulip
valid ice
#

The kid named "Script API General"

warm mason
warm mason
autumn seal
warm mason
autumn seal
#

how many messages could threads realistically take up

distant tulip
#

yeah
can't search in posts yet

wary edge
#

Willing to bet 50% of the messages arent scriptapi related.

distant tulip
#

most of the stuff here are general js

valid ice
#

We have between 10! & 11! messages in this channel yessir

warm mason
#

All messages from the main development posts < messages from the main post script API

autumn seal
warm mason
autumn seal
#

I was joking because 10 factorial is 3628800

valid ice
#

10.06475! yippee!

#

wait I am dum 😛

valid ice
autumn seal
#

I think this channel would show if it was over 200k messages

#

or does it cut off at 100k+

valid ice
#

It cuts off

autumn seal
#

would it ever display 200k+?

#

ohhh okay

gaunt salmonBOT
distant gulch
#

The Lever

#

The Third Block

untold magnet
#

hmmm

distant gulch
#

Oh wait nvm my dumby self just set both of them to the same state 😭

#

But also swapped the way the toggle worked hence why it didn't place redstone on the first press

keen laurel
#

How do you get the name of a chest when it has already been placed?

keen laurel
#

unlucky lol

autumn seal
#

?

pallid portal
#

If a script has a custom component for a block using the interaction function.

Is there a way that allows the player to place a block while looking at this block instead of attempting the interaction which would fail anyways?

pallid portal
pallid portal
pallid portal
warm mason
#

no..

#

you need to use world.baforeEvents.playerIntercactWithBlock

pallid portal
# pallid portal

this is the version with the "playerInteractWithBlock" in place of "onPlayerInteract"

pallid portal
warm mason
#
world.beforeEvents.playerInteractWithBlock.subscribe(data => {
  // Code
}) 
#

If the interaction is successful, then enter data.cancel = true

warm mason
warm mason
pallid portal
#

"[Scripting][error]- TypeError: cannot read property 'registerCustomComponent' of undefined ..."

By replacing "worldInitialize" with "playerInteractWithBlock" as you demonstrated.

world.beforeEvents.worldInitialize.subscribe(eventData => { ...
world.beforeEvents.playerInteractWithBlock.subscribe(data => {...

warm mason
pallid portal
#

And the eventData vs data difference also causes errors.

warm mason
#

This is not a custom component

pallid portal
#

The thing is I intended to use it as a custom component for the block.

So I can assign this script to selected blocks. Not all blocks....

warm mason
#

This is the event that is called when the player clicks on a block

warm mason
#

by giving I will give you an example

#
world.beforeEvents.playerInteractWithBlock.subscribe(data => {
  let block = data.block
  let player = data.player
  let item = data.itemStack
  if (!data.isFirstEvent) return
  if (block.typeId != "wiki:my_block") return
  if (item?.typeId != block.typeId) return

  //If the code has reached this point, then the interaction is successful
  //Cancel the block installation event (if there is one)
  data.cancel = true

  //system.run is needed to maintain privileges
  system.run(() => {
    block.setType("stone")
  })
}) 
#

@pallid portal

pallid portal
#

testing this code

#

and it is broken...

warm mason
#

Well, of course, you didn’t even change the block ID

pallid portal
#

welp...

if I set that to the block in question. It just turns the block into stone when the player tries placing the same block on it...
And it does not work with the axe.

Not only that, it still has the same issues as the previous version. Player is prevented from placing a block on them because the script attempts the interaction and failing.

I do recall a bug with the scripts where the interaction prevented players from placing blocks on them.
so it might be that?

warm mason
#

Well.. I should give up helping newbies with scripts. I'm not that patient for this

#

Sorry, I can't help you..

pallid portal
#

And I am sorry for being clueless.
I do appreciate the help all the same.

wary edge
pallid portal
#

(mini rant at Mojang)
That is ironic how when this addon used HolidayCreatorFeatures. Players were able to place blocks and still do the interaction.
So much for the scripts being better when this feature depricated.

wary edge
pallid portal
#

More options but at the cost of removing features many addons relied on....

wary edge
#

Like, I wager 99% of HCF events are made better. The only one that really "suffered" was interaction.

wary edge
dim tusk
#

Also the HCF removal thing is a long time ago and you still can't get over it?

pallid portal
#

Nope.

More like. When one wants to make something that is arbituarily similar to vanilla minecraft.
Mojang be like: "nope"

Because sure, people can make a pig dance, a block change colour when you step on it, or make a cake explode by feeding it to a rabbit.
But heaven forbid they want to use a feature that is not available in normal minecraft, nor in the stable features...

If everyone could simply make their own games by learning how to code. 99% of the Minecraft playerbase would have left a long time ago.

unique dragon
#

😹

warm mason
pallid portal
dim tusk
#

Here comes the yapping ughh

wary edge
dim tusk
#

If you don't want to learn then don't, if you hate things because of the issues leave, if you hate it don't complain you hate it... You'll never learn if you don't want to learn, learn to adapt in the environment

pallid portal
#

I'll see myself out....

distant tulip
#

@pallid portal
what seem to be the problem?
what are you trying to do

wary edge
#

Fortunately, with this new era, beta features are shipped in small quantities making it much easier to ship to stable 🙂 .

distant tulip
#

-# deferred and editor mode

wary edge
distant tulip
#

yeah i guess so

pallid portal
# distant tulip <@718450311789936730> what seem to be the problem? what are you trying to do

long story short.

I am trying to revive an addon that relied on block events (interact, destroy, and placing)
Since the old events were deprecated. I have begrudgingly turned to scripting.

The interaction aspect of the customcomponents in this case proved problematic because blocks using onPlayerInteract also prevents the player from placing blocks on them.
Because the game attempts interacting with the block, fails, and also fails to place the block.

distant tulip
pallid portal
# distant tulip can you send your block json file

By all means. I dont mind.

The "wood_log" is the block using the custom component.
And the "stripped_interact" is the script.

The component is meant to let the player interact with the block while holding axe to turn it into a different block.
Essentially replicating the vanilla mechanic of stripping log blocks.

But the issue here is the interaction component prevents players from placing blocks on them.

sterile epoch
#

what can i do to reduce lag in my scripts?

wary edge
sterile epoch
#

okay

sterile epoch
pallid portal
pallid portal
# distant tulip try this out

the script is sadly not linked to the block.

So the script is seemingly running but is not responding to the block it is supposed to respond to.

The block in question now lets the player place blocks on it. But it is because it does not have the interaction function that does the log stripping.

distant gulch
dense inlet
#

Does anyone know if there is a way to stop a Bedrock server using script or run the / commands that would normally be available in the game itself?

jolly citrus
#

is there an event for detecting when a entity’s/player’s inventory is updated/a new item is received

distant tulip
#

no

jolly citrus
#

any good way to implement that then

dim tusk
jolly citrus
#

I tried saving player inventories in a map and updating every 2 ticks checking for any changes but it’s quite slow

#

even with 1 player in the world it gets slowdowns constantly

#

5-7ms

pallid portal
# distant tulip if that didn't work try this

sadly, all of these options have not worked.
They do give a hint at something that should work though.

Because the goal is for these blocks to have this interaction but also allow players to place blocks on them.
I'll tinker with things some more.

ruby haven
#

Can someone help on how to achieve an entity that takes the texture of the ground and makes it as it's own I saw this entity named Ignis that summons blocks that takes the texture of the ground sadly the addon developer used an obfuscater tool to make the code unreadable so I don't know how he did it

wary edge
dim tusk
#

But I'm not sure of it

distant tulip
#

the way others do it is using items equipped in hand of a custom entity

distant tulip
frozen vine
#

Is it possible to check the weather via script? For example, when it's raining and I use an item, it sends a hi in the chat.

#

or is it not possible?

wary edge
celest abyss
#

Guys, does anyone know if it's possible to do a structure load, and after a few seconds it disappears and the world returns to its original state?

wary edge
distant gulch
#

Is this something I can do?

#
world.afterEvents.itemUse.subscribe((e) => {
    if (e.itemStack.typeId == "minecraft:anvil") {
        e.source.applyKnockback(e.source.getViewDirection().x, e.source.getViewDirection().z, 0, -Infinity);
    }
})
jolly citrus
#

is it possible to get the itemstack that is placed on an item frame

olive briar
#

how can i make one entity look at another with script?

#

just look

pallid portal
#

wouldn't you be able to do that in the entity's own json file?

As a behaviour.

olive briar
#

I can't do it

#

I'm unable

#

I don't know if it's in the behavior file or in the animation

#

in this case, I want the entity to rotate the entire body towards another entity

olive briar
#

yes

ruby haven
#
import { world } from '@minecraft/server';

world.afterEvents.entityHurt.subscribe(({ hurtEntity, damageSource }) => {

  const attacker = damageSource.damagingEntity;
  if (attacker?.typeId == 'mz:stomp1') {
    hurtEntity.applyKnockback(0, 0, 10, 1);
  }
  else if (attacker?.typeId == 'mz:stomp2') {
    hurtEntity.applyKnockback(0, 0, 1, 10);
  }

});

How can I make the knock effect like an explosion where the entity is knocked away from the source

ruby haven
thorn flicker
#

||im bad at math||

ruby haven
distant gulch
#

How do I create a Vector 3

#

Do I just make an array then have the three values listed?

#

like const myArray[x, y, z]

#

Would that automatically be a Vector 3?

thorn flicker
#

x, y z

#

not an array

distant gulch
#

How do i create one?

#

I*

thorn flicker
#

create an object.

distant gulch
#

Wdym?

#

Explain further

thorn flicker
#

you dont know what an object is?

distant gulch
#

I want to utilize player.teleport()

#

And I need a vector 3. I can't just put in x, y, z

#

What do I need to make that vector 3 with my own x,y,z coords

wary edge
#

{x: blah, y: blah, z: blah}

thorn flicker
#
{x: 0, y: 0, z: 0}
distant gulch
#
.source.teleport({x: xLocation, y: yLocation, z: zLocation});
#

that works?

thorn flicker
distant gulch
#

yes, they are

#

thanks guys!

thorn flicker
#

np

ruby haven
#

Can I send video here related to scripting?

shut citrus
#

new illager

ruby haven
#

I think they do not allow promoting here

ruby haven
wary edge
dim tusk
# ruby haven

It's just an entity that holds an item specifically a block then position the item so it looks like full blcok

#

I actually have pre-made models and animations, I can send you if you want

rigid meadow
#

do anyone know how to make a script where someone places a block, it disappears without using custom blocks?

ruby haven
dim tusk
ruby haven
# dim tusk

I can't understand the logic on how it works though if it is an invisible entity that holds the item block which positions it or scales it to look like a full block, how does it take the item from the ground?

dim tusk
#

When you summon the entity, it takes the block id below it then put into it's hand using replaceitem command, then despawn after a few seconds
-# based on what I seen in the video

#

It's not really complicated to understand

ruby haven
ruby haven
dim tusk
#

Just apply the model and the animations to the entity

rigid meadow
dim tusk
# ruby haven I'll try and create this script
import { world, system } from '@minecraft/server';

world.afterEvents.entitySpawn.subscribe(({ entity }) => {
   if (entity.typeId === '<mob typeid>') {
      const block = entity.dimension.getBlock(entity.location);
      entity.runCommandAsync(`replaceitem entity @s slot.weapon.mainhand 0 ${block.below().typeId}`);
      system.runTimeout(() => {
         entity.remove();
      }, 2 * 20); // 20 ticks = 1 second
   }
});```
ruby haven
rigid meadow
#

ah yes

#

it would be great to tell me the process of doing it

rigid meadow
dim tusk
rigid meadow
#

like breaks the block

dim tusk
#

So example I have grass block, I right click instead of placing it on ground it won't at all?

rigid meadow
#

um i mean i want so that whenever someone places a block, after 5ish sec, it would break automatically

#

but without using custom blocks

dim tusk
ruby haven
celest abyss
#

@dim tusk , Is it possible to make a form that when pressing a certain button it registers a custom component for the player?

celest abyss
dim tusk
celest abyss
dim tusk
autumn seal
#

Might have the files around if you haven't done it yet

dim tusk
#

I discovered something with the playerButtonInput in the 1.21.60+

#

When the player has the option to hold down to sneak or click once to sneak thingy when you activate click once to activate the class things it's not pressed anymore.

#
world.afterEvents.playerButtonInput.subscribe(({ button, newButtonState, player }) => {
    console.error(button, newButtonState, player.name);
});```
#

but tbh it kinda makes sense cause the player is not holding it anymore the game does not you soo...

#

Let it slide I guess?

subtle cove
dim tusk
#

Instead of pressed till player untoggle the sneak button

#

But I said, it kinda makes sense cause the game is the one who keeps pressing it, not you lol

slow walrus
#

well yeah that makes sense

#

though

#

in this case it's the buttonState, not the input state

#

so it should be pressed

#

and not release until toggled again

dim tusk
slow walrus
#

yeah probably

dim tusk
#

Hmm, let's just wait for other geniuses opinion

sage portal
distant gulch
sage portal
#

There's a slight difference between using infinite in duration and infinite in the calculation of a vector.

#

'sides, I'm not even sure why you need 99999 for knockback anyways, that's just overkill.

jolly citrus
#
const deathMessages = {
    "fall": "%s hit the ground too hard.",
    "drowning": "%s drowned.",
    "fire": "%s burned to death.",
    "fire_tick": "%s was on fire.",
    "lava": "%s tried to swim in lava.",
    "explosion": "%s blew up.",
    "explosion.player": "%s was blown up by %a.",
    "magic": "%s was killed by magic.",
    "projectile": "%s was shot by %a.",
    "melee": "%s was slain by %a.",
    "thorns": "%s was killed by thorns.",
    "falling_block": "%s was squashed by a falling block.",
    "anvil": "%s was squashed by a falling anvil.",
    "cactus": "%s was pricked to death by a cactus.",
    "void": "%s fell out of the world.",
    "lightning": "%s was struck by lightning.",
    "suicide": "%s took their own life.",
    "starvation": "%s starved to death.",
    "freeze": "%s froze to death.",
    "poison": "%s succumbed to poison.",
    "wither": "%s withered away.",
    "custom": "%s died."
};

world.afterEvents.entityDie.subscribe((data) => {
    /**
     * @type {Player}
     */
    let plr = data.deadEntity;

    if (plr.typeId == "minecraft:player") {
        let lasthit = plr.getDynamicProperty("lasthit")??null;
        let plrName = `§c${plr.name}§4[${(plr.getDynamicProperty("deaths") ?? 0) + 1}]§e`
        plr.setDynamicProperty("spawntag", 0);
        let team = FindPlayerTeam(plr.name);

        if (team && team != null) {
            freezeDtr(team, 1800000);
            removeDtr(team);
        }

        plr.runCommandAsync(`inputpermission set @s camera disabled`);
        plr.runCommandAsync(`inputpermission set @s movement disabled`);
        plr.setGameMode(GameMode.spectator);
        plr.setDynamicProperty("deathbanexpiry", Date.now() + 3600000);
        plr.setDynamicProperty("deathbanuntil", 3600000);
        plr.setDynamicProperty("pvpimmunity", 0);

        let deathCause = data.damageSource.cause || "custom";
        let killer = data.damageSource.damagingEntity;
        let deathMessage = deathMessages[deathCause] || "%s died.";
        if (killer && killer.typeId == "minecraft:player") {
            killer.setDynamicProperty("kills", (killer.getDynamicProperty("deaths") ?? 0) + 1);
            let killerName = `§c${killer.name}§4[${(killer.getDynamicProperty("kills") ?? 0) + 1}]§e`
            world.sendMessage(deathMessage.replace("%s", plrName).replace("%a", killerName));
        } else {
            if (lasthit != null) {
                let killer = world.getPlayers({name: lasthit})?.[0]
                if (killer) {
                    killer.setDynamicProperty("kills", (killer.getDynamicProperty("deaths") ?? 0) + 1);
                    let killerName = `§c${lasthit}§4[${(killer.getDynamicProperty("kills") ?? 0) + 1}]§e`
                    deathMessage = deathMessage.replace(".","") + ` thanks to %a.`
                    world.sendMessage(deathMessage.replace("%s", plrName).replace("%a", killerName));
                } else {
                    world.sendMessage(deathMessage.replace("%s", plrName));
                }
            }
            world.sendMessage(deathMessage.replace("%s", plrName));
        }

        plr.setDynamicProperty("deaths", (plr.getDynamicProperty("deaths") ?? 0) + 1);

        system.runTimeout(() => {
            plr.teleport({ x: -1117.5, y: 38, z: 108.5 });
        }, 5);
    }
});

why is the message being sent twice

dim tusk
# jolly citrus ```js const deathMessages = { "fall": "%s hit the ground too hard.", "dr...
if (lasthit != null) {
    let killer = world.getPlayers({name: lasthit})?.[0];
    if (killer) {
        killer.setDynamicProperty("kills", (killer.getDynamicProperty("deaths") ?? 0) + 1);
        let killerName = `§c${lasthit}§4[${(killer.getDynamicProperty("kills") ?? 0) + 1}]§e`;
        deathMessage = deathMessage.replace(".", "") + ` thanks to %a.`;
        world.sendMessage(deathMessage.replace("%s", plrName).replace("%a", killerName));
    } else {
        world.sendMessage(deathMessage.replace("%s", plrName));
    }
}
world.sendMessage(deathMessage.replace("%s", plrName));
#

You have 3 here... And how does the very bottom message trigger?

valid ice
#

Spent the last half hour debugging something.... switched a this to a the in a lore line and it fixed itself 💀

dim tusk
valid ice
#

Databases chad

dim tusk
#
if (lasthit != null) {
    }
} else {
    world.sendMessage(deathMessage.replace("%s", plrName));
}
dim tusk
valid ice
jolly citrus
shut citrus
rapid nimbus
#

Hey everyone

#

Can "world" Script Classes be combined with "Biome Types" Classes?

neat hazel
#

Why is this error occurring?

const replacements = [
  {
    id: "minecraft:wooden_sword",
    lore: ["Line 1", "Line 2", "Line 3"]
  },
  {
    id: "minecraft:apple",
    lore: ["Just one line"]
  }
]

mc.system.runInterval(() => {
  for (const player of mc.world.getPlayers()) {
    const inventory = player.getComponent("inventory")?.container;
    for (let i = 0; i < inventory.size; i++) {
      const item = inventory.getItem(i);
      if (item === undefined) continue;
      if (item?.typeId == replacements.id) { // LINE 21
        item.setLore(replacements.lore); 
        inventory.setItem(i, item);
      }
    }
  }
});
warm mason
#

For example, write console.warn("the file has been updated")

warm mason
warm mason
#

So it would be better to do this:

const replacements = {
  "minecraft:wooden_sword": ["Line 1", "Line 2", "Line 3"],
  "minecraft:apple": ["Just one line"]
}

mc.system.runInterval(() => {
  for (const player of mc.world.getPlayers()) {
    const inventory = player.getComponent("inventory")?.container;
    for (let i = 0; i < inventory.size; i++) {
      const item = inventory.getItem(i);
      if (item === undefined) continue;
      if (replacements[item.typeId] != undefined) { // LINE 21
        item.setLore(replacements[item.typeId]); 
        inventory.setItem(i, item);
      }
    }
  }
});
jolly citrus
#

i want to load some blocks in the world and save them in a variable as my scripts starts up. how do i prevent this from throwing errors when i first join the world (meaning the area is yet to be loaded)

cold grove
warm mason
distant tulip
#

it dose throw errors as far as i remembered

warm mason
distant tulip
warm mason
#

Then why doesn't it work for me?...

distant tulip
#

let me try to make sure

warm mason
#

This is probably about the fact that if you receive a block object and try to use it after unloading it, you get an error