반응형
오늘의 목표
- 눈으로 보이는 타워 투사체 구현
- 타워 생성 시 연출 구현
- 타워 합성 시 연출 구현
투사체 구현 관련 코드입니다.
|
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
|
using UnityEngine;
public class Projectile : MonoBehaviour
{
private Transform _target;
private MonsterAI _targetMonster;
private float _speed;
private int _damage;
private float _lifeTime;
private float _lifeTimer;
private ProjectilePool _poolOwner;
public Projectile PrefabKey { get; private set; }
public void SetPoolOwner(ProjectilePool owner, Projectile prefabKey)
{
_poolOwner = owner;
PrefabKey = prefabKey;
}
public void Init(MonsterAI target, float speed, int damage, float lifeTime = 3f)
{
_targetMonster = target;
_target = (target != null) ? target.transform : null;
_speed = speed;
_damage = damage;
_lifeTime = lifeTime;
_lifeTimer = 0f;
}
private void Update()
{
_lifeTimer += Time.deltaTime;
if (_lifeTimer >= _lifeTime)
{
ReleaseOrDestroy();
return;
}
if (_target == null)
{
ReleaseOrDestroy();
return;
}
Vector3 to = _target.position - transform.position;
float distThisFrame = _speed * Time.deltaTime;
if (to.sqrMagnitude <= distThisFrame * distThisFrame)
{
Hit();
return;
}
Vector3 dir = to.normalized;
transform.position += dir * distThisFrame;
transform.forward = dir;
}
private void Hit()
{
if (_targetMonster != null)
_targetMonster.TakeDamage(_damage);
ReleaseOrDestroy();
}
private void ReleaseOrDestroy()
{
if (_poolOwner != null && ProjectilePool.Instance != null)
{
_poolOwner.Release(this);
return;
}
Destroy(gameObject);
}
}
|
cs |
타워 생성 및 합성 연출 관련 코드 입니다.
|
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
|
using UnityEngine;
using UnityEngine.InputSystem;
using Cysharp.Threading.Tasks;
public class TowerManager : MonoBehaviour
{
public static TowerManager Instance { get; private set; }
[Header("Placement")]
[SerializeField] private Camera mainCamera;
[SerializeField] private LayerMask tileLayerMask;
[Header("Random Build")]
[SerializeField] private TowerGrade buildRollGrade = TowerGrade.Normal;
[SerializeField] private TowerData[] buildPool;
public enum CombineMode
{
Exact,
Random
}
[Header("Combine")]
[SerializeField] private CombineMode combineMode = CombineMode.Exact;
private TowerBase _selectedTower;
private bool _combineBusy;
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
if (mainCamera == null)
{
mainCamera = Camera.main;
}
}
private void Update()
{
if (_combineBusy)
return;
if (Mouse.current == null)
return;
if (Mouse.current.leftButton.wasPressedThisFrame)
{
HandleClick();
}
if (Keyboard.current != null && Keyboard.current.vKey.wasPressedThisFrame)
{
combineMode = (combineMode == CombineMode.Exact) ? CombineMode.Random : CombineMode.Exact;
Debug.Log($"[CombineMode] {combineMode}");
}
if (Keyboard.current != null && Keyboard.current.cKey.wasPressedThisFrame)
{
if (_combineBusy)
return;
TryCombineSelectedTowerAsync().Forget();
}
}
private void HandleClick()
{
Vector2 mousePos = Mouse.current.position.ReadValue();
Ray ray = mainCamera.ScreenPointToRay(mousePos);
if (Physics.Raycast(ray, out RaycastHit hitTower, 1000f, LayerMask.GetMask("Tower")))
{
TowerBase tower = hitTower.collider.GetComponentInParent<TowerBase>();
if (tower != null)
{
SelectTower(tower);
return;
}
}
if (Physics.Raycast(ray, out RaycastHit hitTile, 1000f, tileLayerMask))
{
GridTile tile = hitTile.collider.GetComponent<GridTile>();
if (tile != null)
{
OnTileClicked(tile);
return;
}
}
ClearSelection();
}
private void SelectTower(TowerBase tower)
{
if (_selectedTower == tower)
return;
if (_selectedTower != null)
_selectedTower.SetSelected(false);
_selectedTower = tower;
_selectedTower.SetSelected(true);
}
private void ClearSelection()
{
if (_selectedTower != null)
_selectedTower.SetSelected(false);
_selectedTower = null;
}
public void OnTileClicked(GridTile tile)
{
TryPlaceTower(tile);
}
private void TryPlaceTower(GridTile tile)
{
if (!tile.IsEmpty)
{
Debug.Log("설치 불가 타일이거나 이미 타워가 있습니다.");
return;
}
if (GameManager.Instance == null)
{
Debug.LogError("GameManager 인스턴스가 없습니다.");
return;
}
TowerData rolledData = RollBuildTowerData();
if (rolledData == null)
return;
if (rolledData.towerPrefab == null)
{
Debug.LogError($"[TowerManager] towerPrefab is null in TowerData: {rolledData.name}");
return;
}
int cost = rolledData.buildCost;
if (GameManager.Instance.Gold < cost)
{
Debug.Log("골드가 부족합니다.");
return;
}
Vector3 spawnPos = tile.transform.position;
GameObject towerObj = Instantiate(rolledData.towerPrefab, spawnPos, Quaternion.identity);
TowerBase tower = towerObj.GetComponent<TowerBase>();
if (tower == null)
{
Debug.LogError("rolledData.towerPrefab에 TowerBase 컴포넌트가 없습니다.");
Destroy(towerObj);
return;
}
tower.SetData(rolledData);
tile.SetTower(tower);
tower.SetTile(tile);
GameManager.Instance.AddGold(-cost);
Debug.Log($"[Build] Rolled: {rolledData.towerId} ({rolledData.grade}), cost={cost}");
}
private TowerData RollBuildTowerData()
{
if (buildPool == null || buildPool.Length == 0)
{
Debug.LogError("[TowerManager] buildPool is empty. Assign TowerData assets in Inspector.");
return null;
}
int safety = 0;
while (safety < 50)
{
int idx = Random.Range(0, buildPool.Length);
TowerData d = buildPool[idx];
if (d != null && d.grade == buildRollGrade)
return d;
safety++;
}
Debug.LogWarning("[TowerManager] No TowerData matched buildRollGrade. Check buildPool contents.");
return null;
}
private TowerData RollMergeResultByGrade(TowerGrade targetGrade)
{
if (buildPool == null || buildPool.Length == 0)
{
Debug.LogError("[TowerManager] buildPool is empty. Cannot roll merge result.");
return null;
}
if (TowerDatabase.Instance != null)
{
return TowerDatabase.Instance.GetRandomByGrade(targetGrade);
}
int safety = 0;
while (safety < 100)
{
int idx = Random.Range(0, buildPool.Length);
TowerData d = buildPool[idx];
if (d != null && d.grade == targetGrade)
return d;
safety++;
}
Debug.LogWarning("[TowerManager] No TowerData matched targetGrade for merge result.");
return null;
}
private void FindExactTowers(TowerData grade, System.Collections.Generic.List<TowerBase> outList)
{
outList.Clear();
TowerBase[] allTowers = FindObjectsOfType<TowerBase>();
foreach (var t in allTowers)
{
TowerData d = t.GetData();
if (d == null)
continue;
if (d.towerId == grade.towerId && d.grade == grade.grade)
outList.Add(t);
}
}
private void FindSameGradeTowers(TowerGrade grade, System.Collections.Generic.List<TowerBase> outList)
{
outList.Clear();
TowerBase[] allTowers = FindObjectsOfType<TowerBase>();
foreach (var t in allTowers)
{
TowerData d = t.GetData();
if (d == null)
continue;
if (d.grade == grade)
outList.Add(t);
}
}
private async UniTaskVoid TryCombineSelectedTowerAsync()
{
if (_combineBusy)
return;
_combineBusy = true;
try
{
if (_selectedTower == null)
{
Debug.Log("선택된 타워가 없습니다.");
return;
}
TowerData selectedData = _selectedTower.GetData();
if (selectedData == null)
{
Debug.Log("현재 타워 데이터가 없습니다.");
return;
}
TowerGrade curGrade = selectedData.grade;
if (!TowerGradeHelper.TryGetNextGrade(curGrade, out TowerGrade nextGrade))
{
Debug.Log("더 이상 합성할 수 없는 등급입니다.");
return;
}
if (TowerDatabase.Instance == null)
{
Debug.LogError("TowerDatabase 인스턴스가 없습니다.");
return;
}
// 1) 후보 수집은 모드에 따라 다름
var candidates = new System.Collections.Generic.List<TowerBase>();
if (combineMode == CombineMode.Exact)
FindExactTowers(selectedData, candidates);
else
FindSameGradeTowers(curGrade, candidates);
if (candidates.Count < 3)
{
if (combineMode == CombineMode.Exact)
Debug.Log($"[Exact Combine] 조건 미충족: {selectedData.towerId} ({candidates.Count}/3)");
else
Debug.Log($"[Random Combine] 조건 미충족: grade={curGrade} ({candidates.Count}/3)");
return;
}
// 2) 3개 구성(선택 타워 포함 + 나머지 2개)
var mergeList = new System.Collections.Generic.List<TowerBase>(3);
mergeList.Add(_selectedTower);
for (int i = 0; i < candidates.Count && mergeList.Count < 3; i++)
{
if (candidates[i] == _selectedTower)
continue;
mergeList.Add(candidates[i]);
}
if (mergeList.Count < 3)
{
Debug.Log("합성 대상 3개를 구성하지 못했습니다.");
return;
}
// 3) 결과 TowerData 결정(모드에 따라 다름)
TowerData resultData = null;
if (combineMode == CombineMode.Exact)
{
string nextTowerId = GetNextTowerId(selectedData.towerId, nextGrade);
resultData = TowerDatabase.Instance.Get(nextTowerId);
if (resultData == null)
{
Debug.LogError($"다음 TowerData를 찾을 수 없습니다: {nextTowerId}");
return;
}
}
else
{
resultData = RollMergeResultByGrade(nextGrade);
if (resultData == null)
{
Debug.LogError($"혼합 합성 결과 TowerData를 뽑지 못했습니다. targetGrade={nextGrade}");
return;
}
}
if (TowerMergeVFX.Instance == null)
{
Debug.LogError("TowerMergeVFX.Instance가 없습니다. 씬에 TowerMergeVFX 오브젝트가 있어야 합니다.");
return;
}
Transform[] sources =
{
mergeList[0] != null ? mergeList[0].transform : null,
mergeList[1] != null ? mergeList[1].transform : null,
mergeList[2] != null ? mergeList[2].transform : null
};
Vector3 mergePoint = _selectedTower.transform.position;
Vector3 keepScale = _selectedTower.transform.localScale;
await TowerMergeVFX.Instance.PlayMergeAsync(
sources,
mergePoint,
() =>
{
for (int i = 0; i < mergeList.Count; i++)
{
if (mergeList[i] == null) continue;
if (mergeList[i] == _selectedTower) continue;
Destroy(mergeList[i].gameObject);
}
if (_selectedTower == null) return;
_selectedTower.transform.localScale = keepScale;
_selectedTower.SetData(resultData);
_selectedTower.SetSelected(true);
_selectedTower.PlaySpawnFeedback();
}
);
}
finally
{
_combineBusy = false;
}
}
private string GetNextTowerId(string currentId, TowerGrade nextGrade)
{
int idx = currentId.LastIndexOf('_');
if (idx < 0)
return currentId;
string baseId = currentId.Substring(0, idx);
return $"{baseId}_{nextGrade.ToString().ToLower()}";
}
}
|
cs |
|
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
|
using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
public class TowerMergeVFX : MonoBehaviour
{
public static TowerMergeVFX Instance { get; private set; }
[Header("Timing")]
[SerializeField] private float mergeDuration = 0.22f;
[Header("Motion")]
[SerializeField] private AnimationCurve moveCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f);
[SerializeField] private AnimationCurve scaleCurve = AnimationCurve.EaseInOut(0f, 1f, 1f, 0f);
[Header("FX")]
[SerializeField] private ParticleSystem mergeBurstPrefab;
private void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
}
// sources: 합성에 쓰이는 3개 타워(Transform)
// mergePoint: 빨려 들어갈 위치(대개 중앙 타일 or 결과 타워 생성 위치)
// afterVfx: 연출이 끝난 직후 실행할 실제 합성 로직(3개 제거 + 결과 생성 등)
public async UniTask PlayMergeAsync(Transform[] sources, Vector3 mergePoint, Action afterVfx)
{
if (sources == null || sources.Length == 0)
{
afterVfx?.Invoke();
return;
}
float dur = Mathf.Max(0.05f, mergeDuration);
int n = sources.Length;
Vector3[] startPos = new Vector3[n];
Vector3[] startScale = new Vector3[n];
for (int i = 0; i < n; i++)
{
if (sources[i] == null) continue;
startPos[i] = sources[i].position;
startScale[i] = sources[i].localScale;
}
float t = 0f;
while (t < dur)
{
t += Time.deltaTime;
float u = Mathf.Clamp01(t / dur);
float mu = (moveCurve != null) ? moveCurve.Evaluate(u) : u;
float su = (scaleCurve != null) ? scaleCurve.Evaluate(u) : (1f - u);
for (int i = 0; i < n; i++)
{
Transform tr = sources[i];
if (tr == null) continue;
tr.position = Vector3.Lerp(startPos[i], mergePoint, mu);
tr.localScale = startScale[i] * su;
}
await UniTask.Yield(PlayerLoopTiming.Update);
}
afterVfx?.Invoke();
if (mergeBurstPrefab != null)
{
Instantiate(mergeBurstPrefab, mergePoint, Quaternion.identity);
}
}
}
|
cs |
반응형
'게임 개발 > 랜덤 타워 디펜스' 카테고리의 다른 글
| [랜덤 타워 디펜스] Day 9 버프/디버프 시스템 (0) | 2026.01.08 |
|---|---|
| [랜덤 타워 디펜스] Day 8 몬스터 Wave별 추가 스탯 적용 (0) | 2026.01.02 |
| [랜덤 타워 디펜스] Day 6 타워 랜덤 생성 시스템 구현 (0) | 2025.12.27 |
| [랜덤 타워 디펜스] Day 5 타워 데이터 셋팅 및 합성 시스템 (0) | 2025.12.21 |
| [랜덤 타워 디펜스] Day 4 기초 UI 및 타워 건설 (0) | 2025.12.12 |