libgdx是一个强大的游戏框架,不仅支持2d部分,同时还支持3d部分。
libgdx的3d部分投影主要通过PerspectiveCamera实现。
物体的显示过程:
1. 创建远景相机,角度一般设为67,并设置其位置、观看点、近距离和远距离。
2. 创建模型创建器,并创建出一个物体模型。之后通过模型创建出对应的实例。
3. 创建环境和相机控制器。
4. render函数中进行渲染绘制。
具体实例:
package com.fxb.newtest; import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; public class Lib022_3dTest extends ApplicationAdapter{ PerspectiveCamera camera;
Model model;
ModelInstance instance;
ModelBatch modelBatch;
Environment environment; CameraInputController cameraController; @Override
public void create() {
// TODO Auto-generated method stub
super.create(); camera = new PerspectiveCamera( 67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() );
camera.position.set( 10, 10, 10 );
camera.lookAt( 0, 0, 0 );
camera.near = 1f;
camera.far = 300f;
camera.update(); ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createBox( 5f, 5f, 5f, new Material( ColorAttribute.createDiffuse(Color.GREEN) ), Usage.Position | Usage.Normal );
instance = new ModelInstance( model );
modelBatch = new ModelBatch(); environment = new Environment();
environment.set( new ColorAttribute( ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1f ) );
environment.add( new DirectionalLight().set( 0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f ) ); cameraController = new CameraInputController( camera );
Gdx.input.setInputProcessor( cameraController );
} @Override
public void render() {
// TODO Auto-generated method stub
super.render();
Gdx.gl.glViewport( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() );
Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT ); cameraController.update();
modelBatch.begin( camera );
//modelBatch.render( instance );
modelBatch.render( instance, environment );
modelBatch.end(); } @Override
public void dispose() {
// TODO Auto-generated method stub
modelBatch.dispose();
model.dispose();
super.dispose();
} }
运行结果:
拖拽物体可以变换角度和方向