我正在試驗一個簡單的遊戲。只顯示幾個按鈕和文字。 我想完全將遊戲引擎與視圖,視圖控制器等分開。因此,我將它定義在一個名爲GameEngine的單獨文件和類中。遊戲引擎爲全球?這是正確的方法
我聲明,並在AppDelegate中intialize一個GameEngine情況是這樣的:
#import "GameEngine.h"
GameEngine *this_game; //It's global!
@interface ...{
...
// this_game is not declared here at all
...
}
//No getter/setter defined for this_game
的AppDelegate的實施看起來是這樣的:
#import "MyGameAppDelegate.h"
@implementation ...
// this_game not synthesized
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
this_game = [[GameEngine alloc] init];
this_game.managedObjectContext = self.managedObjectContext;
[this_game initialize_data];
[window addSubview:game_vc.view]; // Display the primary application view
[window makeKeyAndVisible];
}
...
-(void)dealloc{
...
[this_game release];
...
}
OK,有了這樣的方式,這是在主視圖控制器的頭文件中會發生什麼情況:
#import "GameEngine.h"
extern GameEngine *this_game;
// No other reference to this_game in the .h file
而現在的代碼中的.m:
-(void)viewDidLoad{
...
NSLog([this_game test], nil); //Just a quick "I am here" test
...
}
這是所有有囍罰款,整天我可以打電話從全球this_game對象的方法從程序的不同點。有用。
這個問題真的是關於如何接受Objective-C練習的「正確」或恰當的,如果你願意,這種方法可能是什麼?
這是一個壞主意嗎?爲什麼? 有沒有更好的方法?爲什麼它更好?
我的意圖,BTW,是分開GameEngine代碼,以便更容易重用這個平臺和其他移動平臺。所有本地窗口和UI的東西都需要遠離遊戲邏輯。
感謝,
-Martin
如果Apple想要這樣做,Objective-C可能會變成跨平臺。但他們不(但?)...我建議使用C/C++作爲凱提到的遊戲邏輯代碼來重新使用它們。 – Eonil 2011-01-24 18:13:09