#Script API General

1 messages · Page 56 of 1

keen laurel
#

Just saw 2.0.0 was released to beta. What does everyone think is the best new addition to 2.0.0

remote oyster
sterile epoch
#

isn't there a way to add entity filtering to an event subscription?

wary edge
#

Pseudocode.

sterile epoch
#

ik that one, but i remember seeing smthn that looked like ```js
world.afterEvents.entityHurt.subscrive(() => {

}, entity filtering here)

#

but i looked on the docs and dont see it

#

apparently it improves performance

sterile epoch
#

i deffo saw i

#

it*

wary edge
#

Well would you look at that.

scarlet sable
#

Is it possible to make a custom fog?

#

Or ambiante in general

round bone
#

yeah

#

Record is just an object

cold grove
scarlet sable
#

Ty

dull shell
#
  world.beforeEvents.worldInitialize.subscribe(({ blockComponentRegistry }) => {
    blockComponentRegistry.registerCustomComponent('jay4x:egg_block', {
      onTick(event) {
        if (system.currentTick % 20 === 0) {
          const location = event.block.location;
          event.dimension.setType("air", event.block.location);
          event.dimension.spawnParticle('minecraft:totem_particle', event.block.location);  (L 129)
          event.dimension.spawnEntity("minecraft:chicken", event.block.location);
        }
      }
    });
  });```
#

what does that mean?

narrow patio
#

Is that line on setType("air", event.block.location)?

dull shell
#

no i put it in the thing its the SpawnParticle

narrow patio
#

spawnParticle should work
setBlockType instead of setType maybe?

wary edge
dull shell
#

One of my friends helped me with it im not to sure the reason why

#

he uses it for his stuff

wary edge
#

You should not. Use the tick component instead.

dull shell
#

i am inside of my block

#
            "minecraft:custom_components": [
              "jay4x:egg_block"   
              ],
                "minecraft:tick": {
    
                    "interval_range": [600, 2000] 
                }, ```
open urchin
#

if you want to do it every second it should be [20, 20]

dull shell
#

im trying to have it function as a egg so like it doesnt hatch automaticly

#

thats why i put those numbers

#

more randomized

grave thistle
#

Is there a way to check if a block is natural or player-placed? I need to check if a torchflower on farmland blocks are player-placed or grown from a seed

wheat condor
open urchin
grave thistle
#

a fully grown torchflower's ID is minecraft:torchflower. the crop ID isn't what I need since I need to detect if it's fully grown

scarlet sable
cinder shadow
#

Is there no way to use anything that was only available in 1.18.0-beta anymore without moving to 2..0.0-beta?

cinder shadow
#

darn, I shouldn't have updated my preview version

#

now I can't work onmy add-on for a week

cinder shadow
#

I'm pretty sure I use nearly everything available in scripting atm, so I don't have a choice lol

#

I'll just move the files I intend to be for the next stable release somewhere else and start updating

cinder shadow
#

ahh that was relatively easy to fix, only had to update world intitialize and knockback scripts

dim tusk
#

it's worldLoad and vectors2 now right?

#

I forgor if it's XZ or XY

shut citrus
plucky light
#

I have a script that adds ticking areas when a player joins the world and removes them when they leave. I have done this to stop the ticking areas continue on the server noone is online

The problem is it seems they aren't loading correctly every time. Essentially the area gets truncated. I assume they are trying to load too quick? (before the world loads properly?) so they get set to smaller areas?

    for (const key of Object.keys(DefaultTickingAreas)) { 
        let ChosenArea = DefaultTickingAreas[key]
        const TLocation = ChosenArea.Coords1
        const T2Location = ChosenArea.Coords2
        const TName = ChosenArea.Name
        console.log('Added Ticking Area ' + TLocation.x + ' ' + TLocation.y + ' ' + TLocation.z + ' '+ T2Location.x + ' ' + T2Location.y + ' ' + T2Location.z + ' ' + TName)
        joinedplayer.runCommandAsync('tickingarea add ' + TLocation.x + ' ' + TLocation.y + ' ' + TLocation.z + ' '+ T2Location.x + ' ' + T2Location.y + ' ' + T2Location.z + ' ' + TName + ' true')

    }       
}```
#

run from

