#Script API General

1 messages · Page 95 of 1

distant tulip
#

Need a different animation for each perspective

chrome gyro
#

I have to rig it up through an attachable?
I'm just playing the animation direction from a command. Shouldn't the arm move regardless? Or is it named different in FP... Im'a check.

distant tulip
#

Need me to send it?

chrome gyro
#

Actually I think I got the values from you XD. Coddy posted it a long time ago, and I searched and found it. He said it was your values:

{
    "format_version": "1.8.0",
    "animations": {
        "animation.cnb_ppl_swing": {
            "loop": true,
            "animation_length": 0.2917,
            "bones": {
                "rightArm": {
                    "rotation": {
                        "0.0": [0, 0, 0],
                        "0.0833": [-5.41199, 23.06265, 5.38894],
                        "0.125": [-13.31634, 36.7612, 56.32978],
                        "0.1667": [-58.11073, 6.44931, 8.72102],
                        "0.25": [-28.77157, -5.28699, -10.94791],
                        "0.2917": [0, 0, 0]
                    }
                },
                "leftArm": {
                    "rotation": {
                        "0.0417": [-8, 0, 0],
                        "0.1667": [-16, 0, 0],
                        "0.2917": [-8, 0, 0]
                    }
                },
                "body": {
                    "rotation": {
                        "0.0417": [0, 0, 0],
                        "0.1667": [0, 7.5, 0],
                        "0.2917": [0, 0, 0]
                    }
                }
            }
        }
    }
}
#

So I guess... thank you haha.

#

I had one before that was pretty bleh and not accurate, so thanks for that!

#

It's strange that it doesn't play in first person hmm.

#

Maybe it needs position and not rotation?

distant tulip
#

Yeah, lol
Used it in my addon and replay craft yoinked it too

#

Maybe sit it to override

valid ice
#

Planning to do so soon!

distant tulip
#

It is hard to deal with dups when setting items tho

chrome gyro
#

Tried position that didn't do anything.

distant tulip
#

no, the override property in animations

chrome gyro
#

Ooooh the bool property thingy. Got it.

That ok if I use this for my future animations?

distant tulip
chrome gyro
#

Yikes, sorry. Yeah, I usually don't copy paste unless I fully understand it, then I change it to the way I want it just to save time. But yeah no one should have their stuff stolen.

Hmm that didn't work, I tried changing some of the components for the item too, I think attachable might be the only way.

distant tulip
#

you don't have any other animation, right?

chrome gyro
#

So replacing last animation would only remove any hidden ones from vanilla, but I dont' think there are any.

distant tulip
#

weird

chrome gyro
#

Yeh, the only thing I can think is it's not carrying the variable to do it in first person... but Idk if that makes sense either.

#

I'm going to keep messing around with the "animation_controllers" part of the command and see if I can get soemthing to work. I'll let you know if I do.

abstract cave
#

Playerinteractwithentity after event doesnt work for me for some reason

#

im using it correctly too

#

no errors

#

i only get response when i use before event

#

but that comes with its own set of issues

fallow minnow
#

oh

abstract cave
fallow minnow
#

nu uh

neat hazel
#

Is it possible to disable scripted damage?
For example: if the player has a TAG and is attacked, the damage is canceled

fallow minnow
#

yeah but not through scripts

#

use uh

#

player.json

#

or i imagine u could like

#

nvm

neat hazel
leaden elbow
#

can i use server-net on 1.21.90

fallow minnow
#

yeah

leaden elbow
#

what version of the module

#

1.0.0-beta?

fallow minnow
leaden elbow
#

ok thanks

little hull
#

how do i make it so that any system.runtime out inside an if statement will keep running until finished like when i exit the game and rejoin the system will re run

slim forum
#
world.afterEvents.scriptEventCommandMessage.subscribe(event => {
  const player = event.sourceEntity;
  if (event.id === 'player_breaking_block') {
    const block = player.getBlockFromViewDirection();
    if (block) meleeAttackControllers(player, true);
  }
});```

What is going?
jagged gazelle
#

run it in the next available tick by using system: run(), runInterval() or runTimeout()...

#

-# yes, very late response.

jagged gazelle
#

It's in the name, afterEvents or beforeEvents

slim forum
#

scriptEventReceive is not working for me too

jagged gazelle
#

it would never go after since the entity isn't interactable.

jagged gazelle
#

not world.

slim forum
#

Oh, thanks

#

After years, is my first time using scriptevent command

abstract cave
wary edge
little hull
rose light
#

Is there any way to check if a block has been destroyed without me having to constantly check it? For example, I want to detect the blocks that an entity broke; is there a way to do this?

jagged gazelle
jagged gazelle
#

Sorry

little hull
rose light
#

But isn't there a way to detect this?

shy leaf
#

just telling you that checking hotbar change via runInterval is faster than the event

#

it was tested back in preview so i dunno if thats still the case now

jagged gazelle
stark kestrel
#

Is it possible to stop EVERY SINGLE SOUND, even the mining or whatever with scripts, or if you know any other way?

sharp elbow
#

Use a resource pack to disable every sound.

stark kestrel
ivory bough
little hull
#

its safe to use player.name cause the game does not allow a player with the same name

vast grove
#

use player.id if ya wanna store things for each unique player

little hull
vast grove
#

no

little hull
#
const playerName = player.id;
      const entity = player.dimension.spawnEntity("mz:smile", spawnPos);
      if (entity) {
        entity.addTag(`owner_${playerName}`);
        player.teleport(player.location, { facingLocation: entity.location });
        entity.teleport(entity.location, { facingLocation: player.location });
        player.addTag("logic_done");
      }```  this is the summoning logic where i form a bond between the entity and the player
#

world.afterEvents.entityDie.subscribe(({ damageSource: { damagingEntity }, deadEntity }) => {
if (deadEntity.typeId !== 'minecraft:player' || !deadEntity.hasTag("finalDay")) return;

const ownerTag = `owner_${deadEntity.id}`;
const dimension = deadEntity.dimension;
const nearbySmiles = dimension.getEntities({ type: "mz:smile" });

const center = getArenaCenter(); 
if (!center) return;

for (const smile of nearbySmiles) {
  if (smile.hasTag(ownerTag)) {
    smile.triggerEvent("mz:possesing");
    smile.clearVelocity;
    smile.teleport(center, dimension);
    deadEntity.addTag("possesion");
    break;
  }
}
});```  this is how i use it and it is not working why?
vast grove
#

define it's not working. Do you get any errors?

halcyon phoenix
#

can you edit starting variable on particles using setFloat on molangVariableMap?

little hull
vast grove
#

Did you try printing out variables to see if you're using the right variables?

little hull
#

oh i found out the issue its the way i stored the location of arena center thats why lots of function is not working

vast grove
#

Also is there a reason you're using tags instead of dynamic properties?

little hull
#
export let arenaCenter = null;

export function setArenaCenter(center) {
  arenaCenter = center;
}

export function getArenaCenter() {
  return arenaCenter;
}```
little hull
vast grove
#

what type is arenaCenter

little hull
vast grove
#

store it. either on the player or on the world

#

using a DP

#

If you have multiple well then you're gonna have to write your own loading manager

#

I'm making proximity voice chat. I don't have time to work on other things

little hull
#

oh okay thanks for helping

halcyon phoenix
#

TIL that molangVariableMap basically just sets a new variable in a particle you don't need to add a startingVariable

jagged gazelle
#

ok quick question guys

#

In debug shapes, in the constructor it has location object but it also has a property setting the location object too, what's the difference?

