iPhone游戏该如何保存
2010-05-11 16:31:00 来源:WEB开发网//Player.m
//init a player or monster from a coder
- (id) initWithCoder: (NSCoder *) coder
{
type = [[coder decodeObjectForKey:@"type" ] intValue]; //load type number
//init based on type number
[self initWithType: type];
// load x and y position
position.x = [[coder decodeObjectForKey:@"position.x" ] floatValue];
position.y = [[coder decodeObjectForKey:@"position.y" ] floatValue];
health = [[coder decodeObjectForKey:@"health" ] intValue];
return self;
}
The only trick here is that I find out what type of player I’m dealing with first, and then init the correct type. Other than that both snippets follow the same pattern ? init the object with the regular initializer (the same one I would use when starting a new game) and then apply the information from the saved game.
The final part you can’t see is the game information that I discard entirely ? like any particles or damage decals on the screen, or currently playing sound effects. These are all short-term effects that don’t affect the gameplay, and the player won’t miss them when the game reloads. Any ongoing effects ? like flames that can damage characters or poisonous clouds to be avoided- would have to be saved, though. You have to decide what is just a visual effect, and what is part of the simulation.
Starting the party
In case you’ve forgotten how all these methods get called, we kick it all off with these lines:
//load the map from disk; its array of players gets loaded too.
//This causes “intiWithCoder” to be called
myMap = [NSKeyedUnarchiver unarchiveObjectWithFile: filePath];
//take some action if myMap == nil (will happen if save file does not exist)
//save the map to disk; it contains an array of players, so they get saved
更多精彩
赞助商链接