world.afterEvents.playerSpawn.subscribe((eventData) => {

misty dagger
#

Is there a way to directly get the entity which another entity is riding directly from said entity?

misty dagger
#

Ah, it's tied to a component.

random flint
#

Ah, I like that guy. He literally made an orbital laser, an eerily accurate walking spider, and a custom screen/particle renderer, only using entity displays.

amber granite
#

Guys does anyone know how to control .getEntities volume option ?

chrome flint
#

does .addItem() returns the remainder amount that has not been added?

simple zodiac
#

yeh

chrome flint
#

aren't there a .tryAddItem() function?

unique acorn
#

nope

random flint
chilly fractal
#

Doesn't .addItem drop it if they dont have any space left?

random flint
#

No. It just returns leftover in the form of an ItemStack class instance

chilly fractal
#

One sec ima test

#

Oh, you're right..

#

It used to throw it on the ground in the previous versions iirc

edgy elm
#

Hi here. I just want to ask if how do other backpack ui works. Like it can drag item from players inventory to the form. I just guest that it is a chest form. But how does it works? like the draging and putting it all.

unique acorn
#

its not a chest form i think, there is an entity component that gives them inventory

#

this is more of an #1067869022273667152 question but here

edgy elm
winter pumice
#

How can I run commands after a player has joined?

somber cedar
winter pumice
somber cedar
#

from jayly docs:

import { world } from "@minecraft/server";

world.afterEvents.playerSpawn.subscribe((eventData) => {
    let { player, initialSpawn } = eventData;
    if (!initialSpawn) return;

    // This runs when the player joins the game for the first time!
    console.log(player.name, 'joined');
});
distant gulch
#

Does anyone have a list of all icons from Minecraft bedrock ( textures/ui/… )

chilly fractal
#

Download one of the versions and go to resource packs

#

And then textures/ui/ and have fun

fallow rivet
#

Is it possible to make an island system with script?

#

A system used on Skyblock servers

winged gull
#

for that you want to install bedrock launcher on pc and look in the version files

#

also if they are using the textures for a form button texture, then if they just type loading instead of a texture name, then it will use an animated loading texture.

cinder shadow
#

When did they remove world.playSound?

#

Can't find an alternative

wary edge
cinder shadow
#

world.dimension.playSound isn't working either

cinder shadow
wary edge
random flint
#

Is your volume on 0% ?

cinder shadow
#

I guess vanilla equip sounds don't matter 😔

distant tulip
#

dimension.playSound work fine

wary edge
#

Oh wait. I think you're tripping Koala.

#

I was thinking of entity.spawnParticle which is gone I believe. or maybe it never existed.

random flint
shut citrus
#

how to put "0" in playAnimation method?

cinder shadow
distant tulip
#

world.getDimension() ?

random flint
random flint
distant tulip
cinder shadow
wary edge
#

Make sure your sound isn't 0.

shut citrus
distant tulip
random flint
wary edge
#

By that I mean, settings -> audio -> make sure it isn't 0.

cinder shadow
#

yeah but with getDimension I need to specify the dimension

distant tulip
wary edge
#

I had a few instances where I was testing sound and was baffled why it didn't work.

cinder shadow
#

My sound is definitely not off lol

shut citrus
cinder shadow
#

Idk this change just seems pretty bad

distant tulip
cinder shadow
#
const dim = world.getDimension('overworld');
dim.playSound(armor.equipSound, player.location);```
#

so, what if the player is in the Nether?

#

do I need to do a separate getDimension?

distant tulip
#

i mean, you could get the dimension class from the player

#

or where ever you are working on

shut citrus
distant tulip
#

player/entity.dimension

random flint
distant tulip
random flint
#

maybe the problem lies on armor.equipSound

cinder shadow
#

yeah I'm not a fan of this change, I don't get why it was removed

world.getDimension(`${player.dimension.id}`).playSound(armor.equipSound, player.location);
distant tulip
#

...

#

player.dimension.playSound

wary edge
cinder shadow
#

Because this dude said to use getDimension

distant tulip
#

bruh

cinder shadow
distant tulip
#

i said world.dimension is not a thing

cinder shadow
#

back in my day

random flint
distant tulip
#

i don't see why

cinder shadow
random flint
#

Is your issue fixed Koala?

cinder shadow
#

yep and now I need to go back through and change every instance of world.playSound

distant tulip
#

random

cinder shadow
#

Has anyone else had issues where pausing the game will sometimes break anything running on a timer?

winter pumice
#

or stable

cinder shadow
#

any version with game pausing

winter pumice
#

not on stable but in preview yes sometimes

sharp elbow
#

Break how?

winter pumice
#

but it does not break or something just minor lag difference

cinder shadow
#

the timer is completely cancelled

#

I have a passive health regeneration system for example js //passive health regeneration if(healthComponent.currentValue == healthComponent.effectiveMax) { player.__passiveHealthRegeneration = 400; } else { player.__passiveHealthRegeneration == 0 ? (healthComponent.setCurrentValue(healthComponent.currentValue + 1), player.__passiveHealthRegeneration = 400): player.__passiveHealthRegeneration--; }

#

I've had this completely stop working between pauses at times

granite badger
#

that's not a timer (?), that's just counting how many js frames has been through

cinder shadow
#

In other words, a timer

#

ahh wait

#

It happens because of /reload, not pausing 😔

lucid scroll
#

Is it possible to move a camera across dimensions? Via scripting?

So far it seems impossible to me, but I'd believe that there's a way I just don't know.

untold copper
#

is there a function that detects when you left click a block

past blaze
lucid scroll
dim tusk
dusk agate
#

100000 msgs

valid ice
#

For the 100000th time

untold copper
shut citrus
#
entity.playAnimation(s, { nextState: "x", blendOutTime: 0.1, stopExpression: `${"0"}`, 
controller: ctrl})```
is it right?
dim tusk
#

Guys, can someone remind me again if the 'dyeable' component doesn't work on vanilla items

random flint
#

it doesn't? oww man 😔

dim tusk
#

Unless it's fixed in the current preview

full brook
#

how to know if minecraft:falling_block entity is anvil

random flint
#

You don't. You guess. Maybe you store every existing anvil in the world and check if a falling block spawns on that particular coordinate.

plucky light
#

block.typeID is return undefined. Any reason why?

    const { player, block } = eventData;
    const eventLoc = block.location
    console.warn(block.typeID + ' ' + eventLoc.x + ' ' + eventLoc.y + ' ' +eventLoc.z)

    if (block.typeId === "minecraft:barrel" && eventLoc.x === -538 && eventLoc.y === 112 && eventLoc.z === 1980) {
        console.log("Barrel Used ");
        return;
    };
});```
ivory bough
#

[main.js] ran with error: [SyntaxError: Could not find export 'Vector' in module '@minecraft/server']
How to solve this?

plucky light
#

..... thanks. I missed that

ivory bough
celest abyss
#

I'm trying to detect if the player moved the camera But this doesn't work

const player_direction = new Map();
const CHECK_INTERVAL = 30;

system.runInterval(() => {
  world.getAllPlayers().forEach(player => {
    if (red == true) {
      const vm = player.getViewDirection()
      const previousDirection = player_direction.get(player.name);

      if (previousDirection) {

        const dx = vm.x - previousDirection.x;
        const dy = vm.y - previousDirection.y;
        const dz = vm.z - previousDirection.z;

        if (Math.abs(dx) > 0.01 || Math.abs(dy) > 0.01 || Math.abs(dz) > 0.01) {
          player.runCommandAsync("gamemode spectator @s")

      }}}
  })

}, CHECK_INTERVAL)

subtle cove
ivory bough
empty yoke
#

Is there any application for minecraft bedrock that allows to generate entire packs automatically based on the user's requests?

chilly fractal
chilly fractal
chilly fractal
# celest abyss I'm trying to detect if the player moved the camera But this doesn't work ```js...
let plrLoc = player.location, plrView = player.getViewDirection(), runID = system.runInterval(() => {
  if (!this || !this.isValid()) {
    system.clearRun(runID);
    return;
  }
  if (!Object.keys(plrLoc).every(key => plrLoc[key] === player.location[key]) || !Object.keys(plrView).every(key => plrView[key] === player.getViewDirection()[key])) {
    system.clearRun(runID);
    // moved
    player.sendMessage(`§g[§6§lServer§r§g] §cYou Moved!.`);
    return;
  };
}, 20);

You can remove the .location part of the snippet above.

empty yoke
empty yoke
#

In addition to this, an integrated editing system for each file type generates the content and you can send requests on specific files where the bot intervenes and modifies every particularity requested by the user.

chilly fractal
#

And i certainly don't do commissions either

#

My code is closed source until i decide not

#

So either you make the code that generates the pack by yourself or get a team to help or even just let them make it completely or don't ask me or anyone else to make it.

#

If there is a tool that already exists and you wanna use it sure but don't go around guilt trippin' people

empty yoke
trail marten
#

can dynamic property affect player's performance? (even the world dynamic property)

ivory bough
#

@subtle cove

import { world, system, Player } from "@minecraft/server";
import { Vec3 } from "./vector/vec3.js";
system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    if (player.isSleeping) {
      Player.runCommandAsync("function sleep");
    };
    if (!player.isSleeping) {
      Player.runCommandAsync("event entity @e[type=space:shadow_anomaly despawn")
    }
  }
}, 5);

system.runInterval(() => {
  for (let player of world.getPlayers()) {
    let srcLoc = player.getHeadLocation();
    const blockList = [
      "minecraft:oak_log",
      "minecraft:spruce_log",
      "minecraft:dark_oak_log",
      "minecraft:birch_log",
      "minecraft:jungle_log",
      "minecraft:acacia_log",
      "minecraft:mangrove_log",
      "minecraft:cherry_log"
    ];

    let blockRaycastHit = player.getBlockFromRay(
      new Vec3(srcLoc.x, srcLoc.y + 0.1, srcLoc.z),
      player.getViewDirection(),
      { maxDistance: 10 }
    );

    let block = blockRaycastHit?.block;

    if (block && blockList.includes(block.typeId)) {
      Player.runCommandAsync("function block");
    }
  }
}, 10);

system.beforeEvents.watchdogTerminate.subscribe((event) => {
  event.cancel = true;
});

Scripting][error]-TypeError: not a function at <anonymous> (anomaly.js:9)

[Scripting][error]-TypeError: not a function at <anonymous> (anomaly.js:32)

gaunt salmonBOT
trail marten
ivory bough
trail marten
#

but you're trying to run a command on all player

ivory bough
trail marten
#

Player is a class. you've defined player in for (const player of world.getAllPlayers()) already

#

try changing all uppercassed Player to lowercased player

ivory bough
ivory bough
trail marten
#

have you reloaded yet? (/reload)

ivory bough
#

I even reopened the world

trail marten
#
import { world, system, Player } from "@minecraft/server";
import { Vec3 } from "./vector/vec3.js";

system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    if (player.isSleeping) {
        player.runCommandAsync("function sleep");
    };
    if (!player.isSleeping) {
        player.runCommandAsync("event entity @e[type=space:shadow_anomaly despawn")
    }
  }
}, 5);

