Skip to content

Example: Simple drawing and click handling

Maximilian Dorn edited this page Sep 12, 2023 · 5 revisions

Simple drawing and click handling

Image this example in action

import dev.cerus.maps.api.MapScreen;
import dev.cerus.maps.api.Marker;
import dev.cerus.maps.api.event.PlayerClickScreenEvent;
import dev.cerus.maps.api.graphics.ColorCache;
import dev.cerus.maps.api.graphics.MapGraphics;
import dev.cerus.maps.plugin.map.MapScreenRegistry;
import dev.cerus.maps.util.Vec2;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.map.MapCursor;
import org.bukkit.map.MinecraftFont;
import org.bukkit.plugin.java.JavaPlugin;

public class ExamplePlugin extends JavaPlugin implements Listener {

    @Override
    public void onEnable() {
        this.getServer().getPluginManager().registerEvents(this, this);
    }

    @EventHandler
    public void onScreenClick(final PlayerClickScreenEvent event) {
        final MapScreen screen = event.getClickedScreen();
        final Vec2 pos = event.getClickPos();

        final MapGraphics<?, ?> graphics = screen.getGraphics();
        graphics.fillComplete(ColorCache.rgbToMap(255, 255, 255));

        final String text = "You've clicked at %d %d".formatted(pos.x, pos.y);
        // Draw centered text
        graphics.drawText(
                (graphics.getWidth() / 2) - (MinecraftFont.Font.getWidth(text) * 2 / 2),
                (graphics.getHeight() / 2) - (MinecraftFont.Font.getHeight() * 2 / 2),
                text,
                ColorCache.rgbToMap(0, 0, 0),
                2
        );

        screen.clearMarkers();
        screen.addMarker(new Marker(
                pos.x * 2 + 2,
                pos.y * 2 + 2,
                (byte) 0, MapCursor.Type.RED_X, true, new TextComponent("HERE!")
        ));

        // Send map updates to every online player and cancel event
        screen.sendMaps(false);
        event.setCancelled(true);
    }

    @EventHandler
    public void onJoin(final PlayerJoinEvent event) {
        // Make every screen visible to the player
        for (final MapScreen screen : MapScreenRegistry.getScreens()) {
            screen.spawnFrames(event.getPlayer());
            screen.sendMaps(true, event.getPlayer());
        }
    }

}