GroovyEffect - 视觉效果基类
GroovyEffect 是自定义视觉效果的抽象基类,继承自 Kotlin 核心的 VisualEffect 类。封装了效果生命周期管理的常用字段和方法。
类定义
groovy
package scripts.libs
import cn.org.bukkit.craneattribute.core.effect.VisualEffect
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
abstract class GroovyEffect extends VisualEffect {
Player looker // 观察者玩家
Entity entity // 目标实体
long duration // 持续时间(tick)
GroovyEffect(Player looker, Entity entity, long duration) {
this.looker = looker
this.entity = entity
this.duration = duration
}
// ...
}生命周期方法
| 方法 | 调用时机 | 用途 |
|---|---|---|
onSpawn() | 调用 spawn() 后立即执行 | 创建全息字、粒子等初始资源 |
onTick() | 每个游戏刻调用一次 | 更新动画、移动位置、播放音效 |
onDespawn() | 持续时间到期后调用 | 删除全息字、停止粒子、释放资源 |
常用字段
| 字段 | 类型 | 说明 |
|---|---|---|
looker | Player | 能看到此效果的观察者 |
entity | Entity | 效果关联的目标实体 |
duration | long | 持续 tick 数(20 tick = 1 秒) |
tick | long | 当前已运行的 tick 数(自动递增) |
end | boolean | 标记效果是否已结束 |
使用示例
groovy
package scripts.expansions
import groovy.transform.CompileStatic
import org.bukkit.entity.Entity
import org.bukkit.entity.Player
import scripts.libs.GroovyEffect
@CompileStatic
class DamageEffect extends GroovyEffect {
private String message
DamageEffect(Player looker, Entity entity, String message, long duration) {
super(looker, entity, duration)
this.message = message
}
@Override
void onSpawn() {
if (looker != null && looker.isOnline()) {
looker.sendMessage(message)
}
}
@Override
void onTick() {
// 每 tick 逻辑——此处为简单示例
}
@Override
void onDespawn() {
if (looker != null && looker.isOnline()) {
looker.sendMessage("§7效果结束")
}
}
}
// 使用:new DamageEffect(player, entity, "§e触发!", 40).spawn()注意事项
- 必须在
onDespawn()中清理所有创建的资源(全息字、粒子等),否则造成内存泄漏 - 避免在
onTick()中执行耗时操作 - 使用前检查
entity和looker是否有效(非 null、在线) - 所有操作必须在主线程执行