system.runInterval(() => {
  for (let player of world.getPlayers()) {
    let srcLoc = player.getHeadLocation();
    const blockList = [
      "minecraft:oak_log",
      "minecraft:spruce_log",
      "minecraft:dark_oak_log",
      "minecraft:birch_log",
      "minecraft:jungle_log",
      "minecraft:acacia_log",
      "minecraft:mangrove_log",
      "minecraft:cherry_log"
    ];

    let blockRaycastHit = player.getBlockFromRay(
      new Vec3(srcLoc.x, srcLoc.y + 0.1, srcLoc.z),
      player.getViewDirection(),
      { maxDistance: 10 }
    );

    let block = blockRaycastHit?.block;

    if (block && blockList.includes(block.typeId)) {
        player.runCommandAsync("function block");
    }
  }
}, 10);

system.beforeEvents.watchdogTerminate.subscribe((event) => {
  event.cancel = true;
});
trail marten
#

figured out the problem

dim tusk
prisma shard
#

such nice meeting you

#

you remember me

#

let's move to off-topic

trail marten
# ivory bough
import { world, system, Player } from "@minecraft/server";
import { Vec3 } from "./vector/vec3.js";

system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    if (player.isSleeping) {
        player.runCommandAsync("function sleep");
    };
    if (!player.isSleeping) {
        player.runCommandAsync("event entity @e[type=space:shadow_anomaly despawn")
    }
  }
}, 5);

system.runInterval(() => {
  for (let player of world.getPlayers()) {
    let srcLoc = player.getHeadLocation();
    const blockList = [
      "minecraft:oak_log",
      "minecraft:spruce_log",
      "minecraft:dark_oak_log",
      "minecraft:birch_log",
      "minecraft:jungle_log",
      "minecraft:acacia_log",
      "minecraft:mangrove_log",
      "minecraft:cherry_log"
    ];

    let blockRaycastHit = player.getBlockFromViewDirection({ maxDistance: 10 });
    let block = blockRaycastHit?.block;

    if (block && blockList.includes(block.typeId)) {
        player.runCommandAsync("function block");
    }
  }
}, 10);

system.beforeEvents.watchdogTerminate.subscribe((event) => {
  event.cancel = true;
});

the error lies from player.getBlockFromRay() which is not a function.

#

i've replaced it

random flint
trail marten
dim tusk
dim tusk
prisma shard
random flint
#

My skin still do

amber granite
#

Guys

#

Why tickarea command dosen't work properly

#

Bruh nothing works properly: |

ivory bough
distant tulip
ivory bough
distant tulip
#

is it?

ivory bough
ivory bough
# distant tulip is it?
import { world, system, Player } from "@minecraft/server";
import { Vec3 } from "./vector/vec3.js"
system.runInterval(() => {
  for (const player of world.getAllPlayers()) {
    if (player.isSleeping) {
      world.getDimension("overworld").runCommandAsync("function sleep");
    };
    if (!player.isSleeping) {
      return;
    }
  }
}, 5);

system.runInterval(() => {
  for (let player of world.getPlayers()) {
    let srcLoc = player.getHeadLocation();
    const blockList = [
      "minecraft:oak_log",
      "minecraft:spruce_log",
      "minecraft:dark_oak_log",
      "minecraft:birch_log",
      "minecraft:jungle_log",
      "minecraft:acacia_log",
      "minecraft:mangrove_log",
      "minecraft:cherry_log"
    ];

    let blockRaycastHit = player.getBlockFromRay(
      new Vec3(srcLoc.x, srcLoc.y + 0.1, srcLoc.z),
      player.getViewDirection(),
      { maxDistance: 10 }
    );

    let block = blockRaycastHit?.block;

    if (typeof block !== "undefined" && block.includes(block.typeId) && blockList.includes(block.typeId)) {
      world.getDimension("overworld").runCommandAsync("function block");
    }
  }
}, 10);

system.beforeEvents.watchdogTerminate.subscribe((event) => {
  event.cancel = true;
});

[Scripting][error]-TypeError: not a function at <anonymous> (anomaly.js:32)

distant tulip
#

it is a dimension function

ivory bough
distant tulip
#

Minecraft Server API Analysis
not published yet

ivory bough
distant tulip
#

-# nice name btw

amber granite
#

@distant tulip

distant tulip
#

?

amber granite
#

I finally finish it

distant tulip
#

it?

amber granite
#

Yes

distant tulip
#

i will assume you meant the chunk loader

amber granite
#

Yes

distant tulip
#

cool

ivory bough
grave thistle
#

how do i detect the splash potion type thrown? I need to detect when a standard water splash potion is used

upper adder
#

Has anyone given me a function to listen to a block event?

distant tulip
upper adder
#

Play places a block

grave thistle
distant tulip
distant gulch
#

hey guys

chilly fractal
distant tulip
chilly fractal
#

@distant gulch you can set a global var after you finish stuff

chilly fractal
#

Send your code so i can give you a more personalized answer

#

Oop

#

Mentioned someone else lol

ivory bough
chilly fractal
#

Fixed it now

distant gulch
#
    private async generateLayer(height: number, startVector: Vector2Interface, endVector: Vector2Interface): Promise<void> {
        const startX = startVector.x;
        const startY = startVector.y;

        const endX = endVector.x;
        const endY = endVector.y;

        return new Promise((resolve) => {
            const generator = function* () {
                for (let x = startX; x <= endX; x++) {
                    for (let z = startY; z <= endY; z++) {
    
                        yield;            
                    }
                }
    
                resolve();
            }

            system.runJob(generator.bind(this)());
        });

I want to resolve my promise when the iterations have been complete, is this how it works?

ivory bough
amber granite
#

U know math ?

drifting ravenBOT
#
Info

This bot was created by SmokeyStack for the purpose of making a FAQ bot for the Bedrock Add-Ons Discord Server.

Managing Entries

To manage entries, please make a pull request on GitHub.

Source Code
#
Learn JavaScript

As the Script API is a framework built on JavaScript code, having an understanding of JavaScript is key.

If you are being shown this, then you most likely are a beginner with JS and could use a little guidance.

Videos on Learning JavaScript
Javascript in 1 hour
Javascript Classes in 1 hour

Web Guide:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

Reference Sites:
https://www.w3schools.com/jsref/default.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
https://javascript.info

amber granite
#

@ivory bough

drifting ravenBOT
ivory bough
amber granite
#

Both

drifting ravenBOT
distant tulip
distant tulip
amber granite
#
  • practice
#

Programming is like math , the more u practice the more u get professional in it

ivory bough
amber granite
#

Use Vscode

distant tulip
#

"mobile"

amber granite
#

If Bridge is buggy

#

Try to follow this

#

@ivory bough

boreal siren
#

help with ItemStack, specifically how to find out what item the player is holding and how to set lore and check it.

subtle cove
cerulean cliff
#

ah yes, I love it

[Scripting][error]-Plugin [pack.name - 0.0.1] - [main.js] ran with error: [SyntaxError: Could not find export 'MinecraftDimensionTypes' in module '@minecraft/server']
#

2.0.0 is awesome

subtle cove
#

remove 'Minecraft'

ivory bough
# subtle cove belated apologies, was sleeping that time 💀 anyhow, everyone's tryna help ever...

Anyways,

import { world, SignSide } from '@minecraft/server';

const loc = world.getDimension("overworld")
const block = loc.getBlock({x:0,y:-60,z:0})
block?.setType("minecraft:sign")
const signComponent = block?.getComponent('minecraft:sign')
signComponent?.setText("hello.",SignSide.Front)
signComponent?.setText("hola.",SignSide.Back)

How to make the sign spawn relative to the player's local coordinates of my choice?

chilly fractal
distant gulch
#

Okay thanks, ill keep that in mind

subtle cove
# boreal siren help with ItemStack, specifically how to find out what item the player is holdin...

I'd use ContainerSlot if there's no enchantments or durability thingy needed

import { world, system, Player } from "@minecraft/server";

/**@param {Player} param  */
function getMainHand(param) {
    const hand = param.getComponent("equippable").getEquipmentSlot("Mainhand");
    return hand.hasItem() && hand;
};

system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const hand = getMainHand(player);
        if (!hand || hand.typeId !== "minecraft:dirt") continue;
        const lore = hand.getLore();
        if (!lore.includes("dirty")) {
            hand.setLore(["dirty"])
        }
    }
})


