声明:
本系列文章使用的Libgdx版本均为0.99版本
Libgdx游戏开发交流群 323876830
TextureRegion即纹理区域, 他所使用的坐标系统是一个原点在左上角, x轴方向向右,y轴方向向下(这里和屏幕坐标不同)。
在纹理上面的区域使用的是uv映射坐标来做的。
可能有些人对uv坐标映射不是太清楚,这里我画了张图
其中
float u, v;
代表起点的uv坐标
float u2, v2;
代表终点的uv坐标
下面我们来看看uv是怎么计算的?
它里面有个setRegion方法,参数是x,y,width,height都是像素单位的
public void setRegion (int x, int y, int width, int height) {
float invTexWidth = 1f / texture.getWidth();
float invTexHeight = 1f / texture.getHeight();
setRegion(x * invTexWidth, y * invTexHeight, (x + width) * invTexWidth, (y + height) * invTexHeight);
regionWidth = Math.abs(width);
regionHeight = Math.abs(height);
}
其中invTexWidth可以这样理解,假如整张纹理宽度代表1的话, 那么纹理宽的的每个像素占的比例大小, 同理invTexHeight。
这样的话, x * invTexWidth就代表x方向的x纹理坐标占比,即为u,y * invTexHeight代表y方向y纹理坐标占比,后两个参数代表终点坐标的uv纹理坐标。
如果想翻转uv坐标要怎么做呢?
这里有个flip方法,可以对uv进行翻转操作,其中有两个参数,是否x方向翻转,是否y方向翻转
public void flip (boolean x, boolean y) {
if (x) {
float temp = u;
u = u2;
u2 = temp;
}
if (y) {
float temp = v;
v = v2;
v2 = temp;
}
}
这里面有一个scroll方法, 我觉的这个方法,非常不错。
public void scroll (float xAmount, float yAmount) {
if (xAmount != 0) {
float width = (u2 - u) * texture.getWidth();
u = (u + xAmount) % 1;
u2 = u + width / texture.getWidth();
}
if (yAmount != 0) {
float height = (v2 - v) * texture.getHeight();
v = (v + yAmount) % 1;
v2 = v + height / texture.getHeight();
}
}
第一个参数是相对于水平方向的相对改变值, 同理yAmount是垂直方向的。
我们可以想象一下有一个空战游戏,里面的背景,我们可以提供一个无缝连接的纹理图片, 当我们垂直方向往上移动的时候,
调用这个方法, 因为uv坐标是取模运算的, 所以坐标都在纹理上面。
还有一个比较实用的方法,split分割。根据宽和高分割成一个二维的TextureRegion数组,如果图片的图像都是比较规则的,
实用这个还是比较好用的。
public TextureRegion[][] split (int tileWidth, int tileHeight)
转载请链接原文地址 http://blog.csdn.net/wu928320442/article/details/17162537