【发布时间】:2014-04-07 15:09:33
【问题描述】:
我想使用 LibGDX 在我的 android 设备屏幕内生成随机位置。
我的sprite width 是150,height 也是150,所以OFFSET = 150。
我的想法是在做width - 150和height - 150时获取屏幕的宽度、高度,生成一个随机数。
像这样:
int x = 150 + Config.RANDOM.nextInt( (int) (Gdx.graphics.getWidth() - Config.OFFSET) );
int y = 150 + Config.RANDOM.nextInt( (int) (Gdx.graphics.getHeight() - Config.OFFSET) );
经过测试,但不幸的是,精灵有时会离开屏幕。 这些是调试输出:
03-05 15:50:22.432: I/System.out(4141): X: 828 Y:1384
03-05 15:50:23.432: I/System.out(4141): X: 391 Y:520
03-05 15:50:24.452: I/System.out(4141): X: 230 Y:917
03-05 15:50:25.462: I/System.out(4141): X: 872 Y:808
03-05 15:50:26.472: I/System.out(4141): X: 827 Y:963
03-05 15:50:27.482: I/System.out(4141): X: 595 Y:382
我的屏幕width/height (Gdx.graphics.getWidth() / Gdx.graphics.getHeight):
03-05 15:52:33.862: I/System.out(5771): Width: 1080.0 Height: 1776.0
我生成的随机位置错了吗?
另外我使用的是纵向模式,我不使用camera.combine,因为它会将我的sprites 旋转180 度。
camera = new OrthographicCamera(w, h);
camera.setToOrtho(true, w, h);
camera.update();
public void render() {
this.spriteRenderer.setProjectionMatrix(this.instance.camera.combined);
this.spriteRenderer.begin();
if (!this.ballon.isPoping()) {
Sprite s = this.ballon.getSprite();
spriteRenderer.draw(s, 50, 50, s.getWidth(), s.getHeight());
}
// else {
// if (!this.ballon.isPoped()) {
// Sprite s = this.ballon.getCurrentAnimation();
// this.spriteRenderer.draw(s, this.ballon.getX(),
// this.ballon.getY(),
// this.ballon.getSprite().getWidth() * SpriteConfiguration.BALLON_SCALE,
// this.ballon.getSprite().getHeight() * SpriteConfiguration.BALLON_SCALE);
// this.ballon.processAnimation();
// }
// }
this.spriteRenderer.end();
}
【问题讨论】:
-
你有什么问题?
-
精灵有时会跳出屏幕。
-
抱歉,我之前的回答无法解决您的问题。当您调用
setToOrtho时,正射摄像机默认在角落有 0,0。您可能需要展示如何生成精灵以及如何绘制它们的代码。如果使用cam.combined会导致精灵旋转,那是不对的。您的调试证明您生成的数字是正确的,所以问题在于您如何使用相机或放置您的精灵。 -
添加组合后它工作正常,但现在我的精灵就像垂直变换了,它的顶部向下看,基本上旋转了 180 度,我已经添加了我的绘图
标签: java android random libgdx