#Checking for adjacent blocks

1 messages Β· Page 1 of 1 (latest)

craggy escarp
#

Making a custom block component. I want it so when a stone block is adjacent to my custom block, it sends a message one time, if this condition becomes false again (no adjacent block) and then becomes true, it should send the message again. Here's what I have:

// Import necessary modules from Minecraft server API
import { world } from '@minecraft/server';

// Subscribe to the 'worldInitialize' event to register custom components
world.beforeEvents.worldInitialize.subscribe(eventData => {
    // Register a custom component named kai:on_tick for trapdoor interaction with redstone
    eventData.blockTypeRegistry.registerCustomComponent('kai:on_tick', {
        onTick(e) {
            // Destructure event data for easier access
            const { block, dimension } = e;
            const { x, y, z } = block.location;

            // Define directions to check
            const directions = [
                { dx: 1, dy: 0, dz: 0 }, // East
                { dx: -1, dy: 0, dz: 0 }, // West
                { dx: 0, dy: 0, dz: 1 }, // South
                { dx: 0, dy: 0, dz: -1 }, // North
                { dx: 0, dy: 1, dz: 0 }, // Up
                { dx: 0, dy: -1, dz: 0 } // Down
            ];

            // Check each direction for a stone block
            for (const { dx, dy, dz } of directions) {
                const blockAdjacent = dimension.getBlock({ x: x + dx, y: y + dy, z: z + dz });

                // Send message if a stone block is found
                if (blockAdjacent?.typeId === 'minecraft:stone') {
                    world.sendMessage("I have the power!!!");
                    break;
                }
            }
        }
    });
});
potent echo
#

To stop rapidly sending you need to make a blockstate

#

So let's say you have example:igotthepower = 0

#

The message checks for stone and for blockstate = 0 and than sets it to 1

#

Than you make the reverse to set it back to 0

#

