一、理解 利用GLKBaseEffect,自定義頂點著色器和片元著色器,結合天空盒子,展示效果 二、技術代碼 CCSkyBoxEffect:天空盒子效果類; CCSkyboxShader.vsh:頂點著色器; CCSkyboxShader.fsh:片元著色器; //立方體場景貼圖紋理處理及頂點數據處 ...
一、理解
利用GLKBaseEffect,自定義頂點著色器和片元著色器,結合天空盒子,展示效果
二、技術代碼
CCSkyBoxEffect:天空盒子效果類;
CCSkyboxShader.vsh:頂點著色器;
CCSkyboxShader.fsh:片元著色器;
//立方體場景貼圖紋理處理及頂點數據處理
- (id)init { self = [super init]; if (self) { _textureCubeMap = [[GLKEffectPropertyTexture alloc] init]; //是否使用原始紋理 _textureCubeMap.enabled = YES; //採樣紋理的opengl名稱 _textureCubeMap.name = 0; //設置紋理類型:立方體貼圖 _textureCubeMap.target = GLKTextureTargetCubeMap; /*紋理用於計算其輸出片段顏色的模式 GLKTextureEnvModeReplace, 輸出顏色由從紋理獲取的顏色.忽略輸入的顏色 GLKTextureEnvModeModulate, 輸出顏色是通過將紋理顏色與輸入顏色來計算所得 GLKTextureEnvModeDecal,輸出顏色是通過使用紋理的alpha組件來混合紋理顏色和輸入顏色來計算的。 */ _textureCubeMap.envMode = GLKTextureEnvModeReplace; _transform = [[GLKEffectPropertyTransform alloc] init]; self.center = GLKVector3Make(0, 0, 0); self.xSize = 1.0; self.ySize = 1.0; self.zSize = 1.0; //立方體的8個頂點 const float vertices[CCSkyboxNumCoords] = { -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5 }; //創建緩存對象,並返回標誌符 glGenBuffers(1, &vertexBufferID); //綁定緩存對象到指定緩存區:頂點 glBindBuffer(GL_ARRAY_BUFFER, vertexBufferID); //將數據拷貝到緩存對象中 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //繪製立方體的三角形帶索引 const GLubyte indices[CCSkyboxNumVertexIndices] = { 1, 2, 3, 7, 1, 5, 4, 7, 6, 2, 4, 0, 1, 2 }; //開闢索引緩存並複製索引數據到緩存區 glGenBuffers(1, &indexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); } return self; }
//坐標實時調整
- (void)setMatrixs { const GLfloat aspectRatio = (GLfloat)(self.view.bounds.size.width)/(GLfloat)(self.view.bounds.size.height); self.baseEffect.transform.projectionMatrix = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(85.0), aspectRatio, 0.1, 20.0); //獲取世界坐標繫到矩陣中 self.baseEffect.transform.modelviewMatrix = GLKMatrix4MakeLookAt(self.eyePosition.x, self.eyePosition.y, self.eyePosition.z, self.lookAtPosition.x, self.lookAtPosition.y, self.lookAtPosition.z, self.upVector.x, self.upVector.y, self.upVector.z); //增加飛機旋轉角度 self.angle += 0.01; //調整腦袋位置 self.eyePosition = GLKVector3Make(-5.0*sinf(self.angle), -5.0, -5.0*cosf(self.angle)); //調整物體位置 self.lookAtPosition = GLKVector3Make(0.0, 1.5+-5.0*sinf(0.3*self.angle), 0.0); }
三、效果圖