Skip to content

InstrumentPlayedEvent

StavWasPlayZ edited this page Jun 11, 2023 · 1 revision

This is an event that is fired from both the client and server side on the Forge event bus, whenever an instrument sound is produced.
The event will trigger for both players and non-players. However, if you wish to listen to player events in specific, you may do so by subscribing to InstrumentPlayedEvent.ByPlayer instead. There, extra information about the player will be provided.

NOTE: Clients will only receive play events from other players within 16 blocks of range, and themselves.

Usages

Sevrer-side

Whenever a player plays a note instrument, it will trigger for them the instrument-specific InstrumentPlayedTrigger trigger. This is done through the InstrumentPlayedEvent.ByPlayer event (source file):

@SubscribeEvent
public static void onInstrumentPlayed(final InstrumentPlayedEvent.ByPlayer event) {
    if (!event.isClientSide)
        INSTRUMENT_PLAYED_TRIGGER.trigger((ServerPlayer)event.player, new ItemStack(ForgeRegistries.ITEMS.getValue(event.instrumentId)));
}

Client-side

To make the shared notes feature a thing, we must listen to any nearby players playing (source file):

@SubscribeEvent
public static void onInstrumentPlayed(final InstrumentPlayedEvent event) {
    if (!event.isClientSide)
        return;

    // If this sound was produced by a player, and that player is ourselves - omit.
    if ((event instanceof ByPlayer) && ((ByPlayer)(event)).player.equals(MINECRAFT.player))
        return;

    // Safeguards etc...

    final AbstractInstrumentScreen screen = (AbstractInstrumentScreen) MINECRAFT.screen;
    // The instrument sound produced has to match the current screen's sounds
    if (!screen.getInstrumentId().equals(event.instrumentId))
        return;
    // Only show the played note in a close distance
    if (!event.pos.closerThan(MINECRAFT.player.blockPosition(), ServerUtil.PLAY_DISTANCE / 3))
        return;


    for (NoteButton note : screen.notesIterable())
        if (note.sound.equals(event.sound)) {
            note.playNoteAnimation(true);
            return;
        }
}
Clone this wiki locally