I have a game screen in which I want to implement both the game itself and the control buttons. I divided this screen into two parts using TABLE.
The control buttons and the game are implemented in different classes. Everything works correctly, except for displaying the game.
How to make the game fit in the top window?
Game Screen code
public class GameScreen implements Screen {
private Main parent;
private Stage stage;
public static SnakeControl snakeControl;
private SpriteBatch batch;
private GameControl game;
public GameScreen(Main main) {
parent = main;
stage = new Stage(new ScreenViewport());
Gdx.input.setInputProcessor(stage);
snakeControl = new SnakeControl();
GameAssets.instance().loadAssets();
batch = new SpriteBatch();
game = new GameControl();
}
#Override
public void show() {
Table table = new Table();
table.setFillParent(true);
table.setDebug(true);
table.row();
table.add(game).expand().pad(10f, 5f, 10f, 5f);
table.row();
table.add(snakeControl.get_tSnakeControl()).fillX().height(GameInfo.SCREEN_HEIGHT/3.5f).pad(0f, 5f, 10f, 5f);
stage.addActor(table);
}
#Override
public void render(float delta) {
game.update(Gdx.graphics.getDeltaTime());
clearScreen();
batch.begin();
game.render(batch);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
batch.end();
}
private void clearScreen() {
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height, true);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
batch.dispose();
GameAssets.instance().dispose();
}
The Game code
public class GameControl extends Actor {
private Board board;
private Snake snake;
private float timeState;
private BitmapFont font;
private GameObject food;
private boolean isGameOver;
public GameControl() {
TextureAtlas atlas = GameAssets.instance().get(GameAssets.SNAKE_PACK);
font = GameAssets.instance().get(GameAssets.PIXEL_FONT);
snake = new Snake(atlas);
board = new Board(snake, GameInfo.SCREEN_WIDTH, GameInfo.SCREEN_HEIGHT);
food = board.generateFood();
init();
}
private void init() {
GameSoundsPlayer.init();
GameSoundsPlayer.playMusic(GameAssets.MEMO_SOUND, false);
}
public void update(float delta) {
if (snake.hasLive()) {
timeState += delta;
snake.handleEvents();
if (timeState >= .09f) {
snake.moveBody();
timeState = 0;
}
if (snake.isCrash()) {
snake.reset();
snake.popLife();
GameSoundsPlayer.playSound(GameAssets.CRASH_SOUND, false);
}
if (snake.isFoodTouch(food)) {
GameSoundsPlayer.playSound(GameAssets.EAT_FOOD_SOUND, false);
Scorer.score();
snake.grow();
food = board.generateFood();
}
} else {
gameOver();
if (Gdx.input.isKeyJustPressed(Input.Keys.ANY_KEY)) start();
}
}
private void gameOver() {
isGameOver = true;
GameSoundsPlayer.stopMusic(GameAssets.MEMO_SOUND);
GameSoundsPlayer.playMusic(GameAssets.GAME_OVER_SOUND, false);
}
private void start() {
GameSoundsPlayer.playMusic(GameAssets.MEMO_SOUND, false);
GameSoundsPlayer.stopMusic(GameAssets.GAME_OVER_SOUND);
isGameOver = false;
snake.reset();
snake.restoreHealth();
food = board.generateFood();
Scorer.reset();
}
public void render(SpriteBatch batch) {
board.render(batch);
food.draw(batch);
snake.render(batch);
if (isGameOver) {
font.draw(batch, "GAME OVER", (GameInfo.SCREEN_WIDTH - 100) / 2, (GameInfo.SCREEN_HEIGHT + 100) / 2);
font.draw(batch, "Press any key to continue", (GameInfo.SCREEN_WIDTH - 250) / 2, (GameInfo.SCREEN_HEIGHT + 50) / 2);
}
font.draw(batch, "Player: ", GameInfo.SCALE * 4, GameInfo.SCREEN_HEIGHT - 10);
font.draw(batch, "Score: " + Scorer.getScore(), GameInfo.SCALE / 2, GameInfo.SCREEN_HEIGHT - 10);
font.draw(batch, "Size: " + snake.getBody().size(), GameInfo.SCALE / 2, GameInfo.SCREEN_HEIGHT - 40);
}
}
I used Viewport for this!!!
#Override
public void render(float delta) {
clearScreen();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()/3);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
Gdx.gl.glViewport(0, Gdx.graphics.getHeight()/3, Gdx.graphics.getWidth(), (Gdx.graphics.getHeight() - Gdx.graphics.getHeight()/3));
game.update(Gdx.graphics.getDeltaTime());
batch.begin();
game.render(batch);
batch.end();
}
Related
Inside my gameplay screen I want to create a Pause Screen Menu which I can select the Retry button or Back to main screen if I click the pause button.I already draw the pause button inside my class.My problem is how can I draw the pause menu screen?
Here is my code
//pause
pause = new Texture("pause.png");
myTextureRegion = new TextureRegion(pause);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
pause_btnDialog = new ImageButton(myTexRegionDrawable); //Set the button up
pause_btnDialog.setPosition(580,1150);
stage.addActor(pause_btnDialog); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
pause_btnDialog.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("Pause Button Pressed");
//Show Pause Screen menu
//game.setScreen(new PauseGameday1(game));
}
});
stage.addActor(pause_btnDialog);
GameScreen
public class IngamedayOne implements Screen ,InputProcessor {
final MyGdxGame game;
// Constant rows and columns of the sprite sheet
private static final int FRAME_COLS = 5, FRAME_ROWS = 1;
private boolean peripheralAvailable;
private static final float ACCELERATION = 20f;
// Objects used
Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
Texture cat ,left_paw,right_paw,progressbar_background,progressbar_knob,pause,meter;
Texture carpet,desk,plants,square_carpet,shoes;
SpriteBatch spriteBatch;
Sprite sprite;
private Texture Background;
ImageButton left_paw_btn,right_paw_btn,pause_btnDialog;
Viewport viewport;
private Stage stage;
// A variable for tracking elapsed time for the animation
float stateTime;
private TextureRegion myTextureRegion;
private TextureRegionDrawable myTexRegionDrawable;
private boolean isPause;
private Group pauseGroup;
//Screen Size
OrthographicCamera camera;
float catSpeed = 50.0f; // 10 pixels per second.
float catX;
float catY;
public boolean paused = false;
public IngamedayOne(final MyGdxGame game) {
this.game = game;
Gdx.input.setCatchBackKey(true);
Gdx.graphics.setContinuousRendering(false);
Gdx.graphics.requestRendering();
stage = new Stage(new StretchViewport( 720, 1280));
camera = new OrthographicCamera();
camera.setToOrtho(false, 720, 1280);
camera.translate( 1280/2, 720/2 );
Gdx.input.setInputProcessor(stage);
spriteBatch = new SpriteBatch();
viewport = new StretchViewport(720, 1280);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Load the sprite sheet as a texture
cat = new Texture(Gdx.files.internal("cat.png"));
sprite = new Sprite(cat);
catX=300;
catY=0;
Gdx.input.setInputProcessor( this);
peripheralAvailable = Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer);
int orientation = Gdx.input.getRotation();
Input.Orientation nativeOrientation = Gdx.input.getNativeOrientation();
viewport = new StretchViewport(720, 1280);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
// Progressbar
progressbar_background = new Texture("progression_map.png");
progressbar_knob = new Texture("cat_head.png");
//pause
pause = new Texture("pause.png");
myTextureRegion = new TextureRegion(pause);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
pause_btnDialog = new ImageButton(myTexRegionDrawable); //Set the button up
pause_btnDialog.setPosition(580,1150);
stage.addActor(pause_btnDialog); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
pause_btnDialog.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
System.out.println("Pause Button Pressed");
//Show Pause Screen menu
game.setScreen(new PauseGameday1(game));
pause();
}
});
stage.addActor(pause_btnDialog);
meter = new Texture("meter.png");
//background
Background = new Texture(Gdx.files.internal("floor.png")); //File from assets folder
// Use the split utility method to create a 2D array of TextureRegions. This is
// possible because this sprite sheet contains frames of equal size and they are
// all aligned.
TextureRegion[][] tmp = TextureRegion.split(cat, cat.getWidth() / FRAME_COLS, cat.getHeight()/ FRAME_ROWS);
// Place the regions into a 1D array in the correct order, starting from the top
// left, going across first. The Animation constructor requires a 1D array.
TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
int index = 0;
for (int i = 0; i < FRAME_ROWS; i++) {
for (int j = 0; j < FRAME_COLS; j++) {
walkFrames[index++] = tmp[i][j];
}
}
// Initialize the Animation with the frame interval and array of frames
walkAnimation = new Animation<TextureRegion>(0.200f, walkFrames);
// Instantiate a SpriteBatch for drawing and reset the elapsed animation
// time to 0
spriteBatch = new SpriteBatch();
stateTime = 0f;
//left_control
left_paw = new Texture(Gdx.files.internal("left_paw.png"));
myTextureRegion = new TextureRegion(left_paw);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
left_paw_btn = new ImageButton(myTexRegionDrawable); //Set the button up
left_paw_btn.setPosition(10,25);
stage.addActor(left_paw_btn); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
left_paw_btn.addListener(new InputListener(){
#Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("Left Button Pressed");
//Start Animation
}
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
}
});
stage.addActor(left_paw_btn);
//right_control
right_paw = new Texture(Gdx.files.internal("right_paw.png"));
myTextureRegion = new TextureRegion(right_paw);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
right_paw_btn = new ImageButton(myTexRegionDrawable); //Set the button up
right_paw_btn.setPosition(517,25);
stage.addActor(right_paw_btn); //Add the button to the stage to perform rendering and take input.
Gdx.input.setInputProcessor(stage);
right_paw_btn.addListener(new InputListener(){
#Override
public void touchUp (InputEvent event, float x, float y, int pointer, int button) {
System.out.println("Right Button Pressed");
//Start Animation
stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
camera.update();
}
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
return true;
}
});
stage.addActor(right_paw_btn);
}
public enum State
{
PAUSE,
RUN,
RESUME,
STOPPED
}
private State state = State.RUN;
#Override
public void show() {
}
#Override
public void render(float delta) {
// clear previous frame
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
camera.update();
spriteBatch.begin();
TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(currentFrame,catX,catY); // Draw current frame at (50, 50)
spriteBatch.draw(meter,190,990);
spriteBatch.draw(progressbar_background,20,1170);
spriteBatch.draw(progressbar_knob,18,1170);
//Moving player on desktop
if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
catX -= Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
catX += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.UP))
catY += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.DOWN))
catY -= Gdx.graphics.getDeltaTime() * catSpeed;
//Mobile acceleration
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
catX -= Gdx.input.getAccelerometerX();
catY += Gdx.input.getAccelerometerY();
}
if(catY<0) {
catY =0;
}
if(catY> Gdx.graphics.getWidth()-100) {
catY =Gdx.graphics.getWidth()-100;
}
if(catX<0){
catX =0;
}
if(catX> Gdx.graphics.getHeight()-250) {
catX =Gdx.graphics.getHeight()-250;
}
switch (state)
{
case RUN:
//do suff here
break;
case PAUSE:
break;
case RESUME:
break;
default:
break;
}
spriteBatch.end();
stage.act(); //acting a stage to calculate positions of actors etc
stage.draw(); //drawing it to render all
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
#Override
public void pause() {
this.state = State.PAUSE;
}
#Override
public void resume() {
this.state = State.RESUME;
}
#Override
public boolean keyDown(int keycode) {
return true;
}
#Override
public boolean keyUp(int keycode) {
return false;
}
#Override
public boolean keyTyped(char character) {
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
#Override
public boolean scrolled(int amount) {
return false;
}
#Override
public void hide() {
}
#Override
public void dispose() { // SpriteBatches and Textures must always be disposed
spriteBatch.dispose();
cat.dispose();
left_paw.dispose();
right_paw.dispose();
stage.dispose();
Background.dispose();
progressbar_background.dispose();
progressbar_knob.dispose();
}
}
Pause Menu
public class PauseGameday1 implements Screen {
final MyGdxGame game;
private Texture Background,pauseImg;
private Stage stage;
SpriteBatch spriteBatch;
OrthographicCamera camera;
private static final int WIDTH= 720;
private static final int HEIGHT= 1280;
private TextureRegion myTextureRegion;
private TextureRegionDrawable myTexRegionDrawable;
Viewport viewport;
public PauseGameday1( MyGdxGame game) {
this.game = game;
stage = new Stage(new StretchViewport( 720, 1280));
camera = new OrthographicCamera();
camera.setToOrtho(false, 720, 1280);
camera.translate( 1280/2, 720/2 );
Gdx.input.setInputProcessor(stage);
spriteBatch = new SpriteBatch();
viewport = new StretchViewport(720, 1280);
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Background = new Texture(Gdx.files.internal("backgroundimage.png")); //background image
pauseImg = new Texture(Gdx.files.internal("pausemenu/pause_text.png"));
}
#Override
public void show() {
}
#Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
camera.update();
spriteBatch.begin();
spriteBatch.setProjectionMatrix(camera.combined);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(pauseImg,230,900);
stage.act(Gdx.graphics.getDeltaTime()); //Perform ui logic
spriteBatch.end();
stage.getViewport().apply();
stage.draw(); //Draw the ui
}
#Override
public void resize(int width, int height) {
viewport.update(width, height);
camera.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2, 0);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
}
}
Can anyone correct my codes?
You only declared pauseGroup but never used in your game, Call pause() method from pause_button. It will create pauseGroup for you and add to your Stage. In pause() method, create Actor(UI) and add to pauseGroup. You can't use multiple screen at a time with your Game class because Game having reference of single Screen.
pause_btnDialog.addListener(new ChangeListener() {
public void changed (ChangeEvent event, Actor actor) {
pause();
}
});
#Override
public void render(float delta) {
// clear previous frame
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
camera.update();
spriteBatch.begin();
spriteBatch.setProjectionMatrix(camera.combined);
if(this.state==State.RESUME)
stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
spriteBatch.draw(Background,0,0);
spriteBatch.draw(currentFrame,catX,catY); // Draw current frame at (50, 50)
spriteBatch.draw(meter,190,990);
spriteBatch.draw(progressbar_background,20,1170);
spriteBatch.draw(progressbar_knob,18,1170);
if(this.state==State.RESUME){
//Moving player on desktop
if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
catX -= Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
catX += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.UP))
catY += Gdx.graphics.getDeltaTime() * catSpeed;
if(Gdx.input.isKeyPressed(Input.Keys.DOWN))
catY -= Gdx.graphics.getDeltaTime() * catSpeed;
//Mobile acceleration
if (Gdx.input.isPeripheralAvailable(Input.Peripheral.Accelerometer))
{
catX -= Gdx.input.getAccelerometerX();
catY += Gdx.input.getAccelerometerY();
}
if(catY<0) {
catY =0;
}
if(catY> Gdx.graphics.getWidth()-100) {
catY =Gdx.graphics.getWidth()-100;
}
if(catX<0){
catX =0;
}
if(catX> Gdx.graphics.getHeight()-250) {
catX =Gdx.graphics.getHeight()-250;
}
}
switch (state)
{
case RUN:
//do suff here
break;
case PAUSE:
break;
case RESUME:
break;
default:
break;
}
spriteBatch.end();
stage.act(); //acting a stage to calculate positions of actors etc
stage.draw(); //drawing it to render all
}
public void pause(){
this.state = State.PAUSE;
pauseGroup = new Group;
Image semiTransparentBG= ......
// setSize(Size of screen) and make it semi transparent.
pauseGroup.addActor(semiTransparentBG);
//crate all other pause UI buttons with listener and add to pauseGroup
stage.addActor(pauseGroup);
}
public void resume() {
if(this.state = State.PAUSE){
this.state = State.RESUME;
pauseGroup.remove();
}
}
when i run emulator and start application i see blinks screen, but on a PC in DesktopLauncher screen is normal.
I can not understand where I made mistakes.
render method override but it does not help.
class starter:
public class Drop extends Game {
Camera cam;
Game game;
SpriteBatch batch;
int tempGameScore = 0;
int dropsGatchered = 0;
Preferences preferences;//сохраняем игру
#Override
public void create() {
batch = new SpriteBatch();
this.setScreen(new MainMenuScreen(this));
}
#Override
public void render() {
super.render();
}
#Override
public void dispose() {
batch.dispose();
}
MainMenu:
I think I'm working wrong with the scene tool.
Can it is necessary as otherwise to draw a scene?
public class MainMenuScreen implements Screen {
Sprite texture;
final Drop game;
Skin skin;
Stage stage;
OrthographicCamera camera;
ImageButton newGameButton, exit, highScore;
Table table;
ImageButton.ImageButtonStyle btnplayStyle, btnscoreStyle, btnexitStyle;
private static TextureAtlas atlas, backAtlas;
public MainMenuScreen(final Drop gam) {
this.game = gam;
atlas = new TextureAtlas(Gdx.files.internal("texture/texture.pack"), true);
backAtlas = new TextureAtlas(Gdx.files.internal("texture/background.pack"), true);
texture = new Sprite(backAtlas.findRegion("background"));
skin = new Skin();
skin.addRegions(atlas);
table = new Table();
camera = new OrthographicCamera();
camera.setToOrtho(false, 800, 480);
stage = new Stage();
stage.addActor(table);
Gdx.input.setInputProcessor(stage);// Make the stage consume events
table();
}
private void table() {
btnplayStyle = new ImageButton.ImageButtonStyle();
btnplayStyle.up = skin.getDrawable("play");//кнопка не нажата
btnplayStyle.over = skin.getDrawable("play");
btnplayStyle.down = skin.getDrawable("play"); // кнопка нажата
newGameButton = new ImageButton(btnplayStyle);
newGameButton.setSize(300, 200);
stage.addActor(newGameButton);
newGameButton.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new GameScreen(game));
}
});
//Button score
btnscoreStyle = new ImageButton.ImageButtonStyle();
btnscoreStyle.up = skin.getDrawable("records");//кнопка не нажата
btnscoreStyle.over = skin.getDrawable("records");
btnscoreStyle.down = skin.getDrawable("records"); // кнопка нажата
highScore = new ImageButton(btnscoreStyle);
highScore.setSize(300, 200);
stage.addActor(highScore);
highScore.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(new Score(game) {
});
}
});
//Button EXIT
btnexitStyle = new ImageButton.ImageButtonStyle();
btnexitStyle.up = skin.getDrawable("exit");//кнопка не нажата
btnexitStyle.over = skin.getDrawable("exit");
btnexitStyle.down = skin.getDrawable("exit"); // кнопка нажата
exit = new ImageButton(btnexitStyle);
exit.setSize(300, 200);
stage.addActor(exit);
exit.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
Gdx.app.exit();
}
});
table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
game.batch.begin();
game.batch.draw(texture, 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
table.add(newGameButton).width(400).height(120);
table.getCell(newGameButton).spaceBottom(30);
table.row();
table.add(highScore).width(400).height(120);
table.getCell(highScore).spaceBottom(30);
table.row();
table.add(exit).width(400).height(120);
table.getCell(exit).spaceBottom(30);
table.row();
game.batch.end();
}
#Override
public void render(float delta) {
stage.act();
stage.draw();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
skin.dispose();
}
}
I think I'm working wrong with the scene tool
In MainMenuScreen you have to draw things in the render() method, not in the show() method. Like this:
#Override
public void render() {
stage.draw();
// ... possibly more drawing code
}
I am making a 2d game using libgdx and am adding hexagon shaped actors to a group which is then added to a stage. For a normal camera you can use camera.zoom in the render method to zoom in and out along with camera.translate to pan around the world.
I have been getting the camera used by the stage using stage.getCamera() and I can still call stage.getcamera().translate however there is no stage.getCamera().zoom option.
Here is my code:
//import statements
public class HexGame implements ApplicationListener{
private Stage stage;
private Texture hexTexture;
private Group hexGroup;
private int screenWidth;
private int screenHeight;
#Override
public void create() {
hexTexture = new Texture(Gdx.files.internal("hex.png"));
screenHeight = Gdx.graphics.getHeight();
screenWidth = Gdx.graphics.getWidth();
stage = new Stage(new ScreenViewport());
hexGroup = new HexGroup(screenWidth,screenHeight,hexTexture);
stage.addActor(hexGroup);
}
#Override
public void dispose() {
stage.dispose();
hexTexture.dispose();
}
#Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
handleInput();
stage.getCamera().update();
}
private void handleInput() {
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
stage.getCamera().translate(-3, 0, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
stage.getCamera().translate(3, 0, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
stage.getCamera().translate(0, -3, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
stage.getCamera().translate(0, 3, 0);
}
//This is the part that doesn't work
/*
if (Gdx.input.isKeyPressed(Input.Keys.Z)) {
stage.getCamera().zoom += 0.02;
}
*/
}
#Override
public void resize(int width, int height) {
stage.getViewport().update(width, height);
}
#Override
public void pause() {
}
#Override
public void resume() {
}
}
Any help is appreciated, and if there is anything else wrong with my code please let me know, I'm new to libgdx. Thanks
Zoom is available in OrthographicCamera class and by default Stage class create a OrthographicCamera
/** Creates a stage with a {#link ScalingViewport} set to {#link Scaling#stretch}. The stage will use its own {#link Batch}
* which will be disposed when the stage is disposed. */
public Stage () {
this(new ScalingViewport(Scaling.stretch, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), new OrthographicCamera()),
new SpriteBatch());
ownsBatch = true;
}
So what you need is to cast your camera to OrthographicCamera:
((OrthographicCamera)stage.getCamera()).zoom += 0.02f;
I need your help for a simple problem.
I implemented my Java game using LibGDX library.
My Game has following structure:
- main menù with some buttons;
- game screen;
- pause menù opened when user press P keyword.
The probles is the this. When I press P, pause menù opens. If I click on MainMenù button in pause menù , the screen go on main menù. After that, If I press on game button , it appears pause menù screen and not game screen.
How can I solve this?
public class MenuPause implements Screen {
private Skin skin;
private Stage stage;
private MyGdxGame game;
private Level level=new Level(true);
private World world;
private GameScreen8Bit GS;
private int era;
/*****Button *******/
private Button saveGame;
private Button loadGame;
private Button continueGame;
private Button exitGame;
private Button mainMenu;
/******************/
private SpriteBatch batch;
private TextureAtlas atlas;
private TextureRegion imagetexture;
public MenuPause(MyGdxGame game, int era){
this.game=game;
}
private void createBasicSkin(){
//Create a font
atlas = new TextureAtlas(Gdx.files.internal("images/textures/game.atlas"));
BitmapFont font = new BitmapFont();
skin = new Skin();
skin.add("default", font);
//Create a texture
Pixmap pixmap = new Pixmap((int)Gdx.graphics.getWidth()/4,(int)Gdx.graphics.getHeight()/10, Pixmap.Format.RGB888);
pixmap.setColor(Color.WHITE);
pixmap.fill();
skin.add("background",new Texture(pixmap));
//Create a button style
TextButton.TextButtonStyle textButtonStyle = new TextButton.TextButtonStyle();
textButtonStyle.up = skin.newDrawable("background", Color.GRAY);
textButtonStyle.down = skin.newDrawable("background", Color.DARK_GRAY);
textButtonStyle.checked = skin.newDrawable("background", Color.DARK_GRAY);
textButtonStyle.over = skin.newDrawable("background", Color.LIGHT_GRAY);
textButtonStyle.font = skin.getFont("default");
skin.add("default", textButtonStyle);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Vector3 touchPos = new Vector3();
touchPos.set((Gdx.input.getX()), (Gdx.graphics.getHeight()-Gdx.input.getY()), 0);
if(exitGame.mousePassage(touchPos))
{
exitGame=new Button(atlas.findRegion("exitNoPressed"));
exitGame.setPos(0, 0);
}
else
{
exitGame=new Button(atlas.findRegion("exit"));
exitGame.setPos(0, 0);
}
if(loadGame.mousePassage(touchPos))
{
loadGame=new Button(atlas.findRegion("loadNoPressed"));
loadGame.setPos(Gdx.graphics.getWidth()/2-atlas.findRegion("loadNoPressed").getRegionWidth()/2, (Gdx.graphics.getHeight()/2));
}
else
{
loadGame=new Button(atlas.findRegion("load"));
loadGame.setPos(Gdx.graphics.getWidth()/2-atlas.findRegion("load").getRegionWidth()/2, (Gdx.graphics.getHeight()/2));
}
if(saveGame.mousePassage(touchPos))
{
saveGame=new Button(atlas.findRegion("saveNoPressed"));
saveGame.setPos(0 , Gdx.graphics.getHeight()/3);
}
else
{
saveGame=new Button(atlas.findRegion("save"));
saveGame.setPos(0 , Gdx.graphics.getHeight()/3);
}
if(continueGame.mousePassage(touchPos))
{
continueGame=new Button(atlas.findRegion("continueNoPressed"));
continueGame.setPos((Gdx.graphics.getWidth() - atlas.findRegion("continueNoPressed").getRegionWidth()) , 0);
}
else
{
continueGame=new Button(atlas.findRegion("continue"));
continueGame.setPos((Gdx.graphics.getWidth() - atlas.findRegion("continue").getRegionWidth()) , 0);
}
if(mainMenu.mousePassage(touchPos))
{
mainMenu=new Button(atlas.findRegion("mainNoPressed"));
mainMenu.setPos(Gdx.graphics.getWidth()/2-atlas.findRegion("mainNoPressed").getRegionWidth()/2 , 0);
}
else
{
mainMenu=new Button(atlas.findRegion("main"));
mainMenu.setPos((Gdx.graphics.getWidth()/2-atlas.findRegion("main").getRegionWidth()/2) , 0);
}
if(Gdx.input.isButtonPressed(Input.Buttons.LEFT)){
if(exitGame.isPressed(touchPos)){
int n= JOptionPane.showConfirmDialog(null,"Sei sicuro di volere uscire dal gioco?", "EXIT", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
if(n==0)
{
System.exit(0);
}
}
if(loadGame.isPressed(touchPos)){
new LoadGame(level,false);
}
if(saveGame.isPressed(touchPos)){
SavePanel savePanel = new SavePanel( level, game,false);
savePanel.save();
}
if(mainMenu.isPressed(touchPos)){
dispose();
this.dispose();
game.setScreen(new MainMenu(game,0));
}
if(continueGame.isPressed(touchPos)){
//game.setScreen(new MainMenu(game));//mainMenu non funziona...eccezione
//game.setScreen(new GameScreen8Bit(game,level));
}
}
batch.begin();
batch.draw(imagetexture,0 , 0);
saveGame.draw(batch);
loadGame.draw(batch);
continueGame.draw(batch);
exitGame.draw(batch);
mainMenu.draw(batch);
batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void show() {
batch = new SpriteBatch();
createBasicSkin();
saveGame= new Button(atlas.findRegion("save"));
saveGame.setPos(0 , Gdx.graphics.getHeight()/3);
loadGame=new Button(atlas.findRegion("load"));
loadGame.setPos(Gdx.graphics.getWidth()/2-atlas.findRegion("load").getRegionWidth()/2, (Gdx.graphics.getHeight()/2));
continueGame=new Button(atlas.findRegion("continue"));
continueGame.setPos((Gdx.graphics.getWidth() - atlas.findRegion("continue").getRegionWidth()) , 0);
exitGame=new Button(atlas.findRegion("exit"));
exitGame.setPos(0, 0);
mainMenu=new Button(atlas.findRegion("main"));
mainMenu.setPos(Gdx.graphics.getWidth()/2-atlas.findRegion("load").getRegionWidth()/2, 0);
Texture immagine=new Texture(Gdx.files.internal("data/ghiacciairid.png"));
if(era==1)
{
immagine=new Texture(Gdx.files.internal("data/8bitrid.png"));
}
else if(era==2)
{
immagine=new Texture(Gdx.files.internal("data/16bitrid.png"));
}
else if(era==3)
{
immagine=new Texture(Gdx.files.internal("data/3d.png"));
}
imagetexture =new TextureRegion(immagine,640,480);
imagetexture.setRegionHeight(480);
imagetexture.setRegionWidth(640);
}
#Override
public void hide() {
dispose();
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
I know this is a year old, but I am answering anyway.
Don't create menu items every frame in render. Create once.
public class GameScreen implements Screen{
private State state; //this keeps track of where
public static enum State{
RUNNING, PAUSE, SAVEGAME
}
public MenuPause(MyGdxGame game, int era){
this.game=game;
state = State.RUNNING
}
#Override
public void show() {
//do the loading and creating here
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
switch(state){
case RUNNING: running();
break;
case PAUSE: pause();
break;
case SAVEGAME: savegame();
break;
default: break;
}
}
private void running(){
}
private void pause(){
}
private void savegame(){
}
}
i'm trying to make my libgdx map scroll, but i dont know the code to make map scroll, please guys help me, i would like the map to scroll like flappy bird game, this is my my code which show the map on the screen
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
position.y = position.y - 4;
if(Gdx.input.isTouched()){
position.y = position.y +10;
}
if(position.y < 0){
position.y = 0;
}
if(position.y > Gdx.graphics.getHeight() -70){
position.y = Gdx.graphics.getHeight() - 70;
}
renderer.setView(camera);
renderer.render();
//tells the computer when to start drawing textures
batch.begin();
batch.draw(Green1, position.x, position.y, 50, 50);
batch.end();
}
#Override
public void show() {
Green1 = new Texture("img/Green1.png");
batch = new SpriteBatch();
position = new Vector2(20, Gdx.graphics.getHeight());
map = new TmxMapLoader().load("maps/map1.tmx");
renderer = new OrthogonalTiledMapRenderer(map);
camera = new OrthographicCamera();
}
#Override
public void hide() {
}
#Override
public void create() {
Green1 = new Texture("img/Green.png");
batch = new SpriteBatch();
position = new Vector2(20, Gdx.graphics.getHeight());
}
#Override
public void resize(int width, int height) {
camera.viewportWidth = width;
camera.viewportHeight = height;
camera.position.set(width/2f, height/3f, 0); //by default camera position on (0,0,0)
camera.update();
}
#Override
public void render() {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
map.dispose();
renderer.dispose();
}
}
When I was learning to build 2D games I used star-assault for an example. You can find their github repository here: https://github.com/chrismorales/2d-sidescroller && https://github.com/chrismorales/2d-sidescroller/blob/master/star-assault/src/net/obviam/starassault/view/WorldRenderer.java should be useful to look at.