gpt4 book ai didi

java - 如何在 FitViewport View 中绘制 Sprite 。 libgdx

转载 作者:太空宇宙 更新时间:2023-11-04 12:50:39 24 4
gpt4 key购买 nike

  • 这里的基本问题是:如何始终将 Sprite 保持在 Fitviewport 内?如何保留对 View 的引用以便获得正确的绘制位置坐标?

我正在尝试将敌人生成到游戏屏幕中。但这是由 FitViewport 处理的,敌人甚至玩家都可以在某些屏幕分辨率下移动到 FitViewport 之外。到目前为止,问题似乎出在 Y 轴上。

FitViewport 是这样制作的:

gameCamera = new OrthographicCamera();
gameCamera.setToOrtho(false);
gameViewport = new FitViewport(MyGame.WORLD_WIDTH,MyGame.WORLD_HEIGHT,gameCamera);
gameViewport.setScreenBounds(0,0,MyGame.WORLD_WIDTH,MyGame.WORLD_HEIGHT);

然后相机位置在 resize() 方法中像这样更新:

gameViewport.update(width,height);  //not used when using the virtual viewport in the render method.
gameCamera.position.set(player.position.x + 200,player.position.y, 0);

然后 update() 方法调用 Player 自己的 update() 方法,其中包含以下几行:

//POSITION UPDATE
if (this.position.x<0) this.position.x=0;
if (this.position.x>Gdx.graphics.getWidth() - width) this.position.x= Gdx.graphics.getWidth() - width;
if (this.position.y<0) this.position.y = 0;
if (this.position.y>PlayScreen.gameViewport.getScreenHeight() - height) this.position.y = PlayScreen.gameViewport.getScreenHeight()- height;

注意,对于 X 轴,我仍在使用 Gdx.graphics 尺寸,因为我尚未使其与 PlayScreen.gameViewport.getScreenHeight() 一起使用(为此目的,gameViewport 已设置为静态)。

同样在敌人生成时(这里相关的问题是,就我所看到的而言,它们在屏幕 Y 之外生成)我在实现所有这些视口(viewport)的屏幕的 update() 方法内有此代码:

//Alien Spawn
if (System.currentTimeMillis() - lastZSpawn >= SpawnTimer){
count++;
lastZSpawn= System.currentTimeMillis();
for (int i=0;i<count;i++){
int x = Gdx.graphics.getWidth();
int y = random.nextInt((int)gameViewport.getScreenHeight() - Alien.height);
if (entities.size()<6){
entities.add(new Alien(new Vector2(x,y),1, alienImages,(float)((0))));
}
}

}

这里还使用 gameViewport.getScreenHeight() 导致 Gdx.graphics 没有给出正确的结果(它确实给了我同样的问题)。

render()方法在批处理和应用视口(viewport)方面正确实现:

MyGame.batch.setProjectionMatrix(gameCamera.combined);
gameViewport.apply();
MyGame.batch.begin();

for (int i = entities.size()-1; i>=0;i--){
entities.get(i).render();
}

最佳答案

你不应该在调整大小时改变你的玩家或敌人的位置,这就是为什么要使用视口(viewport),首先删除所有执行此操作的代码,为了使你的视口(viewport)按照你的预期工作,你需要创建一个新的相机实例,在调整大小时传递新的视口(viewport)宽度和高度,我更喜欢使我的相机静态,这样我就可以从我想要的任何地方访问它的属性,你应该这样做:

public static OrthographicCamera update(int width,int height){
instance = new OrthographicCamera(width, height);
instance.setToOrtho(false);
return instance;
}

关于java - 如何在 FitViewport View 中绘制 Sprite 。 libgdx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35870439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com