我正在使用 cocos2d 3.x 和 Xcode 5.1.1。我正在像糖果迷一样玩游戏,在这里我将精灵加载到 5*5 矩阵,我已经得到了触摸精灵的位置,现在我需要在 (0,0),(3,0),(2,2) 之类的数组中保存和使用该 x,y 值
问问题
89 次
2 回答
1
有几种存储坐标的方法,很难说哪种方式更适合,因为我不知道你说保存时的确切意思......
选项#1
CGPoint _coords = CGPointMake(x, y);
将它们存储在结构中的明显选择CGPoint
,但是该结构旨在存储分数坐标,但它也可以处理整数值。
您不能将 a直接插入到任何集合类型中,CGPoint
例如或,但您可以将它们存储在例如固定大小的 C 数组中,例如:NSArray
NSSet
NSSDictionary
CGPoint _fiveCoordinates[4];
选项 #2
NSString *_coordinates = [NSString stringWithFormat:@"%d %d", x, y];
这是一个快速而丑陋的解决方案,我个人不喜欢它 - 但是在某些情况下是有用的(与选项 #4相比!)。也可以将其存储为任何集合类型,然后您可以提取坐标以供进一步使用,例如:
NSArray *_components = [_coordinates componentsSeparatedByString:@" "];
NSInteger x = [[_components firstObject] integerValue];
NSInteger y = [[_components lastObject] integerValue];
如果您将值存储在一个简单NSArray
的
NSArray *_coordinates = [NSArray arrayWithObjects:@(x), @(y)];
提取过程与上面的想法类似。
选项#3
NSDictionary *_coordinates = [NSDictionary dictionaryWithObjectsAndKeys:@(x), @"x", @(y), @"y"];
一个简单的字典可以完美地存储它们,如果你需要提取值,就像例如
NSInteger x = [[_coordinates valueForKey:@"x"] integerValue];
NSInteger y = [[_coordinates valueForKey:@"y"] integerValue];
选项#4
NSIndexPath *_coordinates = [NSIndexPath indexPathForRow:y inSection:x];
如果您喜欢使用索引路径,这是一种非常直接的存储索引的方法,因为NSIndexPath
广泛使用并且可以直接插入到任何集合类型中。
提取坐标将是相同的简单方法:
NSInteger x = [_coordinates section];
NSInteger y = [_coordinates row];
选项 #5A
另一种明显的方法是创建一个自己的类来存储这些坐标,例如:
。H
@interface MyCoordinates : NSObject { }
@property (nonatomic) NSinteger x;
@property (nonatomic) NSinteger y;
@end
.m
@implementation MyCoordinates
@end
选项#5B
NSCoding
如果您想获得一个纯可序列化对象,您还可以根据协议对其进行扩展,该对象可以与NSArray
永久存储一起存档,例如:
。H
@interface MyCoordinates : NSObject <NSCoding> { }
@property (nonatmic) NSInteger x;
@property (nonatmic) NSInteger y;
@end
.m
@implementation MyCoordinates
#pragma mark - <NSCoding>
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
_x = [[aDecoder decodeObjectForKey:@"x"] integerValue];
_y = [[aDecoder decodeObjectForKey:@"y"] IntegerValue];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:@(_x) forKey:@"x"];
[aCoder encodeObject:@(_y) forKey:@"y"];
}
@end
...或类似的东西,或者您可以将它们组合在一起,因为您认为哪种方式在您个人看来最方便。
于 2014-08-30T08:28:53.380 回答
1
//SET
NSMutableArray* points = [[NSMutableArray alloc] initWithCapacity:10];
CGPoint pointToBeStored = CGPointMake(0,0);
[points addObject:[NSValue valueWithCGPoint:pointToBeStored]];
//GET
NSValue *value = [points objectAtIndex:index];
CGPoint storedPoint = [value CGPointValue];
于 2014-09-02T10:28:31.453 回答