libgdx学习记录22——3d物体创建
libgdx是一个强大的游戏框架,不仅支持2d部分,同时还支持3d部分。
libgdx的3d部分投影主要通过PerspectiveCamera实现。
物体的显示过程:
1. 创建远景相机,角度一般设为67,并设置其位置、观看点、近距离和远距离。
2. 创建模型创建器,并创建出一个物体模型。之后通过模型创建出对应的实例。
3. 创建环境和相机控制器。
4. render函数中进行渲染绘制。
具体实例:
1 package com.fxb.newtest; 2 3 import com.badlogic.gdx.ApplicationAdapter; 4 import com.badlogic.gdx.Gdx; 5 import com.badlogic.gdx.graphics.Color; 6 import com.badlogic.gdx.graphics.GL10; 7 import com.badlogic.gdx.graphics.PerspectiveCamera; 8 import com.badlogic.gdx.graphics.VertexAttributes.Usage; 9 import com.badlogic.gdx.graphics.g3d.Environment; 10 import com.badlogic.gdx.graphics.g3d.Material; 11 import com.badlogic.gdx.graphics.g3d.Model; 12 import com.badlogic.gdx.graphics.g3d.ModelBatch; 13 import com.badlogic.gdx.graphics.g3d.ModelInstance; 14 import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; 15 import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; 16 import com.badlogic.gdx.graphics.g3d.utils.CameraInputController; 17 import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; 18 19 public class Lib022_3dTest extends ApplicationAdapter{ 20 21 PerspectiveCamera camera; 22 Model model; 23 ModelInstance instance; 24 ModelBatch modelBatch; 25 Environment environment; 26 27 CameraInputController cameraController; 28 29 @Override 30 public void create() { 31 // TODO Auto-generated method stub 32 super.create(); 33 34 camera = new PerspectiveCamera( 67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); 35 camera.position.set( 10, 10, 10 ); 36 camera.lookAt( 0, 0, 0 ); 37 camera.near = 1f; 38 camera.far = 300f; 39 camera.update(); 40 41 ModelBuilder modelBuilder = new ModelBuilder(); 42 model = modelBuilder.createBox( 5f, 5f, 5f, new Material( ColorAttribute.createDiffuse(Color.GREEN) ), Usage.Position | Usage.Normal ); 43 instance = new ModelInstance( model ); 44 modelBatch = new ModelBatch(); 45 46 environment = new Environment(); 47 environment.set( new ColorAttribute( ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f ) ); 48 environment.add( new DirectionalLight().set( 0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f ) ); 49 50 cameraController = new CameraInputController( camera ); 51 Gdx.input.setInputProcessor( cameraController ); 52 } 53 54 @Override 55 public void render() { 56 // TODO Auto-generated method stub 57 super.render(); 58 Gdx.gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() ); 59 Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); 60 61 cameraController.update(); 62 modelBatch.begin( camera ); 63 //modelBatch.render( instance ); 64 modelBatch.render( instance, environment ); 65 modelBatch.end(); 66 67 } 68 69 @Override 70 public void dispose() { 71 // TODO Auto-generated method stub 72 modelBatch.dispose(); 73 model.dispose(); 74 super.dispose(); 75 } 76 77 }
运行结果:
拖拽物体可以变换角度和方向