0

我通常用 java 或 c++ 编程,最近我开始使用 Objective-c。在 Objective-c 中寻找向量时,我发现 NSMutableArray 似乎是最好的选择。我正在开发一个 opengl 游戏,我正在尝试为我的精灵创建一个纹理四边形的 NSMutableArray。以下是相关代码:

我定义了带纹理的四边形:

typedef struct {
    CGPoint geometryVertex;
    CGPoint textureVertex;
} TexturedVertex;

typedef struct {
    TexturedVertex bl;
    TexturedVertex br;    
    TexturedVertex tl;
    TexturedVertex tr;    
} TexturedQuad;

我在界面中创建了一个数组:

@interface Sprite() {
    NSMutableArray *quads;
}

我启动数组并基于“宽度”和“高度”创建纹理四边形,它们是单个精灵的尺寸,以及“self.textureInfo.width”和“self.textureInfo.height”,它们是尺寸整个精灵表:

    quads = [NSMutableArray arrayWithCapacity:1];
    for(int x = 0; x < self.textureInfo.width/width; x++) {
    for(int y = 0; y < self.textureInfo.height/height; y++) {
        TexturedQuad q;
        q.bl.geometryVertex = CGPointMake(0, 0);
        q.br.geometryVertex = CGPointMake(width, 0);
        q.tl.geometryVertex = CGPointMake(0, height);
        q.tr.geometryVertex = CGPointMake(width, height);

        int x0 = (x*width)/self.textureInfo.width;
        int x1 = (x*width + width)/self.textureInfo.width;
        int y0 = (y*height)/self.textureInfo.height;
        int y1 = (y*height + height)/self.textureInfo.height;

        q.bl.textureVertex = CGPointMake(x0, y0);
        q.br.textureVertex = CGPointMake(x1, y0);
        q.tl.textureVertex = CGPointMake(x0, y1);
        q.tr.textureVertex = CGPointMake(x1, y1);

        //add q to quads
    }
    }

问题是我不知道如何将四边形“q”添加到数组“quads”中。简单的写 [quads addObject:q] 不起作用,因为参数应该是 id 而不是 TexturedQuad。我已经看到了如何从 int 等创建 id 的示例,但我不知道如何使用我的 TexturedQuad 之类的对象来做到这一点。

4

2 回答 2

5

它的本质是将 C 结构包装在 Obj-C 类中。要使用的 Obj-C 类是NSValue.

// assume ImaginaryNumber defined:
typedef struct {
    float real;
    float imaginary;
} ImaginaryNumber;

ImaginaryNumber miNumber;
miNumber.real = 1.1;
miNumber.imaginary = 1.41;

// encode using the type name
NSValue *miValue = [NSValue value: &miNumber withObjCType:@encode(ImaginaryNumber)]; 

ImaginaryNumber miNumber2;
[miValue getValue:&miNumber2];

请参阅此处了解更多信息。

正如@Bersaelor 指出的那样,如果您需要更好的性能,请使用纯 C 或切换到 Obj-C++ 并使用向量而不是 Obj-C 对象。

于 2012-07-03T16:45:04.507 回答
2

NSMutableArray 接受任何 NSObject* 但不仅仅是结构。

如果您对 Objective-C 编程很认真,请查看一些教程

此外,NSMutableArrays 是为了方便起见,如果您向该数组添加/删除大量对象,请使用普通 C 堆栈。特别是对于您的用例,更底层的方法将获得更好的性能。请记住,Objective-C(++) 只是 C(++) 的超集,因此您可以使用您已经熟悉的任何 C(++) 代码。

当我为 iOS 编写游戏策略时,每当我不得不做繁重的工作时(即每秒调用数百次的递归 AI 函数),我都会切换到 C 代码。

于 2012-07-03T16:44:47.383 回答