libgdx学习记录17——照相机Camera

时间:2023-11-14 09:27:44

照相机在libgdx中的地位举足轻重,贯穿于整个游戏开发过程的始终。一般我们都通过Stage封装而间接使用Camera,同时我们也可以单独使用Camera以完成背景的移动、元素的放大、旋转等操作。

Camera分为PerspectiveCamera(远景照相机)和OrthographicCamera(正交照相机)。

PerspectiveCamera为正常的照相机,当距离物体越远,则物体越小,一般在3D空间中使用。

OrthographicCamera忽略了其Z轴,不管距离物体多远,其大小始终不变,一般在2D平面中使用。

由于我们所涉及的游戏界面都是在2D平面中,因此我们现在只讨论OrthographicCamera。

OrthographicCamera继承自Camera。

主要函数:

SetToOtho(ydown,width,height)指定是否y轴朝下,width和height分别表示照相机的视口宽度和高度。此函数同时还将位置设定在其中心,并执行一次update。

position.set( x, y )指定照相机的位置,一般设置在视口中心,width/2,height/2。

update()更新,就是更新其位置、角度和放大倍数等参数。

translate(x,y,z) 移动

具体代码:

 package com.fxb.newtest;

 import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class Lib017_Camera extends ApplicationAdapter{ OrthographicCamera camera;
Texture texture;
SpriteBatch batch; @Override
public void create() {
// TODO Auto-generated method stub
super.create();
batch = new SpriteBatch();
texture = new Texture( Gdx.files.internal( "data/pal4_0.jpg" ) ); camera = new OrthographicCamera();
camera.setToOrtho( false, 480, 320 ); camera.rotate( 45 );
camera.zoom = 2f;
} public void HandleInput(){
if( Gdx.input.isKeyPressed( Input.Keys.LEFT ) ){
camera.position.add( 2f, 0, 0 );
}
else if( Gdx.input.isKeyPressed( Input.Keys.RIGHT ) ){
camera.position.add( -2f, 0, 0 );
}
else if( Gdx.input.isKeyPressed( Input.Keys.UP ) ){
camera.position.add( 0, -2f, 0 );
}
else if( Gdx.input.isKeyPressed( Input.Keys.DOWN ) ){
camera.position.add( 0, 2f, 0 );
}
else if( Gdx.input.isKeyPressed( Input.Keys.D ) ){
camera.zoom -= 0.05f;
}
else if( Gdx.input.isKeyPressed( Input.Keys.F ) ){
camera.zoom += 0.05f;
}
else if( Gdx.input.isKeyPressed( Input.Keys.A ) ){
camera.rotate( 1 );
}
else if( Gdx.input.isKeyPressed( Input.Keys.S ) ){
camera.rotate( -1 );
}
} @Override
public void render() {
// TODO Auto-generated method stub
super.render();
Gdx.gl.glClearColor( 0, 1, 1, 1 );
Gdx.gl.glClear( GL10.GL_COLOR_BUFFER_BIT ); HandleInput();
//camera.position.add( 0.5f, 0, 0 );
camera.update(); batch.setProjectionMatrix( camera.combined );
batch.begin();
batch.draw( texture, 0, 0 );
batch.end(); } @Override
public void dispose() {
// TODO Auto-generated method stub
batch.dispose();
texture.dispose();
super.dispose();
} }

运行效果:

libgdx学习记录17——照相机Camera

从代码中也可以看出来:

按左右上下按键分别会使图片左右上下移动,而Camera却是向相反的方向移动。

ASDF按键分别对应逆时针旋转、顺时针旋转、放大、缩小等操作。