#
const box = new DebugBox({ x, y, z });
box.location = { x, y, z };```
halcyon phoenix
#

molang is piece of packed up thins

you're gonna set a

const rgb = {red: 0, green: 0, blue:0}
molang.setColorRGB("colors", rgb);

then inside the particle:

#

mojang is an incosistent piece of crap

jagged gazelle
distant tulip
ivory bough
#

How to change player's rotation to up,down,left and forward relative to the world

little hull
#

how do i set the gamemode of player to hardcore trhough scripts?

marsh pebble
#

anyone know how to remove the blocked message in discord?

vast grove
#

You can do a similarly implemented version yourself but tbh there's not much of a point

little hull
# vast grove You can't

i have this addon with an outro scene and i wanna end it like game over where the player can play anymore gues ill just use spectator mode and some functions

vast grove
#

Force set the player to spectator then smilee

shy leaf
halcyon phoenix
halcyon phoenix
#

my bad

vast grove
#

Long time iirc

jagged gazelle
#

Who freaking pinged me.

#

Like damn stop.

lapis heart
#

player.applyImpulse Which script version does it work on?

sterile epoch
#

you can probably use runCommand with that

lapis heart
sterile epoch
#

oh you meant hardcore

#

I read it as hard

#

mb lol

little hull
sterile epoch
#

ye ik

inland merlin
#

We talking difficulty, hardcore im not sure

stark kestrel
#

we cant know if a player stopped mining a block right?

#

nor how much it was broken like a %

#

right?

halcyon phoenix
#

there is no way to check if a block is being mined and the progress of it being mined, iirc there's no event for it nor a poperty on a block

stark kestrel
#

thanks tho

loud frigate
#

Hackyly

halcyon phoenix
#

I don't know if you can check the mining animation

#

if you can do that then you can surely do it

loud frigate
#

Start a timer once player starts punching which there's an event for

#

I think at least

#

But yeah actually could be very tricky so yeah I'll too say no

halcyon phoenix
loud frigate
#

Like you usually do in bedrock

halcyon phoenix
loud frigate
#

Those at least are on the wiki, can just copy those with a script and add them in

#

Unlike literally every other block property that requires more painful hardcoding like hitbox, replaceable, survivability and whatnot

halcyon phoenix
#

yep just manually add the toughness of more than 500 blocks

loud frigate
#

Nah not manually I said with a script

halcyon phoenix
halcyon phoenix
loud frigate
#

That's what the script is for, you send doing your job as a programmer properly if you don't automate the tedious tasks that can be easily automated

stark kestrel
distant tulip
grim pasture
#

100,000 msg!

distant tulip
#

let's go!

gilded shadow
#

how to load and unload chunks manually via scripting

marsh pebble
#

im the 100k message

#

yay

marsh pebble
jagged gazelle
grim pasture
#

can @mental shadow check out my horror game cmds in the develpment

whole axle
#
const tracks = [
  { id: "background_music.1", duration: 55, repeat: 3 },
  { id: "background_music.2", duration: 21, repeat: 6 },
  { id: "background_music.3", duration: 19, repeat: 6 },
  { id: "background_music.4", duration: 26, repeat: 6 },
];

const tracked = new Map();

function getRandom(exclude) {
  const list = exclude ? tracks.filter(t => t.id !== exclude) : tracks;
  return list[Math.floor(Math.random() * list.length)];
}

function playTrack(p, track, remaining, lastTrack) {
  if (!world.getPlayers().some(pl => pl.id === p.id)) return;

  try {
    p.playSound(track.id);
  } catch {
    system.runTimeout(() => playTrack(p, track, remaining, lastTrack), 20);
    return;
  }

  if (remaining > 1) {
    system.runTimeout(() => {
      if (!world.getPlayers().some(pl => pl.id === p.id)) return;
      if (p.getDynamicProperty("music_track") === track.id) {
        playTrack(p, track, remaining - 1, lastTrack);
      }
    }, track.duration * 20);
  } else {
    let next;
    do {
      next = getRandom(track.id);
    } while (next.id === lastTrack);

    p.setDynamicProperty("music_track", next.id);
    playTrack(p, next, next.repeat, track.id);
  }
}

world.afterEvents.playerSpawn.subscribe(e => {
  if (!e.initialSpawn) return;
  const p = e.player;
  tracked.set(p.id, { lastLoc: p.location });
});

#
system.runInterval(() => {
  for (const [id, { lastLoc }] of tracked) {
    const p = world.getPlayers().find(p => p.id === id);
    if (!p) {
      tracked.delete(id);
      continue;
    }

    const curr = p.location;
    if (curr.x !== lastLoc.x || curr.y !== lastLoc.y || curr.z !== lastLoc.z) {
      tracked.delete(id);
      const current = p.getDynamicProperty("music_track");
      const startingTrack = current
        ? tracks.find(t => t.id === current) ?? getRandom()
        : getRandom();

      p.setDynamicProperty("music_track", startingTrack.id);
      playTrack(p, startingTrack, startingTrack.repeat);
    }
  }
}, 5);

My background music works fine, but one issue. Whenever you're in the pause menu you don't hear it, but the ticks are still running and going on to play the next song.

#

How can I fix this?

sullen ocean
whole axle
sullen ocean
#

Okay, so you need to detect when the game gets paused and pause your music player.

sullen ocean
sullen ocean
#

It is beyond my knowledge for how to detect it. I still need to [re-]learn how Add-ons work.

woven loom
sullen ocean
#

Apparently system.runTimeout does not pause when the game is in a paused state.

sullen ocean
# whole axle yes
  1. Does the music go silent when you open the menu or does it actually pause?
  2. Does the music track get abruptly cut off at the end if you had it paused?
wary edge
sullen ocean
#

runInterval has a value of 5... is that in seconds?

woven loom
#

ticks

#

also, why would the server pause

sullen ocean
wary edge
sullen ocean
#

And what Smokey stated.

woven loom
#

ig only client pauses

whole axle
sullen ocean
#

And I assume it resumes when unpaused?

whole axle
#

Yes

woven loom
#

u can use Date.now() to detect pauses then

sullen ocean
#

Doesn't Date.now() always change?

woven loom
#

ye

wary edge
woven loom
#

If he wants to detect pauses that is one way.

wary edge
#

Intriguing.

sullen ocean
wary edge
sharp elbow
#

Hm, that would test a different edge case.

sullen ocean
#

Try setting it to a more manageable time so you can check if it just postpones the timer until the user finally unpauses the game.

sharp elbow
#

I would expect that, if the interval is 50 ticks, and the user waits X ticks before pausing, then after unpausing the interval should wait the remaining 50 – X ticks before invoking the callback

#

The duration that they paused for, Y, should be irrelevant

woven loom
#

Try using wait ticks maybe

sullen ocean
#

I recall that setTimeout and setInterval on web browsers will queue their callbacks to run when it is next possible (so if the user had an alert / prompt / confirm open, it would just wait until it is finally dismissed, and then trigger.

#

It is possible that they can be doing the same.

woven loom
#

They are flushed at the end of the tick.

sharp elbow
#

I would expect that, since those methods operate on ticks, they would be of the same measure as currentTick on System

sullen ocean
woven loom
#

hm

shut vessel
#
function start() {
  for(let i = 10; i < 0; i--){
  system.runTimeout(()=>{
    if(i==0) { 
  const startstart = getScore("start", "start", true);
  const starts = ["scoreboard players set start1 start 1",]
  system.run(()=>{
    starts.forEach(start => {
        try {
          world.getDimension('overworld').runCommand(`${start}`);
          if (startstart == 0) {
          f.role();
          f.startGame();
        }
        } catch (error) {
          console.error(`Erreur d'execution ! executer les commandes suivantes : "${start}":`, error);
        }    
    })})
  return  runCommand(`title @a title §6§lBon Jeu !`)
  } 
    runCommand(`title @a title §6§l${i}`)
  },20)
}
  }```

```js
export async function config(player) {
  new ActionFormData()
    .title("Menu")
    .body(`§8Bienvenue §e${player.nameTag} §8Que voulez vous faire ?`)
    .button(`§8Controle Game`,'textures/ui/darkness_effect')
    .button(`§8Config In-Game`,'textures/ui/free_download')
    .button(`§8Activer/désactiver des évènements`,'textures/ui/darkness_effect')
    

    .show(player)
    .then((r) => {
      if (r.selection == 0) controle(player);
      if (r.selection == 1) ingame(player);
      if (r.selection == 2) activation(player);
    });
}
export async function controle(player) {
   new ActionFormData()
  .title(`Menu Controle`)
  .body(`Que voulez-vous faire ?`)
  .button(`Start`,'textures/items/potion_bottle_splash_saturation')
  .button(`Destart`,'textures/ui/equipped_item_border')

  .show(player).then((r) => {
    if (r.selection === 0) {
     player.sendMessage(`§aVous avez start la partie !`);
     f.start();
    }
           if (r.selection === 1) {
           player.sendMessage(`§aVous avez stoppé le start la partie !`);
           f.destart();
    }
  });
}```
#

Hi, I wanted to know what was wrong with my code. Basically, what I want is for the function to run as a game start so I can launch the game.

sullen ocean
#

Also, I see some places where a semicolon is at and others where you completely omitted it.

shut vessel
sullen ocean
#

First, lets go over the function start() { ... } you made...

#
  • You first do a for loop 10 times.
  • You then queue another function to run after 1 second.
  • It immediately goes and repeats the loop until the 10 times are over.
    The tick ends...
tardy pivot
#

sad to know theres no faceLocation on beforeOnPlayerPlace

sullen ocean
#

All 10 callbacks are queued to happen on the same tick... I don't understand why you are expecting them to be one second apart.

#

system.runTimeout() adds a function to call in the future after a specific number of ticks have happened -- It is not a "wait" / "delay"

shut vessel
#

it's to do a 10 second descending countdown

sullen ocean
#

Nope...

#

When start is called, it adds the function 10 times and tells each one to "run after 20 ticks have elapsed", then start exits.
After that 20 ticks have passed, all 10 of them trigger, one after the other.

shut vessel
#

What is wrong with that?

sullen ocean
#

system.runTimeout runs immediately, but the function inside of it is put off until later.

#

Meaning you rapid-fire 10 system.runTimeout calls on the same tick, then after 20 ticks, every one of them fires back-to-back.

shut vessel
#

yes that's it I want

sullen ocean
#
  1. start() is called.
  2. 10 nearly-identical functions are queued to run exactly 20 ticks after the current tick.
  3. start() ends.
  4. The game can now process other calls happening on the same tick.
  5. The game can now process other ticks before then.
  6. 20 ticks pass and the every one of them are called.
sullen ocean
shut vessel
#

ahhh ok I understand better, well honestly I don't know how to do that I'll admit to you

#

to count down and then activate another function

valid ice
#

If you want it to increase delay between each run of the for loop, you’d have to multiply the 20 ticks by the current index of the loop, so it increases the time for every callback

sullen ocean
valid ice
#

Assuming minimal modifications to existing code is wanted, multiplying by the loop index would do so

#

Fixing something broken is what they asked, and there ya go

Optimizing it, on the other hand

sullen ocean
#

I'd say learning JavaScript better should be the primary goal before continuing... so I won't help further on this task.

shut vessel
#

Isn't the server's principle to help you progress?

buoyant canopy
#

does getEquipment work on obtaining a horse saddle?

#

or should i use commands

jagged gazelle
buoyant canopy
prisma shard
#

GUYS I BROKE MINECRAFT
-# jk i didnt
-# it happened bcuz of my stupid code

#

😂

hazy nebula
#

bruh try system.run

rustic ermine
#

any ideas why this is causing a stack overflow? I am clearly guarding against that in two ways. been trying to figure it out for almost an hour now

world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    if (!event.isFirstEvent) { return; }

    const player = event.player
    if (!player.canInteractWithBlock) {
        return;
    }
    console.warn(event.block.typeId)
})

Object.defineProperties(Player.prototype, {
    blockInteractCooldown: {
        get() { return this['blockInteractCooldown'] },
        set(cooldown: number) { this['blockInteractCooldown'] = cooldown }
    },
    canInteractWithBlock: {
        get() {
            return playerCanInteractWithBlock(this)
        }
    }
})

export function playerCanInteractWithBlock(player: Player): boolean {
    if (player.blockInteractCooldown > Date.now()) { return false; }
    player.blockInteractCooldown = Date.now() + 500;
    return true;
}
#

it's acting like none of the guards are working

#
        get() { return this['blockInteractCooldown'] },

is line 7 in the JS output.

            return playerCanInteractWithBlock(this);

line 14

    canInteractWithBlock: {

12

halcyon phoenix
remote oyster
# rustic ermine it's acting like none of the guards are working

The problem is here:

Object.defineProperties(Player.prototype, {
    blockInteractCooldown: {
        get() { return this['blockInteractCooldown'] },
        set(cooldown: number) { this['blockInteractCooldown'] = cooldown }
    },

The following line calls the getter recursively, because you're referencing blockInteractCooldown inside its own getter.

return this['blockInteractCooldown']

When player.blockInteractCooldown is accessed, it calls the getter. Inside the getter, this['blockInteractCooldown'] is used, which again accesses the getter. So it recurses indefinitely until it overflows: get()this[...]get() → ...

Similar behavior is happening with your setter too. You're not guarding against recursion because your getter/setter access themselves.

rustic ermine
#

I see. I didn't realize what ['foo'] was actually doing. Pretty new to TS.. mainly a rust dev. That makes sense now I think. So, defining the prototype / d.ts interface is essentially doing the same thing as ['foo'] which is causing recursion in that specific scenario because they are named the same thing?

#
export function playerCanInteractWithBlock(player: Player): boolean {
    if (player['blockInteractCooldown'] > Date.now()) { return false; }
    player['blockInteractCooldown'] = Date.now() + 500;
    return true;
}

was my previous code, was just trying to make it cleaner lol

remote oyster
#

In JavaScript/TypeScript:

this['blockInteractCooldown']

…is exactly the same as:

this.blockInteractCooldown

They both invoke the getter if one is defined. So when you define:

Object.defineProperty(Player.prototype, 'blockInteractCooldown', {
    get() { return this['blockInteractCooldown'] }
})

You're effectively saying:

When someone accesses player.blockInteractCooldown, call this function, which returns player.blockInteractCooldown.

An Infinite loop.

rustic ermine
#

Perfect. Thank you for explaining that. Makes complete sense.

#

I'm not sure why, probably lack of sleep, was assuming that obj['foo'] was setting something else.

remote oyster
#

Recursion can be a pesky little thing. Especially when you anticipate your code to behave a different way so it doesn't make blatant sense at first lol.

rustic ermine
#

Yeah, expecting it to work how you planned it out definitely hurts the troubleshooting lol. And the JS stack traces don't help a ton, but looking at them now make sense in this context 🙂

#

rust / cargo errors have spoiled me

remote oyster
#

Lol

rustic ermine
#

I am really surprised how nice TS is though. Is making me want to give Deno a try lol

remote oyster
#

TS is good. I personally can't find myself writing in JS unless I use TS.

rustic ermine
#
Object.defineProperties(Player.prototype, {
    _block_ICD: {
        value: Date.now(),
        writable: true,
    },
    blockInteractCooldown: {
        get() { return this._block_ICD; },
        set(cooldown: number) { this._block_ICD = cooldown }
    },

easy fix. thanks again

#

vanilla JS is masochism. there's really people out there getting paid to write that.

#

one of my coworkers is doing a python class at the moment and I've been helping him at points and it blows my mind that there are widely used languages that just... dont have any concept of types

remote oyster
#

Yea, they have attempted to patch things up in Python a little bit since 3.5 after the devs realized it's limitations.

#

Can implement optional typing with some additional tooling.

rustic ermine
#

it's a good language for smaller scripting. he's doing it for a cybersecurity course. neat how much it can do in a small amount of code. TS feels like a really nice balance too

#

wish it was easier to set up with node though

remote oyster
#

TS was definitely a blessing to the JS community. People were using patterns from typed languages (like Java, C#), but the tooling couldn’t help back when TS didn't exist so Microsoft said let's change that. One of the few things I believe Microsoft did right.

rustic ermine
#

I feel they should have made it its own thing honestly, but that would have broken browser compatibility and probably would have never been widely adopted since there was already so much literal garbage out there

remote oyster
#

Yea, it's only purpose was to bring better support for static types, classes, interfaces, enums, compile-time checking (really important and saves a lot of time debugging), and ECM support during its early stages.

rustic ermine
#

wasm is a good start though, but still continues to have a lot of issues with FFI and threading

remote oyster
#

I haven't messed with web assembly yet.

rustic ermine
#

Its neat but doesn't deliver on its promises yet. even with a compiled language -> wasm output, it is hard to make it faster than native js because there is so much overhead on function calls

remote oyster
#

Nope, that's a no-go for me. Unnecessary resources.

rustic ermine
#

yep. eventually itll get there im sure. and it does provide code protection for those that care about that. the current deal breaker for me is that it is still single-thread only so not really viable for ECS architecture

#

anyway, thanks for the help, I really appreciate it 🙂

remote oyster
#

No, problem.

halcyon phoenix
#

what is this in js? never used it before

rustic ermine
#

reference to itself

class Player {
  thing: number
  constructor(thing: number) { 
     this.thing = thing;
  }
}
#

make sense?

#
    class MyClass {
        value: string = "Hello";

        greet() {
            console.log(this.value); // 'this' refers to the MyClass instance
        }
    }

another example

distant tulip
#

depend on the environment, in browsers in the global scope it refer to the window

nova flame
#

@distant tulipYo minato

distant tulip
#

sup

nova flame
#

What do i put into the terminal to make the ts compile?

#

i did it yesterday with crafter but i forgot the command

distant tulip
#

tsc

nova flame
#

thats it?

nova flame
distant tulip
#

you do have a tsconfig.json?

nova flame
#

yes

#

i have the whole ts setup

#

it worked yesterday

distant tulip
#

do you mind sending it

nova flame
#

i just restarted my pc now broken

#

u able to hop in vc and look at my screen?

distant tulip
#

give me a sec

nova flame
#

alright thanks

halcyon phoenix
halcyon phoenix
nova flame
#

someone pls help 🙏

woven loom
#

Why u asking that in the script channel

nova flame
#

oh whoops i thought i was in json ui

north frigate
#

(neovim + plugins)

vast grove
#

Oh gosh not mobile, pleaaasseee, anything but a mobile, ILL USE ASSEMBLY IF I HAVE TO BUT NOT MOBILE!

halcyon phoenix
#

however I long to see arduino compatible ones

woven loom
north frigate
#

what's helix

woven loom
#

Editor like neovim

#

Install helix and ts Lang server done

distant tulip
#

Why is lables and dividers get passed to the response form values

round bone
#

what are they passing?

distant tulip
#

Yeah, was debugging a friend script and we found that the reason, it is so stupid

#

That log
[Scripting][warning]-,a,,,a,a,a,,,2,,,a,

glacial widget
#

what would you guys say is a good limit for Dynamic Properties?

round bone
round bone
#

it's pretty hard to hit the limit of keys stored

distant tulip
glacial widget
distant tulip
#

Just don't abuse the use of it
Write and read using it constantly is not a good idea

#

And there is a limit of 10mb per min

round bone
#

use some caching maybe

round bone
#
const [name,sec,min,hou,time,day] = respone2.formValues.filter((value) => value !== undefined);
distant tulip
#

Can't remember, just saying what i heard from my friend

#

Anyway i think this should be treated as a bug and get reported

meager zenith
#

so i am confused on why i have to wrap the methods sometimes in system.run(() =>{}); and sometimes it's fine

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



world.afterEvents.entityDie.subscribe(bg =>{
  const player = bg.damageSource.damagingEntity;

  if( player && player.typeId == "minecraft:player" && player.hasTag("origins:power_bftbg") )
  {

    const effect = player.getEffect("strength");
    if(effect == undefined)
    {  player.addEffect("strength",300,{amplifier:0,showParticles:false}); }
    else if(effect.amplifier == 4)
    { player.addEffect("strength",100,{amplifier:4,showParticles:false});  }
    else
    { player.addEffect("strength",300,{amplifier:(effect.amplifier+1),showParticles:false});  }

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


world.beforeEvents.itemUse.subscribe(pm =>{
  const player = pm.source;
  const item= pm.itemStack;

  if( player.hasTag("origins:power_pig_ancestry") && (item.typeId == "minecraft:porkchop" || item.typeId == "minecraft:cooked_porkchop"))
  {
    pm.cancel = true;
    system.run(()=>{ player.addEffect("poison", 30 , {"amplifier":0 , "showParticles":false}); });
  }

});
#

if i remove the system.run wrap from this one ^^^^ , i'll get this error

#

is it because the second script is using a beforeEvents listener?

sharp elbow
#

Precisely, yes

#

In a BeforeEvent subscription, that code executes in a read-only context, where the world state cannot be changed.

#

Moving code into a system.run invocation will defer execution until later in the tick, when the world state can be changed.

nova flame
#
get(key: any, player = null) {
                let value = (player || world)?.getDynamicProperty(key);
                try { value = JSON.parse(value); } catch (e) {}
                return value;
            },```