subtle cove
# ivory bough Anyways, ``` import { world, SignSide } from '@minecraft/server'; const loc = w...
import { world, system, Player, SignSide } from "@minecraft/server";


system.runInterval(() => {
    for (const player of world.getAllPlayers()) {
        const location = player.location
        location.y = -60
        const block = player.dimension.getBlock(location)
        block?.setType("minecraft:sign")
        const signComponent = block?.getComponent('minecraft:sign')
        signComponent?.setText("hello.",SignSide.Front)
        signComponent?.setText("hola.",SignSide.Back)
    }
})


subtle cove
#

uhh, wdym by "spawn"?

ivory bough
subtle cove
#

ok, btw, only use the part where the player is used, not entirely with the runInterval

#
const location = player.location
location.y = -60
const block = player.dimension.getBlock(location)
```specifically just this sample
cerulean cliff
#

was a bug in bedrock-boost lol

ivory bough
subtle cove
subtle cove
subtle cove
ivory bough
twilit tartan
#

?

ivory bough
subtle cove
#

try block.setType('spruce_standing_sign')

grim raft
#

yo

amber granite
#

@distant tulip

grim raft
#
world.afterEvents.entityDie.subscribe((event) => {
    const { deadEntity } = event
    const variant = deadEntity.getComponent('minecraft:variant')
    const dimension = deadEntity.dimension

    if (deadEntity.typeId === 'minecraft:player' && variant?.value == 0) {

        let { x, y, z } = deadEntity.location

        const inventory = deadEntity.getComponent("inventory").container
        const graveEntity = dimension.spawnEntity('bleach:corpse', { x, y, z })
        const graveInventory = graveEntity.getComponent("inventory").container
        graveEntity.nameTag = `§c${deadEntity.nameTag}§r \n R.I.P`
        graveEntity.addTag(deadEntity.id)

        for (let i = 0; i < 36; i++) {
            const item = inventory.getItem(i)
            inventory.moveItem(i, i, graveInventory)
        }
        const equipment = deadEntity.getComponent('equippable')
        let i = 37
        for (const slot of equipmentSlots) {
            const item = equipment.getEquipmentSlot(slot).getItem()?.clone()
            graveInventory.setItem(i, item)
            equipment.setEquipment(slot)
            i++
        }

        deadEntity.triggerEvent('bleach:get_plus')
        deadEntity.runCommand('gamemode a @s')

    }
}
);```
I want to tp `deadEntity` to the death cords
#

when it dies

chilly fractal
#

You can't do that

#

(It's already dead, how tf are you gonna move something that doesn't exist anymore?)

chilly fractal
#

You mean after it respawns?

grim raft
#

yea

#

the last part also happens after the respawn

deadEntity.triggerEvent('bleach:get_plus')
deadEntity.runCommand('gamemode a @s')```
chilly fractal
#
world.afterEvents.playerSpawn.subscribe((data) => {
  if (data.initialSpawn) return;
  // entity respawned, do some code.
});
grim raft
#

breh

grim raft
unique acorn
obsidian coyote
#

This thread's true message count

amber granite
#

How to make entity immune to kill command

chilly fractal
unique acorn
#

okay

chilly fractal
#

And in the playerSpawn event, retrieve the coords from that object

#

Do:
player.teleport(yourObj[player.id] || {x: 0, y: 0, z: 0});

celest abyss
chilly fractal
#

Also make sure to to save the dimension so edit a little bit

chilly fractal
#

That code is for a player, so use world.getPlayers() if you want to run it for all

celest abyss
chilly fractal
#

Show your code

wary edge
cinder shadow
#

L

simple zodiac
#

what

wary edge
simple zodiac
#

I know there is a limit of 1000 people right? is it because of that?

#

ah didn't know you guys were chilling here

simple zodiac
#

So may the purge continue

wary edge
#

Fire PURGE TIME.

obsidian coyote
simple zodiac
#

nooo

#

don't lock the chanel!

upper adder
#

why three dots

simple zodiac
fallow rivet
simple zodiac
#

hello

fallow rivet
#

How are you?

simple zodiac
#

good

upper adder
dim tusk
celest abyss
# chilly fractal Show your code
world.getAllPlayers().forEach(player => {
  let plrView = player.getViewDirection()
  system.runInterval(() => {
    if (gm == true && red == true) {
      if (Object.keys(plrView).every(key => plrView[key] === player.getViewDirection()[key])) {
        player.kill()
      };
      };
  })

}, 30);
dim tusk
chilly fractal
#

One word, actually two, "Just why?"

chilly fractal
#

Here, use this:

const views = new WeakSet();
system.runInterval(() => {
  const players = world.getPlayers();
  for (let i = 0; i < players.length; i++) {
    const player = players[i], plrView = player.getViewDirection(), cachedView = views.get(player.id);
    if (!cachedView) {
      views.set(player.id, plrView);
      return;
    }
    if (gm == true && red == true) {
      if (!Object.keys(plrView).every(key => plrView[key] === cachedView[key])) {
        player.kill()
      };
    };
  }
}, 30);
celest abyss
chilly fractal
#

That simply won't work

#

As you are not exactly "caching"

#

You are checking a value against the same value

#

Of course it won't flag

chilly fractal
celest abyss
chilly fractal
#

Oop

#

Sorry my bad

#

I updated it

celest abyss
#
[Scripting][error]-TypeError: not an object    at set (native)
    at <anonymous> (main.js:110)

Line 110

views.set(player.id, plrView);
chilly fractal
#

Nah is there a typeError not an object

#

I'm just gonna test in the web rq

#

Oh wait

#

I used WeakMap not WeakSet, my bad.

#

(WeakMap needs the keys to be objects)

#

There, updated again.

celest abyss
#

Not at function
Line

const player = players[i], plrView = player.getViewDirection(), cachedView = views.get(player.id);

pale terrace
#

onPlace custom component throw when the world is loaded?

dim tusk
# celest abyss Not at function Line ```js const player = players[i], plrView = player.getViewD...

Try this.

const views = new Map();

system.runInterval(() => {
  const gm = true;
  const red = true;
  
  for (const player of world.getPlayers()) {
    const plrView = player.getViewDirection();
    const cachedView = views.get(player.id);

    if (!cachedView) {
      views.set(player.id, plrView);
      continue;
    }

    if (gm && red) {
      if (plrView.x !== cachedView.x || 
          plrView.y !== cachedView.y || 
          plrView.z !== cachedView.z) {
        player.kill();
      }
    }
    
    views.set(player.id, plrView);
  }
}, 30);```
celest abyss
#

Is there a way to reset the Map? Since it only works the first time But if you want to use it again the address you see has to be the previous one

celest abyss
#

Ty

cinder shadow
#

why does applyDamage not accept 'projectile' as a cause?

#
hurtEntity.applyDamage(bonusDamage, {cause: 'projectile', damagingEntity:damagingEntity} )
#

Looks like if I wanted it to be via a projectile, I need to use damagingProjectile: instead

drowsy scaffold
#

is there a way to get a player's XUID with only scripts? I can use server-net too if needed

cold grove
#

But you will need to build up your own rest api for that
I guess your script is not public

drowsy scaffold
#

true, there's a request you can make with names to get information like that right?

marsh pebble
dawn zealot
#
        const totalDamageMilestone = {
            totalDamage: getScore(player, `totalDamage`),
            current_milestone: getScore(player, "mile_dmg_count")
        }
        switch (totalDamageMilestone) {
            case totalDamageMilestone.totalDamage >= 250 && totalDamageMilestone.current_milestone == 0:
                player.runCommand(`function milestones/damage`)
                break;
        }
``` is there a reason this isnt working?
valid ice
#

