Unity チュートリアルのタワーディフェンステンプレートを触ってみる(15)

Unity チュートリアルのタワーディフェンステンプレートを触ってみる(14)では「標的設定と砲撃編」を進め、砲弾の作成とタワーオブジェクトの改良を行った。今回は砲弾に対して追加した Damager コンポーネントの解説を進めていく。
1.標的設定と砲撃編 – Damager.cs
Damager.cs について稚拙ながら解説
「Damager.cs」は「Assets/Scripts/ActionGameFramework/Health/Damager.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 using System;
using Core.Health;
using Core.Utilities;
using UnityEngine;
using Random = UnityEngine.Random;
namespace ActionGameFramework.Health
{
/// <summary>
/// A component that does damage to damageables
/// </summary>
public class Damager : MonoBehaviour
{
/// <summary>
/// The amount of damage this damager does
/// </summary>
public float damage;
/// <summary>
/// The event that fires off when the damager has been damaged
/// </summary>
public Action<Vector3> hasDamaged;
/// <summary>
/// Random chance to spawn collision projectile prefab
/// </summary>
[Range(0, 1)]
public float chanceToSpawnCollisionPrefab = 1.0f;
/// <summary>
/// The particle system to fire off when the damager attacks
/// </summary>
public ParticleSystem collisionParticles;
/// <summary>
/// The alignment of the damager
/// </summary>
public SerializableIAlignmentProvider alignment;
/// <summary>
/// Gets the alignment of the damager
/// </summary>
public IAlignmentProvider alignmentProvider
{
get { return alignment != null ? alignment.GetInterface() : null; }
}
/// <summary>
/// The logic to set the value of the damage
/// </summary>
/// <param name="damageAmount">
/// The amount to set the damage by,
/// will not be set for values less than zero
/// </param>
public void SetDamage(float damageAmount)
{
if (damageAmount < 0)
{
return;
}
damage = damageAmount;
}
/// <summary>
/// Damagable will tell damager that it has successful hurt the damagable
/// </summary>
public void HasDamaged(Vector3 point, IAlignmentProvider otherAlignment)
{
if (hasDamaged != null)
{
hasDamaged(point);
}
}
/// <summary>
/// Instantiate particle system and play it
/// </summary>
void OnCollisionEnter(Collision other)
{
if (collisionParticles == null || Random.value > chanceToSpawnCollisionPrefab)
{
return;
}
var pfx = Poolable.TryGetPoolable<ParticleSystem>(collisionParticles.gameObject);
pfx.transform.position = transform.position;
pfx.Play();
}
}
}
27行目 : 「[Range(0, 1)]」は浮動小数点(float)の値が 0 ~ 1 の間に指定する必要があることを指している。
55行目 : 「public void SetDamage(float damageAmount)」はダメージ量の変更を行っている。 0 以上の値でダメージの更新を行う。
67行目 : 「public void HasDamaged(Vector3 point, IAlignmentProvider otherAlignment)」は Damager が Damagable に対してダメージを与えることができるか確認を行っている。
78行目 : 「void OnCollisionEnter(Collision other)」は Damager が他のコリダーに入った時の処理を行っている。コリダーに入った時起こるエフェクトを実行している。