#

Why did this error spawn in

sharp elbow
#

It's telling you that JSON.parse cannot accept an undefined value.

#

Indeed, if that dynamic property is not set, getDynamicProperty returns undefined

#

You could coalesce that null value into "{}" on the line where you define value

#

let value = (player || world)?.getDynamicProperty(key) ?? "{}";

nova flame
night acorn
#

is there a way for system.runTimeout() to not cancel when leaving the world?

#

damn

sharp elbow
#

Depends on what you're trying to do.

#

Directly, not really. You could store the tick that it should execute on into a dynamic property and do some shenanigans to schedule it again when the world reopens, but the API cannot perfectly store a function's state; the callback function must be pure and not dependent on external information.

#

Could you be more specific on what you want to do? There may be a way to implement it

sharp elbow
lapis heart
#

hello
in player.applyImpulse What is the value system that y receives?
For example, if y = 1 like player.applyImpulse({ x: 0, y: 1, z: 0 })
how high will it rise?

distant tulip
#

mass?

lapis heart
distant tulip
#

You should test that i guess

lapis heart
distant tulip
#

Yeah

lapis heart
night acorn
rustic ermine
#

Going on an assumption here since quickJS doesn't have JIT. JSON marshalling slow? At work so can't test, just mentally trying to think of how to store data

