/
SpellDrainLife.zn
169 lines (136 loc) · 7.55 KB
/
SpellDrainLife.zn
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
library SpellDrainLife requires optional HandleHT {
/* === Настройки заклинания === */
constant integer abilityId = 'SUdl'; // Равкод способности
constant string lightingType = "DRAL"; // Тип молнии
constant real lightingZ = 50; // Высота молнии
constant real timerPeriod = .05; // Частота срабатывания таймера
constant real damagePeriod = 1; // Частота нанесения урона
constant string casterEffectPath = "Abilities\\Spells\\Other\\Drain\\DrainCaster.mdl";
constant string casterEffectAttach = "chest";
constant string targetEffectPath = "Abilities\\Spells\\Other\\Drain\\DrainTarget.mdl";
constant string targetEffectAttach = "chest";
hashtable ht; // Хэштаблица для записи данных на хэндл юнита
key drainKey; // Ключ для хранения структуры на юните
location loc = Location(0, 0); // Точка для получения высоты
unit caster, target;
timer ticker;
integer level, casterId, tickerId;
real distanceMax;
// Время действия
function getExpireTime() -> real {
return I2R(5+level);
}
// Максимальная дальность
function getDistanceMax() -> real {
return I2R(1000 + 200*level);
}
// Функция, вызываемая при нанесении урона
function onDamage() {
real damage = 20 + level*20; // 40/60/80
UnitDamageTarget(caster, target, damage, false, true, ATTACK_TYPE_MAGIC, DAMAGE_TYPE_NORMAL, WEAPON_TYPE_WHOKNOWS);
SetWidgetLife(caster, GetWidgetLife(caster) + damage);
}
/* === Реализация заклинания === */
// Реализуем свою функцию получения высоты юнита, чтоб не тянуть зависимости
function GetUnitZ(unit target) -> real {
MoveLocation(loc, GetUnitX(target), GetUnitY(target));
return GetLocationZ(loc) + GetUnitFlyHeight(target);
}
// Реализуем свою функцию получения квадрата расстояния в 3D, чтоб не считать корень
function Distance(real xa, real ya, real za, real xb, real yb, real zb) -> real {
real dx = xb - xa;
real dy = yb - ya;
real dz = zb - za;
return dx*dx + dy*dy + dz*dz;
}
function destroy(){
tickerId = GetHandleId(ticker);
PauseTimer(ticker);
DestroyTimer(ticker);
RemoveSavedInteger(ht, casterId, drainKey);
DestroyLightning(LoadLightningHandle(ht, tickerId, 'ligt'));
DestroyEffect(LoadEffectHandle(ht, tickerId, 'effC'));
DestroyEffect(LoadEffectHandle(ht, tickerId, 'effT'));
FlushChildHashtable(ht, tickerId);
}
function onInit(){
trigger t = CreateTrigger();
integer i;
// Используем одну хэштаблицу для хранения данных на хэндлах
// При её отсутствии инициализируем новую
static if (LIBRARY_HandleHT) ht = HandleHT;
else ht = InitHashtable();
// Слушаем событие каста для всех игроков, экономя лишний вызов функции
for (0 <= i < bj_MAX_PLAYER_SLOTS) TriggerRegisterPlayerUnitEvent(t, Player(i), EVENT_PLAYER_UNIT_SPELL_EFFECT, null);
TriggerAddAction(t, function(){
if (abilityId != GetSpellAbilityId()) return; // Используем return чтоб не использовать Condition
caster = GetTriggerUnit();
casterId = GetHandleId(caster);
target = GetSpellTargetUnit();
// Удаляем предыдущий таймер, если он существует
ticker = LoadTimerHandle(ht, casterId, drainKey);
if (ticker != null) destroy();
// Создаём таймер и сохраняем на него нужные данные
ticker = CreateTimer();
tickerId = GetHandleId(ticker);
SaveTimerHandle(ht, casterId, drainKey, ticker); // Сохраняем таймер на кастера для уничтожения предыдущей молнии
SaveUnitHandle(ht, tickerId, 'cast', caster);
SaveUnitHandle(ht, tickerId, 'targ', target);
level = GetUnitAbilityLevel(caster, abilityId);
SaveInteger(ht, tickerId, 'levl', level);
distanceMax = getDistanceMax();
SaveReal(ht, tickerId, 'dist', distanceMax * distanceMax); // Используем квадрат расстояния, чтоб не считать корень
SaveReal(ht, tickerId, 'expr', getExpireTime());
SaveReal(ht, tickerId, 'perd', 0);
SaveReal(ht, tickerId, 'time', 0);
SaveLightningHandle(ht, tickerId, 'ligt', AddLightningEx(
lightingType,
true,
GetUnitX(caster),
GetUnitY(caster),
GetUnitZ(caster) + lightingZ,
GetUnitX(target),
GetUnitY(target),
GetUnitZ(target) + lightingZ
));
SaveEffectHandle(ht, tickerId, 'effC', AddSpecialEffectTarget(casterEffectPath, caster, casterEffectAttach));
SaveEffectHandle(ht, tickerId, 'effT', AddSpecialEffectTarget(targetEffectPath, target, targetEffectAttach));
TimerStart(ticker, timerPeriod, true, function() {
real xc, yc, zc, xt, yt, zt, time;
ticker = GetExpiredTimer();
tickerId = GetHandleId(ticker);
caster = LoadUnitHandle(ht, tickerId, 'cast');
casterId = GetHandleId(caster);
target = LoadUnitHandle(ht, tickerId, 'targ');
level = LoadInteger(ht, tickerId, 'levl');
// Считаем количество времени, прошедшего с момента каста для нанесения урона
time = LoadReal(ht, tickerId, 'perd') + timerPeriod;
if (time >= damagePeriod){
time = 0;
onDamage();
}
SaveReal(ht, tickerId, 'perd', time);
// Двигаем молнию за целями
xc = GetUnitX(caster);
yc = GetUnitY(caster);
zc = GetUnitZ(caster) + lightingZ;
xt = GetUnitX(target);
yt = GetUnitY(target);
zt = GetUnitZ(target) + lightingZ;
MoveLightningEx(LoadLightningHandle(ht, tickerId, 'ligt'), true, xc, yc, zc, xt, yt, zt);
// Считаем прошедшее время
time = LoadReal(ht, tickerId, 'time') + timerPeriod;
SaveReal(ht, tickerId, 'time', time);
// При несоблюдении одного из условий прекращаем действие заклинаия
if (
!UnitAlive(caster) ||
!UnitAlive(target) ||
time >= LoadReal(ht, tickerId, 'expr') ||
Distance(xc, yc, zc, xt, yt, zt) >= LoadReal(ht, tickerId, 'dist') ||
GetUnitCurrentOrder(caster) == 851973/*stunned*/
) destroy();
});
});
t = null;
}
}