LibGDX_4.3: 舞台(Stage)
-
概述 舞台(Stage)是众多演员(Actor)“表演”的地方,可以看做是一个包含不同层次演员的 2D 场景,能够处理视口(整体缩放显示 / 屏幕适配)和 接收输入事件(触屏,鼠标点击,按键按下等)自己处理以及将事件分发给演员。
-
舞台类(Stage) 舞台类中的部分方法:
float getWidth(): 获取舞台的宽度
float getHeight(): 获取舞台的高度
void act(float delta): 更新舞台逻辑,并批处理舞台中的演员(自动逐个调用演员的 act() 方法更新演员逻辑)
void draw(): 绘制舞台,并批处理舞台中的演员(自动逐个调用演员的 draw() 方法绘制演员)
void dispose() : 释放舞台中的所有资源
boolean addListener(EventListener listener): 添加事件监听到舞台
boolean removeListener(EventListener listener): 移除监听器
void addActor(Actor actor): 增加一个演员到舞台中
void clear(): 移除舞台中的所有演员
Array
- 代码示例
这里引用前面章节中自定义的演员:
package com.libgdx.test;
import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor;
/**
-
自定义演员 */ public class MyActor extends Actor {
private TextureRegion region;
public MyActor(TextureRegion region) { super(); this.region = region; setSize(this.region.getRegionWidth(), this.region.getRegionHeight()); }
public TextureRegion getRegion() { return region; }
public void setRegion(TextureRegion region) { this.region = region; setSize(this.region.getRegionWidth(), this.region.getRegionHeight()); }
@Override public void act(float delta) { super.act(delta); }
@Override public void draw(Batch batch, float parentAlpha) { super.draw(batch, parentAlpha); if (region == null || !isVisible()) { return; } batch.draw( region, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation() ); }
}
游戏主程序的启动入口类:
package com.libgdx.test;
import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Stage;
/**
-
游戏主程序的启动入口类 */ public class MainGame extends ApplicationAdapter {
// 纹理 private Texture texture;
// 自定义的演员 private MyActor actor;
// 舞台 private Stage stage;
@Override public void create() { // 创建纹理, badlogic.jpg 图片的宽高为 256 * 256 texture = new Texture(Gdx.files.internal("badlogic.jpg")); // 创建演员, 位置默认为为 (0, 0), 在舞台左下角 actor = new MyActor(new TextureRegion(texture));
// 使用默认的构造方法创建舞台, 宽高默认为屏幕宽高 stage = new Stage(); // 将 演员 添加到舞台中, 由舞台去更新演员的逻辑和绘制 stage.addActor(actor);}
@Override public void render() { // 黑色清屏 Gdx.gl.glClearColor(0, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
/* * 舞台自己维护了纹理画布(SpriteBatch), 并且在绘制前后自动分别调用了 begin() 和 end() 方法, * 所以渲染舞台时, 只需要调用舞台的 act() 和 draw() 方法即可 */ // 更新舞台逻辑,并批处理舞台中的演员(自动逐个调用演员的 act() 方法更新演员逻辑) stage.act(); // 绘制舞台,并批处理舞台中的演员(自动逐个调用演员的 draw() 方法绘制演员) stage.draw();}
@Override public void dispose() { // 释放纹理资源 if (texture != null) { texture.dispose(); } // 释放舞台资源 if (stage != null) { stage.dispose(); } }
}
运行结果:
---------------------
作者:xietansheng
来源:CSDN
原文:https://blog.csdn.net/xietansheng/article/details/50187111
版权声明:本文为博主原创文章,转载请附上博文链接!
发表评论