几年前,我在尝试为我正在创建的动作游戏学习 OpenGL 时遇到了同样的问题。然而,当我深入研究文档和教程时,我得出的结论是它比我想象的要复杂得多。以下是我学到的一些信息:
-
OpenGL 和 OpenGL ES 不一样,Xcode 上的 OpenGL ES 也和 android 上的不一样,因为 Apple 修改了一些语法。
-
Xcode 上的 OpenGL ES 有几个不同的版本:
-
ES1 (固定管线):不需要着色器程序。它更简单,但选项更少。
-
ES2/ES3(可编程流水线):使用shader,选项更多,但更复杂。
后来我换了平台,改用windows,因为pc上的opengl教程更详细,可以找到很多示例项目。与使用 Xcode 相比,基础知识更容易学习。
我建议你在Windows等另一个平台上学习绘制形状的基本概念以及编程着色器,等你有更多经验后再回到Xcode。
不过,如果你坚持使用 Xcode,我可以提供一些可以成功编译且不会出错的示例代码。以下代码是在 OpenGL ES1 上编写的。只需创建一个新的Single View Application 并粘贴以下代码:
ViewController.h:
#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
@interface ViewController : GLKViewController
@end
ViewController.m:
#import "ViewController.h"
typedef struct {
GLKVector3 PositionCoordinates;
}VertexData;
#define SQUARE_SIZE 120.0f
VertexData Vertices[] = {
{0.0f, 0.0f, 0.0f},
{SQUARE_SIZE, 0.0f, 0.0f},
{0.0f, SQUARE_SIZE, 0.0f},
{0.0f, SQUARE_SIZE, 0.0f},
{SQUARE_SIZE, 0.0f, 0.0f},
{SQUARE_SIZE, SQUARE_SIZE, 0.0f}
};
@interface ViewController ()
@property (nonatomic, strong) EAGLContext *Context;
@property (nonatomic, strong) GLKBaseEffect *BaseEffect;
@end
@implementation ViewController {
GLuint _VertexBufferID;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.Context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
GLKView *View = (GLKView *)self.view;
View.context = self.Context;
[EAGLContext setCurrentContext:self.Context];
self.BaseEffect = [[GLKBaseEffect alloc] init];
self.BaseEffect.useConstantColor = YES;
self.BaseEffect.constantColor = GLKVector4Make(255/255.0f, 255/255.0f, 255/255.0f, 1.0f);
self.BaseEffect.transform.projectionMatrix = GLKMatrix4MakeOrtho(0, self.view.bounds.size.width, 0, self.view.bounds.size.height, 0, 100);
glClearColor(0/255.0f, 0/255.0f, 0/255.0f, 1.0f);
glGenBuffers(1, &_VertexBufferID);
glBindBuffer(GL_ARRAY_BUFFER, _VertexBufferID);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(GLKVertexAttribPosition);
glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), NULL);
}
#pragma mark - GLKView delegate methods
-(void)glkView:(GLKView *)view drawInRect:(CGRect)rect {
glClear(GL_COLOR_BUFFER_BIT);
[self.BaseEffect prepareToDraw];
glDrawArrays(GL_TRIANGLES, 0, 6);
}
-(void)Update {
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
如果您使用的是Storyboards,请记住将 ViewController 上的视图更改为 GLKView 类,如图所示。
编译,然后,BOOM!一个多汁的白色方块已经成熟,可以编辑了!
当我第一次成功编写这段代码时,我泪流满面。从我从 Youtube 教程中学到的一些代码修改它。如果我能再见到他,我要感谢那个人。希望这对你有帮助:)
附:我有一个“OpenGL ES3 模板项目”示例代码的副本,其中两个 3D 立方体相互旋转,但这要复杂得多。