console warn values and see what things are returning

dawn zealot
# valid ice console warn values and see what things are returning

im trying a different way now

        const totalDamageMilestones = [
            250,
            2500
        ]

        totalDamageMilestones.forEach(milestone => {
            for (let i = 0; i <= 14; i++) {
                if (getScore(player, `totalDamage`) >= milestone && getScore(player, "mile_dmg_count") == i)
                    player.runCommand(`function milestones/damage`)
            }
        })
``` however its running alot more than it should
#

oh i see the problem

#

i cant seem to find anything but does anyone know how to get the length of the current array being used in a foreach?

#
        totalDamageMilestones.forEach(milestone => {
            console.warn(milestone.length)
            if (getScore(player, `totalDamage`) >= milestone && milestone.length == getScore(player, "mile_dmg_count"))
                player.runCommand(`function milestones/damage`)
        })
dim tusk
#

-# nvm you fixed it already

dim tusk
#

totalDamageMilestone.length

dawn zealot
#

because its cycling through them

cinder shadow
dim tusk
#

I mena yes you could nvm, but it will return the lengths of the string not an array

dawn zealot
#

i meant like the current one its cycling through

#
        const totalDamageMilestones = [
            250,
            2500
        ]

        totalDamageMilestones.forEach(milestone => {
            console.warn(milestone.length)
            if (getScore(player, `totalDamage`) >= milestone && milestone.length == getScore(player, "mile_dmg_count"))
                player.runCommand(`function milestones/damage`)
        })
``` full code
#

basically if its cycling through 2500 i need it to return a 1

dim tusk
dawn zealot
#

this is me getting rid of this THING...

dim tusk
# dawn zealot yes
const array = ['apple', 'banana', 'cherry'];

array.forEach((item, index) => {
  console.warn(`Item: ${item}, Index: ${index}`);
});```
valid ice
#

Could do something using js const mile_dmg_count = [ 0, 0, 7500, //index 2 12500, ... 500000000, ]

bright dove
dawn zealot
bright dove
dim tusk
bright dove
#

Literally command function execution in script using runCommand is insane

cinder shadow
#

Clearly less lines is more efficient

bright dove
#

I agree

#

me is making giant class

dawn zealot
bright dove
#

you see, this can cause a billion imports from different part of the code, but mist often, ít works

valid ice
#

native methods always better

dawn zealot
#

perfect

bright dove
#

what the

#

okay that is kinda better

valid ice
#

runCommands are wildly inefficient, just saying

dawn zealot
# bright dove quick ≠ performant

yeah well im not some guys who spends his life perfecting it for the minecraft marketplace just for them to decline it bc u forgot to change the texture of a grass block

valid ice
#

Would recommend native methods, or using async

dawn zealot
valid ice
#

skull

dawn zealot
#

tps 20 :)

#

sometimes 18 but we dont talk about that

bright dove
#

and they accept it just fine

dawn zealot
bright dove
#

i am looking at you Honeyfrost

valid ice
#

I used 'em for mine and had delays of up to 5 ms. Removed them, and it went away.
dunno what you're using, but they are not good in large amounts.

bright dove
#

runCommand is an easy way to obliterate your addon

dawn zealot
#

old system

cinder shadow
valid ice
dawn zealot
bright dove
valid ice
#

good, I guess?

marsh pebble
#

What's the smartest plot system you've seen

valid ice
#

runJob OP?

dawn zealot
marsh pebble
#

oops wrong server

valid ice
cinder shadow
#

I tried and failed to use it, ended up just removing the word async and my stuff that was async still worked

marsh pebble
valid ice
bright dove
marsh pebble
#

Not mine. it was an old yt vid like 8 yrs ago used old execute and everything. Video didnt reach over 200 views and owner took down

bright dove
marsh pebble
#

so now i have a plot addon that works and i have no idea if any 1 else has it.

dawn zealot
#

😭

bright dove
marsh pebble
dawn zealot
valid ice
#

I hope one day Navi deletes runCommand (all commands are available with native methods)

dawn zealot
marsh pebble
#

for "dumb" people

dawn zealot
#

made realm servers for 6 years hell no

bright dove
#

that literally cause your game to drop by like 10ms

marsh pebble
dim tusk
#

there's a pattern you can simplify it

dawn zealot
valid ice
#

From what I've seen, function files are really efficient

But coupled with a runCommand they become useless lol

dawn zealot
dim tusk
dawn zealot
dawn zealot
#

o

#

and how

solar dagger
#

@dawn zealot bro I see that you're using commands, not bad for starting out but the API actually has methods for these things

solar dagger
#

Yeah just go to the Microsoft wiki and look in the API section. Scoreboard is a thing. And the Item stack can be removed too

bright dove
#

It is better to call native methods

dawn zealot
#

it doesnt matter breh

solar dagger
#

For now the cmds are fine but I would recommend to update it in the future

dawn zealot
#

its justt a realm that runs perfectly fine with 11 people on it

solar dagger
#

Or if you need help with it just ask here

valid ice
#

Hey have you heard of this thing called native methods, I'm pretty sure they haven't been talked about at all before in the last ten minutes

marsh pebble
dawn zealot
marsh pebble
#

Why

dawn zealot
#

who rly calls it mods nowadays

marsh pebble
#

df

dim tusk
# dawn zealot ?
const totalDamageMilestones = [];
for (let milestone = 250, i = 0; i < 14; i++, milestone *= 2) {
    totalDamageMilestones.push(Math.round(milestone));
}
console.log(totalDamageMilestones);```
dim tusk
dawn zealot
# bright dove I agree

also to make u more mad, whenever an entity kills and entity it spawns an entity to say it, it dies too dw

marsh pebble
valid ice
#

the world modded should be added to automod tbh

valid ice
#

Will bring it up with Sean tomorrow

dawn zealot
marsh pebble
#

The building.

dawn zealot
valid ice
#

Bro is using "hypixel pit elemental" map 😭

dawn zealot
#

i got permisson like 3 years ago to use it

dawn zealot
#

not 2500 nor the next

marsh pebble
dim tusk
#

You probably did it wrong

dawn zealot
#

its set damage breh the image u replied to does not follow the set milestones

#

for example number 8 is 500k damage

dim tusk
#

Hmm

dawn zealot
#

ur number 8 is 32k in the image u sent

dim tusk
#

I mean in the end you can automate it 😝

dawn zealot
#

not when its set damage

dim tusk
dawn zealot
#

coddy is alil goofy today

marsh pebble
#

So What's your fav server you've made guys?

dawn zealot
#

had 40k realm members when realms were peak

dim tusk
#

anyways

#

I need to go back do math wiat

#

Lemme redo the math earlier

dawn zealot
#

i cant find the damn emoji

marsh pebble
dawn zealot
#

😤 there we go

dim tusk
dawn zealot
dawn zealot
#

joking

marsh pebble
#

No like the builds bro

#

idc abt the members

bright dove
#

Galacticraft

dim tusk
#

I want to redo my whole life

dawn zealot
marsh pebble
#

i cant

dawn zealot
marsh pebble
#

no internet

dawn zealot
marsh pebble
#

Hi

bright dove
dawn zealot
marsh pebble
dawn zealot
marsh pebble
dawn zealot
#

the good old days

marsh pebble
#

my eyes

dawn zealot
#

when scoreboards were massive

marsh pebble
#

Why isnt realm code working

#

(jk)

dawn zealot
#

Minecraft Bedrock Edition Top 5 Best Realms 2021 [Xbox One/MCPE,PS4] #18

Hey guys and today I will be going over the top 5 realms for Minecraft Bedrock Edition. These realms will have game modes such as pixelmon, skyblock, and even Factions. Watch the video to the very end to join all the working realms and get their realm codes!