Rough example (not actual code cause I'm not home rn)
If blockadjacent.id == minecraft:stone && example:igotthepower == 0 {
example:igotthepower = 1
send message "I got the power"
}

#

And to reset it
If !blockadjacent.id == minecraft:stone && example:igotthepower == 1 {
example:igotthepower = 0
send message "I dont got the power"
}

craggy escarp
#

So a block state

potent echo
#

Well that's to stop the repeating

craggy escarp
#

Isn't there anyway I can make it without a block state?

potent echo
#

Well yeah just a loose value

#

Idk if it works per block tho

#

Block state makes sure its per block

#

I'm pretty sure a loose value is universally shared

craggy escarp
#

Yeah that's unfortunate

potent echo
#

But this is by far the easiest way to do it

#

If you want I could send an example when I'm home later

#

But I think you got this

craggy escarp
#

I feel dumb lol, I was just so against using a block state

#

But yeah, there's just no other option..

potent echo
#

What are you gonna do with it now

#

Custom Redstone? πŸ‘€

craggy escarp
#

Detect for redstone yup

potent echo
#

Nice, this type of stuff is gonna be awesome to see

craggy escarp
#

Ignoring my mental stupidity, this was easier than I expected

potent echo
#

Dw we all have our moments

#

I had a seizure one using a not on a block detect 😭

craggy escarp
#

lol

#

Im still pretty new to JS anyway so im proud of this

potent echo
#

I'm super new aswell πŸ’€

#

These last 2 weeks are like the first week's I actually started some serious coding lol

#

But great job nonetheless

craggy escarp
#

Thanks!

tribal coral
#

this could also be used for block connection

craggy escarp
#

Im most likely updating my fence template next

tribal coral
#

i was about to say also Kaioga i love your block data viewer pack

craggy escarp
#

Thanks! King made most of it iirc, is really useful

potent echo
tribal coral
#

its sad it doesnt work for other consoles as it doesnt import to realms

#

the block data viewer

tribal coral
potent echo
#

When I'm home, not home atm

tribal coral
#

okay ty im working on FNAF Help Wanted Blocks i could use this for the Prize Counter Sign Block i been struggling with

potent echo
#

One of my favorites besides the originals

#

Are you doing low poly or Vanilla style

tribal coral
#

its acutally part of dlc for Hirx MC

#

i need to update it to 1.20.01 and up so it works with custom compoments

potent echo
#

Oh you I've seen this guy before

tribal coral
#

jajajaj yeah im that guy

potent echo
#

Well I'll release it later today

#

Give me like 4 hours our so

#

Even less actually

tribal coral
#

i'll be sure to credit you too.

potent echo
#

No need, I'm just happy to spread the knowledge

#

The more advancements we make as a community the better the addon quality

tribal coral
#

yep

potent echo
#

If anything just point others towards it so they can learn too

iron fern
potent echo
craggy escarp
iron fern
# craggy escarp Yup! Realized early today, changed it to: ```js block.west()?.ge...

You can use map if you don't want to use state... I know it's fixed but yeah, maybe in future

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

const blockStates = new Map();

world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockTypeRegistry.registerCustomComponent('kai:on_tick', {
        onTick(e) {
            const { block, dimension } = e;
            const { x, y, z } = block.location;
            const blockKey = `${x},${y},${z}`;

            // Get adjacent blocks
            const north = block.north();
            const east = block.east();
            const south = block.south();
            const west = block.west();
            const above = block.above();
            const below = block.below();

            // Check if any adjacent block has redstone power greater than 0
            const adjacentBlocks = [north, east, south, west, above, below];
            let hasRedstonePower = adjacentBlocks.some(adjacentBlock => adjacentBlock?.getRedstonePower() > 0);

            const previousState = blockStates.get(blockKey) || false;

            if (hasRedstonePower && !previousState) {
                // Send message if adjacent block gains power
                world.sendMessage("I have the power!!!");
                block.setPermutation(block.permutation.withState('kai:powered', true))
            } else if (!hasRedstonePower && previousState) {
                // Send message if adjacent block loses power
                world.sendMessage("I lost the power!!!");
                block.setPermutation(block.permutation.withState('kai:powered', false))
            }

            // Update the state
            blockStates.set(blockKey, hasRedstonePower);
        }
    });
});
craggy escarp
#

I think it'll be better for the template to use block states

#

What is Map though?

iron fern
# craggy escarp What is Map though?

data structure that allows you to store key-value pairs where both the keys and the values can be of any data type, including objects or primitive values like strings, numbers, or symbols.

#
const myMap = new Map();

myMap.set('key1', 'value1');
myMap.set(2, 'value2');
myMap.set({ key: 'objectKey' }, 'value3');

console.log(myMap.get('key1'));  // Output: 'value1'
console.log(myMap.get(2));        // Output: 'value2'
const objKey = { key: 'objectKey' };
console.log(myMap.get(objKey));   // Output: 'value3'


console.log(myMap.has('key1'));   // Output: true
console.log(myMap.has('unknownKey')); // Output: false

myMap.delete('key1');

 myMap.forEach((value, key) => {
    console.log(`${key}: ${value}`);
});
// Output:
// 2: value2
// [object Object]: value3

console.log(myMap.size); // Output: 2 (after deleting one entry)
craggy escarp
#

I see

#

That's good to know, thanks

iron fern
#

Or cannot interact with it fully

#

Try disabling the onTick and check if you can interact with it

craggy escarp
#

I can yeah

iron fern
#

That's also the reason I suggest not to use state

craggy escarp
#

That issue will be gone if I don't use a state?

iron fern
iron fern
craggy escarp
#

How would it change the open state with that?

#

I don't see anything that does it

iron fern
craggy escarp
#

Nice, that works well

#

Thanks!

iron fern
#

You're welcome heh

iron fern
craggy escarp
#

Most likely

iron fern
craggy escarp
#

Thanks! It'll be rewarding

#

[Scripting][error]-TypeError: cannot read property 'playSound' of undefined at onTick (onTick.js:49)

robust orioleBOT
#
Debug Result