spice finch
#

do custom item components exist in the 2.0.0 stable release or do I have to use the 2.1.0-beta?

wary edge
spice finch
#

oh, I think I am confusing myself then

rustic ermine
#

Was thinking to create a cache map split into chunks of per chestUI page (keys) and value would be a BankPage class that holds a map of <itemID_enum, number> then using a reverse map that just returns the minecraft:itemid string to recreate the items. Sounds good in my head but no way to test at the moment 🫤

#

Then just saving as JSON to dynamic properties on player logout and on an interval per player started when they logged in, recreating cache on server start

lapis heart
#

hello
in player.applyImpulse What is the value system that y receives?
For example, if y = 1 like player.applyImpulse({ x: 0, y: 1, z: 0 })
how high will it rise?

rustic ermine
rustic ermine
granite badger
lapis heart
granite badger
#

Still different depending on the condition, you’d have to guess the values

lapis heart
tawny peak
#

does anyone have an example of what the header, divider and label look like on forms?

untold magnet
dusky flicker
#

i think coding minecraft my own and making it moddable is easier than understanding what the hell the script api will do

#

seriously there are times i fell the engine simply ignores some pieces of code

untold magnet
#

for no reason

wheat condor
rapid sail
#

im trying to make a script where you step on a block and your leggings get enchanted with swift sneak 3 and your boots get enchanted with soul speed 3

woven loom
#

custom block?

rapid sail
#

yes

woven loom
#

check out register block components thing

rapid sail
#

i know how to make block compoents its the script to apply the enchantments to the armor

alpine nebula
#

Is it possible to get the maximum and minimum of the block state values using scripts?

wary edge
#

Do note however if multiple blocks use the same state, it will return the min and max of all the blocks.

alpine nebula
#

Oh, okay. Thanks anyway.

woven loom
# rapid sail i know how to make block compoents its the script to apply the enchantments to t...
import { EquipmentSlot, ItemStack, Player, EntityComponentTypes, ItemEnchantableComponent } from '@minecraft/server';
import { MinecraftItemTypes } from '@minecraft/vanilla-data';

function giveEquipment(player) {
    const equipmentCompPlayer = player.getComponent(EntityComponentTypes.Equippable);
    if (equipmentCompPlayer) {
        let itemStack = equipmentCompPlayer.getEquipment(EquipmentSlot.Feet);
        
        if (itemStack) {
            let enchant = itemStack.getComponent( ItemEnchantableComponent.componentId )
            if (enchant)
                enchant.addEnchantment( { type: "", level: 0 } )
        }
        
    }
}

rapid sail
#

i'll give this a shot real quick

#

would the function go inside the OnStep registry? or above it?

woven loom
#

ye

#

call that in step func

rapid sail
#

mk

#

vanilla data is not recognized

woven loom
#

???

rapid sail
#

make sure its in the manifest

#

heres the error
Minecraft/vanilla-data is unrecognized if this is a Native module, did you remember to add it to your manifest.json

distant tulip
#

well...
read the error?

rapid sail
#

so i apply it I'm sorry i have no Internet rn again our router sucks

distant tulip
#

add the module to your manifest dependencies

rapid sail
#

no version is need for it?

rapid sail
#

so do i put the node_modules in the script folder?

rapid sail
#

mk cool

halcyon phoenix
halcyon phoenix
#

is there any method to break a block? I can't find a method on the block class.

little hull
ripe dune
sly valve
#

guys guys

#

Can i still delete a dynamic property by setting it's value to undefined?

jagged gazelle
#

Btw, for the debug utilities shape thing rotation property.

#

where's the pivot point of it, I mean where it will rotate? The center of the start and end location?

#

and before saying "test it". No I can't.

halcyon phoenix
#

Thanks

nova flame
#
const target: Player
= players[r.formValues![1]];
#

any1 know whats up here

remote oyster
remote oyster
#

That assumes you named it formData. Change it accordingly. It will print and show you what formValues consist of.

nova flame
#

alright thanks

halcyon phoenix
#

it's impossible to getBlock() on an unloaded chunk, is there any way to load it? I have a chunk scanner

round bone
#

you can load it using /tickingarea or some loading entity I think

halcyon phoenix
#

thanks

#

how do I check if a function generator or a runjob is done?

acoustic basin
#

guys, how do i get rid of Has Custom Properties text on an item

halcyon phoenix
acoustic basin
#

my item has custom component v2.0, but sure it's not the reason. the reason must be that there are also dynamic properties on the item, how to get rid of it?

halcyon phoenix
acoustic basin
#

like entity tags and stuff

#

nametags

halcyon phoenix
#

yes

acoustic basin
#

okey, thank you

open urchin
acoustic basin
halcyon phoenix
#

the circle option in ticking area is a chunk right?

#

I mean it considers the min height and max height?

prisma shard
#
    const line = new DebugLine(
            pts[i],
            pts[j]
        );

        line.timeLeft = 60;

        debugDrawer.addShape(line);

^^ please help. I am drawing some lines using debug drawer. But the lines just appears for 1 or half second and dissapears immediately.

#

The timeLeft property doesn't work . isn't it meant to remove the line after 60 seconds, if i set the timeLeft to 60?

#

I tried runInterval but it sets the line forever, even if i tried clearRun() and removeAll() in debugDrawer, doesnt work.

#

and for clarification meow

#

@distant tulip *calling the debugdrawer specialist meow

jagged gazelle
distant tulip
worldly heath
#

Is it possible to detect rightclicking a non interactive block ?

jagged gazelle
worldly heath
jagged gazelle
#

It's in the name itself, before it happens and after it happens.

worldly heath
#

i only tested afterevent of this and assumed its for intereactables only

jagged gazelle
#

since the block isn't interactable the "after" wouldn't be triggered since it never successfully happened unlike before since it's "before" no matter if successful after or not.

worldly heath
#

gonna try it

distant tulip
jagged gazelle
#

tho it will trigger multiple times iirc

distant tulip
#

there is a property to filter out first interact

jagged gazelle
#

Just use isFirstEvent

worldly heath
#

Thanks

halcyon phoenix
#

anybody know how to compile this?

public static completeJob(generator: Generator<void, void, void>, onComplete: () => void): number {
    function* jobWithCompletion() {
        yield* generator
        onComplete()
    }

    const job = jobWithCompletion()
    const runId = system.runJob(job)
    return runId
}
#

Aeverkan is not replying

halcyon phoenix
#

I don't know how to run it

halcyon phoenix
#

I was trying to get help if it's possible to run something after a runJob finishes.

minor horizon
#

Are Jigsaw structures still experimental? Are custom mini-biomes experimental as well?

sharp elbow
#

Alternatively, you can convert TypeScript code into JavaScript code by removing TS-specific features: Those are primarily type annotations, and TS-specific keywords, like interface, type, namespace, and satisfies

#

In this case, the only TS-specific features are the type annotations in the method declaration

public static completeJob(generator, onComplete) {
    function* jobWithCompletion() {
        yield* generator
        onComplete()
    }

    const job = jobWithCompletion()
    const runId = system.runJob(job)
    return runId
}
minor horizon
#

Will these new properties work on non-player entities? Or is the equippable component still out-of-order?

