RandomAnimations.cs
2.68 KB
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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/**
* Gerenciador de animações de intervalo de inatividade.
*
* Não atribua as animações (nomes) diretamente do PlayerManager,
* utilize a função setRandomAnimations() do GenericPlayerManager.
*/
public class RandomAnimations : MonoBehaviour {
public PlayerManager playerManager;
// Reproduz animações a cada time segundos, sujeito à probabilidade.
public int time = 3;
// Probabilidade, de 0 a 1, de reproduzir animações no tempo determinado.
public float probability = 0.3F;
private string[] names = new string[] {};
private int lastIndex = -1;
// GameObjects que requisitaram o bloqueio das animações
private HashSet<String> blockingObjects = new HashSet<String>();
/* Bloquear animações para o GameObject object. */
public void lockFor(String id) {
lock (this.blockingObjects) {
this.blockingObjects.Add(id);
}
}
/* Desbloquear animações para o GameObject object. */
public void unlockFor(String id) {
lock (this.blockingObjects) {
this.blockingObjects.Remove(id);
}
}
/* Desbloquear animações para todos os GameObjects. */
public void unlockAll() {
lock (this.blockingObjects) {
this.blockingObjects.Clear();
}
}
/* Atribui as animações e inicia o processo para reproduzir. */
public void setAnimations(string[] names)
{
this.names = names;
StartCoroutine("playRandom");
}
/* Processo que reproduz animações a cada time segundos com a probabilidade probability.
* Enquanto houver GameObjects bloqueando, não reproduz nenhuma animação.
* Quando não houver nenhum bloqueio, espera time e reproduz animação de acordo com probability. */
private IEnumerator playRandom()
{
while (true)
{
while (this.playerManager.isPlayingIntervalAnimation())
yield return new WaitForSeconds(1);
bool isNotBlocked;
lock (this.blockingObjects) {
isNotBlocked = this.blockingObjects.Count == 0;
}
if (isNotBlocked)
{
yield return new WaitForSeconds(this.time);
lock (this.blockingObjects) {
if (this.blockingObjects.Count > 0)
continue;
}
int index = sortIndex();
if (index != -1)
{
if (index == this.lastIndex)
index = sortIndex();
//this.playerManager.play(this.names[index], true, false, true);
this.playerManager.playIntervalAnimation(this.names[index]);
}
}
yield return null;
}
}
/* Escolhe uma animação de names ou nanhuma de acordo com probability. */
private int sortIndex()
{
int rand = new System.Random().Next((int) (this.names.Length / this.probability));
return rand < this.names.Length ? rand : -1;
}
}