There is an error in this [code](#1240355786996187238 message):

onTick.js:13:28 - error TS2339: Property 'player' does not exist on type 'BlockComponentTickEvent'.

13             const { block, player } = e;
                              ~~~~~~

craggy escarp
#

ph

iron fern
#

Wait

iron fern
craggy escarp
#

Nope

#

Didn't worked

iron fern
craggy escarp
#

Im using these sounds in on_interact

#

It says

[Scripting][error]-TypeError: Incorrect number of arguments to function. Expected 2-3, received 1    at onTick (onTick.js:49)
iron fern
#

Nvm im stupid

craggy escarp
iron fern
#

That's why I ask you to use block.dimension.playSound()

craggy escarp
craggy escarp
#

Yes

iron fern
# craggy escarp Yes

Wait don't use the const sound just put the name inside to test of it still persists the error

#

Iike directly put block.dimension.playSound('open.wodden_trapdoor'); @craggy escarp

robust orioleBOT
#
Debug Result

There is an error in this [code](#1240355786996187238 message):

onTick.js:49:29 - error TS2554: Expected 2-3 arguments, but got 1.

49             block.dimension.playSound(sound);
                               ~~~~~~~~~~~~~~~~

  @minecraft/server.d.ts:4940:32
    4940     playSound(soundId: string, location: Vector3, soundOptions?: WorldSoundOptions): void;
                                        ~~~~~~~~~~~~~~~~~
    An argument for 'location' was not provided.

craggy escarp
#

Yeah the error persists

iron fern
#

block.dimension.playSound('open.wodden_trapdoor', block.location); @craggy escarp

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

const blockStates = new Map();

world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockTypeRegistry.registerCustomComponent('kai:on_tick', {
        onTick(e) {
            const { block } = e;
            const { x, y, z } = block.location;
            const blockKey = `${x},${y},${z}`;
            const currentState = block.permutation.getState('kai:open');

            const north = block.north();
            const east = block.east();
            const south = block.south();
            const west = block.west();
            const above = block.above();
            const below = block.below();

            const adjacentBlocks = [north, east, south, west, above, below];
            let hasRedstonePower = adjacentBlocks.some(adjacentBlock => adjacentBlock?.getRedstonePower() > 0);

            const previousState = blockStates.get(blockKey) || false;

            if (hasRedstonePower && !previousState) {
                block.setPermutation(block.permutation.withState('kai:open', true));
                world.sendMessage("I have the power!!!");
            } else if (!hasRedstonePower && previousState) {
                block.setPermutation(block.permutation.withState('kai:open', false));
                world.sendMessage("I lost the power!!!");
            }

            blockStates.set(blockKey, hasRedstonePower);

            const sound = currentState ? 'open.wooden_trapdoor' : 'close.wooden_trapdoor';

            block.dimension.playSound(sound, block.location);
        }
    });
});```
robust orioleBOT
#
Debug Result

There is an error in this [code](#1240355786996187238 message):

<repl>.js:8:28 - error TS2339: Property 'player' does not exist on type 'BlockComponentTickEvent'.

8             const { block, player } = e;
                             ~~~~~~

craggy escarp
#

No error, but no sound played

craggy escarp
robust orioleBOT
#
No Errors

No errors in [code](#1240355786996187238 message)

iron fern
#

block.dimension.playSound('open.wodden_trapdoor', block.location); @craggy escarp

#

Did you try this?

craggy escarp
#

Doing block.dimension.playSound(sound, block.location); plays it constantly lol

iron fern
#

It makes sense cause you put that onTick

#

Put the sound player inside of the js if (hasRedstonePower.....

#

Get @craggy escarp?

craggy escarp
#

I think so, let me try

#

works, thanks!

iron fern
craggy escarp
#

I think is better if I do it without defining a constant for soun

#

Like this?

if (hasRedstonePower && !previousState) {
                // Send message if adjacent block gains power
                block.dimension.playSound('open.wodden_trapdoor', block.location);
                block.setPermutation(block.permutation.withState('kai:open', true));
                world.sendMessage("I have the power!!!");
            } else if (!hasRedstonePower && previousState) {
                // Send message if adjacent block loses power
                block.dimension.playSound('close.wodden_trapdoor', block.location);
                block.setPermutation(block.permutation.withState('kai:open', false));
                world.sendMessage("I lost the power!!!");
            }

Sound not playing tho

iron fern
craggy escarp
#

Im trying another thing now

iron fern
craggy escarp
#

What worked was block.dimension.playSound(sound, block.location);

#

Which I switched to avoud using any constant for sound

craggy escarp
#

But it isn't

iron fern
craggy escarp
#

only sound

iron fern
#
import { world } from '@minecraft/server';

const blockStates = new Map();

world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockTypeRegistry.registerCustomComponent('kai:on_tick', {
        onTick(e) {
            const { block } = e;
            const { x, y, z } = block.location;
            const blockKey = `${x},${y},${z}`;
            const currentState = block.permutation.getState('kai:open');

            const north = block.north();
            const east = block.east();
            const south = block.south();
            const west = block.west();
            const above = block.above();
            const below = block.below();

            const adjacentBlocks = [north, east, south, west, above, below];
            const sound = currentState ? 'open.wooden_trapdoor' : 'close.wooden_trapdoor';
            let hasRedstonePower = adjacentBlocks.some(adjacentBlock => adjacentBlock?.getRedstonePower() > 0);

            const previousState = blockStates.get(blockKey) || false;

            if (hasRedstonePower && !previousState) {
                block.setPermutation(block.permutation.withState('kai:open', true));
                world.sendMessage("I have the power!!!");
                block.dimension.playSound(sound, block.location);
            } else if (!hasRedstonePower && previousState) {
                block.setPermutation(block.permutation.withState('kai:open', false));
                world.sendMessage("I lost the power!!!");
                block.dimension.playSound(sound, block.location);
            }

            blockStates.set(blockKey, hasRedstonePower);
        }
    });
});```
robust orioleBOT
#
No Errors