open urchin
#

equippable component is still disabled

minor horizon
#

Sad

rose light
#

Would there be any way to get if the player is in the first camera or third camera through the script?

lapis heart
#

I have a delay between each tick and tick in system.runInterval(() => { what is the solution ?

lapis heart
# wary edge What do you mean?

I have a code in wich system.runInterval(() => {,runs every tick. For example, when the player reaches the ground, activate player.applyImpulse, but sometimes it takes a while to activate the ifs.

wary edge
#

How long is a while?

#

That could just be your logic being terrible.

lapis heart
lapis heart
wary edge
#

Well it's hard to help when you don't fully show your code and properly explain things alongside video to showcase your issues.

lapis heart
# wary edge Well it's hard to help when you don't fully show your code and properly explain ...
import { world, system, Player, Dimension, EquipmentSlot } from "@minecraft/server"

const fallingPlayers = new Map();

system.runInterval(() => {
  for (const player of world.getPlayers()) {
    
    if (player.isFalling && !fallingPlayers.has(player.id)) {
      
      const startY = Math.floor(player.location.y);
      fallingPlayers.set(player.id, {
        startY: startY,
        fallDistance: 0,
        isTracking: true
      });
    }
    
    
    if (fallingPlayers.has(player.id) && fallingPlayers.get(player.id).isTracking) {
      const data = fallingPlayers.get(player.id);
      const currentY = Math.floor(player.location.y);
      
      data.fallDistance = data.startY - currentY;
      
       const loc = player.location;
        const hitBlock = player.dimension.getBlockFromRay(loc, { x: 0, y: -1, z: 0 }, { maxDistance: 2, includeLiquidBlocks: false })
      
      if(hitBlock && data.fallDistance >= 3) {
          const boot = player.getComponent("equippable").getEquipment(EquipmentSlot.Feet)
          if (boot?.typeId == "minecraft:leather_boots") {
              player.addEffect("resistance", 1, { amplifier: 255, showParticles: false });
          }
      }
      
      if (!player.isFalling) {
        data.isTracking = false;
        
        const blockBelow = player.dimension.getBlock({
          x: Math.floor(player.location.x),
          y: Math.floor(player.location.y) - 1,
          z: Math.floor(player.location.z)
        });
        
        if (blockBelow.typeId !== "minecraft:air" && blockBelow.typeId !== "minecraft:water" && blockBelow.typeId !== "minecraft:lava") {
          
          const boot = player.getComponent("equippable").getEquipment(EquipmentSlot.Feet)
          if (boot?.typeId == "minecraft:leather_boots") {
            
            
            const fallDistance = data.fallDistance;
            
            if (fallDistance >= 3 && fallDistance < 7) {
              player.applyImpulse({ x: 0, y: 0.7, z: 0 });
            } else if (fallDistance >= 7 && fallDistance < 10) {
              player.applyImpulse({ x: 0, y: 1.1, z: 0 });
            } else if (fallDistance >= 10 && fallDistance < 15) {
              player.applyImpulse({ x: 0, y: 1.3, z: 0 });
            } else if (fallDistance >= 15 && fallDistance < 22) {
              player.applyImpulse({ x: 0, y: 1.5, z: 0 });
            } else if (fallDistance >= 22 && fallDistance < 30) {
              player.applyImpulse({ x: 0, y: 2.1, z: 0 });
            } else if (fallDistance >= 30 && fallDistance < 40) {
              player.applyImpulse({ x: 0, y: 2.5, z: 0 });
            } else if (fallDistance >= 40 && fallDistance < 55) {
              player.applyImpulse({ x: 0, y: 3, z: 0 });
            } else if (fallDistance >= 55) {
              player.applyImpulse({ x: 0, y: 3.3, z: 0 });
            }
            player.playSound(`mob.slime.death`)
            
          }
        }
        
        fallingPlayers.delete(player.id);
      }
    }
  }

Upon reaching the ground, player.applyImpulse is supposed to activate immediately and quickly. + Sometimes it doesn't activate because the tick action doesn't sync with the player's arrival on the ground (like the end of the video).

sharp elbow
#

From what I remember, applyImpulse on the player has some desync issues. Try applyKnockback?

halcyon phoenix
halcyon phoenix
lapis heart
sharp elbow
#

Pretty similar. It takes two arguments, a Vector3 like applyImpulse and a vertical knockback number

lapis heart
sharp elbow
#

You can think of it as the y-component of the vector3

lapis heart
sharp elbow
#

Well, then let's examine what the code is doing

sharp elbow
#

Seems like you are guesstimating how long it takes for the player to hit the ground. If the player is within 2 blocks of the block beneath them, we apply resistance. What if the player falls farther than 2 blocks in that tick? (this will vary with server latency)

#

I tested with applyKnockback and it felt pretty responsive, at least on PC, so I don't think it's an issue with runInterval.

#

But I was able to die consistently if I fell from 100 blocks up

#

If I were you, I would take the player's y-velocity and compare it against the distance left to travel. If the velocity is greater, then we know the player will likely hit the ground that next tick.

// find the distance expected to fall given the player's xz coordinates
// compare against their y-velocity
// if the y-velocity offset would result in hitting the ground, apply resistance
const loc = player.location;
const hitBlock = player.dimension.getBlockFromRay(
    loc,
    { x: 0, y: -1, z: 0 },
    { includeLiquidBlocks: false }
)

if(hitBlock) {
    const hitLocation = {
        x: hitBlock.block.x + hitBlock.faceLocation.x,
        y: hitBlock.block.y + hitBlock.faceLocation.y,
        z: hitBlock.block.z + hitBlock.faceLocation.z,
    }
    const deltaLocation = {
        x: hitLocation.x - loc.x,
        y: hitLocation.y - loc.y,
        z: hitLocation.z - loc.z,
    }
    const distance = Math.hypot(deltaLocation.x, deltaLocation.y, deltaLocation.z);
    const velocity = player.getVelocity();
    if (Math.abs(velocity.y) + 0.08 > distance) {
        const boot = player.getComponent("equippable").getEquipment(EquipmentSlot.Feet)
        if (boot?.typeId == "minecraft:leather_boots") {
            player.addEffect("resistance", 1, { amplifier: 255, showParticles: false });
        }
    }
}
#

This still isn't quite accurate though, as while it's mathematically sound, it can still vary with server latency

#

(Best solution is to prevent damage with the "minecraft:damage_sensor" component, but I suspect that's not an option for your development)

sharp elbow
#

Oh, and you could reduce your large number of else if statements to a single applyImpulse with a math function. Math.log(Math.min(fallDistance, 100) / 4) (for all x ≥ 4) feels like a sweet spot

distant tulip
prisma shard
#

lol

sharp elbow
#

Ah, Desmos' graphing calculator

distant tulip
gaunt salmonBOT
prisma shard
#

I think I saw that in snowstorm iirc

jagged gazelle
#

blockbench, snowstorm, molang grapher, dialogue designer...

#

I might have missed something

prisma shard
#

ok

dusky flicker
wheat condor
#

i mean that they re in the minecraft code they re not items done with json like custom foods

buoyant canopy
#

is the locator bar data driven in anyway in bedrock?

night loom
#

Where can I change the fishing loot from water?

fallow minnow
#

is it smart to create a new dynamic property on the world for each playert

#

like could that affect the world/performance in any way

distant tulip
fallow minnow
#

indefinitely

deep quiver
fallow minnow
deep quiver
fallow minnow
#

no like

#

permanently

deep quiver
#

every tick?

fallow minnow
#

each player will have their own dynamic property

#

on join itll create one

#

and then ill cache it

deep quiver
#

yeah

fallow minnow
#

and then once they leave itll save

deep quiver
#

that should be no problem

#

I dont see a issue in one dynmic property

#

its on the very low side actually

fallow minnow
#

idk if u understand

#

like

#

if i have 250 players

#

each player gets their own dynamic property on the WORLD not the player

deep quiver
#

no yeah, thats fine

fallow minnow
#

so that would be 250 individual properties on the world

deep quiver
#

250 is not that much

fallow minnow
#

what about 1000

deep quiver
#

it should scale well

#

you can have 1 million

fallow minnow
#

with no performance changes?

deep quiver
#

nope, not gonna change anything perfomance wise

#

its stored on storage

#

it will only take storage, but not perfomance. It only takes perfomance, if you read/write

fallow minnow
#

ah ok

#

has someone tested this

deep quiver
#

you can test it, by just filling a random world with millions of dynamic properties

distant tulip
little hull
halcyon phoenix
#

has there been any cases where classes where used inside addons?

nova flame
#
const target: Player = players[r.formValues[1]];
const obj = variables[r.formValues[2]];```
#

anyone know why this just appeared

#

I just switched to ts

#

now random errors be spawning

#

the errors are at r.formValues[1] and r.formValues[2]

twilit sky
# nova flame the errors are at r.formValues[1] and r.formValues[2]

The errors may be at r.formValues[1] and r.formValues[2], but they come from further up.

That first error is TypeScript saying it isn't 100% sure r.formValues is valid.

I can't really help without seeing more of the code.

Those other errors are likely related, it's saying you're trying to treat something that isn't an array as one.

You obviously cannot do this: true[2]. true isn't an array.

nova flame
#

is the problem here?

twilit sky
#

That looks a bit strange, that's likely the reason.

You don't need both type definitions, you have that

string | number | boolean

As well as as string. They don't go together.

nova flame
#

so which should i get rid of

twilit sky
#

The first one is if you're making a new value. You're not, so get rid of that one.

as string is a type cast, and that's you telling TypeScript you're 100% sure it'll be a string.

nova flame
#

i got rid of the first ones and the error is exacatly the same

#

what does it mean that boolean values or undefined cant be used as an index type

#

i never used them?

#

do i need to specify that its not?

twilit sky
#

Probably should've asked this first: What's the exclamation mark for in r.formValues![0]? I've never seen it myself.

#

I suspect that's where the boolean is coming from.

nova flame
#

its because the top error

#

My friend told me when i see that error

#

i add an exclaimation mark

#

it does wor

#

work

#

in getting rid of the error

#

but the rest stay

#

which is what i need to get rid of

twilit sky
#

Are those other errors coming from that line?

nova flame
#

yes

#

oh no sorryu

#

they are from here

#

const target: Player = players[r.formValues[1]];

nova flame
#

but when i remove the "!"

#

it does

twilit sky
#

Does

const unparsedPrice = r.formValues[0] as string

work?

nova flame
#

error "r.formValues is possibly undefined"

twilit sky
#

Where is that variable coming from?

Can you show all of your code? It's really hard to tell from just 3 lines.

nova flame
#

sure

#
import { Player, world } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { addScore, getScore } from "utils";

const variables = [
    `Coins`,
    `Gems`
]
export default function PayUI(player: Player) {
    const f = new ModalFormData();
    const players = world.getAllPlayers().filter((p) => p.name != player.name);
    if (players.length == 0) {
        player.sendMessage(`Theres Nobody Else Online!`);
        return player.playSound('note.bass');
    }
    f.title("§gPay Players");
    f.textField("price", "e.g. 20");
    f.dropdown("Choose Player", players.map((p) => p.name));
    f.dropdown("Choose Score", variables);
    f.show(player).then(r => {
        if (r.canceled) return;
        const unparsedPrice = r.formValues[0] as string;
        const target = players[r.formValues[1]];
        const obj = variables[r.formValues[2]];
        if (!unparsedPrice || !target) return;
        const payAmount = parseInt(unparsedPrice);
        
        if (payAmount < 1) {
            player.sendMessage(`Number Has To Be More Than 0!`);
            return player.playSound('note.bass');
        }
        if (getScore(player, obj) >= payAmount) {
            // Removes money
            addScore(player, obj, -payAmount);

            // Adds money
            addScore(target, obj, payAmount);
            player.sendMessage(`§dYou have just sent §g${payAmount} ${obj}§d to ${target.name}!`);
            target.sendMessage(`§dYou have just recieved §g${payAmount} ${obj}§d from ${player.name}!`);
            target.playSound('note.pling');
        }

        else {
            player.sendMessage(`You dont have enough money!`);
            player.playSound('note.bass');
        }
    })
}
#

thats the whole thing

twilit sky
#

Which errors is it showing now? Is it still showing the undefined error?

nova flame
#

these 3

#

first line error is "r.formValues is possibly undefined"

#

the other 2 are

wheat condor
nova flame
wheat condor
nova flame
#

like what would make it more readable

twilit sky
#

That's TypeScript saying it's not 100% sure formValues will always be valid. That's from the built in ModalFormResponse class.

You can either tell TypeScript it'll always be valid or do a runtime check.

You can do a runtime check like this:

if (!r.formValues) return
wheat condor
#

dont use r.formvalues

twilit sky
#

Right under your other guard if (r.canceled) return;

It doesn't matter the order, it just has to be before the rest of the code. Because it's a guard.

nova flame
#

thanks

#

we fixed that

#

but

#

what are these 3?

twilit sky
#

It thinks you're trying to do this:

true[1]
Not that.

It thinks you're trying to do this:

Players[true]

nova flame
#

but why?

#

and how do i fix?

wheat condor
nova flame
#

alright thanks

wheat condor
#

that's just a tip to not write r.formValues[0]

wheat condor
nova flame
#

i made this code when i knew basically 0 about coding it was heavily helped by friend

twilit sky
#

A good rule is to not write anything you don't understand. That's what I do.

nova flame
#

yeah probably a good idea

#

still lost 😢

twilit sky
#

Can you see the vanilla type declaration? Go to that.

wheat condor
wheat condor
#

that is the npm pack

twilit sky
#

Yes, that's the one. Now see that readonly formValues?: (boolean | number | string)[]?

nova flame
#

yes i do

twilit sky
#

That's telling you that formValues is an array that contain booleans, numbers, or strings. TypeScript does not know what those array elements will be, just that it'll either be a boolean, string, or number.

Therefore, when you do formValue[2], to TypeScript, that could be either a boolean, string, or number.

Also, the question mark ? at the end means that the array might not even exist. That's why you were getting that "r.formValues is possibly undefined" error earlier.

nova flame
#

so i need to tell it which it will be?

twilit sky
#

Yes, you can do that with as.

#

That's a type cast.

nova flame
#

after the last ]?

#

Ive got it

twilit sky
#

Before. It looks a bit strange:

const obj = variables[r.formValues[2] as number];

nova flame
#

thanks very much i will test it now

wheat condor
#

ill never understand typeScript users its just like java but more complex

twilit sky
#

It makes your variables more certain; you won't end up accidentally putting a number where a string will be.

sharp elbow
#

Even better: If you know exactly how many values you will pass, you could enforce formValues to be a tuple. Then accessing certain indices would return the specific type at that index.

#

I haven't worked with forms enough to have a specific pattern to suggest, though.

ivory bough
#
let fieldOffset = 0;
let fieldZ = 100000;
world.afterEvents.playerSpawn.subscribe((event) => {
  if (hasPlayerJoined === false) {
    hasPlayerJoined = true;
    nullTploc = event.player.location;
  }
  if (dimensionGenerated === false || dimensionGenerated === true) {
    dimensionGenerated = true;
    function* fieldLoop(){
      for ( ; fieldZ <= 500000; fieldZ += 16) {
        for ( ; fieldOffset <= 400000; fieldOffset += 16) {
      if (Math.random() < 0.5) {
        overworld.runCommand(`structure load mystructure:fieldtree ~ ~200 ~${fieldZ}`);
        overworld.runCommand(`structure load mystructure:fieldtree ~${100000 - fieldOffset} ~200 ~${fieldZ}`);
      } else {
        overworld.runCommand(`structure load mystructure:fieldbase ~ ~200 ~${fieldZ}`);
        overworld.runCommand(`structure load mystructure:fieldbase ~${100000 - fieldOffset} ~200 ~${fieldZ}`);
      }
      if (Math.random() < 0.5) {
        overworld.runCommand(`structure load mystructure:fieldtree ~${100000 + fieldOffset} ~200 ~${fieldZ}`);
      } else {
        overworld.runCommand(`structure load mystructure:fieldbase ~${100000 + fieldOffset} ~200 ~${fieldZ}`);
       }
          yield;
        }
      }
    }
    system.runJob(fieldLoop());
  }
});

This only generates straight for some reason and not sideways too

jagged gazelle
ivory bough
final ocean
#

How to use debug script??

woven loom
#

???

buoyant canopy
#

can we tag a player with something that isn't saved on relog?

#

the only thing i can think of, is adding the player id to a list, and check if it is in it.

sly valve
buoyant canopy
#

that's basically the same thing i said, but thanks anyway

sly valve
wheat condor
woven loom
#

Array vs object

wheat condor
#

set is an array?

woven loom
#

It like that

#

But unique values only

wheat condor
#

so basically map is faster

woven loom
#

The map is key value based.

wheat condor
#

oh nvm i got it

#

key-value
value

sly valve
#

Yep like that

#

Set is good if you have an array like

const invalidItems = new Set([
  ....
]);
wicked girder
#

Does anyone know where dynamic properties get stored?

round bone
#

.dat files

buoyant canopy
woven loom
#

Nbt

wicked girder
#

does mcc toolchest pe not show them?

woven loom
#

I saw some guy access them with that.

#

U can also use old Universal MC editor

wicked girder
#

Whats the best to use for a giant world lol

buoyant canopy
woven loom
#

I only used UMC editor

wicked girder
#

You got a link to it

#

not the paid one

buoyant canopy
woven loom
woven loom
#

But like i said I remember someone using mcc

empty yoke
#

Is there a way to cancel riding?

woven loom
#

Try Cancel interact with entity event

wary edge
empty yoke
#

But is having an active ticking area for a game area not recommended?

wary edge
empty yoke
wary edge
#

A ticking chunk that has basically nothing vs a ticking chunk that has redstone machines and lots of mobs

empty yoke
wary edge
#

Yeah that shouldnt be a major issue but as always, do some testing yourself. Your mileage may vary depending on your device.

empty yoke
warm mason
#

This code works well..

#

But as soon as I remove console.warn....

#

Of course, I may not know something, but it seems to me that something is definitely wrong here.

cinder shadow
#

you'll find something very funny

warm mason
#

._.

cinder shadow
#

oh wait maybe they finally fixed it when they started doing all of their biome work

#

for a while getting someones biome when they were above one of those biomes would say they were in that one, even when on the surface

#

and the surface one would be in the cave

#

what exactly is the issue with the images though

halcyon phoenix
halcyon phoenix
#

what's the difference between a container and a containerSlot?

twilit sky
# halcyon phoenix what's the difference between a container and a containerSlot?

You can likely infer the difference from the name: Containers are used for multiple ContainerSlots. A chest will have a Container component.

You can use more sorting related methods if you have the Container.

The ContainerSlot will have more information about what's specifically inside it.

The player's equipment slots are not within a Container, they are all ContainerSlots.

halcyon phoenix
#

on the other hand I got this bug? where it seems that setting item dynamic property has a delay compared to setting entity dynamic property. Is there really a delay?

twilit sky
# halcyon phoenix

I don't see the problem you're referring to.

The console looks like it prints it out in the correct order: shrine energy, then item energy. That's the way you've ordered your print statements.

halcyon phoenix
#

I added some delay counts and it fixed it but I don't know why that happens

warm mason
halcyon phoenix
# warm mason show ``updateLore`` function
function updateLore(itemStack, currentEnergy, maxEnergy, blockName) {
    
    itemStack.setLore([
        `§r§6Life Energy:`,
        `§r§c${JSON.stringify(currentEnergy)} / ${JSON.stringify(maxEnergy)}`,
        `§r§6Block Essence:`,
        `§r§c${JSON.stringify(blockName)}`
    ]);

};
sly valve
halcyon phoenix
#

do integers work inside lores?

halcyon phoenix
#

its just

beforeEventInteract
system run
itemVal -=1
item.setDynamicProperty(itemVal)
entityVal +=1
entity.setDynamicProperty(entityVal)

nova flame
#

What do i do if i need to do world.getAllEntities but its not a thing

halcyon phoenix
nova flame
#

alr ty

sly valve
halcyon phoenix
dense sun
#

any example to make custom commands

rustic ermine
#

Can't decide if I should do my database server with TS/deno, Go, or Rust lol. Only issue I have with doing it in TS is the cached DB memory size since JS classes are pretty large and no structs

jagged gazelle
#

map is the only way I can store new DebugLine() right?

#

I need to still have access it since I am removing them sometimes.

woven loom
#

Btw, there is a bug where it draws shapes in all dimensions at the same coordinates.

jagged gazelle
#

oh that's fire 😀

jagged gazelle
woven loom
jagged gazelle
woven loom
#

Oh xd

buoyant canopy
#

Have we found a way to localize texts which have linebreaks in them?

buoyant canopy
#

does it work anywhere? forms, hud, how to play screen?

buoyant canopy
#

Oh my god it works!

proud saddle
#

did developers fix the player.applyImpulse in latest previews?
last time i checked it was broken

proud saddle
#

now it does'nt work like that?

night acorn
#

does anyone know the intrisic block state for whether a campfire is lit?

night acorn
#

found it anyway

#

its extinguished

wary edge
sterile epoch
neat hazel
#

Is it possible to put a name on the item with translate?
Something like this:

item.nameTag = {
          rawtext: [
            {
              translate: "item.enchanted_book.name"
            }
          ]
        }```
jagged gazelle
neat hazel
#

Thanks

floral vessel
#

why isn't onPlayerBreak triggering in my custom block component? I have another event in the same component which works fine and I have reloaded my world.

    onPlayerBreak: ({block}) => {
        world.sendMessage("ran");
        let below = block.below();
        if (below.type === "fb:dragonberry_plant"){
            below.setPermutation(below.permutation.withState("fb:stage", 0));
        }
    }
floral vessel
wary edge
north rapids
#

hey, can i add translation to an item lore?

#

nvmd

jagged gazelle
floral vessel
#

does applyImpulse work on players in v2?

woven loom
#

ye

floral vessel
#

sweet

#

I have been mislead

#

it does not

woven loom
#

it does

#

try 2.1

floral vessel
#

I'm staying on stable

buoyant canopy
rustic ermine
#

pretty new to JS/TS.. not seeing a direct way to do this in the docs; I am trying to make my bedrock server's main script listen for events from my database server. I see that we are limited to HTTP so that makes it a bit tricky. anyone done something like this? the main reasoning is that I want my database server (written in Go) to do a majority of the world/logic processing because I don't want hundreds of different things running on the quickJS runtime for obvious reasons

vast grove
#

Send a request for receiving events every so often smilee

rustic ermine
#

hmm. yeah, that actually seems kind of obvious now lol. thanks. probably just way overthinking/overcomplicating it

#

could probably make a basic RPC api to handle that to keep packet sizes small

shy leaf
#

thats all

#

client doesnt like a sudden shift in player's velocity so youll have a lot of rubberbandings

floral vessel
shy leaf
#

but applyImpulse directly sets the velocity, and client doesnt have anything that handles this

floral vessel
#

that has to be the dumbest thing I've ever heard

#

why would they not just use knockback when running applyImpulse

shy leaf
floral vessel
#

bruuuh

#

they really don't have a way to tell the client to change velocity

#

this has to be the most absurdly fixable problem I've seen

shy leaf
#

i dunno, i feel like theres something deep in the root

#

there are a lot of instances where you can cause rubberbands

#

like auto step component on player entity

floral vessel
#

If I had to guess it's probably just because it would be too much of a pain in the ass for them to add a packet for it

shy leaf
shy leaf
#

its just that it doesnt work 99% of times

#

hence the rubberbanding

#

this is probably related with server authoritative movement change

shy leaf
tardy pivot
#

cant wait for beforeEvents playerplaceblock to be released from beta

jagged gazelle
jagged gazelle
#

and -beta is like an experimental version they are waiting it to be done.

sterile epoch
#

hasn't chatSend been in beta for months now 😭

#

idk why they don't just release that event atp

lethal flame
#

what version currently script api stable version?

sharp elbow
#

2.0.0

lethal flame
valid ice
sly valve
distant tulip
#

what happened to itemUseOn event in the latest beta

wary edge
distant tulip
#

why so

#

any replacement?

wary edge
distant tulip
#

oh, lol i thought it is the other way around

wary edge
distant tulip
#

yeah, for some reason i thought the other event that was removed

#

thanks

long cargo
#

how to detect player place block?

warm mason
#
world.afterEvents.playerPlaceBlock.subscribe(data => {
  const block = data.block;
  const player = data.player;
})
fallow minnow
halcyon phoenix
#

player.spawnParticle() is client sided right?

north frigate
#

man idk why I open this channel for no reason I don't even ask a question

#

but I feel like I should

distant tulip
prisma shard
#

I like watching people getting problems solved

#

And actually you can learn from it

fallen cape
#

Am I right that headers and titles are count into modal form data's return values?

sterile epoch
#

does debugDrawer.removeAll(); just not work?

wheat condor
prisma shard
sterile epoch
#

damn, so annoying

#

guess a map that stores every shape will do

prisma shard
#

I tried runInterval but then I can't remove it

sterile epoch
#

there's a time till it dies

#

you can set it to not die

prisma shard
#

didn't work

sterile epoch
#

interesting

#

let me try

#

Works for me

prisma shard
# sterile epoch Works for me
import { world, system } from "@minecraft/server"
import { debugDrawer, DebugLine } from '@minecraft/debug-utilities';

function getBoxVertices(A, B) {
    const xMin = Math.min(A.x, B.x), xMax = Math.max(A.x, B.x);
    const yMin = Math.min(A.y, B.y), yMax = Math.max(A.y, B.y);
    const zMin = Math.min(A.z, B.z), zMax = Math.max(A.z, B.z);

    return [
        { x: xMin, y: yMin, z: zMin },
        { x: xMin, y: yMin, z: zMax },
        { x: xMin, y: yMax, z: zMin },
        { x: xMin, y: yMax, z: zMax },
        { x: xMax, y: yMin, z: zMin },
        { x: xMax, y: yMin, z: zMax },
        { x: xMax, y: yMax, z: zMin },
        { x: xMax, y: yMax, z: zMax }
    ];
}

function drawBoxOutline(cornerA, cornerB) {
    const pts = getBoxVertices(cornerA, cornerB);
    const edges = [
        [0, 1], [0, 2], [0, 4],
        [7, 6], [7, 5], [7, 3],
        [1, 3], [1, 5],
        [2, 3], [2, 6],
        [4, 5], [4, 6]
    ];

    for (const [i, j] of edges) {

        const line = new DebugLine(
            pts[i],
            pts[j]
        );
        line.timeLeft = 60;

        debugDrawer.addShape(line);
    }
}

world.beforeEvents.playerBreakBlock.subscribe(async ({ block, itemStack, cancel }) => {
    if (itemStack?.typeId === "minecraft:stick") {
        cancel = true;
        world.setDynamicProperty("l1", block.location);
        world.sendMessage("set pos")
    }
    if (itemStack?.typeId === "minecraft:blaze_rod") {
        cancel = true;
        const l2 = block.location;
        const l1 = world.getDynamicProperty("l1")
        world.sendMessage("set pos 2")

        drawBoxOutline(l1, l2)
    }
})

#

Here's my script

#

Which does not work

#

can you see what's the problem

#

Select a stick and break block then take blaze and break select block

#

It'll draw the debug shape

#

@sterile epoch

#

maybe identify the problem for me

sterile epoch
cerulean cliff
#

Any chance we can get the type of item from an item entity in scripting?

prisma shard
safe stream
#

Is there a quick way to access all spawn eggs (item ids)? or do I need to make a library

open urchin
safe stream
#

oh thats smart, ty!!

sullen pollen
#

onStepOn(event) {
event.block // Block impacted by this event.
event.dimension // Dimension that contains the block.
event.entity // The entity that stepped on the block. May be undefined.
}

how can i use this script to make a block that will break if you step on it?

thorn flicker
#

within the setblock command, you need to enter the block's coordinates through template literals

jagged gazelle
#

I miss my goofy ahh helping every people in this channel every damn second lmao

woven loom
#

huh

coral ridge
#

need help with this code i tried asking ai but it didn't work


// Create scoreboard objectives if they don't exist
function createScoreboardObjective(name) {
  try {
    world.scoreboard.getObjective(name);
  } catch {
    world.scoreboard.addObjective(name, name, name);
  }
}

createScoreboardObjective("isRightClicking");
createScoreboardObjective("isLeftClicking");

// Reset scores every tick to 0
system.runInterval(() => {
  for (const player of world.getPlayers()) {
    player.scoreboard.setScore("isRightClicking", 0);
    player.scoreboard.setScore("isLeftClicking", 0);
  }
}, 1);

// Detect right-click (item use)
world.events.itemUse.subscribe(event => {
  const player = event.source;
  if (!player || !player.isPlayer()) return;
  player.scoreboard.setScore("isRightClicking", 1);
});

// Detect left-click (attack)
world.events.entityHit.subscribe(event => {
  const player = event.source;
  if (!player || !player.isPlayer()) return;
  player.scoreboard.setScore("isLeftClicking", 1);
});

what i want here is to detect whenever a player right-clicks with any item and left click and convert it into a score

woven loom
#

so what is the issue here

coral ridge
#

ye alot

#

[Scripting][error]-TypeError: cannot read property 'setScore' of undefined at <anonymous> (main.js:18)

#

a lot of these

#

and some

#

I can't send it i reach text limit

halcyon phoenix
warped blaze
#

Player class doesn't have a scoreboard property lol

#

that's the problem

coral ridge
warped blaze
#

you must access the scoreboards via
world.scoreboard.getObjective(name).getScore(Player)

warped blaze
warped blaze
#

it's either afterEvents or beforeEvents

#

isPlayer() method doesn't exist :v

#

a lot of things are wrong there

true isle
#

can you fire and event in an unloaded chunk?

prisma shard
jagged gazelle
jagged gazelle
#

you need to get the objective first and use that objective to setScore()

#
const obj = world.scoreboard.getObjective(objectiveId: string);

obj.setScore(participant: Entity | ScoreboardIdentity | string, scoreToSet: number):```
#

same goes to addScore()

coral ridge
#

I'll try to rewrite the code

bold stratus
#

How do I detect enchantments on the item a player is holding and display something like: Diamond Sword [Sharpness I]?

wary edge
ivory bough
#
world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
    if (!event.block.permutation.matches('minecraft:jukebox')) {
        if (event.itemStack?.typeId === "space:disc_14") {
            system.run(() => {
                event.block.dimension.playSound("broken.disc14", event.block.location);
            });
        } else if (event.itemStack?.typeId === "space:disc_15") {
          system.run(() => {
                event.block.dimension.playSound("broken.disc15", event.block.location);
            });
       } else if (event.itemStack?.typeId === "space:disc_16") {
          system.run(() => {
                event.block.dimension.playSound("broken.disc16", event.block.location);
            });
         }
      }
   }
});

It shows unhandled promise rejection at last line

meager pulsar
#

is gametest still on beta?

wary edge
shrewd relic
#

can someone look at my line 82 and check why my hit reduction logic not working? i'll consider it working if the debug message gets printed :DD

wary edge
#

Clueless Would like to make a correction. EntityLoad does work, EntityInitializationCause.Loaded does not work.

sullen pollen
#

anyone know an script to make a 2d block behave like this?

wheat condor
neat hazel
#

How to give a tag after this entity spawns?

mc.world.afterEvents.playerPlaceBlock.subscribe(event => {
  const block = event.block;
  const loc = block.location;
  const player = event.player;
  const dim = player.dimension;

  if (block.typeId == "minecraft:dirt") {
    dim.spawnEntity("hash:shooting.machine.1", loc);
    player.runCommand(`setblock ${loc.x} ${loc.y} ${loc.z} air`);
  }
});```
distant tulip
#

or just
dim.spawnEntity("hash:shooting.machine.1", loc).addTag("name")

warped blaze
#

I just experienced a Mandela effect

#

i thought it was possible to save dynamic properties on Blocks

tardy pivot
#

world.beforeEvents.playerInteractWithBlock.subscribe((event) => {
const { block, itemStack } = event;

if (block.typeId !== "minecraft:jukebox") {
let toPlay;
if (itemStack?.typeId === "space:disc_14") toPlay = "broken.disc14"
else if (itemStack?.typeId === "space:disc_15") toPlay = "broken.disc15"
else if (itemStack?.typeId === "space:disc_16") toPlay = "broken.disc16"
if (toPlay) system.run (() => block.dimension.playSound(toPlay, block.location))
}
});

little hull
#

how do i detect when the attachable equipped by the player is being used to attack like right clicking or left clicking?

halcyon phoenix
#

anybody her has any idea why setFloat() doesn't set tickVariables and staringVaribales?

#

it creates it's own variable

final ocean
#
world.afterEvents.playerBreakBlock.subscribe(event => {
    try {
        const { player, block, brokenBlockPermutation } = event;
        const blockId = brokenBlockPermutation.type.id;
        const droppedItemId = getItemIdFromBlockId(blockId);

        if (droppedItemId) {
            event.setDrops([]); // Likely around line 95-100
            const inventory = player.getComponent("inventory");
            if (!inventory || !inventory.container) {
                player.sendMessage("§cLỗi: Không thể truy cập kho đồ của người chơi.");
                return;
            }
            const container = inventory.container;
            const itemStack = new ItemStack(droppedItemId, 1);
            const overflowItems = container.addItem(itemStack); // Likely around line 100-105
            if (overflowItems) {
                player.dimension.spawnItem(overflowItems, block.location);
            }
            player.playSound("random.pop", { location: player.location });
        }
    } catch (e) {
        console.error("Lỗi chung trong addon tự động nhặt đồ:", e.stack);
    }
});

How to fix

#

Compiler found 2 errors:

mine.js:95:19 - error TS2339: Property 'setDrops' does not exist on type 'PlayerBreakBlockAfterEvent'.

95             event.setDrops([]); // Likely around line 95-100
                     ~~~~~~~~

``````ansi
mine.js:110:67 - error TS2339: Property 'stack' does not exist on type 'unknown'.

110         console.error("Lỗi chung trong addon tự động nhặt đồ:", e.stack);
                                                                      ~~~~~

boreal siren
#

Please help, I have a script that works fine in a single world, but when I uploaded the world to a server (in my case, aternos) the script does not start at all

#

What to do in this case, I have never worked with scripts on servers

prisma shard
round bone
shrewd relic
#

const equipmentInventory = entity.getComponent(mc.EntityEquippableComponent.componentId);
if (equipmentInventory) {
const chestArmor = equipmentInventory.getEquipment(mc.EquipmentSlot.Chest)?.typeId;
if (chestArmor) {
adminDebug(source, Chest armor equipped: ${chestArmor});
if (ARMOR_PROTECTION[chestArmor]) {
adminDebug(source, Hit to the chest! Chestplate: ${chestArmor});
damageMultiplier -= ARMOR_PROTECTION[chestArmor];
}
} else {
adminDebug(source, "No chest armor equipped.");
}

    const headArmor = equipmentInventory.getEquipment(mc.EquipmentSlot.Head)?.typeId;
    if (headArmor) {
        adminDebug(source, `Head armor equipped: ${headArmor}`);
        if (ARMOR_PROTECTION[headArmor] && hitPart === "Head") {
            adminDebug(source, `Hit to the head! Helmet: ${headArmor}`);
            damageMultiplier -= ARMOR_PROTECTION[headArmor];
        }
    } else if (hitPart === "Head") {
        adminDebug(source, "No helmet equipped.");
    }
}
#

im gonna go nuts

#

the script aint reading the armor protection thingy

#

D:

granite cape
#

looking good

halcyon phoenix
deep quiver
dusky flicker
#

i think that at least [player, playerPos] = [v.player, v.player.position] is more readable

vast grove
granite cape
granite cape
bold stratus
#

can addon read others addon dynamicproperty?

halcyon phoenix
# wary edge No.

so the scope of getDynamicProperty() is only in the addon itself?

sharp elbow
# granite cape looking good

What gets me is the lack of var/let/const in declaring those variables. "player" and "playerPos" are scoped globally here

tardy pivot
#

is there a way to detect or modify hunger points?

dusky flicker
halcyon phoenix
#

system message?

dusky flicker
#

i forgot the name

#

that shit on system

#

its got a command as well

#

this lil guy

#

yeah i totwlly forgot its name

halcyon phoenix
#

ohhh thanks

dusky flicker
#

i think there are 2 projects that help doing so

gaunt salmonBOT
sage portal
#

Are player.ids exclusive to each world or do the same ids persist in every world?

sly valve
#

But the host always has the same ID

sage portal
#

Got it, thanks

sly valve
#

You're welcome

grim raft
#

how do I detect i there are blocks above the player with getBlockFromRay?

#

deleted my code of trying to make it work so I cant send it for fix lol