#5 Dynasty Fa...

▶ Play video
#

found it

#

number 4

#

ignore shiftery acting like an npc

marsh pebble
#

My friend has a realm that he won from a giveaway that is locked on a paypal acc that he doesnt have access too and it's for like another 4 years or sum

#

But he's using it for fucking smp

marsh pebble
#

I've actually seen this video b4

dawn zealot
#

lmao W

#

i also owned project prisons too

marsh pebble
dawn zealot
#

not me ^

marsh pebble
#

Wait but didnt you say

#

40k members

dawn zealot
#

on aquiver prisons the club had 40k realm members at one point yeah

marsh pebble
dawn zealot
#

aquiver was peak lock down

#

xbox group posts were the shit

#

man now i wanna remake that prisons

#

fuck sake 6am motivation gonna make me do it

marsh pebble
#

I like xbox groups Bc most ppl on there havent seen much of any good servers other than "skygens" Or "Bedrok boxes"

dawn zealot
marsh pebble
#

They've evolved

#

"Need women" "Who can be my dog" "just talking 17+"

#

oh and like some time in summer the group post were getting botted and xbox didnt fix for like 4 weeks

#

Like 2022 i think

dawn zealot
#

that was pain bruh

valid ice
#

script API where

dawn zealot
#

console.warn(that was pain bruh)

marsh pebble
dawn zealot
#

i wanna remake old realm now

valid ice
marsh pebble
dawn zealot
#

yk on ur chest ui thingy majig

#

how do i change the title font to minecraftten?

marsh pebble
#

🤔

valid ice
marsh pebble
#

Oh yeah does anyone know who the discord user "zoro" is?

#

Tiktok is eaiser getting "follows" on

dawn zealot
marsh pebble
#

One video blows up and you have like 5k+ followers

#

NO

dawn zealot
marsh pebble
#

Im not saying your 20k isnt "impressive" but 15k on youtube is prob more inpresive than "Tiktok"

valid ice
#

#off-topic guys

dawn zealot
#

anyway how do i change it?

valid ice
#

Rocket league ain't script API

dawn zealot
valid ice
#

change what, the topic?

#

no

dawn zealot
valid ice
#

Dunno

dawn zealot
#

...

valid ice
#

I ain't the json UI guy

dawn zealot
#

dumbest but smartest person i ever met

marsh pebble
#

Anyone wanna change my script api

dawn zealot
#

got it but uhhh yeahhh..

#

anyway gn fixed it also 👍

marsh pebble
#

@dawn zealot

#

Do yk any plot addons or like vaults

ivory bough
#

const location = {
y: player.location.y,
x: player.location.x,
z: player.location.z + 2.5
};
How to covert this from ~~~2.5 to ^^^2.5

dull shell
#
  world.afterEvents.playerInteractWithBlock.subscribe((event) => {
    if (event.block.typeId == "jay4x:gold_block") {
      let player = event.player;

    
    event.player?.runCommand(`say interact`);
    }
  })```
I have no errors but this isnt working?
dull shell
#

okay so it works when I place a block on it

marsh pebble
dim tusk
trail marten
#

there's a property player.id for every player. does that mean we could use it to identify them even though if they have changed their gamertag/name?

dim tusk
#

their id is consistent thru worldd

valid ice
trail marten
shut citrus
#

how to check passable block in getBlock method

untold magnet
#

sup, is it possible to detect the entity component group via scripts?

untold magnet
#

so, how am i going to detect if the entity is angry, like detecting angry wolf or angry bee's?

chilly fractal
#

Yo what up bois

#

What should i do today?

dim tusk
#

try using the js world.afterEvents.dataDrivenEntityTrigger.subscribe(ev => { const { entity, eventId } = ev; for (const modifier of ev.getModifiers()) { const { addedComponentGroups, removedComponentGroups } = modifier; } });

amber granite
#

Or just detect whenever player damages that dog

#

u want it universal ?

#
if (entity.hasComponent("minecraft:movement") && entity.hasComponent("minecraft:target")) {
    console.log("Entity is likely in attack mode (angry).");
}
dim tusk
dim tusk
#

either way just use 'target' (beta)

amber granite
#

Trying to get target component

#

So if it s angry it will target someone

#

Like wolf and vex etc...

dim tusk
#

Ok umm, first of all there's no target component second of all why bother checking if entity has movement component

dim tusk
amber granite
#

Sure ?

dim tusk
#

or won't

dim tusk
#

in short inaccurate

chilly fractal
#

I feel like someone who has a little bit of json ui knowledge made a chest ui before

#

I wanna know if there is a chest ui that exists or not...

dim tusk
chilly fractal
#

Guess i should be the first

#

Lmao jk

dim tusk
#

The best example is obviously, Herobrine's one

chilly fractal
dim tusk
chilly fractal
#

What?

dim tusk
chilly fractal
#

Man i feel tired

#

I can't type as fast as i used to a few weeks ago

#

Nah i dont see a chest ui

untold magnet
#

not beta

amber granite
#

Then use entityHurtEntity event

#

And detect

untold magnet
#

detecting if the entity IS angry or not ( just checking if it is possible )

#

||yippie, its raining :D||

chilly fractal
#

Not sure what other ui you are talkin' about coddy

#

I'm so frickin' tired

#

I'm gonna go sleep even tho it's 12pm over here

untold magnet
dim tusk
#

Its probably in the #1046947779118895114 I'll try to find it for you

untold magnet
dim tusk
untold magnet
untold magnet
#

beta or stable?

dim tusk
untold magnet
#

good, i just have to learn how it works exactly

dim tusk
#

fun fact.

#

I used that to detect breeding

#

-# thanks to @distant tulip lmfao

untold magnet
fallow rivet
#
import { world, system } from "@minecraft/server"

world.afterEvents.itemUse.subscribe(data => {
const player = data.source;
const item = data.itemStack;
if (item.typeId == "kaos:grappling_hook") {
const entity = player.dimension.spawnEntity("kaos:grappling_hook", player.location);
entity.addTag(`Grappling:${player.name}`);
}})
#

How can I change the direction the spawned entity is looking towards the player's direction?

ivory bough
#
system.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id == "space:sign1") {
   for (const entity of world.getDimension("overworld").getEntities(typeId: "space:anomaly")) {
     const player = world.getAllPlayers(();
     const message1 = "I am always watching you,";
     const message2 ="Always watch your back,";
     const message3 = "Don't sleep,";
     const random =  Math.floor(Math.random() * 3) + 1;
     const location = entity.location;
    const block = player.dimension.getBlock(location);
    if (random === 1) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message1 + player.name,SignSide.Front);
    };
    if (random === 2) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message2 + player.name,SignSide.Front);
    };
    if (random === 3) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message3 + player.name,SignSide.Front);
    };
   }
  }
});
ivory bough
knotty plaza
knotty plaza
#

And its not typeId, its just type

ivory bough
knotty plaza
#

Also your player variable is actually an array of players

ivory bough
knotty plaza
trail marten
#

this is pretty complex question, but if anyone knows..

#

how many buttons() could an ActionFormData() hold? (@minecraft/server-ui)
and how many options could a dropdown() from ModalFormData() hold?

knotty plaza
untold magnet
untold magnet
#

this will work fine right?

world.afterEvents.dataDrivenEntityTrigger.subscribe(ev => {const {entity, eventId} = ev;
  if (entity?.typeId === 'minecraft:bee') {if (eventId === 'angry_bee') entity?.setDynamicProperty('angry', true); else entity?.setDynamicProperty('angry', false); if (eventId === 'angry_bee' && eventId === 'has_nectar') entity?.setDynamicProperty('angry_nectar', true); else entity?.setDynamicProperty('angry_nectar', false)};
  if (entity?.typeId === 'minecraft:wolf') if (eventId === 'minecraft:wolf_angry') entity?.setDynamicProperty('angry', true); else entity?.setDynamicProperty('angry', false);
});;```![bao_foxxo_smug](https://cdn.discordapp.com/emojis/933257119443071027.webp?size=128 "bao_foxxo_smug")
fading sand
#

Anyone have an example code for an sneak input event signal?

ivory bough
#
system.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id == "space:sign1") {
   for (const entity of world.getDimension("overworld").getEntities({ type: "space:anomaly" })) {
     const player = world.getAllPlayers();
     const message1 = "I am always watching you,";
     const message2 ="Always watch your back,";
     const message3 = "Don't sleep,";
     const random =  Math.floor(Math.random() * 3) + 1;
     const location = entity.location;
     const block = entity.dimension.getBlock(location);
    if (random === 1) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message1 + player.name,SignSide.Front);
    };
    if (random === 2) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message2 + player.name,SignSide.Front);
    };
    if (random === 3) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message3 + player.name,SignSide.Front);
    };
   }
  }
});

