Temporizador simples para jogos
hamishwillee
(Talk | contribs) m (Hamishwillee - Automated change of category from Lang-PT to Unlikely Category. (Moving)) |
hamishwillee
(Talk | contribs) m (Hamishwillee - Add Abstract) |
||
| (One intermediate revision by one user not shown) | |||
| Line 1: | Line 1: | ||
| − | Este artigo apresenta um temporizador (''timer'') simples para jogos, baseado na classe <tt>CIdle</tt>. | + | [[Category:Symbian C++]][[Category:Code Examples]][[Category:Games]][[Category:Lang-Portuguese]] |
| − | + | {{Abstract|Este artigo apresenta um temporizador (''timer'') simples para jogos, baseado na classe <tt>CIdle</tt>.}} | |
| + | {{ArticleMetaData | ||
| + | |sourcecode= <!-- Link to example source code e.g. [[Media:The Code Example ZIP.zip]] --> | ||
| + | |installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) --> | ||
| + | |devices= <!-- Devices tested against - e.g. ''devices=Nokia 6131 NFC, Nokia C7-00'') --> | ||
| + | |sdk= <!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Nokia Qt SDK 1.1]) --> | ||
| + | |platform= <!-- Compatible platforms - e.g. Symbian^1 and later, Qt 4.6 and later --> | ||
| + | |devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) --> | ||
| + | |dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 --> | ||
| + | |signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer --> | ||
| + | |capabilities=<!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. --> | ||
| + | |keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase --> | ||
| + | |id= <!-- Article Id (Knowledge base articles only) --> | ||
| + | |language=Lang-Portuguese | ||
| + | |translated-by= <!-- [[User: XXXXX]] --> | ||
| + | |translated-from-title=<!-- Title only --> | ||
| + | |translated-from-id= <!-- Id of translated revision --> | ||
| + | |review-by=<!-- After re-review: [[User:username]] --> | ||
| + | |review-timestamp=<!-- After re-review: YYYYMMDD --> | ||
| + | |update-by=<!-- After significant update: [[User:username]]--> | ||
| + | |update-timestamp=<!-- After significant update: YYYYMMDD --> | ||
| + | |creationdate=20070627 | ||
| + | |author=[[User:Lpvalente]] | ||
| + | }} | ||
A classe <tt>CIdle</tt> é um [[objetos ativos|objeto ativo]] que é executado quando não existe nenhum outro com prioridade maior esperando para ser executado. Ao contrário de outras alternativas encontradas no Symbian OS, <tt>CIdle</tt> não usa um intervalo de tempo pré-definido para gerar eventos. | A classe <tt>CIdle</tt> é um [[objetos ativos|objeto ativo]] que é executado quando não existe nenhum outro com prioridade maior esperando para ser executado. Ao contrário de outras alternativas encontradas no Symbian OS, <tt>CIdle</tt> não usa um intervalo de tempo pré-definido para gerar eventos. | ||
| Line 137: | Line 160: | ||
} | } | ||
</code> | </code> | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
Latest revision as of 07:26, 21 November 2011
Este artigo apresenta um temporizador (timer) simples para jogos, baseado na classe CIdle.
Dados do artigo
A classe CIdle é um objeto ativo que é executado quando não existe nenhum outro com prioridade maior esperando para ser executado. Ao contrário de outras alternativas encontradas no Symbian OS, CIdle não usa um intervalo de tempo pré-definido para gerar eventos.
Definindo a classe
class CCustomTimer : public CBase
{
public:
// Cria uma instância da classe. MTimerListener
// é um objeto interessado ("interessado") em tratar o evento de tempo.
static CCustomTimer* NewL (MTimerListener & aListener);
~CCustomTimer ();
// Iniciar o temporizador.
void Start ();
// Cancelar o temporizador.
void Cancel ();
private:
// Função que é usada internamente para notificar o interessado
// que vai receber o evento de tempo. Requerida pelo CIdle.
static TInt IdleCallBack (TAny* aPtr);
private:
// Construtor, guarda a referência para o interessado.
CCustomTimer (MTimerListener & aListener)
: iListener (& aListener)
{}
// Segunda parte do construtor de duas fases.
void ConstructL ();
private:
MTimerListener * iListener; // o interessado
CIdle* iIdle;
};
A interface MTimerListener é definida como a seguir:
class MTimerListener
{
public:
virtual void OnTimer () = 0;
};
A classe CCustomTimer é implementada deste modo:
void CCustomTimer::ConstructL ()
{
iIdle = CIdle::NewL (CIdle::EPriorityIdle);
}
CCustomTimer::~CCustomTimer ()
{
if (iIdle)
{
iIdle->Cancel ();
delete iIdle;
}
}
void CCustomTimer::Start ()
{
if (!iIdle->IsActive () )
iIdle->Start (TCallBack (IdleCallBack, this) );
}
void CCustomTimer::Cancel ()
{
iIdle->Cancel();
}
TInt CCustomTimer::IdleCallBack (TAny* aPtr)
{
CCustomTimer* me = ((CCustomTimer*)aPtr);
me->iListener->OnTimer ();
return ETrue;
}
Uso
// Suponha que o jogo deve rodar a 30 quadros por segundo. Dessa forma,
// é necessário calcular o intervalo de tempo (time step) para atender
// a esse requisito. O tempo é especificado em microsegundos.
const TInt KTargetTimeStep = 1000000 / 30;
void MyGame::OnTimer ()
{
// Tratar dados de entrada (teclado)
ProcessInput ();
// Nessa parte será calculado o número de time steps a serem
// executados, para que jogo não fique atrasado.
// Guardar o tempo atual.
TTime time;
time.HomeTime();
// Calcular o tempo decorrido desde a última atualização.
// iStartTime é membro da classe MyGame.
TInt elapsed = I64LOW (time.MicroSecondsFrom (iStartTime).Int64());
// Atualizar o tempo total até o momento. A variável iTotalTime
// também é membro da classe MyGame.
iTotalTime += elapsed;
// Calcular quantas atualizações devem ser executadas. Observe que
// a divisão é inteira (ou seja, 5 / 2 = 2).
elapsed = iTotalTime / KTargetTimeStep;
for (TInt i = 0; i < elapsed; ++i)
Update ();
// Subtrair o tempo correspondente aos time steps processados.
iTotalTime -= elapsed * KTargetTimeStep;
iStartTime = time.Int64();
// Desenhar.
Render ();
}

