cocos2dx-3.x學習筆記二:隨機數的生成及注意問題
cocos2dx-3.x提供了一個用於生成【0,1)之間浮點數的巨集定義CCRANDOM_0_1
1. 巨集定義說明
首先檢視原始碼,定位分析:
1 2 3 4 |
/**
@def CCRANDOM_0_1
returns
a random float between 0 and 1
*/
#define
CCRANDOM_0_1() cocos2d::rand_0_1()
|
cocos2d::rand_0_1()函式的原型為:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/**
*
Returns a random float between 0 and 1. *
It can be seeded using std::srand(seed);
*/
inline float rand_0_1()
{
//
FIXME: using the new c++11 random engine generator
//
without a proper way to set a seed is not useful.
//
Resorting to the old random method since it can
//
be seeded using std::srand()
return std:: rand ()
/ ( float )RAND_MAX; //
return cocos2d::random(0.f, 1.f);
};
|
從上面的原始碼可以看出,CCRANDOM_0_1()其實就是呼叫標準庫函式 rand(),隨機生成0 - 1,左開右閉區間內的浮點數
2. rand函式
標準庫函式生成隨機數,採用的是rand函式,生成一個【0, RAND_MAX】 之間的整數,常用的例項如:
1 2 3 4 5 6 7 8 9 |
#include
<time.h>
#include
<stdlib.h>
int main()
{
srand ((unsigned int ) time (0));
// 設定隨機數種子
printf ( "%d\n" , rand ());
return 0;
}
|
3. CCRANDOM_0_1使用
在具體的使用過程中,需要注意兩點
1. 初始化隨機數種子
2. 注意閉合區間,尤其是生成隨機整數時,更需要確保閉合區間,圓括號的使用----> 檢視下例中第十行
一個使用例子,用於隨機生成0,1兩個整數:(int)(CCRANDOM_0_1() * 2)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include
"cocos2d.h"
int test()
{
struct timeval
now;
gettimeofday(&now,
NULL);
|