No errors in [code](#1240355786996187238 message)

craggy escarp
#

I guess I have to use the constant πŸ€·β€β™‚οΈ

#

No idea why, it just makes no sense

#

But whatever

iron fern
craggy escarp
#

Yeah that will work, just wanted to not use a constant for sound if it was not needed

robust orioleBOT
#
No Errors

No errors in [code](#1240355786996187238 message)

iron fern
craggy escarp
#

Not for now

#

Well yes

craggy escarp
iron fern
#

Right?

craggy escarp
#

spruce

iron fern
# craggy escarp spruce
const north = block.north();
            const east = block.east();
            const south = block.south();
            const west = block.west();
            const below = block.below();

            const adjacentBlocks = [north, east, south, west, below];```

Just exclude the `above`
craggy escarp
#

I have to check for above tho

#

Is just redstone torches that won't work if placed like that above

iron fern
craggy escarp
#

A redstone torch placed like that, yeah

iron fern
# craggy escarp A redstone torch placed like *that*, yeah
if (block.above().typeId !== 'minecraft:lit_redstone_torch' && hasRedstonePower && !previousState) {
                block.setPermutation(block.permutation.withState('kai:open', true));
                world.sendMessage("I have the power!!!");
                block.dimension.playSound(sound, block.location);
            } else if (!hasRedstonePower && previousState) {
                block.setPermutation(block.permutation.withState('kai:open', false));
                world.sendMessage("I lost the power!!!");
                block.dimension.playSound(sound, block.location);
            }```
craggy escarp
iron fern
craggy escarp
#

both are vanilla here

#

Spruce is the only custom trapdoor i'll show in this thread

iron fern
#

Can you check what's the available states of the lit redstone torch @craggy escarp ?

#

I need that as reference

craggy escarp
iron fern
craggy escarp
#

block.permutation.getState no?

iron fern
iron fern
# craggy escarp
import { world } from '@minecraft/server';

const blockStates = new Map();

world.beforeEvents.worldInitialize.subscribe(eventData => {
    eventData.blockTypeRegistry.registerCustomComponent('kai:on_tick', {
        onTick(e) {
            const { block } = e;
            const { x, y, z } = block.location;
            const blockKey = `${x},${y},${z}`;
            const currentState = block.permutation.getState('kai:open');

            const north = block.north();
            const east = block.east();
            const south = block.south();
            const west = block.west();
            const above = block.above();
            const below = block.below();

            const adjacentBlocks = [north, east, south, west, above, below];
            const sound = currentState ? 'open.wooden_trapdoor' : 'close.wooden_trapdoor';
            let hasRedstonePower = adjacentBlocks.some(adjacentBlock => adjacentBlock?.getRedstonePower() > 0);

            const blockAbove = block.above();
            const isRedstoneTorchTop = blockAbove?.typeId === 'minecraft:redstone_torch' &&
                blockAbove.permutation.getState('torch_facing_direction') === 'top';

            const previousState = blockStates.get(blockKey) || false;

            if (hasRedstonePower && !isRedstoneTorchTop && !previousState) {
                block.setPermutation(block.permutation.withState('kai:open', true));
                world.sendMessage("I have the power!!!");
                block.dimension.playSound(sound, block.location);
            } else if ((!hasRedstonePower || isRedstoneTorchTop) && previousState) {
                block.setPermutation(block.permutation.withState('kai:open', false));
                world.sendMessage("I lost the power!!!");
                block.dimension.playSound(sound, block.location);
            }

            blockStates.set(blockKey, hasRedstonePower && !isRedstoneTorchTop);
        }
    });
});
#

@craggy escarp

craggy escarp
#

Thank you!

#

Let me check

#

Ah I see what you made

iron fern
craggy escarp
#

No

iron fern
craggy escarp
#

Maybe im missing something, im not copying and pasting

#

Ah I see

#

It works well!

iron fern
iron fern
craggy escarp
iron fern
#

What's next?

craggy escarp
#

I will need to make the check skip a few blocks

#

Like trapdoors, in this case

iron fern
#

I'm not sure what you're asking, my bad

craggy escarp
#

The custom trapdoor should not open

iron fern
#

Wait the spruce is the custom one right?

craggy escarp
#

ye

iron fern
craggy escarp
#

Yep

iron fern
#

We can exclude that

iron fern
craggy escarp
#

nope

iron fern
#

How do we exclude it tho @craggy escarp ?

#

I mean what's the blcoks needed to be excluded?

craggy escarp
#

I fixed

iron fern
craggy escarp
#

Just

// Check if the adjacent block is not an excluded block and has redstone power greater than 0
            const adjacentBlocks = [north, east, south, west, above, below];
            let hasRedstonePower = adjacentBlocks.some(adjacentBlock => {
                return adjacentBlock?.typeId !== 'minecraft:trapdoor' && adjacentBlock?.getRedstonePower() > 0;
            });
#

Im not sure if there are any other issues

iron fern
#

It will exclude anything as long as there's trapdoor included in the blocks id

craggy escarp
#

It should not exclude everything tho

iron fern
craggy escarp
#

Not following

iron fern
craggy escarp
#

Don't think so

iron fern
#

What's next?

craggy escarp
#

Door?

iron fern
craggy escarp
#

Nope

#

Not yet

iron fern
craggy escarp
#

Unrelated question, would it be possible for me to:
Save block states of X block > Replace X block with Y block > Load saved states in Y block

iron fern
#

Blocks doesn't support Dynamic property unlike entity and items

craggy escarp
#

Lovely

#

Okay back to trapdoor

#

Same with any other redstone directional block

iron fern
#

And make sure it faces the trapdoor

#

Wait I'm thinking lmao

#

So like if the observer is placed on the west of the trapdoor, we need to make sure the observer is facing the trapdoor @craggy escarp

#

Get it?

craggy escarp
#

Yeah

#

Lemme try something

iron fern
#

Like check the west of the trapdoor what's the permutation of the observer to count it as powered

craggy escarp
iron fern
# craggy escarp

I can't help you with just that.... Umm this would be bit tricky tbh

#

Try listing it with a notepad or something cause imma help you with code.

#

Like.

north = <facing direction of the observer should be so it faces at trapdoor>

south = <facing direction of the observer should be so it faces at trapdoor>

west = <facing direction of the observer should be so it faces at trapdoor>

east = <facing direction of the observer should be so it faces at trapdoor>

above = <facing direction of the observer should be so it faces at trapdoor>

below = <facing direction of the observer should be so it faces at trapdoor>

#

@craggy escarp

craggy escarp
#

Im very confused

iron fern
iron fern
craggy escarp
#

Shouldn't I just check if the neighboring block is an observer && is north (example) && cardinal direction is south (example)

robust orioleBOT
#
Debug Result

There are 5 errors in this [code](#1240355786996187238 message):

onTick-1.js:13:28 - error TS2339: Property 'player' does not exist on type 'BlockComponentTickEvent'.

13             const { block, player } = e;
                              ~~~~~~

``````ansi
onTick-1.js:39:59 - error TS2367: This comparison appears to be unintentional because the types 'number' and 'string' have no overlap.

39                 north?.typeId === 'minecraft:observer' && north?.permutation.getState('facing_direction') === 'south',
                                                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
onTick-1.js:40:58 - error TS2367: This comparison appears to be unintentional because the types 'number' and 'string' have no overlap.

40                 east?.typeId === 'minecraft:observer' && east?.permutation.getState('facing_direction') === 'west',
                                                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
onTick-1.js:41:59 - error TS2367: This comparison appears to be unintentional because the types 'number' and 'string' have no overlap.

41                 south?.typeId === 'minecraft:observer' && south?.permutation.getState('facing_direction') === 'north',
                                                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

``````ansi
onTick-1.js:42:58 - error TS2367: This comparison appears to be unintentional because the types 'number' and 'string' have no overlap.

42                 west?.typeId === 'minecraft:observer' && west?.permutation.getState('facing_direction') === 'east'
                                                            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

iron fern
robust orioleBOT
#
No Errors

No errors in [code](#1240355786996187238 message)

iron fern
#

Mybad it took too long.

craggy escarp
#

Works well!

#

Thank you very much

iron fern
iron fern
craggy escarp
#

Still have more work to do, i'll ask here if I have any other doubts, thank you (:

iron fern
#

@craggy escarp

#

We forgot about the above and below

#

Can you check the name of the permutation if the observer is facing up and down?

#

Sorry I forgot about that

craggy escarp
#

Actually @iron fern it doesn't works as intended

tribal coral
#

why do you interact block with custom compoment?

#

is this a bug?

craggy escarp
#

Yeah

tribal coral
#

okay so it will be fixed or is it already fixed in future versions?

craggy escarp
#

It should be fixed, yes

#

When is yet unknown

iron fern
craggy escarp
#

I fixed it πŸ‘

tribal coral
#

is this wrong? how would i fix it?

iron fern
#

e.block.setPermutation(block.permutation.withState('minecraft:cardinal_direction', 'north'))

tribal coral
iron fern
# tribal coral
const direction = block.permutation.getState('minecraft:cardinal_direction');

if (direction === 'north') {
   world.sendMessage('North');
}
#

Gets??

tribal coral
#

ty im trying to work on the block connection using this method

tribal coral
#

nvm it works xd

tribal coral
#

I DID IT

craggy escarp
#

Nice nice!!!

tribal coral
#

i had tor remove it from custom components because it crashes

craggy escarp
#

Something like that should work fine with on player placed

iron fern
#

Which does decrease the ticks

iron fern
craggy escarp
iron fern
#

Don't use onTick, unless you want to make math that if there's no entity on the fence summon another one

craggy escarp
#

Like vanilla fences

#

I'll create a new post to mantain things organized