// Набор игроков, у которых включена аура
private final Set<Player> auraPlayers = ConcurrentHashMap.newKeySet();
// Карта для хранения аур игроков и их изумрудов
private final Map<UUID, PlayerAura> playerAuras = new ConcurrentHashMap<>();
// Количество изумрудов в ауре
private final int emeraldCount = 10;
@Override
public void onEnable() {
getLogger().info("AuraPlugin включен!");
// Регистрация команды
Objects.requireNonNull(getCommand("aura")).setExecutor(this);
// Запуск задачи для обновления аур
startAuraUpdateTask();
}
@Override
public void onDisable() {
getLogger().info("AuraPlugin выключен.");
// Удаление всех аур при выключении плагина
for (PlayerAura aura : playerAuras.values()) {
aura.removeAura();
}
playerAuras.clear();
auraPlayers.clear();
}
// Обработка команды /aura [on|off] <игрок>
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("aura")) {
if (!sender.hasPermission("aura.use")) {
sender.sendMessage(ChatColor.RED + "У вас нет прав использовать эту команду.");
return true;
}
if (args.length != 2) {
sender.sendMessage(ChatColor.RED + "Использование: /aura <on|off> <игрок>");
return true;
}
String action = args[0];
String playerName = args[1];
Player target = Bukkit.getPlayerExact(playerName);
if (target == null) {
sender.sendMessage(ChatColor.RED + "Игрок не найден.");
return true;
}
if (action.equalsIgnoreCase("on")) {
if (auraPlayers.contains(target)) {
sender.sendMessage(ChatColor.YELLOW + "Аура уже включена для " + target.getName() + ".");
} else {
auraPlayers.add(target);
PlayerAura aura = new PlayerAura(target);
playerAuras.put(target.getUniqueId(), aura);
sender.sendMessage(ChatColor.GREEN + "Аура включена для " + target.getName() + ".");
}
} else if (action.equalsIgnoreCase("off")) {
if (!auraPlayers.contains(target)) {
sender.sendMessage(ChatColor.YELLOW + "У этого игрока не была включена аура.");
} else {
auraPlayers.remove(target);
PlayerAura aura = playerAuras.remove(target.getUniqueId());
if (aura != null) {
aura.removeAura();
}
sender.sendMessage(ChatColor.GREEN + "Аура отключена для " + target.getName() + ".");
}
} else {
sender.sendMessage(ChatColor.RED + "Неизвестное действие. Используйте on или off.");
}
return true;
}
return false;
}
// Класс для управления аурой игрока
private static class PlayerAura {
private final Player player;
private final List<Item> emeralds = new ArrayList<>();
private double angleOffset; // Начальный угол для различия аур разных игроков
private final double radius = 1.0; // Радиус ауры
private final double speed; // Скорость вращения
private final Random random = new Random();
PlayerAura(Player player) {
this.player = player;
this.angleOffset = random.nextDouble() * 360; // Случайный начальный угол
// Установка случайной скорости вращения для разнообразия
this.speed = 0.02 + (random.nextDouble() * 0.02); // От 0.02 до 0.04 радиан за тик
spawnEmeralds();
}
// Спавн изумрудов вокруг игрока
private void spawnEmeralds() {
Location baseLocation = player.getLocation().clone().add(0, 1.5, 0); // Положение над головой
for (int i = 0; i < 10; i++) { // 10 изумрудов
double angleDegree = (360 / 10.0) * i + angleOffset;
double angle = Math.toRadians(angleDegree);
double x = radius * Math.cos(angle);
double z = radius * Math.sin(angle);
Location spawnLocation = baseLocation.clone().add(x, 0, z);
// Создание изумруда
Item emerald = player.getWorld().dropItemNaturally(spawnLocation, new ItemStack(Material.EMERALD));
emerald.setVelocity(new Vector(0, 0, 0)); // Остановка движения
emerald.setPickupDelay(Integer.MAX_VALUE); // Запрет на подбор
emerald.setGravity(false); // Отключение гравитации для плавного кружения
emeralds.add(emerald);
}
}
// Обновление позиции изумрудов (кружение и падение)
public void updateAura() {
Location baseLocation = player.getLocation().clone().add(0, 1.5, 0); // Положение над головой
angleOffset += speed;
if (angleOffset >= 360) {
angleOffset -= 360;
}
for (int i = 0; i < emeralds.size(); i++) {
Item emerald = emeralds.get(i);
if (emerald.isDead() || !emerald.isValid()) {
emeralds.remove(emerald);
i--;
continue;
}
double angleDegree = (360 / (double) emeralds.size()) * i + angleOffset;
double angle = Math.toRadians(angleDegree);
double x = radius * Math.cos(angle);
double z = radius * Math.sin(angle);
// Плавное колебание вверх-вниз для эффекта дождя
double y = 1.5 + Math.sin(System.currentTimeMillis() / 500.0 + i) * 0.3;
Location newLocation = baseLocation.clone().add(x, y, z);
emerald.teleport(newLocation);
// Добавление эффекта легкого ускорения вниз
Vector velocity = emerald.getVelocity();
velocity.setY(velocity.getY() - 0.005); // Легкое ускорение вниз
emerald.setVelocity(velocity);
}
}
// Удаление всех изумрудов ауры
public void removeAura() {
for (Item emerald : emeralds) {
emerald.remove();
}
emeralds.clear();
}
}
// Запуск периодической задачи для обновления аур
private void startAuraUpdateTask() {
new BukkitRunnable() {
@Override
public void run() {
for (PlayerAura aura : new ArrayList<>(playerAuras.values())) {
if (!aura.player.isOnline()) {
removeAura(aura.player);
continue;
}
aura.updateAura();
}
}
}.runTaskTimer(this, 0L, 2L); // Запуск каждые 2 тика (~0.1 сек)
}
// Метод для удаления ауры у игрока
private void removeAura(Player player) {
auraPlayers.remove(player);
PlayerAura aura = playerAuras.remove(player.getUniqueId());
if (aura != null) {
aura.removeAura();
}
}
}
name: AuraPlugin
main: com.example.auraplugin.AuraPlugin
version: 1.0
api-version: 1.20
description: Плагин добавляет ауру изумрудов вокруг выбранных игроков.
commands:
aura:
description: Включить или отключить ауру для игрока.
usage: /aura <on|off> <игрок>
permission: aura.use
permissions:
aura.use:
description: Позволяет использовать команду /aura
default: op
Уже лучше, но надо, чтобы изумруда падали вниз, и под игроком исчезали, напиши сразу полный код
Certainly! Below is the complete code for the AuraPlugin, modified to make emeralds fall downward and disappear once they are below the player. This includes both the Java source code and the plugin.yml configuration file.
Java Source Code: AuraPlugin.java
java
package com.example.auraplugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Item;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class AuraPlugin extends JavaPlugin {
// Set of players with the aura enabled
private final Set<Player> auraPlayers = ConcurrentHashMap.newKeySet();
// Map to store player auras and their emeralds
private final Map<UUID, PlayerAura> playerAuras = new ConcurrentHashMap<>();
// Number of emeralds in the aura
private final int emeraldCount = 10;
@Override
public void onEnable() {
getLogger().info("AuraPlugin has been enabled!");
// Register the command
Objects.requireNonNull(getCommand("aura")).setExecutor(this);
// Start the task to update auras
startAuraUpdateTask();
}
@Override
public void onDisable() {
getLogger().info("AuraPlugin has been disabled.");
// Remove all auras when the plugin is disabled
for (PlayerAura aura : playerAuras.values()) {
aura.removeAura();
}
playerAuras.clear();
auraPlayers.clear();
}
/**
* Handles the /aura command.
* Usage: /aura <on|off> <player>
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equalsIgnoreCase("aura")) {
if (!sender.hasPermission("aura.use")) {
sender.sendMessage(ChatColor.RED + "You do not have permission to use this command.");
return true;
}
if (args.length != 2) {
sender.sendMessage(ChatColor.RED + "Usage: /aura <on|off> <player>");
return true;
}
String action = args[0];
String playerName = args[1];
Player target = Bukkit.getPlayerExact(playerName);
if (target == null) {
sender.sendMessage(ChatColor.RED + "Player not found.");
return true;
}
if (action.equalsIgnoreCase("on")) {
if (auraPlayers.contains(target)) {
sender.sendMessage(ChatColor.YELLOW + "Aura is already enabled for " + target.getName() + ".");
} else {
auraPlayers.add(target);
PlayerAura aura = new PlayerAura(target);
playerAuras.put(target.getUniqueId(), aura);
sender.sendMessage(ChatColor.GREEN + "Aura has been enabled for " + target.getName() + ".");
}
} else if (action.equalsIgnoreCase("off")) {
if (!auraPlayers.contains(target)) {
sender.sendMessage(ChatColor.YELLOW + "Aura is not enabled for this player.");
} else {
auraPlayers.remove(target);
PlayerAura aura = playerAuras.remove(target.getUniqueId());
if (aura != null) {
aura.removeAura();
}
sender.sendMessage(ChatColor.GREEN + "Aura has been disabled for " + target.getName() + ".");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown action. Use 'on' or 'off'.");
}
return true;
}
return false;
}
/**
* Inner class to manage a player's aura.
*/
private static class PlayerAura {
private final Player player;
private final List<Item> emeralds = new ArrayList<>();
private double angleOffset; // Initial angle for variation among players
private final double spawnHeight = 3.0; // Height above the player to spawn emeralds
private final double horizontalRadius = 1.5; // Horizontal radius of the spawn circle
private final Random random = new Random();
PlayerAura(Player player) {
this.player = player;
this.angleOffset = random.nextDouble() * 360; // Random initial angle
spawnEmeralds();
}
/**
* Spawns emeralds above the player in a circular pattern.
*/
private void spawnEmeralds() {
Location baseLocation = player.getLocation().clone().add(0, spawnHeight, 0);
for (int i = 0; i < 10; i++) { // 10 emeralds
double angleDegree = (360 / 10.0) * i + angleOffset;
double angle = Math.toRadians(angleDegree);
double x = horizontalRadius * Math.cos(angle);
double z = horizontalRadius * Math.sin(angle);
Location spawnLocation = baseLocation.clone().add(x, 0, z);
// Create the emerald item
Item emerald = player.getWorld().dropItemNaturally(spawnLocation, new ItemStack(Material.EMERALD));
emerald.setPickupDelay(Integer.MAX_VALUE); // Prevent pickup
emerald.setVelocity(new org.bukkit.util.Vector(0, -0.1, 0)); // Give a slight downward velocity
emeralds.add(emerald);
}
}
/**
* Updates the positions of emeralds.
* Emeralds fall naturally due to gravity and are removed once below the player.
*/
public void updateAura() {
Iterator<Item> iterator = emeralds.iterator();
while (iterator.hasNext()) {
Item emerald = iterator.next();
if (emerald.isDead() || !emerald.isValid()) {
iterator.remove();
continue;
}
Location emeraldLocation = emerald.getLocation();
Location playerLocation = player.getLocation();
// If the emerald is below the player's feet, remove it and respawn above
if (emeraldLocation.getY() < playerLocation.getY()) {
emerald.remove();
iterator.remove();
spawnSingleEmerald();
}
}
}
/**
* Spawns a single emerald above the player.
*/
private void spawnSingleEmerald() {
Location baseLocation = player.getLocation().clone().add(0, spawnHeight, 0);
double angleDegree = random.nextDouble() * 360;
double angle = Math.toRadians(angleDegree);
double x = horizontalRadius * Math.cos(angle);
double z = horizontalRadius * Math.sin(angle);
Location spawnLocation = baseLocation.clone().add(x, 0, z);
// Create the emerald item
Item emerald = player.getWorld().dropItemNaturally(spawnLocation, new ItemStack(Material.EMERALD));
emerald.setPickupDelay(Integer.MAX_VALUE); // Prevent pickup
emerald.setVelocity(new org.bukkit.util.Vector(0, -0.1, 0)); // Give a slight downward velocity
emeralds.add(emerald);
}
/**
* Removes all emeralds associated with this aura.
*/
public void removeAura() {
for (Item emerald : emeralds) {
if (emerald != null && !emerald.isDead()) {
emerald.remove();
}
}
emeralds.clear();
}
}
/**
* Starts a scheduled task to update all active auras.
*/
private void startAuraUpdateTask() {
new BukkitRunnable() {
@Override
public void run() {
for (PlayerAura aura : new ArrayList<>(playerAuras.values())) {
if (!aura.player.isOnline()) {
removeAura(aura.player);
continue;
}
aura.updateAura();
}
}
}.runTaskTimer(this, 0L, 2L); // Runs every 2 ticks (~0.1 seconds)
}
/**
* Removes the aura from the specified player.
*
* @param player The player whose aura should be removed.
*/
private void removeAura(Player player) {
auraPlayers.remove(player);
PlayerAura aura = playerAuras.remove(player.getUniqueId());
if (aura != null) {
aura.removeAura();
}
}
}
Explanation of Changes:
Emeralds Falling Down:
Removed Teleportation: The teleport method used to rotate emeralds around the player has been removed. Instead, emeralds are allowed to fall naturally due to gravity.
Enabled Gravity: By default, items have gravity enabled in Bukkit. Hence, setGravity(false) has been removed to allow emeralds to fall.
Set Initial Downward Velocity: Each emerald is given a slight downward velocity (0.1) to ensure they start falling immediately upon spawning.
Removing Emeralds Below the Player:
In the updateAura method, each emerald's Y-coordinate is checked against the player's Y-coordinate.
If an emerald is found below the player, it is removed and immediately respawned above the player to maintain a continuous aura effect.
Simplified Aura Management:
The aura now focuses solely on spawning emeralds above the player and managing their falling behavior.
The rotation logic has been removed to align with the desired falling effect.
Plugin Configuration: plugin.yml
yaml
name: AuraPlugin
main: com.example.auraplugin.AuraPlugin
version: 1.0
api-version: 1.20
description: A plugin that adds a falling emerald aura around selected players.
commands:
aura:
description: Enable or disable the falling emerald aura for a player.
usage: /aura <on|off> <player>
permission: aura.use
permissions:
aura.use:
description: Allows the use of the /aura command.
default: op
Explanation:
Plugin Metadata:
name: The name of the plugin.
main: The main class path.
version: Plugin version.
api-version: The Minecraft server API version the plugin is compatible with.
description: A brief description of what the plugin does.
Commands:
aura:
description: Explains what the command does.
usage: Shows the correct usage of the command.
permission: Specifies the permission node required to use the command.
Permissions:
aura.use:
description: Describes what the permission allows.
default: Sets the default permission level (op means only server operators can use it by default).
How to Compile and Install the Plugin
Set Up Your Development Environment:
Ensure you have Java Development Kit (JDK) installed.
Set up a build tool like Maven or Gradle. Below is a simple Maven setup.
Run mvn clean package to compile the plugin. The resulting JAR file will be in the target directory.
Install the Plugin:
Place the compiled AuraPlugin-1.0.jar (or whatever your JAR is named) into the plugins folder of your Spigot/Bukkit server.
Start or restart the server. The plugin should load, and you should see the message "AuraPlugin has been enabled!" in the server console.
Additional Notes
Performance Considerations:
Spawning multiple item entities can impact server performance, especially with many auras active simultaneously. Monitor your server's performance and adjust the number of emeralds or update intervals as necessary.
Customization:
Number of Emeralds: You can adjust the emeraldCount variable to change how many emeralds are in each aura.
Spawn Height & Radius: Modify the spawnHeight and horizontalRadius variables in the PlayerAura class to change where emeralds spawn relative to the player.
Enhancements:
Particle Effects: For a more visually appealing aura, consider adding particle effects alongside the emeralds.
Configuration File: Implement a config.yml to allow server administrators to customize settings without modifying the code.
Feel free to further customize and enhance the plugin to fit your specific needs!
Use the command /aura on <player> to enable the falling emerald aura for a specific player.
Use the command /aura off <player> to disable the aura.
Note: By default, only server operators (op) have permission to use this command. You can adjust permissions using a permissions plugin like LuckPerms if needed.