This doesn't work for some reason

grim raft
#

so this error appears from here:
[Scripting][error]-TypeError: Native type conversion failed. Function argument [0] expected type: EntityQueryOptions | undefined at <anonymous> (main.js:92)

const graveEntity = dimension.getEntities('bleach:corpse')```
unique dragon
grim raft
#

ty it worked

grim raft
#

the x, y, z

unique dragon
#

or what u mean

grim raft
#

if its even possible

unique dragon
#
const graveEntity = dimension.getEntities({ type: 'bleach:corpse', location: { x, y, z } });
#

use also the maxDistance filter

grim raft
#

hm?

#

never heard of it

unique dragon
#
const graveEntity = dimension.getEntities({ type: 'bleach:corpse', location: { x, y, z }, maxDistance: 1 });
#

like that

grim raft
#

what does it do?

unique dragon
#

it only gets the entities in a certain distance, if you want only in that coords, it could be 1 block distance

unique dragon
fallow rivet
#

Can't I change the direction an entity is facing with a script?

grim raft
#

now this is saying thats its not a function

unique dragon
knotty plaza
unique dragon
knotty plaza
#

That means the first element in the array

unique dragon
grim raft
#

k ty guys

unique dragon
#

👍

fallow rivet
#
function grapplingUse(player) {
const entity = player.dimension.getEntities({tags: [`Grappling:${player.name}`],})[0];
}

I'm trying to make the player jump to the location where the entity is, but it doesn't work.

#

I want to do it like this but it doesn't work

knotty plaza
fallow rivet
#
function grapplingUse(player) {
    const entity = player.dimension.getEntities({ tags: [`Grappling:${player.name}`] })[0];
    if (!entity) return;

    const px = player.location.x, py = player.location.y, pz = player.location.z;
    const ex = entity.location.x, ey = entity.location.y, ez = entity.location.z;

    const dx = ex - px, dy = ey - py, dz = ez - pz;
    const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
    if (distance === 0) return;

    const horizontalDistance = Math.sqrt(dx * dx + dz * dz);
    const fx = horizontalDistance > 0 ? (dx / horizontalDistance) : 0;
    const fz = horizontalDistance > 0 ? (dz / horizontalDistance) : 0;
    const fy = dy / distance;

    const force = Math.min(distance * 1.2, 4);
    const horizontalForce = force * 0.7;
    const verticalForce = force * 0.5 + 0.3;

    player.applyKnockback(fx, fz, horizontalForce, fy * verticalForce);
    entity.remove();
}
#

I did this with AI

#

But it still didn't work as well as I wanted, so I deleted everything.

chilly fractal
cold grove
fallow rivet
#

When you say obstacle, do you mean blocks?

ivory bough
#
system.afterEvents.scriptEventReceive.subscribe((event) => {
  if (event.id == "space:sign1") {
   for (const entity of world.getDimension("overworld").getEntities({ type: "space:anomaly" })) {
     const player = world.getAllPlayers();
     const message1 = "I am always watching you,";
     const message2 ="Always watch your back,";
     const message3 = "Don't sleep,";
     const random =  Math.floor(Math.random() * 3) + 1;
     const location = entity.location;
     const block = entity.dimension.getBlock(location);
    if (random === 1) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message1 + player.name,SignSide.Front);
    };
    if (random === 2) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message2 + player.name,SignSide.Front);
    };
    if (random === 3) {
    block?.setType("standing_sign");
    const signComponent = block?.getComponent("minecraft:sign");
    signComponent?.setText(message3 + player.name,SignSide.Front);
    };
   }
  }
});

This doesn't work for some reason. The sign isn't being placed at the entity's location

cold grove
chilly fractal
#

Why does everyone use world.getAllPlayers tho

chilly fractal
cold grove
ivory bough
#

Then [0]?

chilly fractal
#

And both do the exact same except you can pass params in world.getPlayers()

#

Ye

#

But actually

#

That would do for one player

cold grove
#

also you dont have any reference to determinate wich player you want to target

fallow rivet
#

applyImpulse not working for player?

chilly fractal
#

so either:

for (const player of world.getPlayers()) {
  // code with "player"
}```
cold grove
chilly fractal
ivory bough
fallow rivet
chilly fractal
chilly fractal
#

[0] is the most straightforward approach but in the long run, it wouldn't hurt to use a for loop

cold grove
chilly fractal
ivory bough
chilly fractal
#

.getPlayers() allows for passing entity params, while .getAllPlayers() only returns an array, anyhow, both return an array.

knotty plaza
chilly fractal
#

Fr

chilly fractal
knotty plaza
#

I think they getPlayers used to return an interator instead of an array

ivory bough
chilly fractal
#

But you need to learn about js basics

cold grove
#

here not, maybe your other code you iterated them or selected the first element of the array [0]

chilly fractal
#

Like arrays

#

And you will need to learn about scripting api

ivory bough
chilly fractal
#

I'm fixing it for u

#

Sorry i was away

#

I'll fix it now

marsh pebble
#

Any 1 here good at coding

wary edge
drifting ravenBOT
marsh pebble
#

Okay

chilly fractal
# chilly fractal I'll fix it now
const messages = [
  'I am always watching you..',
  'Always watch your back..',
  'Don\'t sleep..'
];

system.afterEvents.scriptEventReceive.subscribe((event) => {
  if (!event.id.startsWith('space:')) return;
  switch (event.id.split(':')[1]) {
    case 'sign1': {
      for (const entity of world.getDimension('overworld').getEntities({ type: 'space:anomaly' })) {
        const player = entity.dimension.getEntities({type: 'player', closest: 1, location: entity.location})[0];
        const random = Math.ceil(Math.random() * messages.length) - 1;
        const block = entity.dimension.getBlock(entity.location);
        block?.setType('standing_sign');
        block?.getComponent('minecraft:sign')?.setText(`${messages[random]}, ${player.name}`, SignSide.Front);
      }
      break;
    }
    default:
      console.error('Invalid Event Requested.');
      break;
  }
});```
@ivory bough
#

But you must learn js basics

#

I just saved your time a bit

ivory bough
chilly fractal
#

Or actually alot, but again, you must absolutely learn js basics no matter what

ivory bough
marsh pebble
#
import { world } from "@minecraft/server";

const COMMAND_PREFIX = '/';
const overworld = world.getDimension("overworld");

function runCommandAsync(command: string) {
    overworld.runCommandAsync(command);
}

world.beforeEvents.chatSend.subscribe(event => {
    const player = event.sender;
    const message = event.message;

    if (!message.startsWith(COMMAND_PREFIX)) {
        const command = message.replace(COMMAND_PREFIX, '');
        event.cancel = true;

        switch(command) {
            // command: checkblock
            case 'checkblock': {
                const playerPosition = player.location;
    
                try {
                    const blockBelow = player.dimension.getBlockBelow(playerPosition);
                    const blockToCheck = "minecraft:end_portal_frame";
        
                    if (blockBelow && blockBelow.typeId === blockToCheck) {
                        runCommandAsync(`/function locationID`);
                    } else {
                        // no block have been found
                    }
                } catch (err) {
                    console.error(err);
                }
                break;
            }

            case 'test': {
                // test
                break;
            }

            default: {
                player.sendMessage(`No such command: ${command}`);
            }
        }
    }
});;```
celest abyss
#
world.getAllPlayers().forEach(players => {
players.playSound(`random.fuse`,)
       })

