首页 > 解决方案 > 使用项目后标记位置 || Minecraft 插件 Spigot Bukkit

问题描述

我想将玩家点击的方块的位置保存到两个变量中。

我尝试在使用该项目后触发一个事件开始,但该事件仅在我单击空中时生成。

if (p.getItemInHand().getType() == Material.BLAZE_ROD) { System.out.println("TEST"); }

我也尝试过这种设计,但代码仍然无法正常工作:

if ((p.getItemInHand().getType() == Material.BLAZE_ROD) && (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { System.out.println("TEST"); }

总之,我想将两个指示块的位置写入变量。一种是右键单击给定项目,另一种是左键单击相同项目。

我还没有搜索过,但我会马上问,如何检查给定坐标处的块是否存在(是否为空,是否为空气)以及如何设置或替换给定坐标处的选定块一?

标签: javapluginsminecraftbukkit

解决方案


您可以通过PlayerInteractEventAction和实现此Material目的Location。一个例子如下:

import org.bukkit.Location;
import org.bukkit.event.EventHandler;

import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.block.Action;

import org.bukkit.block.Block;
import org.bukkit.Material;

public class YourListener {

    private Location firstLocation;
    private Location secondLocation;
    
    @EventHandler
    public void onPlayerInteractEvent(PlayerInteractEvent event) {
        // Only process when the player has a wooden axe in the hand.
        if (event.getMaterial() == Material.WOODEN_AXE) {
            Action action = event.getAction();
            Block clickedBlock = event.getClickedBlock();
            if (clickedBlock == null) return;
            if (action == Action.LEFT_CLICK_AIR || action == Action.LEFT_CLICK_BLOCK) {
                // Do one thing (left click)
                Material type = clickedBlock.getType(); // Block material (Check if it's Material.AIR or another type)
                firstLocation = clickedBlock.getLocation(); // Save the location
            } else if (action == Action.RIGHT_CLICK_AIR || action == Action.RIGHT_CLICK_BLOCK){
                // Do another thing (right click)
                Material type = clickedBlock.getType(); // Block material (Check if it's Material.AIR or another type)
                secondLocation = clickedBlock.getLocation(); // Save location
                // Let's say you now want to replace the block material to a diamond block:
                clickedBlock.setType(Material.DIAMOND_BLOCK);
            }
        }
    }

}

PlayerInteractEvent具有返回的方法getMaterial()

返回此事件所代表的项目的材质

(玩家手中物品的材质)

然后该getAction()方法返回以下枚举条目之一

  • Action.LEFT_CLICK_AIR: 左键点击空气
  • Action.LEFT_CLICK_BLOCK: 左键点击方块
  • Action.RIGHT_CLICK_AIR: 右键空气
  • Action.RIGHT_CLICK_BLOCK: 右击方块

getClickedBlock()方法返回玩家点击的方块。然后您可以使用方法getType()setType(Material)获取和设置该块的材质。

最后,getLocation()from 方法Block将返回该块的位置。

确保阅读有关此类、枚举和接口的所有文档:


推荐阅读