W298.dev
ProjectsPostsAbout Me
youtube
Pages
ProjectsPostsAbout Me
Posts
TAGS
All
RL-Obstacle-Avoid
RL-Competitive
Robot-Escape
Assembly Definition
ML-Agent
RL-Obstacle-Avoid
RL-Competitive
Unity
RL-Obstacle-Avoid
RL-Competitive
Robot-Escape
Assembly Definition
SERIES
RL-Obstacle-Avoid
RL-Competitive
Robot-Escape

Timer, LevelController

EnemyAI 를 구현하면서 지속적으로 증가하거나 감소하는 Level 들 (seekLevel, detectLevel 등) 이 있는데, 이들을 효과적으로 관리할 수 있는 class 가 있으면 좋을 것 같아 만들어 보았다.
그리고 만드는 김에 Timer class 도 구현해 LevelController 에 사용하였다.
1[System.Serializable]
2public class LevelController
3{
4    public float defaultLevel;
5    public float currentLevel;
6
7    public Timer incTimer;
8    public Timer decTimer;
9
10    public LevelController(float defaultLevel, float incInterval, float decInterval)
11    {
12        this.defaultLevel = defaultLevel;
13
14        incTimer = new Timer(incInterval, () => { if (currentLevel < 100) currentLevel++; });
15        decTimer = new Timer(decInterval, () => { if (currentLevel > 0) currentLevel--; });
16
17        currentLevel = this.defaultLevel;
18    }
19
20    public void Update()
21    {
22        incTimer.Update();
23        decTimer.Update();
24    }
25}
26
1[System.Serializable]
2public class Timer
3{
4    public delegate void ExecuteFunction();
5    public ExecuteFunction exeFunc;
6
7    public bool active = true;
8
9    private float interval;
10    private float timer;
11
12    public Timer(float interval, ExecuteFunction exeFunc)
13    {
14        this.interval = interval;
15        this.exeFunc = exeFunc;
16
17        Reset();
18    }
19
20    public Timer(int frequency, ExecuteFunction exeFunc)
21    {
22        interval = 1f / frequency;
23        timer = interval;
24        this.exeFunc = exeFunc;
25    }
26
27    public void Reset()
28    {
29        timer = interval;
30    }
31
32    public void Update()
33    {
34        if (!active) return;
35        timer -= Time.deltaTime;
36        if (timer < 0)
37        {
38            timer += interval;
39            exeFunc();
40        }
41    }
42}
43