-
Notifications
You must be signed in to change notification settings - Fork 324
/
FoeSpawner.cs
244 lines (211 loc) · 9.65 KB
/
FoeSpawner.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
// Project: Daggerfall Unity
// Copyright: Copyright (C) 2009-2023 Daggerfall Workshop
// Web Site: http://www.dfworkshop.net
// License: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Source Code: https://github.com/Interkarma/daggerfall-unity
// Original Author: Gavin Clayton (interkarma@dfworkshop.net)
// Contributors:
//
// Notes:
//
using System;
using UnityEngine;
using DaggerfallWorkshop.Utility;
using DaggerfallWorkshop.Game.UserInterfaceWindows;
using DaggerfallWorkshop.Game.Entity;
namespace DaggerfallWorkshop.Game.Utility
{
/// <summary>
/// Spawn one or more enemies near player.
/// Will attempt to start placing spawns after game objects are set and spawn count greater than 0.
/// This is a generic spawn helper not tied to any specific system.
/// NOTES:
/// * Spawns foes immediately. Be careful spawning multiple foes as they are likely to become stuck on each other.
/// * The spawner will self-destroy once all foes spawned. Do not attach to anything you want to remain in scene.
/// * There is a prefab carrying this component in Prefabs/Scene for easy spawner setups.
/// * Will attempt to find best parent at time if none specified (e.g. dungeon, interior).
/// * Might need to reduce MinDistance if expecting to spawn in tigt confines like small interiors.
/// </summary>
public class FoeSpawner : MonoBehaviour
{
// Set these values at create time to setup a foe spawn automatically on start
public MobileTypes FoeType = MobileTypes.None;
public int SpawnCount = 0;
public float MinDistance = 4f;
public float MaxDistance = 20f;
public Transform Parent = null;
public bool LineOfSightCheck = true;
public bool AlliedToPlayer = false;
public MobileTypes lastFoeType = MobileTypes.None;
GameObject[] pendingFoeGameObjects;
int pendingFoesSpawned = 0;
bool spawnInProgress = false;
void Awake()
{
// Register as Foe Spawner object
ActiveGameObjectDatabase.RegisterFoeSpawner(gameObject);
}
void Update()
{
// Create new foe list when changed in editor
if (FoeType != MobileTypes.None && FoeType != lastFoeType && SpawnCount > 0)
{
DestroyOldFoeGameObjects(pendingFoeGameObjects);
SetFoeGameObjects(GameObjectHelper.CreateFoeGameObjects(Vector3.zero, FoeType, SpawnCount, alliedToPlayer: AlliedToPlayer));
lastFoeType = FoeType;
}
// Do nothing if no spawns or we are done spawning
if (pendingFoeGameObjects == null || !spawnInProgress)
return;
// Clear pending foes if all have been spawned
if (spawnInProgress && pendingFoesSpawned >= pendingFoeGameObjects.Length)
{
spawnInProgress = false;
Destroy(gameObject);
return;
}
// Try placing foes near player
PlaceFoeFreely(pendingFoeGameObjects, MinDistance, MaxDistance);
if (spawnInProgress)
GameManager.Instance.RaiseOnEncounterEvent();
}
#region Public Methods
/// <summary>
/// Assign an array of pending foe GameObjects to spawn.
/// The spawner will then try to place these foes around player until none remain.
/// Use GameObjectHelper.CreateFoeGameObjects() static method to create foe GameObjects first.
/// </summary>
public void SetFoeGameObjects(GameObject[] gameObjects, Transform parent = null)
{
// Do nothing if array not valid
if (gameObjects == null || gameObjects.Length == 0)
{
spawnInProgress = false;
return;
}
// Store array and start spawning
pendingFoeGameObjects = gameObjects;
pendingFoesSpawned = 0;
spawnInProgress = true;
// Set parent if specified
if (parent)
{
Parent = parent;
for (int i = 0; i < pendingFoeGameObjects.Length; i++)
{
pendingFoeGameObjects[i].transform.parent = parent;
}
}
}
#endregion
#region Private Methods
// Uses raycasts to find next spawn position just outside of player's field of view
void PlaceFoeFreely(GameObject[] gameObjects, float minDistance = 5f, float maxDistance = 20f)
{
const float overlapSphereRadius = 0.65f;
const float separationDistance = 1.25f;
const float maxFloorDistance = 4f;
// Must have received a valid array
if (gameObjects == null || gameObjects.Length == 0)
return;
// Skip this foe if destroyed (e.g. player left building where pending)
if (!gameObjects[pendingFoesSpawned])
{
pendingFoesSpawned++;
return;
}
// Set parent if none specified already
if (!gameObjects[pendingFoesSpawned].transform.parent)
gameObjects[pendingFoesSpawned].transform.parent = GameObjectHelper.GetBestParent();
// Get roation of spawn ray
Quaternion rotation;
if (LineOfSightCheck)
{
// Try to spawn outside of player's field of view
float directionAngle = GameManager.Instance.MainCamera.fieldOfView;
directionAngle += UnityEngine.Random.Range(0f, 4f);
if (UnityEngine.Random.Range(0f, 1f) > 0.5f)
rotation = Quaternion.Euler(0, -directionAngle, 0);
else
rotation = Quaternion.Euler(0, directionAngle, 0);
}
else
{
// Don't care about player's field of view (e.g. at rest)
rotation = Quaternion.Euler(0, UnityEngine.Random.Range(0, 360), 0);
}
// Get direction vector and create a new ray
Vector3 angle = (rotation * Vector3.forward).normalized;
Vector3 spawnDirection = GameManager.Instance.PlayerObject.transform.TransformDirection(angle).normalized;
Ray ray = new Ray(GameManager.Instance.PlayerObject.transform.position, spawnDirection);
// Check for a hit
Vector3 currentPoint;
RaycastHit initialHit;
if (Physics.Raycast(ray, out initialHit, maxDistance))
{
float cos_normal = Vector3.Dot(-spawnDirection, initialHit.normal.normalized);
if (cos_normal < 1e-6)
return;
float separationForward = separationDistance / cos_normal;
// Must be greater than minDistance
float distanceSlack = initialHit.distance - separationForward - minDistance;
if (distanceSlack < 0f)
return;
// Separate out from hit point
float extraDistance = UnityEngine.Random.Range(0f, Mathf.Min(2f, distanceSlack));
currentPoint = initialHit.point - spawnDirection * (separationForward + extraDistance);
}
else
{
// Player might be in an open area (e.g. outdoors) pick a random point along spawn direction
currentPoint = GameManager.Instance.PlayerObject.transform.position + spawnDirection * UnityEngine.Random.Range(minDistance, maxDistance);
}
// Must be able to find a surface below
RaycastHit floorHit;
ray = new Ray(currentPoint, Vector3.down);
if (!Physics.Raycast(ray, out floorHit, maxFloorDistance))
return;
// Ensure this is open space
Vector3 testPoint = floorHit.point + Vector3.up * separationDistance;
Collider[] colliders = Physics.OverlapSphere(testPoint, overlapSphereRadius);
if (colliders.Length > 0)
return;
// This looks like a good spawn position
pendingFoeGameObjects[pendingFoesSpawned].transform.position = testPoint;
FinalizeFoe(pendingFoeGameObjects[pendingFoesSpawned]);
gameObjects[pendingFoesSpawned].transform.LookAt(GameManager.Instance.PlayerObject.transform.position);
// Increment count
pendingFoesSpawned++;
}
// Fine tunes foe position slightly based on mobility and enables GameObject
void FinalizeFoe(GameObject go)
{
var mobileUnit = go.GetComponentInChildren<MobileUnit>();
if (mobileUnit)
{
// Align ground creatures on surface, raise flying creatures slightly into air
if (mobileUnit.Enemy.Behaviour != MobileBehaviour.Flying)
GameObjectHelper.AlignControllerToGround(go.GetComponent<CharacterController>());
else
go.transform.localPosition += Vector3.up * 1.5f;
}
else
{
// Just align to ground
GameObjectHelper.AlignControllerToGround(go.GetComponent<CharacterController>());
}
go.SetActive(true);
}
// Destroy other foes if replaced during spawn
void DestroyOldFoeGameObjects(GameObject[] gameObjects)
{
if (gameObjects == null || gameObjects.Length == 0)
return;
foreach(GameObject go in gameObjects)
{
Destroy(go);
}
}
#endregion
}
}