This should play a sound for all players right?

marsh pebble
#

Not my code.

chilly fractal
ivory bough
marsh pebble
#

Search up a youtube tut for MINECRAFT

chilly fractal
chilly fractal
marsh pebble
#
    runCommandAsync(`function locationID`);```
chilly fractal
ivory bough
chilly fractal
#

You don't need them tho

#

Only watch until about hour 6 or smth

ivory bough
ivory bough
chilly fractal
#

So use a different syntax other than "/"

chilly fractal
ivory bough
chilly fractal
#

Also even if he uses web apis, you only need to look after the stuff like "+=" and other pure js stuff

marsh pebble
#

Instead of

import { world } from "@minecraft/server";

const COMMAND_PREFIX = '/';
const overworld = world.getDimension("overworld");```
Would it be
```JS
import { world } from "@minecraft/server";

const overworld = world.getDimension("overworld");```
marsh pebble
chilly fractal
marsh pebble
#

Hm no.

#

The code is suppose to run a function command when someone is standing on the block.

#

But it's way too chopped

chilly fractal
#

I gotta bounce

marsh pebble
#

Bye

chilly fractal
#

Remember, native methods exist

#

Cya

fallow rivet
#

Is it possible to make applyImpluse work for the player?

coral ermine
#

Is it true that if we use return Inside a loop, it stops running for everyone?

distant tulip
#

yeah, it break from the loop

#

use continue

coral ermine
#

ty

dull shell
#
  world.afterEvents.playerInteractWithBlock.subscribe((event) => {
    if (event.block.typeId == "jay4x:gold_block") {
      let player = event.player;

    
    event.player?.runCommand(`say interact`);
    }
  })```
why does this only work when I place a black on it
wary edge
marsh pebble
#

How whould i go about making it if someone walked or stood on a block a command would run

coral ermine
#

Why player.dimension.getBlockBelow() not detecting water?

unique dragon
#
getBlockBelow(location: Vector3);
distant tulip
#

-# includeLiquidBlocks

unique dragon
#

yup

dull shell
#
  world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    if (event.block.typeId == "jay4x:monitor") {
      let player = event.player;

    event.player?.runCommand(`say interact`); *LINE 62*
    }})```
unique dragon
dull shell
#
  world.beforeEvents.itemUse.subscribe((data) => {
    const player = data.source;
    switch (data.itemStack) {

        event.player?.runCommandAsync(`scoreboard players add @s MoneyStolen 150`);
    }});```
#

wait thats itemUse im trying to interact with a block

wary edge
marsh pebble
#
import { world, system } from "@minecraft/server";

console.log("loaded")

system.runInterval(() => {
    for (const player of world.getPlayers()) {
        const blockLocation = player.location;
        blockLocation.y -= 1;
        const block = player.dimension.getBlock(blockLocation);
        if (block && block.typeId === "skygen:plotp") {// change this to the block eg minecraft:gold_block
            player.runCommandAsync("function locationID")// anything you put in here it will run eg a console.log or in you case the CommandRunning
        }
    }
}, 20);// the '20' is the tick delay```
No work
sterile epoch
#

I think it's the block location.y-=1 because you're trying to reassign something that can't be reassigned

sweet seal
#

How to give a player a dynamic property every 15 ticks if they stand at a certain location without causing lag?

sweet seal
#

well how could i make it

knotty plaza
#

That should not be the problem

knotty plaza
#

If nothing appears on the screen, that means your script is not even being used

marsh pebble
knotty plaza
#

Not exactly, but you can edit the script and it will be applied in game after /reload

#

But your pack has to be inside development_behavior_packs

cold grove
marsh pebble
#

i got it dw

untold magnet
marsh pebble
#

ik why mine isnt working

#

it's "/function locationDB"

untold magnet
marsh pebble
#

njo

#

i misspelled it

#

i put it as "locationID" instead of "locationDB"

sweet seal
#

How to give a player a dynamic property every 15 ticks if they stand at a certain location?

untold magnet
sweet seal
untold magnet
sweet seal
#

i want 3 different gens with different times

#

but id have to do multiple intervals for that

amber granite
#

Yao

untold magnet
#
let count = 0;

system.runInterval(() => {
  count++;
  if (count %100 === 0) { }; // 1s & 20 ticks
  if (count %50 === 0) { }; // 0.5s & 10 ticks, do %75 if u want to make it works every 15 ticks
});;```
round bone
wary edge
round bone
#

I think we should listen to a king of brain rot

#

@last latch

last latch
round bone
#

These sigmas are giving ratio L's to other beacuse there are too many alphas associated with this thread

plucky light
#

This picture is on the bedrock wiki. What app is is? Seems like it might be useful

drowsy scaffold
#

how do I get an authtoken to send HTTP requests with?

still torrent
cold grove
#

in general you dont need tokens to make requests

drowsy scaffold
#

there we go

cold grove
#

You can build a http server that doenst require auth

drowsy scaffold
#

😭 well that's definitely useful to know

#

this is my first time dipping into server-net and HTTP so it's very new to me

#

well not first but first beyond just copy-pasting

cold grove
drowsy scaffold
marsh pebble
#

How whould i do something like :
/scoreboard players operation ${selectedplayer} locationID1 = ${mainplayer} locationID

tawny jungle
#

why do i get a not a function error with if (block.isValid())?

tawny jungle
#

ah

#

thanks

thorn flicker
wary edge
shut citrus
#

how to get passable block at a location

tawny jungle
# wary edge `.isValid`.

its been saying trying to access location ... which is not in a chunk currently loading or ticking i only want the function to run when its in simulation distance

chilly fractal
chilly fractal
# shut citrus how to get passable block at a location
try {
  const block = (dimension).getBlock({x: 0, y: 0, z: 0});
  if (!block.isValid) return; // assuming it is used in a function & you are on preview, however if you are not on preview use .isValid()
  if (!block.isAir || !block.isLiquid) return;
  // block is passable probably.
} catch {
  console.log('Block is unloaded or minecraft is smoking crack or you are coding at 3am and forgor to edit the script accordingly.');
}```
shut citrus
celest abyss
#

closeAllForms is beta?

chilly fractal
chilly fractal
# shut citrus what about tall grass and others?

just edit the if statement to:
if ((!block.isAir || !block.isLiquid) && !passableBlocks.includes(block.typeId)) return;

And define an array named passableBlocks and add all typeIds of passable blocks.

unique acorn
#

its in server-ui 1.3.0

#

so it isn't

deft nest
#
import { system, world } from '@minecraft/server';
import { ChestFormData } from './extensions/forms.js';

world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
  const { player, block } = event;
  if (block.typeId === 'minecraft:iron_block') {
    testGui(player);
  }
});
function testGui(player) {
  new ChestFormData('9')
  .title('Test Gui')
  .button(0, 'Back', ['', 'Back Button', ''], 'minecraft:arrow')
  .button(8, 'Next', ['', 'Next Button', ''], 'minecraft:arrow')
  .show(player).then(response => {
    if (response.canceled) return;
  });
}```
#

@valid ice When I click on the block, the GUI does not open, what is the problem?

#

I think it's not your addon but I couldn't find it.

wary edge
radiant drumBOT