libgdx 学习笔记(二)相机和观察点

本文详细介绍了Libgdx中OrthographicCamera的使用方法及其在2D游戏开发中的作用,包括如何创建和更新相机,以及如何利用它进行视图变换。通过具体实例展示了如何设置和操作OrthographicCamera来实现不同视觉效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Libgdx的Stage类中就默认包含了一个Camera。

Camera类按照功能而言也有很多种,最常用的是OrthographicCamera(正投影相机),Stage中默认Camera的实现类为该类。

OrthographicCamera实现以下功能:

1.移动和旋转镜头

2.放大和缩小

3.改变观察点(视角)

4.窗体和世界的点的转化


相机的使用一般配合着mesh。mesh绘制一个矩形区域


import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.VertexAttribute;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;


public class FirstGame implements ApplicationListener {
private OrthographicCamera camera;
private Mesh squareMesh;// 那些点坐标,颜色,纹理,材质,光照等等的一个集合
private Mesh nearSquare;


@Override
public void create() {
if (squareMesh == null) {
squareMesh = new Mesh(true, 4, 4, new VertexAttribute(
// 表示:储存顶点的数据,每个顶点的数据由三个坐标数组成(x, y ,z ),
Usage.Position, 3, "a_position"),
// 表示:如果想添加颜色
new VertexAttribute(Usage.ColorPacked, 4, "a_color"));
squareMesh.setVertices(new float[] { -0.5f, -0.5f, 0,
Color.toFloatBits(128, 0, 0, 255),  0,-0.5f, 0,
Color.toFloatBits(192, 0, 0, 255), -0.5f, 0.5f, 0,
Color.toFloatBits(192, 0, 0, 255), 0, 0.5f, 0,
Color.toFloatBits(255, 0, 0, 255) });
squareMesh.setIndices(new short[] { 0, 1, 2, 3 });
}
if (nearSquare == null) {
nearSquare = new Mesh(true, 4, 4, new VertexAttribute(
Usage.Position, 3, "a_position"), new VertexAttribute(
Usage.ColorPacked, 4, "a_color"));


nearSquare.setVertices(new float[] {  0, -0.5f, 0,
Color.toFloatBits(0, 0, 128, 255),0.5f, -0.5f, 0,
Color.toFloatBits(0, 0, 192, 255), 0, 0.5f, 0,
Color.toFloatBits(0, 0, 192, 255),0.5f, 0.5f, 0,
Color.toFloatBits(0, 0, 255, 255) });
nearSquare.setIndices(new short[] { 0, 1, 2, 3 });
}
}


@Override
public void dispose() {


}


@Override
public void pause() {


}


@Override
public void render() {
camera.update();
camera.apply(Gdx.gl10);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);// 清空屏幕
squareMesh.render(GL10.GL_TRIANGLE_STRIP, 0, 4);// 绘制矩形
nearSquare.render(GL10.GL_TRIANGLE_STRIP, 0, 4);// 绘制矩形


}


@Override
public void resize(int width, int height) {
float aspectRatio = (float) width / (float) height;
camera = new OrthographicCamera(2f * aspectRatio, 2f);
}


@Override
public void resume() {


}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ada

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值